text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { SpeechToTextApi } from './index'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; import { Http } from '@angular/http'; import { AwsService } from "app/aws/aws.service"; export type ProcessBehavior = "SAVE" | "BUILD"; export class BotEntry { name: string; description: string; version: string; checksum: string; processBehavior: ProcessBehavior; status: string; update: string; created: string; clarificationPrompt: Object[]; abortStatement: Object[]; idleSessionTTLInSeconds: number; intents: Object[]; locale: string; voiceId: string; childDirected: boolean; expandAllVersions: boolean; isSelected: boolean; versions: BotEntry[]; isLoading: boolean; constructor(botInfo: any, private toastr: ToastsManager, private _apiHandler: SpeechToTextApi) { this.name = botInfo.name; this.description = botInfo.description; this.checksum = botInfo.checksum; this.version = botInfo.version; this.processBehavior = botInfo.processBehavior; this.idleSessionTTLInSeconds = botInfo.idleSessionTTLInSeconds; this.childDirected = botInfo.childDirected; this.intents = botInfo.intents; this.status = botInfo.status; this.update = botInfo.update; this.created = botInfo.created; this.clarificationPrompt = botInfo.clarificationPrompt; this.abortStatement = botInfo.abortStatement; this.locale = botInfo.locale; this.voiceId = botInfo.voiceId; this.expandAllVersions = false; this.isSelected = false; this.isLoading = false; } /** * Get the bot of a specific verison * @param version The version of the bot to get **/ public get(version: string): any { var promise = new Promise(function (resolve, reject) { this._apiHandler.getBot(this.name, this.version).subscribe(response => { let obj = JSON.parse(response.body.text()); if (!obj.result.bot.error) { let bot = new BotEntry(obj.result.bot, this.toastr, this._apiHandler); resolve(bot); } else { this.toastr.error("The bot '" + this.name + "' did not refresh properly. " + obj.result.bot.error); reject(); } }, err => { this.toastr.error("The bot '" + this.name + "' did not refresh properly. " + err.message); reject(); }); }.bind(this)); return promise; } /** * Gets information about all of the versions of a bot * @param PageToken A pagination token for fetching the next page of bot versions. If the response to this call is truncated, Amazon Lex returns a pagination token in the response. **/ public getVersions(PageToken: string): any { this.isLoading = true; var promise = new Promise(function (resolve, reject) { this._apiHandler.getBotVersions(this.name, PageToken).subscribe(response => { let obj = JSON.parse(response.body.text()); if (!obj.result.bots.error) { if (PageToken.length <= 1) { this.versions = []; } for (let bot of obj.result.bots) { this.versions.push(new BotEntry(bot, this.toastr, this._apiHandler)); } if (obj.result.nextToken != "") { this.getVersions(obj.result.nextToken); } else { resolve(); this.isLoading = false; } } else { this.toastr.error("The bot versions did not refresh properly. " + obj.result.bots.error); reject(); this.isLoading = false; } }, err => { this.toastr.error("The bot versions did not refresh properly. " + err.message); reject(); this.isLoading = false; }); }.bind(this)); return promise; } /** * Export the bot **/ public export(): void { this._apiHandler.getDesc(this.name, this.version).subscribe(response => { let obj = JSON.parse(response.body.text()); if (!obj.result.desc_file.error) { let descFile = obj.result.desc_file; let blob = new Blob([JSON.stringify(descFile, null, 4)], { type: "application/json" }); let fileName = this.name + ".json"; if (window.navigator.msSaveOrOpenBlob) //Edge { window.navigator.msSaveBlob(blob, fileName); } else //Chrome & FireFox { let a = document.createElement("a"); let fileURL = URL.createObjectURL(blob); a.href = fileURL; a.download = fileName; window.document.body.appendChild(a); a.click(); window.document.body.removeChild(a); URL.revokeObjectURL(fileURL); } this.toastr.success("The bot '" + this.name + "' was exported."); } else { this.toastr.error("The bot '" + this.name + "' was not exported properly. " + obj.result.desc_file.error); } }, err => { this.toastr.error("The bot '" + this.name + "' was not exported properly. " + err.message); }); } /** * Build the bot **/ public build(): void { this._apiHandler.buildBot(this.name).subscribe(response => { let obj = JSON.parse(response.body.text()); if (obj.result.status == "READY") { this.status = "BUILDING"; this.checkBotStatus(); } else { this.toastr.error("The bot '" + this.name + "' was not built properly. " + obj.result.status); } }, err => { this.toastr.error("The bot '" + this.name + "' was not built properly. " + err.message); }); } /** * Publish the bot using a given alias name * @param aliasName The alias name used to publish the bot **/ public publish(aliasName: string): void { this.status = "PUBLISHING"; this._apiHandler.publishBot(this.name, aliasName).subscribe(response => { let obj = JSON.parse(response.body.text()); if (obj.result.status == "READY") { this.toastr.success("The bot '" + this.name + "' was published."); this.checkBotStatus(); } else { this.toastr.error("The bot '" + this.name + "' was not published properly. " + obj.result.status); this.status = "FAILED"; } }, (err) => { this.toastr.error("The bot '" + this.name + "' was not published properly. " + err.message); this.status = "FAILED"; }); } /** * Delete the bot **/ public delete(): any { var promise = new Promise(function (resolve, reject) { if (this.version == "$LATEST") { this._apiHandler.deleteBot(this.name).subscribe(response => { let obj = JSON.parse(response.body.text()); if (obj.result.status == "INUSE") { this.toastr.error("The bot '" + this.name + "' is currently used by an alias. Delete the alisas from '" + this.name + "'"); reject(); } else if (obj.result.status == "DELETED") { this.toastr.success("The bot '" + this.name + "' was deleted."); resolve(); } else { this.toastr.error("The bot '" + this.name + "' could not be deleted. " + obj.result.status); reject(); } }); } else { this._apiHandler.deleteBotVersion(this.name, this.version).subscribe(response => { let obj = JSON.parse(response.body.text()); if (obj.result.status == "INUSE") { this.toastr.error("The selected version of the bot '" + this.name + "' is currently used by an alias. Delete the alisas from '" + this.name + "'"); reject(); } else if (obj.result.status == "DELETED") { this.toastr.success("The selected version of the bot '" + this.name + "' was deleted."); resolve(); } else { this.toastr.error("The selected version of the bot '" + this.name + "' could not be deleted. " + obj.result.status); reject(); } }); } }.bind(this)); return promise; } /** * Save the bot * @param processBehavior If you set the processBehavior element to Build , Amazon Lex builds the bot so that it can be run. If you set the element to Save Amazon Lex saves the bot, but doesn't build it. **/ public save(processBehavior: ProcessBehavior): any { var promise = new Promise(function (resolve, reject) { this.processBehavior = processBehavior; let body = { "bot": this.getInfo() }; this._apiHandler.updateBot(body).subscribe(response => { let obj = JSON.parse(response.body.text()); if (obj.result.status == "ACCEPTED") { this.toastr.success("The bot '" + this.name + "' was updated."); if (this.processBehavior == "BUILD") { this.status = "BUILDING"; this.checkBotStatus(); } resolve(); } else { this.toastr.error("The bot '" + this.name + "' was not updated successfully. " + obj.result.status); reject(); } }, err => { this.toastr.error("The bot '" + this.name + "' was not updated successfully. " + err.message); reject(); }); }.bind(this)); return promise; } /** * Save the bot alias * @param alias The alias to save **/ public saveAlias(alias: Object): any{ var promise = new Promise(function (resolve, reject) { alias["botName"] = this.name; let body = { alias: alias }; this._apiHandler.updateBotAlias(body).subscribe(response => { let obj = JSON.parse(response.body.text()); if (obj.result.status == "ACCEPTED") { this.toastr.success("The bot alias '" + alias["name"] + "' was updated successfully."); resolve(); } else { this.toastr.error("The bot alias'" + alias["name"] + "' was not updated properly. " + obj.result.status); reject(); } }, (err) => { this.toastr.error("The bot alias'" + alias["name"] + "' was not updated properly. " + err.message); reject(); }); }.bind(this)); return promise; } /** * Delete the bot alias * @param alias The alias to delete **/ public deleteAlias(alias): any { var promise = new Promise(function (resolve, reject) { this._apiHandler.deleteBotAlias(alias["name"], this.name).subscribe(response => { let obj = JSON.parse(response.body.text()); if (obj.result.status == "DELETED") { this.toastr.success("The bot alias '" + alias["name"] + "' was deleted successfully."); resolve(); } else { this.toastr.error("The bot alias'" + alias["name"] + "' was not deleted properly. " + obj.result.status); reject(); } }, (err) => { this.toastr.error("The bot alias'" + alias["name"] + "' was not deleted properly. " + err.message); reject(); }); }.bind(this)); return promise; } /** * Check the status of the bot **/ public checkBotStatus(): void { this._apiHandler.getBotStatus(this.name).subscribe(response => { let obj = JSON.parse(response.body.text()); if (obj.result.status.indexOf("ERROR") > -1) { this.toastr.error("The status of bot '" + this.name + "' did not refresh properly. " + obj.result.status); } else { if (obj.result.status == "BUILDING" || obj.result.status == "PUBLISHING") { this.checkBotStatus(); } else { this.status = obj.result.status; } } }, err => { this.toastr.error("The status of bot '" + this.name + "' did not refresh properly. " + err.message); }); } /** * Generate an object that contains all the necessary information to update a bot * @return an object that contains all the necessary information to update a bot **/ private getInfo(): Object { let botInfo = {} let properties = ["name", "description", "locale", "childDirected", "intents", "idleSessionTTLInSeconds", "voiceId", "checksum", "processBehavior", "clarificationPrompt", "abortStatement"]; for (let property of properties) { if (this[property] != undefined) { botInfo[property] = this[property]; } } return botInfo; } }
the_stack
import {Graph} from '../../../graph'; import {OperatorImplementation, OperatorInitialization} from '../../../operators'; import {Tensor} from '../../../tensor'; import {getGlsl} from '../glsl-source'; import {WebGLInferenceHandler} from '../inference-handler'; import {ProgramInfo, TextureType} from '../types'; import {getCoordsDataType} from '../utils'; import {unpackFromChannel} from './packing-utils'; import {parseUpsampleAttributes, scalesValidation, UpsampleAttributes, validateInputs} from './upsample'; const resizeProgramMetadata = { name: 'Resize', inputNames: ['A'], inputTypes: [TextureType.packed] }; export const resize: OperatorImplementation<UpsampleAttributes> = (inferenceHandler: WebGLInferenceHandler, inputs: Tensor[], attributes: UpsampleAttributes): Tensor[] => { validateInputs(inputs, attributes); const output = inferenceHandler.run( { ...resizeProgramMetadata, cacheHint: attributes.cacheKey, get: () => createPackedResizeProgramInfo(inferenceHandler, inputs, attributes) }, inputs); return [output]; }; export const parseResizeAttributesV10: OperatorInitialization<UpsampleAttributes> = (node: Graph.Node): UpsampleAttributes => parseUpsampleAttributes(node, 10); export const parseResizeAttributesV11: OperatorInitialization<UpsampleAttributes> = (node: Graph.Node): UpsampleAttributes => parseUpsampleAttributes(node, 11); const createPackedResizeProgramInfo = (inferenceHandler: WebGLInferenceHandler, inputs: Tensor[], attributes: UpsampleAttributes): ProgramInfo => { const glsl = getGlsl(inferenceHandler.session.backend.glContext.version); const [scales, outputShape] = prepareInputs(inputs, attributes); const isSame = scales.every((s: number) => s === 1) && attributes.coordinateTransformMode !== 'tf_crop_and_resize'; if (isSame) { return { ...resizeProgramMetadata, output: {dims: outputShape, type: inputs[0].type, textureType: TextureType.packed}, hasMain: true, shaderSource: `void main() { vec4 v = ${glsl.texture2D}(X, TexCoords); ${glsl.output} = v; }` }; } const dim = outputShape.length; if (dim < 2) { throw new Error(`output dimension should be at least 2, but got ${dim}`); } const outputHeight = outputShape[dim - 2]; const outputWidth = outputShape[dim - 1]; const inputShape = inputs[0].dims; if (dim !== inputShape.length) { throw new Error(`output dimension should match input ${inputShape.length}, but got ${dim}`); } const inputHeight = inputShape[dim - 2]; const inputWidth = inputShape[dim - 1]; const scalesHeight = scales[dim - 2]; const scalesWidth = scales[dim - 1]; let getSourceFracIndex = ''; if (attributes.mode !== 'linear') { // TODO: support other modes throw new Error(`resize (packed) does not support mode: '${attributes.mode}'`); } switch (attributes.coordinateTransformMode) { case 'asymmetric': getSourceFracIndex = ` vec4 getSourceFracIndex(ivec4 coords) { return vec4(coords) / scaleWHWH; } `; break; case 'half_pixel': getSourceFracIndex = ` vec4 getSourceFracIndex(ivec4 coords) { return (vec4(coords) + 0.5) / scaleWHWH - 0.5; } `; break; case 'align_corners': getSourceFracIndex = ` vec4 getSourceFracIndex(ivec4 coords) { vec4 resized = vec4(${outputWidth}.0 - 1.0, ${outputHeight}.0 - 1.0, ${outputWidth}.0 - 1.0, ${outputHeight}.0 - 1.0); vec4 original = vec4(${inputWidth}.0 - 1.0, ${inputHeight}.0 - 1.0, ${inputWidth}.0 - 1.0, ${inputHeight}.0 - 1.0); vec4 new_scale = original / resized; return vec4(coords) * new_scale; } `; break; default: // TODO:supporting other coordinateTransformModes throw new Error(`resize (packed) does not support coordinateTransformMode: \ '${attributes.coordinateTransformMode}'`); } const coordsDataType = getCoordsDataType(dim); const unpackChannel = unpackFromChannel(); const shaderSource = ` const vec2 inputWH = vec2(${inputHeight}.0, ${inputWidth}.0); const vec4 scaleWHWH = vec4(${scalesHeight}.0, ${scalesWidth}.0, ${scalesHeight}.0, ${scalesWidth}.0); ${unpackChannel} ${getSourceFracIndex} float getAValue(int x10, int r, int c, int d) { return getChannel(getA(x10, r, c, d), vec2(c, d)); } void main() { ${coordsDataType} rc = getOutputCoords(); int batch = rc[0]; int depth = rc[1]; // retrieve the 4 coordinates that is used in the 4 packed output values. ivec4 coords = ivec4(rc.wz, rc.w + 1, rc.z + 1); // calculate the source index in fraction vec4 sourceFrac = getSourceFracIndex(coords); // get the lower and upper bound of the 4 values that will be packed into one texel. ivec4 x00 = ivec4(max(sourceFrac.xy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xy))); ivec4 x01 = ivec4(max(sourceFrac.xw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.xw))); ivec4 x10 = ivec4(max(sourceFrac.zy, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zy))); ivec4 x11 = ivec4(max(sourceFrac.zw, vec2(0.0)), min(inputWH - 1.0, ceil(sourceFrac.zw))); bool hasNextRow = rc.w < ${outputHeight - 1}; bool hasNextCol = rc.z < ${outputWidth - 1}; // pack x00, x01, x10, x11's top-left corner into one vec4 structure vec4 topLeft = vec4( getAValue(batch, depth, x00.x, x00.y), hasNextCol ? getAValue(batch, depth, x01.x, x01.y) : 0.0, hasNextRow ? getAValue(batch, depth, x10.x, x10.y) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.y) : 0.0); // pack x00, x01, x10, x11's top-right corner into one vec4 structure vec4 topRight = vec4( getAValue(batch, depth, x00.x, x00.w), hasNextCol ? getAValue(batch, depth, x01.x, x01.w) : 0.0, hasNextRow ? getAValue(batch, depth, x10.x, x10.w) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.x, x11.w) : 0.0); // pack x00, x01, x10, x11's bottom-left corner into one vec4 structure vec4 bottomLeft = vec4( getAValue(batch, depth, x00.z, x00.y), hasNextCol ? getAValue(batch, depth, x01.z, x01.y) : 0.0, hasNextRow ? getAValue(batch, depth, x10.z, x10.y) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.y) : 0.0); // pack x00, x01, x10, x11's bottom-right corner into one vec4 structure vec4 bottomRight = vec4( getAValue(batch, depth, x00.z, x00.w), hasNextCol ? getAValue(batch, depth, x01.z, x01.w) : 0.0, hasNextRow ? getAValue(batch, depth, x10.z, x10.w) : 0.0, (hasNextRow && hasNextCol) ? getAValue(batch, depth, x11.z, x11.w) : 0.0); // calculate the interpolation fraction on u and v direction vec4 frac = vec4(sourceFrac) - floor(sourceFrac); vec4 clampFrac = clamp(frac, vec4(0.0), vec4(1.0)); vec4 top = mix(topLeft, topRight, clampFrac.ywyw); vec4 bottom = mix(bottomLeft, bottomRight, clampFrac.ywyw); vec4 newValue = mix(top, bottom, clampFrac.xxzz); ${glsl.output} = vec4(newValue); } `; return { ...resizeProgramMetadata, output: {dims: outputShape, type: inputs[0].type, textureType: TextureType.packed}, hasMain: true, shaderSource }; }; const prepareInputs = (inputs: Tensor[], attributes: UpsampleAttributes): [readonly number[], readonly number[]] => { const x = inputs[0]; const xDims = x.dims; let scales = attributes.scales; let outputSizes: number[]|undefined; if (scales.length === 0) { const scalesTensor = inputs[attributes.scalesInputIdx]; if (scalesTensor && scalesTensor.size !== 0) { if (inputs[attributes.sizesInputIdx]) { throw new Error('Only one of scales or sizes must be provided as input.'); } scales = parseScalesData(scalesTensor, attributes.mode, attributes.isResize); } else { const sizesTensor = inputs[attributes.sizesInputIdx]; if (!sizesTensor || sizesTensor.size === 0) { throw new Error('Either scales or sizes MUST be provided as input.'); } outputSizes = Array.from(sizesTensor.integerData); scales = parseScalesDataFromOutputSize(outputSizes, xDims, attributes.mode, attributes.isResize); } } else { if (inputs[attributes.sizesInputIdx]) { throw new Error('Only one of scales or sizes must be provided as input.'); } } const yDims = outputSizes || (xDims.map((dim, i) => Math.floor(dim * scales[i]))); return [scales, yDims]; }; const parseScalesData = (scale: Tensor, mode: string, isResize: boolean): number[] => { const scales = Array.from(scale.floatData); scalesValidation(scales, mode, isResize); return scales; }; const parseScalesDataFromOutputSize = (yDims: readonly number[], xDims: readonly number[], mode: string, isResize: boolean): number[] => { const length = xDims.length; const scales = new Array<number>(length); for (let i = 0, end = length; i < end; i++) { if (xDims[i] === 0) { if (yDims[i] !== 0) { throw new Error('Input dim is zero but required output dim is non-zero.'); } scales[i] = 1; } else { scales[i] = yDims[i] / xDims[i]; } } scalesValidation(scales, mode, isResize); return scales; }; // roi data is not used yet. but leave here for future usage. // const getRoi = (inputs: Tensor[], attributes: UpsampleAttributes) : number[] => { // let roi: number[] = []; // if (attributes.needRoiInput) { // if (attributes.roiInputIdx <= 0) { // throw new Error('Invalid roi input index.'); // } // const roiTensor = inputs[attributes.roiInputIdx]; // roi = roiTensor.size > 0 ? Array.from(roiTensor.floatData) : []; // } else { // roi = new Array(inputs[0].dims.length * 2).fill(0); // } // return roi; // };
the_stack
import { TextFormat } from "../../core/text/TextFormat"; import { AlignType } from "../../ui/FieldTypes"; import { convertFromHtmlColor } from "../ToolSet"; import { XMLIterator, XMLTagType } from "../xml/XMLIterator"; import { XMLUtils } from "../xml/XMLUtils"; import { HtmlElement, HtmlElementType, elementPool } from "./HtmlElement"; import { HtmlParseOptions } from "./HtmlParseOptions"; var s_list1: Array<string> = new Array<string>(); var s_list2: Array<string> = new Array<string>(); export class HtmlParser { protected _textFormatStack: Array<TextFormat>; protected _textFormatStackTop: number; protected _format: TextFormat; protected _elements: Array<HtmlElement>; protected _defaultOptions: HtmlParseOptions; public constructor() { this._textFormatStack = new Array<TextFormat>(); this._format = new TextFormat(); this._defaultOptions = new HtmlParseOptions(); } public parse(aSource: string, defaultFormat: TextFormat, elements: Array<HtmlElement>, parseOptions: HtmlParseOptions): void { if (parseOptions == null) parseOptions = this._defaultOptions; this._elements = elements; this._textFormatStackTop = 0; this._format.copy(defaultFormat); this._format["colorChanged"] = false; let skipText: number = 0; let ignoreWhiteSpace: boolean = parseOptions.ignoreWhiteSpace; let skipNextCR: boolean = false; let text: string XMLIterator.begin(aSource, true); while (XMLIterator.nextTag()) { if (skipText == 0) { text = XMLIterator.getText(ignoreWhiteSpace); if (text.length > 0) { if (skipNextCR && text[0] == '\n') text = text.substr(1); this.appendText(text); } } skipNextCR = false; switch (XMLIterator.tagName) { case "b": if (XMLIterator.tagType == XMLTagType.Start) { this.pushTextFormat(); this._format.bold = true; } else this.popTextFormat(); break; case "i": if (XMLIterator.tagType == XMLTagType.Start) { this.pushTextFormat(); this._format.italic = true; } else this.popTextFormat(); break; case "u": if (XMLIterator.tagType == XMLTagType.Start) { this.pushTextFormat(); this._format.underline = true; } else this.popTextFormat(); break; case "strike": if (XMLIterator.tagType == XMLTagType.Start) { this.pushTextFormat(); this._format.strikethrough = true; } else this.popTextFormat(); break; // case "sub": // { // if (XMLIterator.tagType == XMLTagType.Start) { // this.pushTextFormat(); // this._format.specialStyle = TextFormat.SpecialStyle.Subscript; // } // else // this.popTextFormat(); // } // break; // case "sup": // { // if (XMLIterator.tagType == XMLTagType.Start) { // this.pushTextFormat(); // this._format.specialStyle = TextFormat.SpecialStyle.Superscript; // } // else // this.popTextFormat(); // } // break; case "font": if (XMLIterator.tagType == XMLTagType.Start) { this.pushTextFormat(); this._format.size = XMLUtils.getInt(XMLIterator.attributes, "size", this._format.size); let color: string = XMLIterator.getAttribute("color"); if (color != null) this._format.color = convertFromHtmlColor(color); } else if (XMLIterator.tagType == XMLTagType.End) this.popTextFormat(); break; case "br": this.appendText("\n"); break; case "img": if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) { let element: HtmlElement = elementPool.borrow(HtmlElementType.Image); element.fetchAttributes(); element.name = element.getAttrString("name"); element.format.align = this._format.align; this._elements.push(element); } break; case "a": if (XMLIterator.tagType == XMLTagType.Start) { this.pushTextFormat(); this._format.underline = this._format.underline || parseOptions.linkUnderline; if (!this._format["colorChanged"]) this._format.color = parseOptions.linkColor; let element = elementPool.borrow(HtmlElementType.Link); element.fetchAttributes(); element.name = element.getAttrString("name"); element.format.align = this._format.align; this._elements.push(element); } else if (XMLIterator.tagType == XMLTagType.End) { this.popTextFormat(); let element = elementPool.borrow(HtmlElementType.LinkEnd); this._elements.push(element); } break; case "input": { let element = elementPool.borrow(HtmlElementType.Input); element.fetchAttributes(); element.name = element.getAttrString("name"); element.format.copy(this._format); this._elements.push(element); } break; case "select": { if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) { let element = elementPool.borrow(HtmlElementType.Select); element.fetchAttributes(); if (XMLIterator.tagType == XMLTagType.Start) { s_list1.length = 0; s_list2.length = 0; while (XMLIterator.nextTag()) { if (XMLIterator.tagName == "select") break; if (XMLIterator.tagName == "option") { if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void) s_list2.push(XMLUtils.getString(XMLIterator.attributes, "value", "")); else s_list1.push(XMLIterator.getText()); } } element.setAttr("items", s_list1.slice()); element.setAttr("values", s_list2.slice()); } element.name = element.getAttrString("name"); element.format.copy(this._format); this._elements.push(element); } } break; case "p": if (XMLIterator.tagType == XMLTagType.Start) { this.pushTextFormat(); this._format.align = <AlignType>XMLIterator.getAttribute("align"); if (!this.isNewLine()) this.appendText("\n"); } else if (XMLIterator.tagType == XMLTagType.End) { this.appendText("\n"); skipNextCR = true; this.popTextFormat(); } break; case "ui": case "div": case "li": if (XMLIterator.tagType == XMLTagType.Start) { if (!this.isNewLine()) this.appendText("\n"); } else { this.appendText("\n"); skipNextCR = true; } break; case "html": case "body": //full html ignoreWhiteSpace = true; break; case "head": case "style": case "script": case "form": if (XMLIterator.tagType == XMLTagType.Start) skipText++; else if (XMLIterator.tagType == XMLTagType.End) skipText--; break; } } if (skipText == 0) { text = XMLIterator.getText(ignoreWhiteSpace); if (text.length > 0) { if (skipNextCR && text[0] == '\n') text = text.substr(1); this.appendText(text); } } this._elements = null; } protected pushTextFormat() { let tf: TextFormat; if (this._textFormatStack.length <= this._textFormatStackTop) { tf = new TextFormat(); this._textFormatStack.push(tf); } else tf = this._textFormatStack[this._textFormatStackTop]; tf.copy(this._format); tf["colorChanged"] = this._format["colorChanged"]; this._textFormatStackTop++; } protected popTextFormat() { if (this._textFormatStackTop > 0) { let tf: TextFormat = this._textFormatStack[this._textFormatStackTop - 1]; this._format.copy(tf); this._format["colorChanged"] = tf["colorChanged"]; this._textFormatStackTop--; } } protected isNewLine(): boolean { if (this._elements.length > 0) { let element: HtmlElement = this._elements[this._elements.length - 1]; if (element && element.type == HtmlElementType.Text) return element.text.endsWith("\n"); else return false; } return true; } protected appendText(text: string) { let element: HtmlElement; if (this._elements.length > 0) { element = this._elements[this._elements.length - 1]; if (element.type == HtmlElementType.Text && element.format.equalStyle(this._format)) { element.text += text; return; } } element = elementPool.borrow(HtmlElementType.Text); element.text = text; element.format.copy(this._format); this._elements.push(element); } } export var defaultParser: HtmlParser = new HtmlParser();
the_stack
import Log from '../Utils/Logger'; import BaseLoader from './BaseLoader'; import { RuntimeException } from '../Utils/Exception'; import LoaderStatus from './LoaderStatus'; import LoaderErrors from './LoaderErrors'; import UserConfig from '../Interfaces/UserConfig'; import MediaConfig from '../Interfaces/MediaConfig'; import SeekRange from '../Interfaces/SeekRange'; import SeekHandler from '../Interfaces/SeekHandler'; import getGlobal from '../Utils/getGlobalObject'; import ErrorData from '../Interfaces/ErrorData'; import HJPlayerConfig from '../Interfaces/HJPlayerConfig'; const GlobalEnvironment = getGlobal(); /* Notice: ms-stream may cause IE/Edge browser crash if seek too frequently!!! * The browser may crash in wininet.dll. Disable for now. * * For IE11/Edge browser by microsoft which supports `xhr.responseType = 'ms-stream'` * Notice that ms-stream API sucks. The buffer is always expanding along with downloading. * * We need to abort the xhr if buffer size exceeded limit size (e.g. 16 MiB), then do reconnect. * in order to release previous ArrayBuffer to avoid memory leak * * Otherwise, the ArrayBuffer will increase to a terrible size that equals final file size. */ class MSStreamLoader extends BaseLoader { public Tag: string = 'msstreamLoader' private _seekHandler: SeekHandler private _config: UserConfig public _needStash: boolean = true _xhr: XMLHttpRequest | null = null /** * 流数据读取器 */ _reader: ReadableStreamDefaultReader | null | any = null /** * 总的range */ _totalRange: SeekRange = { from: 0, to: -1 } /** * 当前range */ _currentRange: SeekRange | null = null /** * 请求链接 */ _currentRequestURL: string | null = null _currentRedirectedURL: string | null = null /** * 数据的长度 */ _contentLength: number | null = null /** * 接收到的数据长度 */ _receivedLength: number = 0 /** * 允许收到的最大buffer */ _bufferLimit: number = 16 * 1024 * 1024 // 16MB /** * 最后一次收到buffer长度 */ _lastTimeBufferSize: number = 0 /** * 是否处于连接 */ _isReconnecting: boolean = false /** * 请求流的配置 */ _dataSource: MediaConfig | null = null static isSupported(): boolean { try { if( typeof (GlobalEnvironment as any).MSStream === 'undefined' || typeof (GlobalEnvironment as any).MSStreamReader === 'undefined' ) { return false; } const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com', true); xhr.responseType = <XMLHttpRequestResponseType>'ms-stream'; return xhr.responseType === <XMLHttpRequestResponseType>'ms-stream'; } catch (e) { Log.warn('msstreamLoader', e.message); return false; } } constructor(seekHandler: SeekHandler, config: HJPlayerConfig) { super('xhr-msstream-loader', 'ms flv'); this._seekHandler = seekHandler; this._config = config; } destroy(): void | boolean { if(this.isWorking()) { this.abort(); } if(!this._reader) { return false; } if(this._reader) { this._reader.onprogress = null; this._reader.onload = null; this._reader.onerror = null; this._reader = null; } if(this._xhr) { this._xhr.onreadystatechange = null; this._xhr = null; } super.destroy(); } startLoad(dataSource: MediaConfig, range: SeekRange): void { this._internalOpen(dataSource, range, false); } _internalOpen(dataSource: MediaConfig, range: SeekRange, isSubrange: boolean): void { this._dataSource = dataSource; if(!isSubrange) { this._totalRange = range; } else { this._currentRange = range; } let sourceURL = dataSource.url; if(this._config.reuseRedirectedURL) { if(this._currentRedirectedURL) { sourceURL = this._currentRedirectedURL; } else if(dataSource.redirectedURL !== undefined) { sourceURL = dataSource.redirectedURL; } } const seekConfig = this._seekHandler.getConfig(sourceURL, range); this._currentRequestURL = seekConfig.url; this._reader = new (<any>GlobalEnvironment).MSStreamReader(); const reader = this._reader; reader.onprogress = this._msrOnProgress.bind(this); reader.onload = this._msrOnLoad.bind(this); reader.onerror = this._msrOnError.bind(this); this._xhr = new XMLHttpRequest(); const xhr = this._xhr; xhr.open('GET', seekConfig.url, true); xhr.responseType = <XMLHttpRequestResponseType>'ms-stream'; xhr.onreadystatechange = this._xhrOnReadyStateChange.bind(this); xhr.onerror = this._xhrOnError.bind(this); if(dataSource.withCredentials) { xhr.withCredentials = true; } if(typeof seekConfig.headers === 'object') { const { headers } = seekConfig; Object.keys(headers).forEach((key) => { xhr.setRequestHeader(key, headers[key]); }); } // add additional headers if(typeof this._config.headers === 'object') { const { headers } = this._config; Object.keys(headers).forEach((key) => { xhr.setRequestHeader(key, headers[key]); }); } if(this._isReconnecting) { this._isReconnecting = false; } else { this._status = LoaderStatus.kConnecting; } xhr.send(); } abort() { this._internalAbort(); this._status = LoaderStatus.kComplete; } _internalAbort() { if(this._reader) { if(this._reader.readyState === 1) { // LOADING this._reader.abort(); } this._reader.onprogress = null; this._reader.onload = null; this._reader.onerror = null; this._reader = null; } if(this._xhr) { this._xhr.abort(); this._xhr.onreadystatechange = null; this._xhr = null; } } _xhrOnReadyStateChange(e: Event) { const xhr = <XMLHttpRequest>e.target; if(xhr.readyState === 2) { // HEADERS_RECEIVED if(xhr.status >= 200 && xhr.status <= 299) { this._status = LoaderStatus.kBuffering; if(xhr.responseURL !== undefined) { const redirectedURL = this._seekHandler.removeURLParameters(xhr.responseURL); if( xhr.responseURL !== this._currentRequestURL && redirectedURL !== this._currentRedirectedURL ) { this._currentRedirectedURL = redirectedURL; if(this._onURLRedirect) { this._onURLRedirect(redirectedURL); } } } const lengthHeader = xhr.getResponseHeader('Content-Length'); if(lengthHeader !== null && this._contentLength === null) { const length = parseInt(lengthHeader, 10); if(length > 0) { this._contentLength = length; if(this._onContentLengthKnown) { this._onContentLengthKnown(this._contentLength); } } } } else { this._status = LoaderStatus.kError; if(this._onError) { this._onError(LoaderErrors.HTTP_STATUS_CODE_INVALID, { code: xhr.status, reason: xhr.statusText }); } else { throw new RuntimeException( `MSStreamLoader: Http code invalid, ${xhr.status} ${xhr.statusText}` ); } } } else if(xhr.readyState === 3) { // LOADING if(xhr.status >= 200 && xhr.status <= 299) { this._status = LoaderStatus.kBuffering; const msstream = xhr.response; this._reader.readAsArrayBuffer(msstream); } } } _xhrOnError(e: Event) { this._status = LoaderStatus.kError; const type = LoaderErrors.EXCEPTION; const info = { code: -1, reason: `${e.constructor.name} ${e.type}` }; if(this._onError) { this._onError(type, info); } else { throw new RuntimeException(info.reason); } } _msrOnProgress(e: any): void { const reader = e.target; const bigbuffer = reader.result; if(bigbuffer == null) { // result may be null, workaround for buggy M$ this._doReconnectIfNeeded(); return; } const slice: ArrayBuffer = bigbuffer.slice(this._lastTimeBufferSize); this._lastTimeBufferSize = bigbuffer.byteLength; const byteStart = this._totalRange.from + this._receivedLength; this._receivedLength += slice.byteLength; if(this._onDataArrival) { this._onDataArrival(slice, byteStart, this._receivedLength); } if(bigbuffer.byteLength >= this._bufferLimit) { Log.info( this.Tag, `MSStream buffer exceeded max size near ${byteStart + slice.byteLength}, reconnecting...` ); this._doReconnectIfNeeded(); } } /** * 重新连接 */ _doReconnectIfNeeded() { if(this._contentLength == null || this._receivedLength < this._contentLength) { this._isReconnecting = true; this._lastTimeBufferSize = 0; this._internalAbort(); const range = { from: this._totalRange.from + this._receivedLength, to: -1 }; this._internalOpen(<MediaConfig> this._dataSource, range, true); } } _msrOnLoad(e: Event) { // actually it is onComplete event this._status = LoaderStatus.kComplete; if(this._onComplete) { this._onComplete( this._totalRange.from, this._totalRange.from + this._receivedLength - 1 ); } } _msrOnError(e: ErrorEvent) { this._status = LoaderStatus.kError; let type: string | number = 0; let info:ErrorData | null = null; if(this._contentLength && this._receivedLength < this._contentLength) { type = LoaderErrors.EARLY_EOF; info = { code: -1, reason: 'MSStream meet Early-Eof' }; } else { type = LoaderErrors.EARLY_EOF; info = { code: -1, reason: `${e.constructor.name} ${e.type}` }; } if(this._onError) { this._onError(type, info); } else { throw new RuntimeException(info.reason); } } } export default MSStreamLoader;
the_stack
module TDev { export class TutorialInstruction { public decl:AST.Decl; public stmt:AST.Stmt; public targetName:string; public targetKind:Kind; public addButton: Ticks; public calcButton: Ticks; public calcIntelli: Ticks; public label: string; public addToken:AST.Token; public addToken2:AST.Token; // used when inserting library token public delToken:AST.Token; public addAfter:AST.Token; public isOpStmt:boolean; public localName:string; public editString:string; public isEnumVal: boolean; public languageHint: string; public showTokens:AST.Token[]; public stmtToInsert:AST.Stmt; public toInlineActions:boolean; public diffSize:number; public promoteToFieldNamed:string; public promoteToFieldOf:string; public storeInVar:string; public inlineActionNames:AST.LocalDef[]; } function reorderDiffTokens(toks:AST.Token[]) { function skipDeletes(p:number) { while (p < toks.length && toks[p + 1] == null) p += 2; return p } function moveToken(trg:number, src:number) { if (src == trg) return Util.assert(trg < src) var t0 = toks[src + 0] var t1 = toks[src + 1] toks.splice(src, 2) toks.splice(trg, 0, t0, t1) } if (toks[0] instanceof AST.FieldName && toks[1] == null) { var p = skipDeletes(2) if (toks[p + 1] instanceof AST.FieldName) { moveToken(2, p) return } } var assignmentPos = -1 for (var i = 0; i < toks.length; i += 2) { if (toks[i] == null && toks[i + 1].getOperator() == ":=") assignmentPos = i } if (assignmentPos > 0) { var dels:AST.Token[] = [] var adds:AST.Token[] = [] var keeps:AST.Token[] = [] for (var i = 0; i < assignmentPos + 2; i += 2) { if (toks[i] == null) adds.push(toks[i], toks[i + 1]) else if (toks[i + 1] == null) dels.push(toks[i], toks[i + 1]) else keeps.push(toks[i], toks[i + 1]) } if (keeps.length == 0) { var newTokens = adds.concat(dels).concat(toks.slice(assignmentPos + 2)) toks.splice(0, toks.length) toks.pushRange(newTokens) return } } for (var i = 0; i < toks.length; i += 2) { if (toks[i + 1] == null) { var p = skipDeletes(i + 2) if (toks[i] instanceof AST.PropertyRef && toks[p + 1] instanceof AST.PropertyRef) { moveToken(i, p) return } } } } export class Step { public text: string; public autorunDone = false; constructor(public parent:StepTutorial, public data:AST.Step) { } public hasStar() { return !this.data.autoMode; } public element(hint : boolean) : HTMLElement { var docs = this.parent.renderDocs(this.data.docs) var e = div(null) Browser.setInnerHTML(e, docs); if (!hint) MdComments.attachVideoHandlers(e, true); var t = e.innerText || ""; if (t.length > 4096) t = t.substr(0, 4096); this.text = t; return e; } public showDiff() { var r = new Renderer() r.showDiff = true var s = r.dispatch(this.data.template) var d = div("diffOuter") Browser.setInnerHTML(d, s); var m = new ModalDialog() m.add(d) Util.setupDragToScroll(d) d.style.maxHeight = (SizeMgr.windowHeight * 0.8) / SizeMgr.topFontSize + "em"; m.fullWhite() m.show() } public show() { var e = this.element(true); if (dbg) e.appendChild(HTML.mkButton(lf("diff (dbg)"), () => this.showDiff())) TheEditor.setStepHint(e) this.autorunDone = false; } public nextInstruction():TutorialInstruction { var matching = Script.things.filter(a => this.data.matchesDecl(a)) var op:TutorialInstruction = null; if (matching.length == 0) { var toRename:AST.Decl; if (this.data.template instanceof AST.Action) { if ((<AST.Action>this.data.template).isPage()) toRename = Script.actions().filter(a => /^show(\s*\d*)/.test(a.getName()))[0] else toRename = Script.actions().filter(a => /^do stuff(\s*\d*)/.test(a.getName()))[0] } else if (this.data.template instanceof AST.RecordDef) { toRename = Script.records().filter(r => r.recordType == (<AST.RecordDef>this.data.template).recordType && /^thing\s*\d*/i.test(r.getCoreName()))[0] } else if (this.data.template instanceof AST.GlobalDef) { toRename = Script.variables().filter(r => /^v\s*\d*/.test(r.getName()))[0] } if (toRename) this.parent.renameIndex[this.data.declName()] = toRename else { toRename = this.parent.renameIndex[this.data.declName()] if (toRename && Script.things.indexOf(toRename) < 0) toRename = null } op = new TutorialInstruction() if (toRename) { op.decl = toRename op.stmt = toRename instanceof AST.Action ? (<AST.Action>toRename).header : toRename instanceof AST.RecordDef ? (<AST.RecordDef>toRename).nameHolder : toRename instanceof AST.GlobalDef ? (<AST.GlobalDef>toRename) : null op.targetName = this.data.declName() } else { if (this.data.template instanceof AST.Action) { var act = <AST.Action>this.data.template op.addButton = act.isPage() ? Ticks.sideAddPage : Ticks.sideAddAction; op.label = lf("we need a new {0}", act.isPage() ? lf("page") : lf("function")); } else if (this.data.template instanceof AST.RecordDef) { var rec = <AST.RecordDef>this.data.template if (rec.recordType == AST.RecordType.Table) { op.addButton = Ticks.sideAddTable; op.label = lf("we need a new table") } else if (rec.recordType == AST.RecordType.Index) { op.addButton = Ticks.sideAddIndex; op.label = lf("we need a new index") } else if (rec.recordType == AST.RecordType.Decorator) { op.addButton = Ticks.sideAddDecorator; op.label = lf("we need a new decorator") } else { op.addButton = Ticks.sideAddObject; op.label = lf("we need a new object") } } else if (this.data.template instanceof AST.GlobalDef) { var glb = <AST.GlobalDef>this.data.template op.addButton = Ticks.sideAddVariable op.label = lf("we need to a new variable") } else { Util.oops(lf("declaration type not supported in tutorial")) } } return op; } // TODO handle case when matching.length > 1 var currAction = matching[0] AST.Diff.templateDiff(currAction, this.data.template, { approxNameMatching: true, placeholderOk: true, tutorialMode: true, preciseStrings: this.data.preciseStrings, tutorialCustomizations: this.parent.customizations }) function lookupLocal(name:string) { if (currAction instanceof AST.Action) return (<AST.Action>currAction).allLocals.filter(l => l.getName() == name)[0] else return null } function localKind(name:string) { var l = lookupLocal(name) if (l) return l.getKind() else return api.core.Unknown } // we currently cannot recover from this; have them delete the statement function differentLoopVars(stmt:AST.Stmt) { var alt = stmt.diffAltStmt if (!alt) return false var v0 = stmt.loopVariable() var v1 = alt.loopVariable() return (v0 && v1 && v0.getName() != v1.getName()) } function findFirst(stmt:AST.Stmt) { if (op) return; if (stmt instanceof AST.Block) { var b = <AST.Block>stmt b.stmtsWithDiffs().forEach(findFirst) return; } if (stmt.diffStatus == 1) { var lastCurr = null var past = false var firstCurr = null; (<AST.Block>stmt.parent).stmtsWithDiffs().forEach(s => { if (s == stmt) past = true var curr = s.diffAltStmt if (s.diffStatus < 0) curr = s; else if (curr && curr.diffStatus < 0) curr = null; if (curr) { if (past && !firstCurr) firstCurr = curr; if (!past) lastCurr = curr; } }) op = new TutorialInstruction(); if (firstCurr && firstCurr.isPlaceholder()) lastCurr = firstCurr; if (lastCurr && lastCurr.isPlaceholder()) { op.stmt = lastCurr op.stmtToInsert = stmt if (stmt instanceof AST.InlineActions) op.toInlineActions = true op.showTokens = [null, AST.mkOp(stmt.nodeType())] return } if (lastCurr) { if (stmt.nodeType() == "elseIf" && lastCurr instanceof AST.If) { var prevBody = (<AST.If>lastCurr).rawElseBody if (prevBody && prevBody.stmts[0] && prevBody.stmts[0].isPlaceholder()) { op.stmt = prevBody.stmts[0] op.stmtToInsert = stmt op.showTokens = [null, AST.mkOp("if")] return; } } op.stmt = lastCurr op.calcButton = Ticks.btnAddDown op.label = lf("add line below") } else if (firstCurr) { op.stmt = firstCurr op.calcButton = Ticks.btnAddUp op.label = lf("add line above") } else if (stmt.parent instanceof AST.ParameterBlock) { var blk = <AST.ParameterBlock>stmt.parent var act = <AST.ActionHeader>blk.parent if (blk == act.outParameters) op.calcButton = Ticks.sideActionAddOutput else op.calcButton = Ticks.sideActionAddInput op.stmt = act.diffAltStmt op.label = lf("need a parameter") } else if (stmt instanceof AST.RecordField) { op.calcButton = (<AST.RecordField>stmt).isKey ? Ticks.recordAddKey : Ticks.recordAddValue op.label = lf("need a field") } return; } else if (stmt.diffStatus < 0) { if (stmt.isPlaceholder()) return; op = new TutorialInstruction() op.stmt = stmt; op.calcButton = Ticks.btnCut op.label = lf("need to delete this") return; } else if (differentLoopVars(stmt)) { op = new TutorialInstruction() op.stmt = stmt.diffAltStmt; op.calcButton = Ticks.btnCut; op.label = lf("need to delete this") return; } else { var eh = stmt.calcNode() if (eh && eh.diffTokens) { var d = eh.diffTokens reorderDiffTokens(d) Util.assert(!op) op = new TutorialInstruction() op.stmt = stmt.diffAltStmt var i = 0; var localAssignment = false var isVarDef = stmt instanceof AST.ExprStmt && (<AST.ExprStmt>stmt).isVarDef() var isLocal = (t:AST.Token) => t && t.getThing() instanceof AST.LocalDef; var firstTok = Util.even(d).filter(t => t != null)[0] var promoteToFieldOf = "" var promoteToGlobal = false var promoteToName = "" var lookupDecl = (n:string) => Script.things.filter(t => t.getName() == n)[0]; if (stmt instanceof AST.InlineActions) { op.inlineActionNames = (<AST.InlineActions>stmt).actions.stmts.map(s => (<AST.InlineAction>s).name) } if (stmt instanceof AST.ExprStmt && eh.tokens.length >= 4 && eh.tokens[2].getOperator() == ":=" && eh.parsed.getCalledProperty() == api.core.AssignmentProp) (() => { var trg = (<AST.Call>eh.parsed).args[0] var refDat = trg.referencedData() var refFld = trg.referencedRecordField() var promoteKind = null if (refDat && !lookupDecl(refDat.getName())) { promoteToGlobal = true promoteToName = refDat.getName() promoteKind = refDat.getKind() } else if (refFld) { var fldOn = (<AST.Call>trg).args[0].getThing() if (fldOn instanceof AST.LocalDef) { var fldOnLocal = (<AST.Action>currAction).allLocals.filter(l => l.getName() == fldOn.getName())[0] if (fldOnLocal) { var fldRec = fldOnLocal.getKind() if (fldRec.getRecord() && !fldRec.getProperty(refFld.getName())) { promoteToFieldOf = fldOn.getName() promoteToName = refFld.getName() promoteKind = refFld.dataKind } } } } if (promoteToName) { TheEditor.intelliProfile.incr("promoteRefactoring") if (d[0] == null && d[2] == null && d[4] == null) { i = 6; } else { var currCall = (<AST.ExprStmt>stmt.diffAltStmt).calcNode().parsed if (currCall.getCalledProperty() == api.core.AssignmentProp) { var th = (<AST.Call>currCall).args[0].getThing() if (th instanceof AST.LocalDef && th.getName() == promoteToName && th.getKind().toString() == promoteKind.toString()) { op.promoteToFieldNamed = promoteToName op.promoteToFieldOf = promoteToGlobal ? "data" : promoteToFieldOf op.addToken = AST.mkOp(":="); op.addAfter = (<AST.Call>currCall).args[0] } } } } })(); if ((isVarDef || promoteToName) && firstTok && firstTok.getOperator() == ":=") { op.addAfter = null op.delToken = firstTok return; } if (op.promoteToFieldNamed) { return } if (isVarDef && d.length >= 4 && d[0] == null && isLocal(d[1]) && d[2] == null && d[3].getOperator() == ":=") { localAssignment = true; i = 4; } if (isVarDef && (<AST.ExprStmt>stmt.diffAltStmt).isVarDef() && d.length >= 6 && d[4] && d[5] && d[4].getOperator() == ":=") { var locAdd = d[1]; var locRem = d[2]; var ok = true if (!locAdd && !locRem) { locAdd = d[3] locRem = d[0] } else { if (d[0] || d[3]) ok = false; } if (ok && isLocal(locAdd) && isLocal(locRem)) { op.addAfter = locRem op.localName = locAdd.getThing().getName() op.addToken = locAdd return; } } op.showTokens = d.slice(i) var placeholderKind:Kind = null for (; i < d.length; i += 2) { if (d[i]) op.addAfter = d[i] if (d[i + 1] == null) { if (typeof d[i].getLiteral() == "string" && d[i + 3] && typeof d[i + 3].getLiteral() == "string") { var lv = d[i + 3].getLiteral() if (d[i] instanceof AST.FieldName) op.localName = lv else { op.editString = lv op.isEnumVal = (<AST.Expr>d[i + 3]).enumVal != null op.languageHint = (<AST.Expr>d[i + 3]).languageHint; } op.addToken = d[i + 3] } else if (d[i].getThing() instanceof AST.PlaceholderDef && !d[i + 2]) { // the next token will delete the placeholder def placeholderKind = d[i].getThing().getKind() continue; } else { var j = i + 2 var lastOk = i while (j < d.length) { if (d[j] != null && d[j + 1] != null) break; if (d[j + 1] == null) lastOk = j; j += 2 } op.addAfter = null op.delToken = d[lastOk] } return; } else if (d[i] == null) { if (typeof d[i + 1].getLiteral() == "string" && d[i + 2] && typeof d[i + 2].getLiteral() == "string") { op.editString = d[i + 1].getLiteral() op.addToken = d[i + 1] op.addAfter = d[i + 2] op.isEnumVal = (<AST.Expr>d[i + 1]).enumVal != null op.languageHint = (<AST.Expr>d[i + 1]).languageHint; } else { if (placeholderKind && placeholderKind.getRoot() == api.core.Ref && d[i + 1].getThing() instanceof AST.LocalDef && d[i + 3].getProperty() && !localKind(d[i + 1].getThing().getName()).getProperty(d[i + 3].getProperty().getName())) { op.promoteToFieldNamed = d[i + 3].getProperty().getName() op.promoteToFieldOf = d[i + 1].getThing().getName() } op.addToken = d[i + 1] if (d[i + 2] == null && d[i + 3] != null) op.addToken2 = d[i + 3] } return; } } if (localAssignment) { op.addAfter = null // beginning op.addToken = d[1] op.addToken2 = d[3] op.showTokens = d op.storeInVar = d[1].getText() return; } if (promoteToName) { op.addAfter = null // beginning op.addToken = d[1] op.addToken2 = d[3] op.showTokens = d op.storeInVar = promoteToName return; } op = null // undo } } var arr = stmt.children() for (var i = 0; i < arr.length; ++i) { if (arr[i] instanceof AST.Stmt) findFirst(<AST.Stmt>arr[i]) } } function setPers(rp:AST.RecordPersistence) { op = new TutorialInstruction() op.calcButton = rp == AST.RecordPersistence.Local ? Ticks.recordPersLocal : rp == AST.RecordPersistence.Cloud ? Ticks.recordPersCloud : Ticks.recordPersTemporary; op.label = lf("set persistance to ") + AST.RecordDef.recordPersistenceToString(rp, Script.isCloud); } if (this.data.template instanceof AST.Action) { if ((<AST.Action>currAction).isAtomic != (<AST.Action>this.data.template).isAtomic) { TheEditor.intelliProfile.incr("actionSettings") op = new TutorialInstruction() op.calcButton = Ticks.actionPropAtomic op.stmt = (<AST.Action>currAction).header op.label = lf("make the function ") + ((<AST.Action>this.data.template).isAtomic ? lf("atomic") : lf("non-atomic")) } else { findFirst((<AST.Action>this.data.template).header) } } else if (this.data.template instanceof AST.RecordDef) { var rec = <AST.RecordDef>this.data.template var rec0 = <AST.RecordDef>currAction var rp = rec.getRecordPersistence() if (rp != rec0.getRecordPersistence()) { setPers(rp); op.stmt = rec0.recordPersistence } else { findFirst(rec.keys) findFirst(rec.values) } } else if (this.data.template instanceof AST.GlobalDef) { var glb = <AST.GlobalDef>this.data.template var glb0 = <AST.GlobalDef>currAction var rp = glb.getRecordPersistence() if (rp != glb0.getRecordPersistence()) { setPers(rp); } else if (glb.getKind().toString() != glb0.getKind().toString()) { op = new TutorialInstruction(); op.targetKind = glb.getKind() } } else { Util.oops("") } if (!op && this.data.command == "change") { AST.visitExprHolders(currAction, (stmt, eh) => { if (op) return eh.tokens.forEach(t => { var call = t.getCall() if (call && call.referencedData() && call.referencedData().getName() == this.data.commandArg) { TheEditor.intelliProfile.incr("searchArtRefactoring"); op = new TutorialInstruction(); op.stmt = stmt op.addAfter = t op.addToken = t op.calcIntelli = Ticks.calcEditArt op.label = lf("customize the art!") } }) }) } if (op) { op.diffSize = AST.Diff.diffSize(this.data.template) op.decl = currAction; if (!op.stmt) { if (currAction instanceof AST.RecordDef) { op.stmt = (<AST.RecordDef>currAction).values } else if (currAction instanceof AST.GlobalDef) { op.stmt = (<AST.GlobalDef>currAction) } } } if (op && op.addToken && op.addToken.getOperator()) { var opprop = api.core.Unknown.getProperty(op.addToken.getOperator()) if (opprop && opprop.getInfixPriority() == api.opStmtPriority) { TheEditor.intelliProfile.incr(opprop.getName()) op.isOpStmt = true; } } if (op && op.addToken && op.addToken.getLocalDef() && op.addToken.getLocalDef().isHiddenOut) TheEditor.intelliProfile.incr("outAssign") return op } } export class MultiTimer { private timeoutId:any; private version = 1; public running = false; constructor(private callback:()=>void) { } public poke() { if (!this.running) this.start(1); } public stop() { ++this.version; if (this.timeoutId) window.clearTimeout(this.timeoutId); this.timeoutId = null this.running = false; } public start(ms:number) { this.stop() var v = this.version; this.running = true; this.timeoutId = Util.setTimeout(ms, () => { if (v == this.version) { this.running = false; this.callback(); } }) } } export class StepTutorial { private steps: Step[]; private stepsPerAction:any; private currentStep = -1; public mdcmt:MdComments; private stepShown = false; public waitingFor:string; private timer: MultiTimer = new MultiTimer(() => TipManager.showScheduled()) private goalTimer: MultiTimer; private maxProgressDelay = 8000; private prevDiffSize = -1; private stepStartTime: number; public disableUpdate = false; private fromReply = false; private finalCountdown = false; private finalHTML:string; private initialHTML:string; private showInitialStep:boolean; public expectingSearch = 0; public goalTips = 0; private initialMode = true; private recoveryMode = false; private needHelpCount = 0; private lastModalDuration:number = undefined; private seenDoItYourself = false; public renameIndex:StringMap<AST.Decl> = {}; private progressId:string; public hasValidators = false; public hourOfCode = false; private translatedTutorial: TDev.AST.TranslatedTutorialInfo = undefined; public customizations:AST.TutorialCustomizations; constructor(private app:AST.App, private topic:HelpTopic, firstTime: boolean, private guid:string) { this.progressId = this.topic.json.id; this.steps = AST.Step.splitActions(app).map(s => new Step(this, s)) var act = this.stepsPerAction = {} this.steps.forEach((a, i) => { var baseName = a.data.declName() if (a.data.validator) this.hasValidators = true; if (!act.hasOwnProperty(baseName)) act[baseName] = [] act[baseName].push(i) }) this.showInitialStep = firstTime; this.hourOfCode = /#hourOfCode/i.test(this.topic.json.text || ""); this.resetCustomizations() var skipActions:StringMap<boolean> = {} TheEditor.intelliProfile.loadFrom(app, true) if (this.isEnabled()) { var rend = new Renderer(); rend.hideErrors = true; this.mdcmt = new MdComments(rend, null); this.mdcmt.showCopy = false; this.mdcmt.blockExternalLinks = app.blockExternalLinks; this.goalTimer = new MultiTimer(() => { if (!this.disableUpdate && !this.initialMode) TheEditor.calculator.goalTip() }) this.currentStep = Script.editorState.tutorialStep || 0; // if (this.steps.slice(0, this.currentStep + 1).some(s => s.data.hintLevel == "semi")) // this.seenDoItYourself = true; Script.editorState.tutorialNumSteps = this.steps.length; this.finalHTML = this.getHTML("final"); this.initialHTML = this.getHTML("main") || ("<h2>" + Util.htmlEscape(this.app.getName()) + "</h2>"); if (firstTime) { this.stepStartTime = new Date().getTime(); this.postProgress(); } } } private resetCustomizations() { this.customizations = { stringMapping: {}, artMapping: {} } } public updateProfile(ip:AST.IntelliProfile) { if (this.steps.some(s => !!s.data.addDecl || s.data.addsAction)) { ip.incr("addNewButton") ip.incr("dataSection"); } } public renderDocs(code:AST.Stmt[]):string { var prev = Script try { setGlobalScript(this.app) return this.mdcmt.extractStmts(code) } finally { setGlobalScript(prev) } } private getHTML(name:string) { var final = this.app.actions().filter(a => a.getName() == name)[0] if (final) { return this.renderDocs(final.body.stmts) } else { return null; } } private getRunDelay() { var factor = this.hasValidators ? 1 : 2; return this.getProgressDelay() * factor; } private getProgressDelay() { return Math.min(500 + this.currentStep * 1000, this.maxProgressDelay) } public needHelp() { this.disableUpdate = false; if (!this.initialMode) { this.needHelpCount++; this.recoveryMode = true; } this.update() } public startAsync() : Promise { return this.translateAsync(Util.getTranslationLanguage()) .then(() => { if (this.showInitialStep) { this.showInitialStep = false; return this.firstStepAsync(); } return this.stepStartedAsync(); }); } public dump():string { var r = "" this.steps.forEach((s, i) => { r += "STEP " + i + "\n" r += s.data.docs.map(s => s.serialize()) + s.data.template.serialize() r += "===================================================================\n" }) return r } private postProgress(duration: number = undefined, text = undefined) { var help = this.currentStep > 0 ? this.needHelpCount : undefined; this.needHelpCount = 0; var goalTips = this.currentStep > 0 ? this.goalTips : undefined; this.goalTips = 0; var modalDuration = this.currentStep > 0 ? this.lastModalDuration : undefined; this.lastModalDuration = undefined if (modalDuration) modalDuration /= 1000; var playDuration = this.currentStep > 0 ? TheEditor.lastPlayDuration() : undefined; Cloud.postPrivateApiAsync("progress", { progressId: this.progressId, index: this.currentStep, duration: duration, text: text, helpCalls: help, goalTips: goalTips, modalDuration: modalDuration, playDuration: playDuration, }).done(undefined,() => { }); // don't wait, don't report error var data = <{ [id: string]: Cloud.Progress; }>{}; var n = Math.round(Util.now() / 1000) var prog = { guid: this.guid, index: this.currentStep, lastUsed: n, numSteps: this.steps.length, completed: this.currentStep >= this.steps.length ? n : undefined }; data[this.progressId] = prog; Cloud.storeProgress(data); Cloud.postPendingProgressAsync().done(); // create a new tracking pixel and add it to the tree var trackUrl = this.topic.pixelTrackingUrl(); if (trackUrl) { var anon = this.loadAnonymousId(); if (anon) { trackUrl += "?scriptid=" + this.progressId + "&index=" + prog.index + "&total=" + prog.numSteps + "&completed=" + !!prog.completed + "&time=" + prog.lastUsed + "&anonid=" + anon; var pixel = <HTMLImageElement> document.createElement("img"); pixel.className = "tracking-pixel"; pixel.src = trackUrl; pixel.onload = (el) => pixel.removeSelf(); pixel.onerror = (el) => pixel.removeSelf(); elt("root").appendChild(pixel); } } // pushing directly into event hubs var eventHubsInfo = this.topic.eventHubsTracking(); if (eventHubsInfo) { var anon = this.loadAnonymousId(); if (anon) { var url = 'https://' + eventHubsInfo.namespace + '.servicebus.windows.net/' + eventHubsInfo.hub + '/publishers/' + anon + '/messages?timeout=60&api-version=2014-01'; var token = eventHubsInfo.token; var payload = { anonid: anon, scriptid: this.progressId, index: prog.index, total: prog.numSteps, completed: !!prog.completed, time: prog.lastUsed } this.postEventHubsData(url, token, payload, 5); } } } private postEventHubsData(url: string, token: string, payload: any, retry : number) { Util.log('event hubs: ' + url); Util.log('event hubs token: ' + token); var tryAgain = () => { if (client.status != 401 && --retry > 0) { Util.log('retrying events hub'); Util.setTimeout(1000 * (10 - retry),() => this.postEventHubsData(url, token, payload, retry)); } } try { var client = new XMLHttpRequest(); client.open('POST', url); client.setRequestHeader('Authorization', token); client.setRequestHeader("Content-Type", 'application/atom+xml;type=entry;charset=utf-8'); client.ontimeout = tryAgain; client.onerror = tryAgain; client.send(JSON.stringify(payload)); } catch (e) { Util.reportError("tutorialeventhubs", e, false); } } private loadAnonymousId(): string { if (!Script || !this.topic.json) return ""; var anon = Script.editorState.tutorialAnonymousId; if (!anon) { var ids = JSON.parse(localStorage["tutorialAnonymousIds"] || "{}"); anon = ids[this.topic.json.userid]; if (!anon) { anon = Script.editorState.tutorialAnonymousId = ids[this.topic.json.userid] = Util.guidGen(); localStorage["tutorialAnonymousIds"] = JSON.stringify(ids); } } return anon; } public showDiff() { var s = this.steps[this.currentStep] if (s) s.showDiff() } private stepCompleted(skipUpdate = false) { var step = this.steps[this.currentStep]; if (step && step.hasStar()) TDev.Browser.EditorSoundManager.tutorialStepFinished(); if (this.currentStep + 1 <= this.steps.length) { this.currentStep = this.currentStep + 1; Script.editorState.tutorialStep = this.currentStep; var now = new Date().getTime(); var duration = (now - this.stepStartTime) / 1000; this.stepStartTime = now; var text = step ? ((step.data.command ? ("*" + step.data.command + "* ") : "") + step.text) : undefined; this.postProgress(duration, text); } if (this.currentStep >= this.steps.length) { TheEditor.removeTutorialLibs(); TipManager.setTip(null); this.stepShown = false; if (!skipUpdate) { this.update(); } return; } this.stepShown = false this.prevDiffSize = -1; if (!skipUpdate) { this.stepStartedAsync().done(() => { this.timer.start(500); this.update(); }); } } private modalTime(start:number) { this.lastModalDuration = Util.now() - start } private nowPublish() { TheEditor.leaveTutorial(); // always leave tutorial // not generally signed in if (!Cloud.getUserId() || !Cloud.isOnline() || !Cloud.canPublish() || !Script) return; // author explicitely wanted to skip step if (!this.topic || /none/i.test(this.topic.nextTutorials()[0])) return; World.getInstalledHeaderAsync(Script.localGuid).done((h: Cloud.Header) => { if (h.status == "published") return Promise.as(); var screenshotDataUri = TheEditor.lastScreenshotUri(); var start = Util.now() var m = new ModalDialog(); this.disableUpdate = true; m.add(div('wall-dialog-header', lf("you did it!"))); m.addHTML(lf("Publish your script, so that everyone can run it.")) m.add(div('wall-dialog-buttons', HTML.mkButton(lf("publish"), () => { this.disableUpdate = false; ScriptNav.publishScript(dbg ? false : true, uploadScreenshot ? screenshotDataUri : undefined) this.update() }), HTML.mkButton(lf("maybe later"), () => { this.disableUpdate = false; m.dismiss(); }) )); var uploadScreenshot = true; var uploadScreenshotCheck = HTML.mkCheckBox(lf("upload screenshot"), b => uploadScreenshot = b, uploadScreenshot); if (screenshotDataUri) { var previewImage = HTML.mkImg(screenshotDataUri); previewImage.setAttribute('class', 'publishScreenshot'); m.add(previewImage); m.add(div('wall-dialog-body', uploadScreenshotCheck)); m.setScroll(); } m.fullWhite(); var d = Cloud.mkLegalDiv() d.style.marginTop = "1em"; d.style.opacity = "0.6"; m.add(d); m.show(); }); } private addHocFinishPixel(m : ModalDialog) { // add tracking pixel to dialog if (this.hourOfCode) { m.add(HTML.mkImg('https://code.org/api/hour/finish_touchdevelop.png', 'tracking-pixel')); } } private openHocFinish() { window.open("https://code.org/api/hour/finish", "hourofcode", "menubar=no,status=no,titlebar=no,location=no,scrollbars=no,toolbar=no,width=500,height=550", true); } private keepTinkering(advertise :boolean) { TipManager.setTip(null); if (!Script) return; // when running in office mix, notify host that the tutorial was completed if (advertise && Script.editorState && Script.editorState.tutorialId) { Util.log("tutorial complete: " + Script.editorState.tutorialId); var msg = RT.JsonObject.wrap({ kind: "tutorialComplete__Send", tutorialId: Script.editorState.tutorialId }); RT.Web.post_message_to_parent(Cloud.config.rootUrl, msg, null); RT.Web.post_message_to_parent("http://localhost:15669", msg, null); } this.stepShown = true; var m = new ModalDialog(); var willHourOfCodeFinal = false; var willNowPublish = false; m.onDismiss = () => { tick(Ticks.tutorialEnd); if (Script) { TheEditor.saveStateAsync({ forReal: true }).done(() => { if (willNowPublish) this.nowPublish(); else if (willHourOfCodeFinal) this.openHocFinish(); }) } } if (this.finalHTML) { var finalDiv = m.addHTML(this.finalHTML); MdComments.attachVideoHandlers(finalDiv, true); if (this.translatedTutorial) StepTutorial.addTranslatedDocs(m, finalDiv, !!this.translatedTutorial.manual, this.translatedTutorial.finalDocs); } else { m.add(this.createStars()); m.add(div('wall-dialog-header', lf("Well done!"))); m.add(div('wall-dialog-body', lf("You can keep customizing your script as much as you want. Have fun!"))); } m.add(div('wall-dialog-buttons', Util.delayButton( HTML.mkButton(lf("finished"), () => { willNowPublish = true; m.dismiss(); }), 1000, true) )); if (this.hourOfCode) m.add(div('wall-dialog-body hoc-notice', span('hoc-link', lf("get my Hour of Code™ certificate")).withClick(() => { tick(Ticks.hourOfCodeFinal); this.openHocFinish(); }) )); if (Browser.EditorSettings.widgets().nextTutorialsList) { var nextTutorials = this.topic.nextTutorials(); if (!/none/i.test(nextTutorials[0])) { m.add(div('wall-dialog-header', lf("next tutorials..."))); var loadingMoreTutorials = div('wall-dialog-box', lf("loading...")); m.add(loadingMoreTutorials); Browser.TheHub.tutorialsByUpdateIdAsync() .done(progs => { loadingMoreTutorials.removeSelf(); var moreTutorials = <HTMLUListElement>createElement('ul', 'tutorial-list'); var tutLength = 8 - (moreTutorialsId ? 1 : 0); var allTutorials = []; // TODO: fix all tutorials var theme = Browser.EditorSettings.currentTheme; var score = (ht: HelpTopic) => { var sc = 0; if (this.hourOfCode && ht.isHourOfCode()) sc += 100; if (/jetpack|flashverse/i.test(ht.id)) sc += 25; if (/jump/i.test(ht.id)) sc += 20; if (progs[ht.updateKey()]) sc -= 50; if (theme && theme.scriptSearch) sc += ht.hashTags().indexOf(theme.scriptSearch) > -1 ? 200 : 0; return sc; }; allTutorials.stableSort((a, b) => { var sca = score(a); var scb = score(b); return sca > scb ? 1 : sca < scb ? -1 : 0; }); while (nextTutorials.length < tutLength && allTutorials.length > 0) { var tut = allTutorials.pop() nextTutorials.push(tut.id); } nextTutorials.forEach(tutid => moreTutorials.appendChild(createElement('li', '', Browser.TheHub.tutorialTile(tutid, (h) => { m.dismiss() })))); var moreTutorialsId = this.topic.moreTutorials(); if (moreTutorialsId) moreTutorials.appendChild(createElement('li', '', Browser.TheHub.topicTile(moreTutorialsId, lf("More")))); m.add(div('wall-dialog-body', moreTutorials)); }, e => { loadingMoreTutorials.setChildren([lf("Oops, we could not load your progress.")]); }); } } this.addHocFinishPixel(m); m.fullWhite(); m.setScroll(); m.show(); } private translateAsync(to : string) : Promise { // of TranslatedTutorialInfo if (this.translatedTutorial) return Promise.as(this.translatedTutorial); if (!to || /^en(-us)?$/i.test(to) || Cloud.isOffline() || !Cloud.config.translateCdnUrl || !Cloud.config.translateApiUrl) return Promise.as(undefined); tick(Ticks.tutorialTranslateScript, to); var tutorialId = this.topic.json.id; return ProgressOverlay.lockAndShowAsync(lf("translating tutorial...")) .then(() => { Util.log('loading tutorial translation from blob'); var blobUrl = HTML.proxyResource(Cloud.config.translateCdnUrl + "/translations/" + to + "/" + tutorialId); return Util.httpGetJsonAsync(blobUrl).then((blob) => { this.translatedTutorial = blob; return this.translatedTutorial; }, e => { // requestion translation Util.log('requesting tutorial translation'); var url = HTML.proxyResource(Cloud.config.translateApiUrl + '/translate_tutorial?scriptId=' + tutorialId + '&to=' + to); return Util.httpGetJsonAsync(url).then((js) => { this.translatedTutorial = js.info; return this.translatedTutorial; }, e => { Util.log('tutorial translation failed, ' + e); return this.translatedTutorial = { steps: [] }; }); }); }).then(() => ProgressOverlay.hide(), e => () => ProgressOverlay.hide()); } private firstStepAsync() { var r = new PromiseInv(); this.disableUpdate = true; TipManager.setTip(null); var m = new ModalDialog(); var start = Util.now() m.onDismiss = () => { this.disableUpdate = false; this.modalTime(start) r.success(this.stepStartedAsync()); } m.add(this.createStars(false)); var initialDiv = m.addHTML(this.initialHTML); MdComments.attachVideoHandlers(initialDiv, true); if (this.translatedTutorial) StepTutorial.addTranslatedDocs(m, initialDiv, !!this.translatedTutorial.manual, this.translatedTutorial.startDocs); m.fullWhite(); m.add(div('wall-dialog-buttons', Util.delayButton(HTML.mkButton(lf("let's get started!"), () => m.dismiss()), 1000, true) )); // add tracking pixel to dialog + notice if (this.hourOfCode) { m.addHTML("<div class='hoc-notice'>The 'Hour of Code™' is a nationwide initiative by Computer Science Education Week and Code.org to introduce millions of students to one hour of computer science and computer programming.</div>"); m.add(HTML.mkImg('https://code.org/api/hour/begin_touchdevelop.png', 'tracking-pixel')); } m.setScroll(); m.show(); return r; } private youAreOnYourOwnAsync() { var r = new PromiseInv() var m = new ModalDialog() m.addHTML(lf("<h3>no more tips!</h3>")) m.addHTML(lf("From now on we won't show you the code to write. Follow the instructions and tap run when you think you are done.")) m.addHTML(lf("Try tweaking your code until you get it right. If you get stuck, tap the tutorial bar.")); Util.delayButton(m.addOk(lf("ok, let's roll!")), 1500, true) m.fullWhite() m.onDismiss = () => { this.disableUpdate = false; this.update(); r.success(null) }; TipManager.setTip(null); this.disableUpdate = true m.show() return r } private switchToNormalMode() { var st = this.steps[this.currentStep] if (!st) return false this.initialMode = st.data.hintLevel == "full" if (this.initialMode) return false if (st.data.hintLevel != "semi" || this.seenDoItYourself || ModalDialog.currentIsVisible()) return false; var tmpl = TheEditor.calculator.goalHTML() if (!tmpl) return false; var goal = elt("calcGoalLine"); // the do it yourself dialog is shown when tapping the goal line if (!this.seenDoItYourself && goal) { this.seenDoItYourself = true; this.disableUpdate = true; var tip = <Tip>{ title: lf("enter this code"), description: Cloud.config.hintLevel == "full" ? lf("if you are stuck, tap the goal line") : undefined, el: goal, forceBottom: true }; TipManager.setTip(tip); Util.setTimeout(10000, () => { if (TipManager.isCurrent(tip)) { this.disableUpdate = false; this.update(); } }) return true; } return false } private isFirstStep() { return !this.steps.slice(0, this.currentStep).some(s => s.hasStar()) } private congrats = lf("excellent; great job; awesome; cool; you rock; well done; outstanding; you got it; right on").split(/\s*[;؛]\s*/); private stepStartedAsync() { var step = this.steps[this.currentStep]; if (step && step.hasStar()) { return new Promise((onSuccess, onError, onProgress) => { this.disableUpdate = true; TipManager.setTip(null); var start = Util.now() var m = new ModalDialog(); m.onDismiss = () => { this.disableUpdate = false; this.modalTime(start); TDev.Browser.EditorSoundManager.tutorialStepNew(); this.timer.start(500); this.update(); onSuccess(undefined); } m.add(this.createStars()); if (!this.isFirstStep() && !step.data.avatars && !step.data.noCheers) m.add(dirAuto(div('wall-dialog-header', Util.capitalizeFirst(Random.pick(this.congrats) + '!')))); var elementDiv = div('wall-dialog-body', step.element(false)); m.add(elementDiv); if (this.translatedTutorial && this.translatedTutorial.steps[this.currentStep]) StepTutorial.addTranslatedDocs(m, elementDiv, !!this.translatedTutorial.manual, this.translatedTutorial.steps[this.currentStep].docs); m.fullWhite(); m.setScroll(); var previousStep = this.currentStep - 1; while (!!this.steps[previousStep] && !this.steps[previousStep].hasStar()) previousStep--; m.add(div('wall-dialog-buttons tutDialogButons', // TODO: mine tutorial locale /-/.test(this.topic.id) ? HTML.mkLinkButton(lf("rewind"),() => { this.replyDialog() }) : null, TheEditor.widgetEnabled("tutorialGoToPreviousStep", true) && previousStep > 0 && this.steps[previousStep].hasStar() ? HTML.mkLinkButton(lf("go to previous step"),() => { this.replyAsync(previousStep).done(() => { m.dismiss(); }); }) : null, Util.delayButton(HTML.mkButton(lf("let's do it!"), () => m.dismiss()), 2000) ) ); if (this.hourOfCode) { // https://docs.google.com/document/d/1d48vn_aN2aImmPkF9TK7xGDu_IVrHzjPXVGVEuv0pGw/pub m.add(div('wall-dialog-body hoc-notice hoc-link', lf("i'm finished with my Hour of Code™")).withClick(() => { tick(Ticks.hourOfCodeDoneStep); m.dismiss(); var btns = {}; btns[lf("keep editing")] = () => { tick(Ticks.hourOfCodeKeepCoding); this.startAsync().done(); }; btns[lf("get my certificate")] = () => { tick(Ticks.hourOfCodeConfirm); this.openHocFinish(); } ModalDialog.askMany(lf("Are you finished coding?"), lf("You can come back later to finish the tutorial!"), btns); })); } m.show(); }); } else if (!step) { this.keepTinkering(false) return Promise.as(); } else { this.disableUpdate = false; return Promise.as(); } } static addTranslatedDocs(m: ModalDialog, elementDiv: HTMLElement, manualTranslation : boolean, translatedDocs: string) { if (translatedDocs) { if (manualTranslation) { HTML.pauseVideos(elementDiv); Browser.setInnerHTML(elementDiv, translatedDocs); MdComments.attachVideoHandlers(elementDiv, true); } else { var trElementDiv = <HTMLDivElement>div('wall-dialog-body'); Browser.setInnerHTML(trElementDiv, translatedDocs); MdComments.attachVideoHandlers(trElementDiv, Util.seeTranslatedText()); var trNotice = div('translate-notice', lf("Translations by Microsoft® Translator, tap to see original...")) .withClick(() => { trElementDiv.style.display = 'none'; HTML.pauseVideos(trElementDiv); elementDiv.style.display = 'block'; Util.seeTranslatedText(false); }); trElementDiv.appendChild(trNotice); var elNotice = div('translate-notice', lf("tap to translate with Microsoft® Translator...")) .withClick(() => { elementDiv.style.display = 'none'; HTML.pauseVideos(elementDiv); trElementDiv.style.display = 'block'; Util.seeTranslatedText(true); }); elementDiv.appendChild(elNotice); m.add(trElementDiv); if (Util.seeTranslatedText()) { elementDiv.style.display = 'none'; HTML.pauseVideos(elementDiv); } else { trElementDiv.style.display = 'none'; HTML.pauseVideos(trElementDiv); } } } } private createStars(colors = true) { var stars = div('wall-dialog-body tutorialStars'); var numStars = 0 var lightStars = []; var allStars = []; for(var i = -1; i < this.steps.length; ++i) { if (i == -1 || this.steps[i].hasStar()) { numStars++; var checkpoint = i > -1 && (this.steps[i].data.stcheckpoint || i == this.steps.length - 1); var completed = colors && i < this.currentStep; var shape = checkpoint ? "award" : "star"; var color = completed ? checkpoint ? 'blueviolet' : '#EAC117' : "#ddd"; var star = HTML.mkImg('svg:' + shape + ',' + color + ',clip=100'); allStars.push(star); if (completed) lightStars.push(star); stars.appendChild(star); } } var maxStars = numStars > 32 ? 24 : 16; var rows = Math.ceil(numStars / maxStars); var starSize = Math.min(3, 21 / 0.8 / numStars) if (rows == 1) { Util.childNodes(stars).forEach(e => { e.style.width = starSize + "em" e.style.height = starSize + "em" }) } else { var row = Math.ceil(allStars.length / rows); starSize = Math.min(2.5, 21 / 0.8 / row) stars = div('wall-dialog-body'); var sk = 0; for(var ri = 0; ri < rows; ++ri) { var rowDiv = div('tutorialStars'); stars.appendChild(rowDiv); for(var rr = 0; rr < row && sk < allStars.length; ++rr) { var aa = allStars[sk++]; aa.style.width = starSize + "em" aa.style.height = starSize + "em" rowDiv.appendChild(aa); } } } if (lightStars.peek()) Util.coreAnim("pulseStar", 1500, lightStars.peek()); else { var interval = 3000 / numStars; var delay = 10; allStars.forEach(star => { Util.setTimeout(delay, () => Util.coreAnim("pulseStar", interval * 3, star)) delay += interval; }) } return stars; } private stopOverlayHandler = () => {}; private runOverlay: HTMLElement; private showRunOverlay(step: Step) { if (this.runOverlay && this.runOverlay.parentElement) return; var tip = div('tip tip-tl', div('tipInner', div('tipTitle', lf("tap there")), div('tipDescr', lf("to continue")))) tip.style.bottom = "calc(50% - 3em)"; tip.style.right = "calc(50% - 3em)"; this.runOverlay = div("modalOverlay" /* , tip */) this.runOverlay.withClick(() => { if (this.runOverlay) { this.runOverlay.removeSelf() this.runOverlay = null; } Runtime.theRuntime.stopAsync().done() }); this.runOverlay.style.backgroundColor = "rgba(255, 255, 79, 0.1)"; this.runOverlay.style.cursor = "pointer"; elt("editorContainer").appendChild(this.runOverlay) this.stopOverlayHandler = () => { if (this.runOverlay) { this.runOverlay.removeSelf() this.runOverlay = null; } } Util.setTimeout(3000, () => { if (this.runOverlay) this.runOverlay.appendChild(tip) }) } public notify(cmd:string) { var step = this.steps[this.currentStep] if (cmd == "showside" || cmd == "hideside") { this.update() return } if (cmd == "run") { if (this.waitingFor == "validator") { TheEditor.currentRt.validatorAction = step.data.validator TheEditor.currentRt.validatorActionFlags = step.data.validatorArg Plugins.setupEditorObject(Script.localGuid, false) if (SizeMgr.splitScreen) this.showRunOverlay(step) return } if (SizeMgr.splitScreen) { this.showRunOverlay(step) } else { this.scheduleTapRun(step); this.timer.start(this.getRunDelay()); } return; } if (cmd == "editArtDone" && this.waitingFor == "editArt") { this.stepCompleted() Util.setTimeout(1000, () => this.update()) return; } if (cmd == "runBack" || (SizeMgr.splitScreen && cmd == "runStop")) { this.stopOverlayHandler(); var ed = TheEditor.consumeRtEditor() TheEditor.clearAnnotations(undefined) if (ed && ed.allAnnotations.length > 0) { AST.Json.setStableId(Script) TheEditor.injectAnnotations(ed.allAnnotations) } if (this.waitingFor == "run" || (this.waitingFor == "validator" && TheEditor.getRuntimeTutorialState().validated)) { TheEditor.getRuntimeTutorialState().validated = false this.stepCompleted() Util.setTimeout(1000, () => this.update()) } else { this.update() } Util.setTimeout(0, () => TheEditor.refreshDecl()) return; } if (cmd == "publish") { if (this.waitingFor == "publish") { this.stepCompleted() Util.setTimeout(1000, () => this.update()) } else { this.update(); } return; } if (cmd == "compile") { if (this.waitingFor == "compile") { this.stepCompleted() Util.setTimeout(1000, () => this.update()) } else { this.update(); } } if (cmd == "stepCompleted") { // force tip display and wait for user to stop whenever he wants this.scheduleTapRun(step); TipManager.showScheduled(); } if (cmd == "delay") { document.getElementById("btn-tutorialNextStep").style.display = "none"; this.stepCompleted(); return; } if (/^plugin:/.test(cmd)) { if (this.waitingFor == cmd) // plugin started, waiting to finish this.stepCompleted(true); else this.update(); return; } } private scheduleTapRun(step: Step) { if (SizeMgr.splitScreen) TipManager.scheduleTip({ tick: Ticks.wallStop, title: lf("tap there"), description: lf("to continue") }) else TipManager.scheduleTip({ tick: Ticks.wallBack, title: lf("tap there"), description: lf("to continue") }) } private toInlineActions(ins:TutorialInstruction) { Util.setTimeout(1, () => { var exprStmt = <AST.ExprStmt>ins.stmt; var block = <AST.CodeBlock>exprStmt.parent; var idx = block.stmts.indexOf(exprStmt); if (idx < 0) return; var inl = new AST.InlineActions(); inl.expr = exprStmt.expr; block.setChild(idx, inl) TheEditor.initIds(inl) if (TheEditor.hasModalPane()) TheEditor.nodeTap(inl, true); else TheEditor.refreshDecl() this.update() }) } public isActive() { return !!this.steps[this.currentStep]; } static lastTinkering = 0; private expectedKind:Kind; public update() { if (this.disableUpdate) return; if (!Script) return; if (this.switchToNormalMode()) return; var step = this.steps[this.currentStep] this.timer.poke(); if (!step) { if (this.stepShown) return; TipManager.setTip(null); TheEditor.calculator.applyInstruction(null) this.stepShown = true; var d = div(null); Browser.setInnerHTML(d, this.finalHTML || ("<h3>" + lf("Tutorial completed") + "</h3>")); TheEditor.setStepHint(d) if (!this.finalCountdown) { this.finalCountdown = true; if (Date.now() - StepTutorial.lastTinkering < 30000) return; StepTutorial.lastTinkering = Date.now(); var cnt = () => { if (!ModalDialog.currentIsVisible()) { this.keepTinkering(true) } else { Util.setTimeout(500, cnt) } }; Util.setTimeout(500, cnt) } return; } this.waitingFor = null var hasDeclList = () => { if (TheEditor.hasModalPane() && !TheEditor.hasDeclList()) { TipManager.setTip({ tick: Ticks.calcSearchBack, title: lf("tap there"), description: lf("need to edit elsewhere") }) TheEditor.calculator.applyInstruction(null); return false; } if (!TheEditor.hasDeclList()) { TipManager.setTip({ tick: Ticks.editBtnSideSearch, title: lf("tap there"), description: lf("go to list of things in your script") }) return false; } return true } if (step.data.validator && !TheEditor.getRuntimeTutorialState().validated) { if (Script.editorState.tutorialRedisplayed) { TipManager.setTip(null) } else { TipManager.setTip({ tick: Ticks.sideTutorialRedisplay, title: lf("tap there for instructions"), description: lf("show how to complete this activity") }) } this.waitingFor = "validator" if (!ModalDialog.currentIsVisible() && !Script.editorState.tutorialValidated) { Script.editorState.tutorialValidated = true; if (!this.isFirstStep()) this.youAreOnYourOwnAsync().done(); } return } if (step.data.autoMode) { if (this.fromReply) { this.fromReply = false; if (SizeMgr.splitScreen && step.data.autoMode == "run" && !step.autorunDone) { this.disableUpdate = true; step.autorunDone = true TheEditor.runMainAction() } this.stepCompleted() } else { this.disableUpdate = true; this.replyAsync(this.currentStep + 1).done(); } return } this.fromReply = false; var ins = step.nextInstruction() if (ins && ins.toInlineActions) { this.toInlineActions(ins); return } if (ins && ins.calcIntelli == Ticks.calcEditArt) this.waitingFor = "editArt" if (!this.stepShown) { step.show() this.stepShown = true } if (ins == null) { var complete = () => { TipManager.setTip(null); TheEditor.calculator.applyInstruction(null); this.stepCompleted(); }; if (!step.data.command || step.data.command == "none" || step.data.command == "empty") { complete(); return; } TheEditor.calculator.applyInstruction(null) // when the user is not signed in, we don't want to ask them to sign in to compile var cmd = step.data.command; if (Cloud.isRestricted() && cmd == "compile" && !Cloud.getUserId()) cmd = "run"; switch (cmd) { case "delay": this.waitingFor = "delay"; TipManager.setTip(null); // (<any>TheEditor).hideStmtEditor(); // TheEditor.showVideo(); TheEditor.resetSidePane(); document.getElementById("btn-tutorialNextStep").style.display = "inline-block"; Util.setTimeout(3000, () => { TipManager.setTip({ tick: Ticks.tutorialNextStep, title: lf("tap here to move on to the next step"), description: lf("move on to the next step"), }); }); return; case "run": this.waitingFor = "run" TipManager.setTip({ tick: TheEditor.calculator.stmt ? Ticks.calcSearchRun : Ticks.codeRun, title: lf("tap there to run your app"), description: this.currentCommandArg() || "" }) return; case "publish": if (ScriptEditorWorldInfo.status == "published") { this.stepCompleted() return } if (!hasDeclList()) return; this.waitingFor = cmd; TipManager.setTip({ tick: Ticks.sidePublish, title: lf("tap there"), description: lf("publish your script") }) return; case "compile": TheEditor.intelliProfile.incr("codeCompile"); TheEditor.intelliProfile.incr("calcSearchCompile"); this.waitingFor = "compile" TipManager.setTip({ tick: Ticks.codeCompile, title: lf("tap there to compile your script"), description: this.currentCommandArg() || "" }) return; case "plugin": var pluginId = Util.htmlEscape(this.currentCommandArg().replace(/\s/, '').toLowerCase()); this.waitingFor = "plugin:" + pluginId; if (!hasDeclList()) return; if (TheEditor.calculator.stmt) { TipManager.setTip({ tick: Ticks.calcSearchBack, title: lf("tap there"), description: lf("need plugin buttons") }) } else { TipManager.setTip({ tick: Ticks.sideButtonPlugin, tickArg: pluginId, title: lf("tap there to run your app"), description: lf("run the plugin") }) } return; case "change": this.stepCompleted(); Util.setTimeout(1000, () => this.update()); return; default: HTML.showErrorNotification(lf("unknown tutorial step: {0}", cmd)) this.stepCompleted() return; } } // HTML.showProgressNotification("ds: " + ins.diffSize + " (prev: " + this.prevDiffSize + ")") if (!this.goalTimer.running) this.goalTimer.start(15000); if (this.prevDiffSize < 0) { this.prevDiffSize = ins.diffSize; } else { var progress = this.prevDiffSize - ins.diffSize if (this.recoveryMode && progress >= 1) { this.recoveryMode = false; } if (progress > 0) { this.prevDiffSize = ins.diffSize; this.goalTimer.start(15000); } } if (this.initialMode || this.recoveryMode) this.timer.start(100); else this.timer.start(100000); // it's really the goal timer that should kick in var expS = this.expectingSearch; if (expS > 0) this.expectingSearch--; if (SizeMgr.splitScreen && !TheEditor.currentRt.isStopped()) { this.showRunOverlay(this.steps[this.currentStep]); return } if (ins.addButton) { if (!ScriptNav.addAnythingVisible) { if (!hasDeclList()) return; TipManager.setTip({ tick: Ticks.sideAddAnything, title: lf("tap there"), description: ins.label }) } else if (!elt("btn-" + Ticker.tickName(ins.addButton))) { TipManager.setTip({ tick: Ticks.sideMoreOptions, title: lf("tap there"), description: lf("We need more options") }); } else { TipManager.setTip({ tick: ins.addButton, title: lf("tap there"), description: ins.label, }) } return } Util.assert(!!ins.stmt) if (ins.decl != TheEditor.lastDecl) { if (expS) return; if (!hasDeclList()) return var switchDecl = () => { if (ins.decl == TheEditor.lastDecl) return; if (TheEditor.scriptNav.htmlForDecl(ins.decl)) { TipManager.setTip({ decl: ins.decl, title: lf("tap there"), description: lf("we need to edit another thing"), }) } else { TipManager.setTip(null) Util.setTimeout(300, switchDecl) } }; switchDecl() return } var selectorOk = ins.calcButton == Ticks.btnAddDown || ins.calcButton == Ticks.btnAddUp var currStmt = TheEditor.editedStmt(selectorOk) this.expectedKind = ins.targetKind; if (TheEditor.hasModalPane() && (!currStmt || (ins.stmt != currStmt && (currStmt instanceof AST.RecordPersistenceKind || !TheEditor.codeVisible())))) { TipManager.setTip({ tick: Ticks.calcSearchBack, title: lf("tap there"), description: lf("need to edit elsewhere") }) } else if (ins.stmt != currStmt && // the diff engine uses the AST.ActionHeader // while the DeclNameHolder is pointing at the Action stmt !(ins.stmt instanceof AST.ActionHeader && currStmt instanceof AST.DeclNameHolder && (<AST.DeclNameHolder>currStmt).parentDecl instanceof AST.Action && (<AST.ActionHeader>ins.stmt).action == (<AST.DeclNameHolder>currStmt).parentDecl) ) { if (ins.stmt.renderedAs) { var target = <HTMLElement>ins.stmt.renderedAs.firstChild var forceBottom = false; var clientHeight: number = undefined; if (ins.calcButton == Ticks.btnAddDown) { var lastLine = target while (target) { if (target.className == "line") lastLine = target target = <HTMLElement>target.nextSibling } target = lastLine } else if (ins.calcButton == Ticks.sideActionAddInput || ins.calcButton == Ticks.sideActionAddOutput) { clientHeight = target.clientHeight; target = <HTMLElement>target.firstElementChild; forceBottom = true; } TipManager.setTip({ el: target, forceBottom: forceBottom, clientHeight : clientHeight, title: lf("tap there"), description: lf("select that line") }) } } else if (ins.targetName) { var trg = elt("renameBox") || elt("renameBox2") if (trg) TipManager.setTip({ el: trg, title: lf("type: {0}", ins.targetName), description: lf("tap [ok] when done"), }) else TipManager.setTip({ el: elt("inlineEditCloseBtn"), title: lf("type: {0}", ins.targetName), description: lf("tap here when done"), }) } else if (ins.targetKind) { if (VariableProperties.kindSelectorVisible) { // waiting for notifyKindList() TipManager.setTip(null); } else { TipManager.setTip({ tick: Ticks.btnChangeKind, title: lf("tap there"), description: lf("need a {0}", ins.targetKind.toString().toLowerCase()), }) } } else if (ins.calcButton) { TipManager.setTip({ tick: ins.calcButton, title: lf("tap there"), description: ins.label || "", }) } else { TheEditor.calculator.applyInstruction(ins) return; } TheEditor.calculator.applyInstruction(null) } private currentCommandArg(): string { var step = this.steps[this.currentStep]; var commandArg : string = undefined; if (step) { commandArg = step.data.commandArg; if (this.translatedTutorial && this.translatedTutorial.steps[this.currentStep] && this.translatedTutorial.steps[this.currentStep].commandArg) commandArg = this.translatedTutorial.steps[this.currentStep].commandArg } return commandArg; } public notifyKindList(elts:HTMLElement[]) { if (!this.expectedKind) { TipManager.setTip({ tick: Ticks.chooseCancel, title: lf("tap there"), description: lf("go back..."), }) return; } var el = elts.filter(e => (<any>e).theNode == this.expectedKind)[0] TipManager.setTip({ el: el, title: lf("tap there"), description: lf("select {0}", this.expectedKind.toString()) }) } public isEnabled() { return this.steps.length > 0 } private replyModalDialog:ModalDialog; public replyAsync(stepNo:number) : Promise { var scr = AST.Step.reply(Script, this.app, this.steps.slice(0, stepNo).map(s => s.data), this.customizations) return TheEditor.loadScriptTextAsync(ScriptEditorWorldInfo, scr, JSON.stringify(Script.editorState)).then(() => { if (this.replyModalDialog) { this.replyModalDialog.dismiss() this.replyModalDialog = null } TheEditor.addTutorialValidatorLibrary() TheEditor.renderDefaultDecl(); TheEditor.queueNavRefresh(); this.currentStep = stepNo ? stepNo - 1 : 0; this.disableUpdate = false; this.fromReply = true; this.update(); }); } public replyDialog() { var m = new ModalDialog() this.replyModalDialog = m; var d = this.topic.render(Browser.TopicInfo.attachCopyHandlers); var outer = div("tutReply", div(null, HTML.mkButton(lf("diff for current step"), () => this.showDiff()) ), d) m.add(outer) Util.setupDragToScroll(outer) outer.style.maxHeight = (SizeMgr.windowHeight * 1.2) / SizeMgr.topFontSize + "em"; m.fullWhite() m.show() } } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [route53resolver](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonroute53resolver.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Route53resolver extends PolicyStatement { public servicePrefix = 'route53resolver'; /** * Statement provider for service [route53resolver](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonroute53resolver.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to associate an Amazon VPC with a specified firewall rule group * * Access Level: Write * * Dependent actions: * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_AssociateFirewallRuleGroup.html */ public toAssociateFirewallRuleGroup() { return this.to('AssociateFirewallRuleGroup'); } /** * Grants permission to associate a specified IP address with a Resolver endpoint. This is an IP address that DNS queries pass through on the way to your network (outbound) or your VPCs (inbound) * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_AssociateResolverEndpointIpAddress.html */ public toAssociateResolverEndpointIpAddress() { return this.to('AssociateResolverEndpointIpAddress'); } /** * Grants permission to associate an Amazon VPC with a specified query logging configuration * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_AssociateResolverQueryLogConfig.html */ public toAssociateResolverQueryLogConfig() { return this.to('AssociateResolverQueryLogConfig'); } /** * Grants permission to associate a specified Resolver rule with a specified VPC * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_AssociateResolverRule.html */ public toAssociateResolverRule() { return this.to('AssociateResolverRule'); } /** * Grants permission to create a Firewall domain list * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_CreateFirewallDomainList.html */ public toCreateFirewallDomainList() { return this.to('CreateFirewallDomainList'); } /** * Grants permission to create a Firewall rule within a Firewall rule group * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_CreateFirewallRule.html */ public toCreateFirewallRule() { return this.to('CreateFirewallRule'); } /** * Grants permission to create a Firewall rule group * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_CreateFirewallRuleGroup.html */ public toCreateFirewallRuleGroup() { return this.to('CreateFirewallRuleGroup'); } /** * Grants permission to create a Resolver endpoint. There are two types of Resolver endpoints, inbound and outbound * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_CreateResolverEndpoint.html */ public toCreateResolverEndpoint() { return this.to('CreateResolverEndpoint'); } /** * Grants permission to create a Resolver query logging configuration, which defines where you want Resolver to save DNS query logs that originate in your VPCs * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_CreateResolverQueryLogConfig.html */ public toCreateResolverQueryLogConfig() { return this.to('CreateResolverQueryLogConfig'); } /** * For DNS queries that originate in your VPC, grants permission to define how to route the queries out of the VPC * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_CreateResolverRule.html */ public toCreateResolverRule() { return this.to('CreateResolverRule'); } /** * Grants permission to delete a Firewall domain list * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_DeleteFirewallDomainList.html */ public toDeleteFirewallDomainList() { return this.to('DeleteFirewallDomainList'); } /** * Grants permission to delete a Firewall rule within a Firewall rule group * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_DeleteFirewallRule.html */ public toDeleteFirewallRule() { return this.to('DeleteFirewallRule'); } /** * Grants permission to delete a Firewall rule group * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_DeleteFirewallRuleGroup.html */ public toDeleteFirewallRuleGroup() { return this.to('DeleteFirewallRuleGroup'); } /** * Grants permission to delete a Resolver endpoint. The effect of deleting a Resolver endpoint depends on whether it's an inbound or an outbound endpoint * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_DeleteResolverEndpoint.html */ public toDeleteResolverEndpoint() { return this.to('DeleteResolverEndpoint'); } /** * Grants permission to delete a Resolver query logging configuration * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_DeleteResolverQueryLogConfig.html */ public toDeleteResolverQueryLogConfig() { return this.to('DeleteResolverQueryLogConfig'); } /** * Grants permission to delete a Resolver rule * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_DeleteResolverRule.html */ public toDeleteResolverRule() { return this.to('DeleteResolverRule'); } /** * Grants permission to remove the association between a specified Firewall rule group and a specified VPC * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_DisassociateFirewallRuleGroup.html */ public toDisassociateFirewallRuleGroup() { return this.to('DisassociateFirewallRuleGroup'); } /** * Grants permission to remove a specified IP address from a Resolver endpoint. This is an IP address that DNS queries pass through on the way to your network (outbound) or your VPCs (inbound) * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_DisassociateResolverEndpointIpAddress.html */ public toDisassociateResolverEndpointIpAddress() { return this.to('DisassociateResolverEndpointIpAddress'); } /** * Grants permission to remove the association between a specified Resolver query logging configuration and a specified VPC * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_DisassociateResolverQueryLogConfig.html */ public toDisassociateResolverQueryLogConfig() { return this.to('DisassociateResolverQueryLogConfig'); } /** * Grants permission to remove the association between a specified Resolver rule and a specified VPC * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_DisassociateResolverRule.html */ public toDisassociateResolverRule() { return this.to('DisassociateResolverRule'); } /** * Grants permission to get information about a specified Firewall config * * Access Level: Read * * Dependent actions: * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetFirewallConfig.html */ public toGetFirewallConfig() { return this.to('GetFirewallConfig'); } /** * Grants permission to get information about a specified Firewall domain list * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetFirewallDomainList.html */ public toGetFirewallDomainList() { return this.to('GetFirewallDomainList'); } /** * Grants permission to get information about a specified Firewall rule group * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetFirewallRuleGroup.html */ public toGetFirewallRuleGroup() { return this.to('GetFirewallRuleGroup'); } /** * Grants permission to get information about an association between a specified Firewall rule group and a VPC * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetFirewallRuleGroupAssociation.html */ public toGetFirewallRuleGroupAssociation() { return this.to('GetFirewallRuleGroupAssociation'); } /** * Grants permission to get information about a specified Firewall rule group policy, which specifies the Firewall rule group operations and resources that you want to allow another AWS account to use * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetFirewallRuleGroupPolicy.html */ public toGetFirewallRuleGroupPolicy() { return this.to('GetFirewallRuleGroupPolicy'); } /** * Grants permission to get the DNSSEC validation support status for DNS queries within the specified resource * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetResolverDnssecConfig.html */ public toGetResolverDnssecConfig() { return this.to('GetResolverDnssecConfig'); } /** * Grants permission to get information about a specified Resolver endpoint, such as whether it's an inbound or an outbound endpoint, and the IP addresses in your VPC that DNS queries are forwarded to on the way into or out of your VPC * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetResolverEndpoint.html */ public toGetResolverEndpoint() { return this.to('GetResolverEndpoint'); } /** * Grants permission to get information about a specified Resolver query logging configuration, such as the number of VPCs that the configuration is logging queries for and the location that logs are sent to * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetResolverQueryLogConfig.html */ public toGetResolverQueryLogConfig() { return this.to('GetResolverQueryLogConfig'); } /** * Grants permission to get information about a specified association between a Resolver query logging configuration and an Amazon VPC. When you associate a VPC with a query logging configuration, Resolver logs DNS queries that originate in that VPC * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetResolverQueryLogConfigAssociation.html */ public toGetResolverQueryLogConfigAssociation() { return this.to('GetResolverQueryLogConfigAssociation'); } /** * Grants permission to get information about a specified Resolver query logging policy, which specifies the Resolver query logging operations and resources that you want to allow another AWS account to use * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetResolverQueryLogConfigPolicy.html */ public toGetResolverQueryLogConfigPolicy() { return this.to('GetResolverQueryLogConfigPolicy'); } /** * Grants permission to get information about a specified Resolver rule, such as the domain name that the rule forwards DNS queries for and the IP address that queries are forwarded to * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetResolverRule.html */ public toGetResolverRule() { return this.to('GetResolverRule'); } /** * Grants permission to get information about an association between a specified Resolver rule and a VPC * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetResolverRuleAssociation.html */ public toGetResolverRuleAssociation() { return this.to('GetResolverRuleAssociation'); } /** * Grants permission to get information about a Resolver rule policy, which specifies the Resolver operations and resources that you want to allow another AWS account to use * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_GetResolverRulePolicy.html */ public toGetResolverRulePolicy() { return this.to('GetResolverRulePolicy'); } /** * Grants permission to add, remove or replace Firewall domains in a Firewall domain list * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ImportFirewallDomains.html */ public toImportFirewallDomains() { return this.to('ImportFirewallDomains'); } /** * Grants permission to list all the Firewall config that current AWS account is able to check * * Access Level: List * * Dependent actions: * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListFirewallConfigs.html */ public toListFirewallConfigs() { return this.to('ListFirewallConfigs'); } /** * Grants permission to list all the Firewall domain list that current AWS account is able to use * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListFirewallDomainLists.html */ public toListFirewallDomainLists() { return this.to('ListFirewallDomainLists'); } /** * Grants permission to list all the Firewall domain under a speicfied Firewall domain list * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListFirewallDomains.html */ public toListFirewallDomains() { return this.to('ListFirewallDomains'); } /** * Grants permission to list information about associations between Amazon VPCs and Firewall rule group * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListFirewallRuleGroupAssociations.html */ public toListFirewallRuleGroupAssociations() { return this.to('ListFirewallRuleGroupAssociations'); } /** * Grants permission to list all the Firewall rule group that current AWS account is able to use * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListFirewallRuleGroups.html */ public toListFirewallRuleGroups() { return this.to('ListFirewallRuleGroups'); } /** * Grants permission to list all the Firewall rule under a speicfied Firewall rule group * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListFirewallRules.html */ public toListFirewallRules() { return this.to('ListFirewallRules'); } /** * Grants permission to list the DNSSEC validation support status for DNS queries * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListResolverDnssecConfigs.html */ public toListResolverDnssecConfigs() { return this.to('ListResolverDnssecConfigs'); } /** * For a specified Resolver endpoint, grants permission to list the IP addresses that DNS queries pass through on the way to your network (outbound) or your VPCs (inbound) * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListResolverEndpointIpAddresses.html */ public toListResolverEndpointIpAddresses() { return this.to('ListResolverEndpointIpAddresses'); } /** * Grants permission to list all the Resolver endpoints that were created using the current AWS account * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListResolverEndpoints.html */ public toListResolverEndpoints() { return this.to('ListResolverEndpoints'); } /** * Grants permission to list information about associations between Amazon VPCs and query logging configurations * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListResolverQueryLogConfigAssociations.html */ public toListResolverQueryLogConfigAssociations() { return this.to('ListResolverQueryLogConfigAssociations'); } /** * Grants permission to list information about the specified query logging configurations, which define where you want Resolver to save DNS query logs and specify the VPCs that you want to log queries for * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListResolverQueryLogConfigs.html */ public toListResolverQueryLogConfigs() { return this.to('ListResolverQueryLogConfigs'); } /** * Grants permission to list the associations that were created between Resolver rules and VPCs using the current AWS account * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListResolverRuleAssociations.html */ public toListResolverRuleAssociations() { return this.to('ListResolverRuleAssociations'); } /** * Grants permission to list the Resolver rules that were created using the current AWS account * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListResolverRules.html */ public toListResolverRules() { return this.to('ListResolverRules'); } /** * Grants permission to list the tags that you associated with the specified resource * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to specify an AWS account that you want to share a Firewall rule group with, the Firewall rule group that you want to share, and the operations that you want the account to be able to perform on the configuration * * Access Level: Permissions management * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_PutFirewallRuleGroupPolicy.html */ public toPutFirewallRuleGroupPolicy() { return this.to('PutFirewallRuleGroupPolicy'); } /** * Grants permission to specify an AWS account that you want to share a query logging configuration with, the query logging configuration that you want to share, and the operations that you want the account to be able to perform on the configuration * * Access Level: Permissions management * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_PutResolverQueryLogConfigPolicy.html */ public toPutResolverQueryLogConfigPolicy() { return this.to('PutResolverQueryLogConfigPolicy'); } /** * Grants permission to specify an AWS account that you want to share rules with, the Resolver rules that you want to share, and the operations that you want the account to be able to perform on those rules * * Access Level: Permissions management * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_PutResolverRulePolicy.html */ public toPutResolverRulePolicy() { return this.to('PutResolverRulePolicy'); } /** * Grants permission to add one or more tags to a specified resource * * Access Level: Tagging * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_TagResource.html */ public toTagResource() { return this.to('TagResource'); } /** * Grants permission to remove one or more tags from a specified resource * * Access Level: Tagging * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_UntagResource.html */ public toUntagResource() { return this.to('UntagResource'); } /** * Grants permission to update selected settings for an Firewall config * * Access Level: Write * * Dependent actions: * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_UpdateFirewallConfig.html */ public toUpdateFirewallConfig() { return this.to('UpdateFirewallConfig'); } /** * Grants permission to add, remove or replace Firewall domains in a Firewall domain list * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_UpdateFirewallDomains.html */ public toUpdateFirewallDomains() { return this.to('UpdateFirewallDomains'); } /** * Grants permission to update selected settings for an Firewall rule in a Firewall rule group * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_UpdateFirewallRule.html */ public toUpdateFirewallRule() { return this.to('UpdateFirewallRule'); } /** * Grants permission to update selected settings for an Firewall rule group association * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_UpdateFirewallRuleGroupAssociation.html */ public toUpdateFirewallRuleGroupAssociation() { return this.to('UpdateFirewallRuleGroupAssociation'); } /** * Grants permission to update the DNSSEC validation support status for DNS queries within the specified resource * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_UpdateResolverDnssecConfig.html */ public toUpdateResolverDnssecConfig() { return this.to('UpdateResolverDnssecConfig'); } /** * Grants permission to update selected settings for an inbound or an outbound Resolver endpoint * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_UpdateResolverEndpoint.html */ public toUpdateResolverEndpoint() { return this.to('UpdateResolverEndpoint'); } /** * Grants permission to update settings for a specified Resolver rule * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_route53resolver_UpdateResolverRule.html */ public toUpdateResolverRule() { return this.to('UpdateResolverRule'); } protected accessLevelList: AccessLevelList = { "Write": [ "AssociateFirewallRuleGroup", "AssociateResolverEndpointIpAddress", "AssociateResolverQueryLogConfig", "AssociateResolverRule", "CreateFirewallDomainList", "CreateFirewallRule", "CreateFirewallRuleGroup", "CreateResolverEndpoint", "CreateResolverQueryLogConfig", "CreateResolverRule", "DeleteFirewallDomainList", "DeleteFirewallRule", "DeleteFirewallRuleGroup", "DeleteResolverEndpoint", "DeleteResolverQueryLogConfig", "DeleteResolverRule", "DisassociateFirewallRuleGroup", "DisassociateResolverEndpointIpAddress", "DisassociateResolverQueryLogConfig", "DisassociateResolverRule", "ImportFirewallDomains", "UpdateFirewallConfig", "UpdateFirewallDomains", "UpdateFirewallRule", "UpdateFirewallRuleGroupAssociation", "UpdateResolverDnssecConfig", "UpdateResolverEndpoint", "UpdateResolverRule" ], "Read": [ "GetFirewallConfig", "GetFirewallDomainList", "GetFirewallRuleGroup", "GetFirewallRuleGroupAssociation", "GetFirewallRuleGroupPolicy", "GetResolverDnssecConfig", "GetResolverEndpoint", "GetResolverQueryLogConfig", "GetResolverQueryLogConfigAssociation", "GetResolverQueryLogConfigPolicy", "GetResolverRule", "GetResolverRuleAssociation", "GetResolverRulePolicy", "ListTagsForResource" ], "List": [ "ListFirewallConfigs", "ListFirewallDomainLists", "ListFirewallDomains", "ListFirewallRuleGroupAssociations", "ListFirewallRuleGroups", "ListFirewallRules", "ListResolverDnssecConfigs", "ListResolverEndpointIpAddresses", "ListResolverEndpoints", "ListResolverQueryLogConfigAssociations", "ListResolverQueryLogConfigs", "ListResolverRuleAssociations", "ListResolverRules" ], "Permissions management": [ "PutFirewallRuleGroupPolicy", "PutResolverQueryLogConfigPolicy", "PutResolverRulePolicy" ], "Tagging": [ "TagResource", "UntagResource" ] }; /** * Adds a resource of type resolver-dnssec-config to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/access-control-overview.html/#access-control-resources * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onResolverDnssecConfig(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:route53resolver:${Region}:${Account}:resolver-dnssec-config/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type resolver-query-log-config to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/access-control-overview.html/#access-control-resources * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onResolverQueryLogConfig(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:route53resolver:${Region}:${Account}:resolver-query-log-config/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type resolver-rule to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/access-control-overview.html/#access-control-resources * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onResolverRule(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:route53resolver:${Region}:${Account}:resolver-rule/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type resolver-endpoint to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/access-control-overview.html/#access-control-resources * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onResolverEndpoint(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:route53resolver:${Region}:${Account}:resolver-endpoint/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type firewall-rule-group to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/access-control-overview.html/#access-control-resources * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onFirewallRuleGroup(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:route53resolver:${Region}:${Account}:firewall-rule-group/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type firewall-rule-group-association to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/access-control-overview.html/#access-control-resources * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onFirewallRuleGroupAssociation(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:route53resolver:${Region}:${Account}:firewall-rule-group-association/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type firewall-domain-list to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/access-control-overview.html/#access-control-resources * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onFirewallDomainList(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:route53resolver:${Region}:${Account}:firewall-domain-list/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type firewall-config to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/access-control-overview.html/#access-control-resources * * @param resourceId - Identifier for the resourceId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onFirewallConfig(resourceId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:route53resolver:${Region}:${Account}:firewall-config/${ResourceId}'; arn = arn.replace('${ResourceId}', resourceId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import React, { useState, useMemo, useEffect } from "react"; import { OrgComponent } from "@ui_types"; import { Model, Api } from "@core/types"; import humanize from "humanize-string"; import * as g from "@core/lib/graph"; import * as R from "ramda"; import * as ui from "@ui"; import { stripUndefinedRecursive } from "@core/lib/utils/object"; import * as styles from "@styles"; import { SvgImage, SmallLoader } from "@images"; import { MIN_ACTION_DELAY_MS } from "@constants"; import { wait } from "@core/lib/utils/wait"; import { logAndAlertError } from "@ui_lib/errors"; const getComponent = (envParentType: "app" | "block") => { const Settings: OrgComponent< ({ appId: string } | { blockId: string }) & {} > = (props) => { const { graph, graphUpdatedAt } = props.core; const envParentId = "appId" in props.routeParams ? props.routeParams.appId : props.routeParams.blockId; const envParent = graph[envParentId] as Model.App | Model.Block; const currentUserId = props.ui.loadedAccountId!; const envParentTypeLabel = humanize(envParentType); const org = g.getOrg(graph); const { canRename, canUpdateSettings, canDelete, canManageEnvironments } = useMemo(() => { const canUpdateSettings = envParent.type == "app" ? g.authz.canUpdateAppSettings(graph, currentUserId, envParentId) : g.authz.canUpdateBlockSettings(graph, currentUserId, envParentId); return { canRename: envParent.type == "app" ? g.authz.canRenameApp(graph, currentUserId, envParentId) : g.authz.canRenameBlock(graph, currentUserId, envParentId), canUpdateSettings, canDelete: envParent.type == "app" ? g.authz.canDeleteApp(graph, currentUserId, envParentId) : g.authz.canDeleteBlock(graph, currentUserId, envParentId), canManageEnvironments: envParent.type == "app" ? g.authz.hasAppPermission( graph, currentUserId, envParentId, "app_manage_environments" ) : g.authz.hasOrgPermission( graph, currentUserId, "blocks_manage_environments" ), }; }, [graphUpdatedAt, envParentId, currentUserId]); const [name, setName] = useState(envParent.name); const [autoCaps, setAutoCaps] = useState(envParent.settings.autoCaps); const [autoCommitLocals, setAutoCommitLocals] = useState( envParent.settings.autoCommitLocals ); const [confirmDeleteName, setConfirmDeleteName] = useState(""); const [updatingSettings, setUpdatingSettings] = useState(false); const [renaming, setRenaming] = useState(false); const [awaitingMinDelay, setAwaitingMinDelay] = useState(false); const [isDeleting, setIsDeleting] = useState(false); const settingsFlagsState = { autoCaps, autoCommitLocals, }; const settingsState: Model.EnvParentSettings = { ...settingsFlagsState }; useEffect(() => { setName(envParent.name); setAutoCaps(envParent.settings.autoCaps); setAutoCommitLocals(envParent.settings.autoCommitLocals); setConfirmDeleteName(""); setUpdatingSettings(false); }, [envParentId]); useEffect(() => { if (renaming && envParent.name == name && !awaitingMinDelay) { setRenaming(false); } }, [envParent.name, awaitingMinDelay]); const settingsUpdated = () => { return !R.equals( stripUndefinedRecursive(envParent.settings), stripUndefinedRecursive(settingsState) ); }; const nameUpdated = envParent.name != name; const dispatchSettingsUpdate = () => { if (updatingSettings || !settingsUpdated()) { return; } setUpdatingSettings(true); if (!awaitingMinDelay) { setAwaitingMinDelay(true); wait(MIN_ACTION_DELAY_MS).then(() => setAwaitingMinDelay(false)); } props .dispatch({ type: envParentType == "app" ? Api.ActionType.UPDATE_APP_SETTINGS : Api.ActionType.UPDATE_BLOCK_SETTINGS, payload: { id: envParentId, settings: settingsState, }, }) .then((res) => { if (!res.success) { logAndAlertError( `There was a problem updating ${envParentType} settings.`, (res.resultAction as any)?.payload ); } }); }; useEffect(() => { dispatchSettingsUpdate(); }, [JSON.stringify(settingsFlagsState)]); useEffect(() => { if (updatingSettings && !awaitingMinDelay) { setUpdatingSettings(false); } }, [JSON.stringify(envParent.settings), awaitingMinDelay]); const renderRename = () => { if (canRename) { return ( <div> <div className="field"> <label>{envParentTypeLabel} Name</label> <input type="text" disabled={renaming} value={name} onChange={(e) => setName(e.target.value)} /> <button className="primary" disabled={!name.trim() || name == envParent.name || renaming} onClick={() => { setRenaming(true); setAwaitingMinDelay(true); wait(MIN_ACTION_DELAY_MS).then(() => setAwaitingMinDelay(false) ); props .dispatch({ type: envParentType == "app" ? Api.ActionType.RENAME_APP : Api.ActionType.RENAME_BLOCK, payload: { id: envParent.id, name }, }) .then((res) => { if (!res.success) { logAndAlertError( `There was a problem renaming the ${envParentType}.`, (res.resultAction as any)?.payload ); } }); }} > {renaming ? "Renaming..." : "Rename"} </button> </div> </div> ); } else { return ""; } }; const renderSettings = () => { if (!canUpdateSettings) { return; } let autoCapsOption: "inherit" | "overrideTrue" | "overrideFalse"; if (typeof autoCaps == "undefined") { autoCapsOption = "inherit"; } else { autoCapsOption = autoCaps ? "overrideTrue" : "overrideFalse"; } let autoCommitLocalsOption: "inherit" | "overrideTrue" | "overrideFalse"; if (typeof autoCommitLocals == "undefined") { autoCommitLocalsOption = "inherit"; } else { autoCommitLocalsOption = autoCommitLocals ? "overrideTrue" : "overrideFalse"; } return ( <div> <div className="field"> <label>Auto-Upcase Variable Names?</label> <div className="select"> <select value={autoCapsOption} disabled={updatingSettings} onChange={(e) => { let val: boolean | undefined; if (e.target.value == "inherit") { val = undefined; } else { val = e.target.value == "overrideTrue"; } setAutoCaps(val); }} > <option value="inherit"> Inherit from org settings ( {org.settings.envs.autoCaps ? "Yes" : "No"}) </option> <option value="overrideTrue">Yes</option> <option value="overrideFalse">No</option> </select> <SvgImage type="down-caret" /> </div> </div> {/* <div className="field"> <label>Auto-Commit Locals On Change?</label> <div className="select"> <select value={autoCommitLocalsOption} disabled={updatingSettings} onChange={(e) => { let val: boolean | undefined; if (e.target.value == "inherit") { val = undefined; } else { val = e.target.value == "overrideTrue"; } setAutoCommitLocals(val); }} > <option value="inherit"> Inherit from org settings ( {org.settings.envs.autoCommitLocals ? "Yes" : "No"}) </option> <option value="overrideTrue">Yes</option> <option value="overrideFalse">No</option> </select> <SvgImage type="down-caret" /> </div> </div> */} </div> ); }; const renderManageEnvironments = () => { if (!canManageEnvironments) { return; } return <ui.ManageEnvParentEnvironments {...props} />; }; const renderDelete = () => { if (canDelete) { return ( <div className="field"> <label>Delete {envParentTypeLabel}</label> <input type="text" value={confirmDeleteName} disabled={isDeleting} onChange={(e) => setConfirmDeleteName(e.target.value)} placeholder={`To confirm, enter ${envParentType} name here...`} /> <button className="primary" disabled={isDeleting || confirmDeleteName != envParent.name} onClick={async () => { setIsDeleting(true); await wait(500); // add a little delay for a smoother transition props.setUiState({ justDeletedObjectId: envParentId }); props .dispatch({ type: envParentType == "app" ? Api.ActionType.DELETE_APP : Api.ActionType.DELETE_BLOCK, payload: { id: envParentId }, }) .then((res) => { if (!res.success) { logAndAlertError( `There was a problem deleting the ${envParentType}.`, (res.resultAction as any)?.payload ); } }); }} > {isDeleting ? `Deleting ${envParentTypeLabel}...` : `Delete ${envParentTypeLabel}`} </button> </div> ); } }; const renderDangerZone = () => { if (canDelete) { return ( <div className="danger-zone"> <h3>Danger Zone</h3> {renderDelete()} </div> ); } }; return ( <div className={styles.OrgContainer}> <h3> {updatingSettings || renaming ? <SmallLoader /> : ""} {envParentTypeLabel} <strong>Settings</strong> </h3> {nameUpdated ? ( <span className="unsaved-changes">Unsaved changes</span> ) : ( "" )} {renderRename()} {renderSettings()} {renderManageEnvironments()} {renderDangerZone()} </div> ); }; return Settings; }; export const AppSettings = getComponent("app"); export const BlockSettings = getComponent("block");
the_stack
// ////////////////////////////////////////////////////////////////////////////////// // // prettycron.js // Generates human-readable sentences from a schedule string in cron format // // Based on an earlier version by Pehr Johansson // http://dsysadm.blogspot.com.au/2012/09/human-readable-cron-expressions-using.html // // ////////////////////////////////////////////////////////////////////////////////// // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // ////////////////////////////////////////////////////////////////////////////////// const dayjs = require('dayjs'); const advancedFormat = require('dayjs/plugin/advancedFormat'); const calendar = require('dayjs/plugin/calendar'); dayjs.extend(advancedFormat); dayjs.extend(calendar); const later = require('later'); (function() { const ordinal = { ordinalSuffix(num: number) { const ordinalsArray = ['th', 'st', 'nd', 'rd']; // Get reminder of number by hundred so that we can counter number between 11-19 const offset = num % 100; // Calculate position of ordinal to be used. Logic : Array index is calculated based on defined values. const ordinalPos = ordinalsArray[ (offset - 20) % 10 ] || ordinalsArray[ offset ] || ordinalsArray[0]; // Return suffix return ordinalPos; }, toOrdinal(num: number) { // Check if number is valid // if( !validateNumber(num) ) { // return `${num} is not a valid number`; // } // If number is zero no need to spend time on calculation if (num === 0) { return num.toString(); } return num.toString() + this.ordinalSuffix(num); }, }; // For an array of numbers, e.g. a list of hours in a schedule, // return a string listing out all of the values (complete with // "and" plus ordinal text on the last item). const numberList = function(numbers: any[]) { if (numbers.length < 2) { return ordinal.toOrdinal(numbers[0]); } const last_val = numbers.pop(); return `${numbers.join(', ')} and ${ordinal.toOrdinal(last_val)}`; }; const stepSize = function(numbers: any[]) { if (!numbers || numbers.length <= 1) return 0; const expectedStep = numbers[1] - numbers[0]; if (numbers.length == 2) return expectedStep; // Check that every number is the previous number + the first number return numbers.slice(1).every(function(n,i,a) { return (i === 0 ? n : n - a[i - 1]) === expectedStep; }) ? expectedStep : 0; }; const isEveryOther = function(stepsize: number, numbers: any[]) { return numbers.length === 30 && stepsize === 2; }; const isTwicePerHour = function(stepsize: number, numbers: any[]) { return numbers.length === 2 && stepsize === 30; }; const isOnTheHour = function(numbers: any[]) { return numbers.length === 1 && numbers[0] === 0; }; const isStepValue = function(stepsize: number, numbers: any[]) { // Value with slash (https://en.wikipedia.org/wiki/Cron#Non-Standard_Characters) return numbers.length > 2 && stepsize > 0; }; // For an array of numbers of seconds, return a string // listing all the values unless they represent a frequency divisible by 60: // /2, /3, /4, /5, /6, /10, /12, /15, /20 and /30 const getMinutesTextParts = function(numbers: any[]) { const stepsize = stepSize(numbers); if (!numbers) { return { beginning: 'minute', text: '' }; } const minutes = { beginning: '', text: '' }; if (isOnTheHour(numbers)) { minutes.text = 'hour, on the hour'; } else if (isEveryOther(stepsize, numbers)) { minutes.beginning = 'other minute'; } else if (isStepValue(stepsize, numbers)) { minutes.text = `${stepsize} minutes`; } else if (isTwicePerHour(stepsize, numbers)) { minutes.text = 'first and 30th minute'; } else { minutes.text = `${numberList(numbers)} minute`; } return minutes; }; // For an array of numbers of seconds, return a string // listing all the values unless they represent a frequency divisible by 60: // /2, /3, /4, /5, /6, /10, /12, /15, /20 and /30 const getSecondsTextParts = function(numbers: any[]) { const stepsize = stepSize(numbers); if (!numbers) { return { beginning: 'second', text: '' }; } if (isEveryOther(stepsize, numbers)) { return { beginning: '', text: 'other second' }; } else if (isStepValue(stepsize, numbers)) { return { beginning: '', text: `${stepsize} seconds` }; } else { return { beginning: 'minute', text: `starting on the ${numbers.length === 2 && stepsize === 30 ? 'first and 30th second' : `${numberList(numbers)} second`}` }; } }; // Parse a number into day of week, or a month name; // used in dateList below. const numberToDateName = function(value: any, type: any) { if (type === 'dow') { return dayjs().day(value - 1).format('ddd'); } else if (type === 'mon') { return dayjs().month(value - 1).format('MMM'); } }; // From an array of numbers corresponding to dates (given in type: either // days of the week, or months), return a string listing all the values. const dateList = function(numbers: any[], type: any) { if (numbers.length < 2) { return numberToDateName(`${numbers[0]}`, type); } const last_val = `${numbers.pop()}`; const output_text = ''; // No idea what is this nonsense so comenting it out for now. // for (let i = 0, value; value = numbers[i]; i++) { // if (output_text.length > 0) { // output_text += ', '; // } // output_text += numberToDateName(value, type); // } return `${output_text} and ${numberToDateName(last_val, type)}`; }; // Pad to equivalent of sprintf('%02d'). Both moment.js and later.js // have zero-fill functions, but alas, they're private. // let zeroPad = function(x:any) { // return (x < 10) ? '0' + x : x; // }; const removeFromSchedule = function(schedule: any, member: any, length: any) { if (schedule[member] && schedule[member].length === length) { delete schedule[member]; } }; // ---------------- // Given a schedule from later.js (i.e. after parsing the cronspec), // generate a friendly sentence description. const scheduleToSentence = function(schedule: any, useSeconds: boolean) { let textParts = []; // A later.js schedules contains no member for time units where an asterisk is used, // but schedules that means the same (e.g 0/1 is essentially the same as *) are // returned with populated members. // Remove all members that are fully populated to reduce complexity of code removeFromSchedule(schedule, 'M', 12); removeFromSchedule(schedule, 'D', 31); removeFromSchedule(schedule, 'd', 7); removeFromSchedule(schedule, 'h', 24); removeFromSchedule(schedule, 'm', 60); removeFromSchedule(schedule, 's', 60); // let everySecond = useSeconds && schedule['s'] === undefined; // let everyMinute = schedule['m'] === undefined; // let everyHour = schedule['h'] === undefined; const everyWeekday = schedule['d'] === undefined; const everyDayInMonth = schedule['D'] === undefined; // let everyMonth = schedule['M'] === undefined; const oneOrTwoSecondsPerMinute = schedule['s'] && schedule['s'].length <= 2; const oneOrTwoMinutesPerHour = schedule['m'] && schedule['m'].length <= 2; const oneOrTwoHoursPerDay = schedule['h'] && schedule['h'].length <= 2; const onlySpecificDaysOfMonth = schedule['D'] && schedule['D'].length !== 31; if (oneOrTwoHoursPerDay && oneOrTwoMinutesPerHour && oneOrTwoSecondsPerMinute) { // If there are only one or two specified values for // hour or minute, print them in HH:MM format, or HH:MM:ss if seconds are used // If seconds are not used, later.js returns one element for the seconds (set to zero) const hm = []; // let m = dayjs(new Date()); for (let i = 0; i < schedule['h'].length; i++) { for (let j = 0; j < schedule['m'].length; j++) { for (let k = 0; k < schedule['s'].length; k++) { const s = dayjs() .hour(schedule['h'][i]) .minute(schedule['m'][j]) .second(schedule['s'][k]) .format(useSeconds ? 'HH:mm:ss' : 'HH:mm'); hm.push(s); // m.hour(schedule['h'][i]); // m.minute(schedule['m'][j]); // m.second(schedule['s'][k]); // hm.push(m.format( useSeconds ? 'HH:mm:ss' : 'HH:mm')); } } } if (hm.length < 2) { textParts.push(hm[0]); } else { const last_val = hm.pop(); textParts.push(`${hm.join(', ')} and ${last_val}`); } if (everyWeekday && everyDayInMonth) { textParts.push('every day'); } } else { const seconds = getSecondsTextParts(schedule['s']); const minutes = getMinutesTextParts(schedule['m']); let beginning = ''; let end = ''; textParts.push('Every'); // Otherwise, list out every specified hour/minute value. const hasSpecificSeconds = schedule['s'] && ( schedule['s'].length > 1 && schedule['s'].length < 60 || schedule['s'].length === 1 && schedule['s'][0] !== 0); if (hasSpecificSeconds) { beginning = seconds.beginning; end = seconds.text; } if (schedule['h']) { // runs only at specific hours if (hasSpecificSeconds) { end += ' on the '; } if (schedule['m']) { // and only at specific minutes const hours = `${numberList(schedule['h'])} hour`; if (!hasSpecificSeconds && isOnTheHour(schedule['m'])) { textParts = ['On the']; end += hours; } else { beginning = minutes.beginning; end += `${minutes.text} past the ${hours}`; } } else { // specific hours, but every minute end += `minute of ${numberList(schedule['h'])} hour`; } } else if (schedule['m']) { // every hour, but specific minutes beginning = minutes.beginning; end += minutes.text; if (!isOnTheHour(schedule['m']) && (onlySpecificDaysOfMonth || schedule['d'] || schedule['M'])) { end += ' past every hour'; } } else if (!schedule['s'] && !schedule['m']) { beginning = seconds.beginning; } else if (!useSeconds || !hasSpecificSeconds) { // cronspec has "*" for both hour and minute beginning += minutes.beginning; } textParts.push(beginning); textParts.push(end); } if (onlySpecificDaysOfMonth) { // runs only on specific day(s) of month textParts.push(`on the ${numberList(schedule['D'])}`); if (!schedule['M']) { textParts.push('of every month'); } } if (schedule['d']) { // runs only on specific day(s) of week if (schedule['D']) { // if both day fields are specified, cron uses both; superuser.com/a/348372 textParts.push('and every'); } else { textParts.push('on'); } textParts.push(dateList(schedule['d'], 'dow')); } if (schedule['M']) { if (schedule['M'].length === 12) { textParts.push('day of every month'); } else { // runs only in specific months; put this output last textParts.push(`in ${dateList(schedule['M'], 'mon')}`); } } return textParts.filter(function(p) { return p; }).join(' '); }; // ---------------- // Given a cronspec, return the human-readable string. const toString = function(cronspec: any, sixth: boolean) { const schedule = later.parse.cron(cronspec, sixth); return scheduleToSentence(schedule['schedules'][0], sixth); }; // Given a cronspec, return the next date for when it will next run. // (This is just a wrapper for later.js) const getNextDate = function(cronspec: any, sixth: boolean) { later.date.localTime(); const schedule = later.parse.cron(cronspec, sixth); return later.schedule(schedule).next(); }; // Given a cronspec, return a friendly string for when it will next run. // (This is just a wrapper for later.js and moment.js) const getNext = function(cronspec: any, sixth: boolean) { return dayjs(getNextDate(cronspec, sixth)).calendar(); }; // Given a cronspec and numDates, return a list of formatted dates // of the next set of runs. // (This is just a wrapper for later.js and moment.js) const getNextDates = function(cronspec: any, numDates: any, sixth: boolean) { const schedule = later.parse.cron(cronspec, sixth); const nextDates = later.schedule(schedule).next(numDates); const nextPrettyDates = []; for (let i = 0; i < nextDates.length; i++) { nextPrettyDates.push(dayjs(nextDates[i]).calendar()); } return nextPrettyDates; }; // ---------------- // attach ourselves to window in the browser, and to exports in Node, // so our functions can always be called as prettyCron.toString() const global_obj = (typeof exports !== 'undefined' && exports !== null) ? exports : (window as any).prettyCron = {}; global_obj.toString = toString; global_obj.getNext = getNext; global_obj.getNextDate = getNextDate; global_obj.getNextDates = getNextDates; }).call(this);
the_stack
import React, { useContext, useEffect, useLayoutEffect, useRef, useState } from 'react'; import { xarrowPropsType } from '../types'; import useXarrowProps from './useXarrowProps'; import { XarrowContext } from '../Xwrapper'; import XarrowPropTypes from './propTypes'; import { getPosition } from './utils/GetPosition'; const log = console.log; const Xarrow: React.FC<xarrowPropsType> = (props: xarrowPropsType) => { // log('xarrow update'); const mainRef = useRef({ svgRef: useRef<SVGSVGElement>(null), lineRef: useRef<SVGPathElement>(null), headRef: useRef<SVGElement>(null), tailRef: useRef<SVGElement>(null), lineDrawAnimRef: useRef<SVGElement>(null), lineDashAnimRef: useRef<SVGElement>(null), headOpacityAnimRef: useRef<SVGElement>(null), }); const { svgRef, lineRef, headRef, tailRef, lineDrawAnimRef, lineDashAnimRef, headOpacityAnimRef } = mainRef.current; useContext(XarrowContext); const xProps = useXarrowProps(props, mainRef.current); const [propsRefs] = xProps; let { labels, lineColor, headColor, tailColor, strokeWidth, showHead, showTail, dashness, headShape, tailShape, showXarrow, animateDrawing, zIndex, passProps, arrowBodyProps, arrowHeadProps, arrowTailProps, SVGcanvasProps, divContainerProps, divContainerStyle, SVGcanvasStyle, _debug, shouldUpdatePosition, } = propsRefs; animateDrawing = props.animateDrawing as number; const [drawAnimEnded, setDrawAnimEnded] = useState(!animateDrawing); const [, setRender] = useState({}); const forceRerender = () => setRender({}); const [st, setSt] = useState({ //initial state cx0: 0, //x start position of the canvas cy0: 0, //y start position of the canvas cw: 0, // the canvas width ch: 0, // the canvas height x1: 0, //the x starting point of the line inside the canvas y1: 0, //the y starting point of the line inside the canvas x2: 0, //the x ending point of the line inside the canvas y2: 0, //the y ending point of the line inside the canvas dx: 0, // the x difference between 'start' anchor to 'end' anchor dy: 0, // the y difference between 'start' anchor to 'end' anchor absDx: 0, // the x length(positive) difference absDy: 0, // the y length(positive) difference cpx1: 0, // control points - control the curviness of the line cpy1: 0, cpx2: 0, cpy2: 0, headOrient: 0, // determines to what side the arrowhead will point tailOrient: 0, // determines to what side the arrow tail will point arrowHeadOffset: { x: 0, y: 0 }, arrowTailOffset: { x: 0, y: 0 }, headOffset: 0, excRight: 0, //expand canvas to the right excLeft: 0, //expand canvas to the left excUp: 0, //expand canvas upwards excDown: 0, // expand canvas downward startPoints: [], endPoints: [], mainDivPos: { x: 0, y: 0 }, xSign: 1, ySign: 1, lineLength: 0, fHeadSize: 1, fTailSize: 1, arrowPath: ``, labelStartPos: { x: 0, y: 0 }, labelMiddlePos: { x: 0, y: 0 }, labelEndPos: { x: 0, y: 0 }, }); /** * The Main logic of path calculation for the arrow. * calculate new path, adjusting canvas, and set state based on given properties. * */ useLayoutEffect(() => { if (shouldUpdatePosition.current) { // log('xarrow getPosition'); const pos = getPosition(xProps, mainRef); // log('pos', pos); setSt(pos); shouldUpdatePosition.current = false; } }); // log('st', st); const xOffsetHead = st.x2 - st.arrowHeadOffset.x; const yOffsetHead = st.y2 - st.arrowHeadOffset.y; const xOffsetTail = st.x1 - st.arrowTailOffset.x; const yOffsetTail = st.y1 - st.arrowTailOffset.y; let dashoffset = dashness.strokeLen + dashness.nonStrokeLen; let animDirection = 1; if (dashness.animation < 0) { dashness.animation *= -1; animDirection = -1; } let dashArray, animation, animRepeatCount, animStartValue, animEndValue = 0; if (animateDrawing && drawAnimEnded == false) { if (typeof animateDrawing === 'boolean') animateDrawing = 1; animation = animateDrawing + 's'; dashArray = st.lineLength; animStartValue = st.lineLength; animRepeatCount = 1; if (animateDrawing < 0) { [animStartValue, animEndValue] = [animEndValue, animStartValue]; animation = animateDrawing * -1 + 's'; } } else { dashArray = `${dashness.strokeLen} ${dashness.nonStrokeLen}`; animation = `${1 / dashness.animation}s`; animStartValue = dashoffset * animDirection; animRepeatCount = 'indefinite'; animEndValue = 0; } // handle draw animation useLayoutEffect(() => { if (lineRef.current) setSt((prevSt) => ({ ...prevSt, lineLength: lineRef.current?.getTotalLength() ?? 0 })); }, [lineRef.current]); // set all props on first render useEffect(() => { const monitorDOMchanges = () => { window.addEventListener('resize', forceRerender); const handleDrawAmimEnd = () => { setDrawAnimEnded(true); // @ts-ignore headOpacityAnimRef.current?.beginElement(); // @ts-ignore lineDashAnimRef.current?.beginElement(); }; const handleDrawAmimBegin = () => (headRef.current.style.opacity = '0'); if (lineDrawAnimRef.current && headRef.current) { lineDrawAnimRef.current.addEventListener('endEvent', handleDrawAmimEnd); lineDrawAnimRef.current.addEventListener('beginEvent', handleDrawAmimBegin); } return () => { window.removeEventListener('resize', forceRerender); if (lineDrawAnimRef.current) { lineDrawAnimRef.current.removeEventListener('endEvent', handleDrawAmimEnd); if (headRef.current) lineDrawAnimRef.current.removeEventListener('beginEvent', handleDrawAmimBegin); } }; }; const cleanMonitorDOMchanges = monitorDOMchanges(); return () => { setDrawAnimEnded(false); cleanMonitorDOMchanges(); }; }, [showXarrow]); //todo: could make some advanced generic typescript inferring. for example get type from headShape.elem:T and // tailShape.elem:K force the type for passProps,arrowHeadProps,arrowTailProps property. for now `as any` is used to // avoid typescript conflicts // so todo- fix all the `passProps as any` assertions return ( <div {...divContainerProps} style={{ position: 'absolute', zIndex, ...divContainerStyle }}> {showXarrow ? ( <> <svg ref={svgRef} width={st.cw} height={st.ch} style={{ position: 'absolute', left: st.cx0, top: st.cy0, pointerEvents: 'none', border: _debug ? '1px dashed yellow' : null, ...SVGcanvasStyle, }} overflow="auto" {...SVGcanvasProps}> {/* body of the arrow */} <path ref={lineRef} d={st.arrowPath} stroke={lineColor} strokeDasharray={dashArray} // strokeDasharray={'0 0'} strokeWidth={strokeWidth} fill="transparent" pointerEvents="visibleStroke" {...(passProps as any)} {...arrowBodyProps}> <> {drawAnimEnded ? ( <> {/* moving dashed line animation */} {dashness.animation ? ( <animate ref={lineDashAnimRef} attributeName="stroke-dashoffset" values={`${dashoffset * animDirection};0`} dur={`${1 / dashness.animation}s`} repeatCount="indefinite" /> ) : null} </> ) : ( <> {/* the creation of the line animation */} {animateDrawing ? ( <animate ref={lineDrawAnimRef} id={`svgEndAnimate`} attributeName="stroke-dashoffset" values={`${animStartValue};${animEndValue}`} dur={animation} repeatCount={animRepeatCount} /> ) : null} </> )} </> </path> {/* arrow tail */} {showTail ? ( <g fill={tailColor} pointerEvents="auto" transform={`translate(${xOffsetTail},${yOffsetTail}) rotate(${st.tailOrient}) scale(${st.fTailSize})`} {...(passProps as any)} {...arrowTailProps}> {tailShape.svgElem} </g> ) : null} {/* head of the arrow */} {showHead ? ( <g ref={headRef as any} // d={normalArrowShape} fill={headColor} pointerEvents="auto" transform={`translate(${xOffsetHead},${yOffsetHead}) rotate(${st.headOrient}) scale(${st.fHeadSize})`} opacity={animateDrawing && !drawAnimEnded ? 0 : 1} {...(passProps as any)} {...arrowHeadProps}> <animate ref={headOpacityAnimRef} dur={'0.4'} attributeName="opacity" from="0" to="1" begin={`indefinite`} repeatCount="0" fill="freeze" /> {headShape.svgElem} </g> ) : null} {/* debug elements */} {_debug ? ( <> {/* control points circles */} <circle r="5" cx={st.cpx1} cy={st.cpy1} fill="green" /> <circle r="5" cx={st.cpx2} cy={st.cpy2} fill="blue" /> {/* start to end rectangle wrapper */} <rect x={st.excLeft} y={st.excUp} width={st.absDx} height={st.absDy} fill="none" stroke="pink" strokeWidth="2px" /> </> ) : null} </svg> {labels.start ? ( <div style={{ transform: st.dx < 0 ? 'translate(-100% , -50%)' : 'translate(-0% , -50%)', width: 'max-content', position: 'absolute', left: st.cx0 + st.labelStartPos.x, top: st.cy0 + st.labelStartPos.y - strokeWidth - 5, }}> {labels.start} </div> ) : null} {labels.middle ? ( <div style={{ display: 'table', width: 'max-content', transform: 'translate(-50% , -50%)', position: 'absolute', left: st.cx0 + st.labelMiddlePos.x, top: st.cy0 + st.labelMiddlePos.y, }}> {labels.middle} </div> ) : null} {labels.end ? ( <div style={{ transform: st.dx > 0 ? 'translate(-100% , -50%)' : 'translate(-0% , -50%)', width: 'max-content', position: 'absolute', left: st.cx0 + st.labelEndPos.x, top: st.cy0 + st.labelEndPos.y + strokeWidth + 5, }}> {labels.end} </div> ) : null} {_debug ? ( <> {/* possible anchor connections */} {[...st.startPoints, ...st.endPoints].map((p, i) => { return ( <div key={i} style={{ background: 'gray', opacity: 0.5, borderRadius: '50%', transform: 'translate(-50%, -50%)', height: 5, width: 5, position: 'absolute', left: p.x - st.mainDivPos.x, top: p.y - st.mainDivPos.y, }} /> ); })} </> ) : null} </> ) : null} </div> ); }; ////////////////////////////// // propTypes Xarrow.propTypes = XarrowPropTypes; export default Xarrow;
the_stack
import { expect } from "chai"; import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend"; import { ContentSpecificationTypes, KeySet, Ruleset, RuleTypes } from "@itwin/presentation-common"; import { Presentation } from "@itwin/presentation-frontend"; import { initialize, terminate } from "../../../IntegrationTests"; import { printRuleset } from "../../Utils"; describe("Learning Snippets", () => { let imodel: IModelConnection; beforeEach(async () => { await initialize(); imodel = await SnapshotConnection.openFile("assets/datasets/Properties_60InstancesWithUrl2.ibim"); }); afterEach(async () => { await imodel.close(); await terminate(); }); describe("Content Customization", () => { describe("PropertyCategorySpecification", () => { it("allows referencing by `id`", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.Id.Ruleset // There's a content rule for returning content of given `bis.Subject` instance. The rule contains a custom // category specification that is referenced by properties override, putting all properties into the // "Custom" category. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.SelectedNodeInstances, propertyCategories: [{ id: "custom-category", label: "Custom", }], propertyOverrides: [{ name: "*", categoryId: "custom-category", }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure the field is assigned a category with correct label const content = (await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]), descriptor: {}, }))!; expect(content.descriptor.fields.length).to.be.greaterThan(0); content.descriptor.fields.forEach((field) => { expect(field.category).to.containSubset({ label: "Custom", }); }); }); it("uses `label` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.Label.Ruleset // There's a content rule for returning content of given `bis.Subject` instance. In addition, // it puts all properties into a custom category with "Custom Category" label. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.SelectedNodeInstances, propertyCategories: [{ id: "custom-category", label: "Custom Category", }], propertyOverrides: [{ name: "*", categoryId: "custom-category", }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure the field is assigned a category with correct label const content = (await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]), descriptor: {}, }))!; expect(content.descriptor.fields.length).to.be.greaterThan(0); content.descriptor.fields.forEach((field) => { expect(field.category).to.containSubset({ label: "Custom Category", }); }); }); it("uses `description` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.Description.Ruleset // There's a content rule for returning content of given `bis.Subject` instance. In addition, it puts // all properties into a custom category with a description. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.SelectedNodeInstances, propertyCategories: [{ id: "custom-category", label: "Custom Category", description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", }], propertyOverrides: [{ name: "*", categoryId: "custom-category", }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.Description.Result // Ensure category description is assigned const content = (await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]), descriptor: {}, }))!; expect(content.descriptor.categories).to.containSubset([{ label: "Custom Category", description: "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", }]); // __PUBLISH_EXTRACT_END__ }); it("uses `parentId` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.ParentId.Ruleset // There's a content rule for returning content of given `bis.Subject` instance. In addition, it // puts all properties into a custom category with "Nested Category" label which in turn is put into "Root Category". const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.SelectedNodeInstances, propertyCategories: [{ id: "root-category", label: "Root Category", }, { id: "nested-category", parentId: "root-category", label: "Nested Category", }], propertyOverrides: [{ name: "*", categoryId: "nested-category", }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Ensure categories' hierarchy was set up correctly const content = (await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]), descriptor: {}, }))!; expect(content.descriptor.fields.length).to.be.greaterThan(0); content.descriptor.fields.forEach((field) => { expect(field.category).to.containSubset({ label: "Nested Category", parent: { label: "Root Category", }, }); }); }); it("uses `priority` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.Priority.Ruleset // There's a content rule for returning content of given `bis.Subject` instance. The produced content // is customized to put `CodeValue` property into "Category A" category and `UserLabel` property into // "Category B" category. Both categories are assigned custom priorities. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.SelectedNodeInstances, propertyOverrides: [{ name: "CodeValue", categoryId: "category-a", }, { name: "UserLabel", categoryId: "category-b", }], propertyCategories: [{ id: "category-a", label: "Category A", priority: 1, }, { id: "category-b", label: "Category B", priority: 2, }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.Priority.Result // Ensure that correct category priorities are assigned const content = (await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]), descriptor: {}, }))!; expect(content.descriptor.fields).to.containSubset([{ label: "Code", category: { label: "Category A", priority: 1, }, }]); expect(content.descriptor.fields).to.containSubset([{ label: "User Label", category: { label: "Category B", priority: 2, }, }]); // __PUBLISH_EXTRACT_END__ }); it("uses `autoExpand` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.AutoExpand.Ruleset // There's a content rule for returning content of given `bis.Subject` instance. The produced content // is customized to put all properties into a custom category which has the `autoExpand` flag. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.SelectedNodeInstances, propertyOverrides: [{ name: "*", categoryId: "custom-category", }], propertyCategories: [{ id: "custom-category", label: "Custom Category", autoExpand: true, }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.AutoExpand.Result // Ensure that categories have the `expand` flag const content = (await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]), descriptor: {}, }))!; expect(content.descriptor.categories).to.containSubset([{ label: "Custom Category", expand: true, }]); // __PUBLISH_EXTRACT_END__ }); it("uses `renderer` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.Renderer.Ruleset // There's a content rule for returning content of given instance. The produced content // is customized to put all properties into a custom category which uses a custom "my-category-renderer" // renderer. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.SelectedNodeInstances, propertyOverrides: [{ name: "*", categoryId: "custom-category", }], propertyCategories: [{ id: "custom-category", label: "Custom Category", renderer: { rendererName: "my-category-renderer", }, }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // __PUBLISH_EXTRACT_START__ Presentation.Content.Customization.PropertyCategorySpecification.Renderer.Result // Ensure that categories have the `expand` flag const content = (await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet([{ className: "BisCore:Subject", id: "0x1" }]), descriptor: {}, }))!; expect(content.descriptor.categories).to.containSubset([{ label: "Custom Category", renderer: { name: "my-category-renderer", }, }]); // __PUBLISH_EXTRACT_END__ }); }); }); });
the_stack
"use strict"; import { objCreateFn } from "@microsoft/applicationinsights-shims"; import dynamicProto from "@microsoft/dynamicproto-js"; import { IAppInsightsCore, ILoadedPlugin } from "../JavaScriptSDK.Interfaces/IAppInsightsCore" import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; import { IPlugin, ITelemetryPlugin } from "../JavaScriptSDK.Interfaces/ITelemetryPlugin"; import { IChannelControls } from "../JavaScriptSDK.Interfaces/IChannelControls"; import { ITelemetryItem } from "../JavaScriptSDK.Interfaces/ITelemetryItem"; import { INotificationManager } from "../JavaScriptSDK.Interfaces/INotificationManager"; import { INotificationListener } from "../JavaScriptSDK.Interfaces/INotificationListener"; import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger"; import { IProcessTelemetryContext, IProcessTelemetryUpdateContext } from "../JavaScriptSDK.Interfaces/IProcessTelemetryContext"; import { createProcessTelemetryContext, createProcessTelemetryUnloadContext, createProcessTelemetryUpdateContext, createTelemetryProxyChain } from "./ProcessTelemetryContext"; import { createDistributedTraceContext, initializePlugins, sortPlugins, _getPluginState } from "./TelemetryHelpers"; import { eLoggingSeverity, _eInternalMessageId } from "../JavaScriptSDK.Enums/LoggingEnums"; import { IPerfManager } from "../JavaScriptSDK.Interfaces/IPerfManager"; import { getGblPerfMgr, PerfManager } from "./PerfManager"; import { ICookieMgr } from "../JavaScriptSDK.Interfaces/ICookieMgr"; import { createCookieMgr } from "./CookieMgr"; import { arrForEach, isNullOrUndefined, getSetValue, setValue, isNotTruthy, isFunction, objExtend, objFreeze, proxyFunctionAs, proxyFunctions, throwError, toISOString, arrIndexOf } from "./HelperFuncs"; import { strExtensionConfig, strIKey } from "./Constants"; import { DiagnosticLogger, _InternalLogMessage, _throwInternal, _warnToConsole } from "./DiagnosticLogger"; import { getDebugListener } from "./DbgExtensionUtils"; import { ITelemetryPluginChain } from "../JavaScriptSDK.Interfaces/ITelemetryPluginChain"; import { ChannelControllerPriority, createChannelControllerPlugin, createChannelQueues, IChannelController, IInternalChannelController, _IInternalChannels } from "./ChannelController"; import { ITelemetryInitializerHandler, TelemetryInitializerFunction } from "../JavaScriptSDK.Interfaces/ITelemetryInitializers"; import { TelemetryInitializerPlugin } from "./TelemetryInitializerPlugin"; import { createUniqueNamespace } from "./DataCacheHelper"; import { createUnloadHandlerContainer, IUnloadHandlerContainer, UnloadHandler } from "./UnloadHandlerContainer"; import { TelemetryUpdateReason } from "../JavaScriptSDK.Enums/TelemetryUpdateReason"; import { ITelemetryUpdateState } from "../JavaScriptSDK.Interfaces/ITelemetryUpdateState"; import { ITelemetryUnloadState } from "../JavaScriptSDK.Interfaces/ITelemetryUnloadState"; import { TelemetryUnloadReason } from "../JavaScriptSDK.Enums/TelemetryUnloadReason"; import { SendRequestReason } from "../JavaScriptSDK.Enums/SendRequestReason"; import { strAddNotificationListener, strDisabled, strEventsDiscarded, strEventsSendRequest, strEventsSent, strRemoveNotificationListener, strTeardown } from "./InternalConstants"; import { IDistributedTraceContext } from "../JavaScriptSDK.Interfaces/IDistributedTraceContext"; const strValidationError = "Plugins must provide initialize method"; const strNotificationManager = "_notificationManager"; const strSdkUnloadingError = "SDK is still unloading..."; const strSdkNotInitialized = "SDK is not initialized"; // const strPluginUnloadFailed = "Failed to unload plugin"; const defaultInitConfig = { // Have the Diagnostic Logger default to log critical errors to the console loggingLevelConsole: eLoggingSeverity.CRITICAL }; /** * Helper to create the default performance manager * @param core * @param notificationMgr */ function _createPerfManager (core: IAppInsightsCore, notificationMgr: INotificationManager) { return new PerfManager(notificationMgr); } function _validateExtensions(logger: IDiagnosticLogger, channelPriority: number, allExtensions: IPlugin[]): { all: IPlugin[]; core: ITelemetryPlugin[] } { // Concat all available extensions let coreExtensions: ITelemetryPlugin[] = []; // Check if any two extensions have the same priority, then warn to console // And extract the local extensions from the let extPriorities = {}; // Extension validation arrForEach(allExtensions, (ext: ITelemetryPlugin) => { if (isNullOrUndefined(ext) || isNullOrUndefined(ext.initialize)) { throwError(strValidationError); } const extPriority = ext.priority; const identifier = ext.identifier; if (ext && extPriority) { if (!isNullOrUndefined(extPriorities[extPriority])) { _warnToConsole(logger, "Two extensions have same priority #" + extPriority + " - " + extPriorities[extPriority] + ", " + identifier); } else { // set a value extPriorities[extPriority] = identifier; } } // Split extensions to core and channelController if (!extPriority || extPriority < channelPriority) { // Add to core extension that will be managed by BaseCore coreExtensions.push(ext); } }); return { all: allExtensions, core: coreExtensions }; } function _isPluginPresent(thePlugin: IPlugin, plugins: IPlugin[]) { let exists = false; arrForEach(plugins, (plugin) => { if (plugin === thePlugin) { exists = true; return -1; } }); return exists; } function _createDummyNotificationManager(): INotificationManager { return objCreateFn({ [strAddNotificationListener]: (listener: INotificationListener) => { }, [strRemoveNotificationListener]: (listener: INotificationListener) => { }, [strEventsSent]: (events: ITelemetryItem[]) => { }, [strEventsDiscarded]: (events: ITelemetryItem[], reason: number) => { }, [strEventsSendRequest]: (sendReason: number, isAsync: boolean) => { } }); } export class BaseCore implements IAppInsightsCore { public static defaultConfig: IConfiguration; public config: IConfiguration; public logger: IDiagnosticLogger; public _extensions: IPlugin[]; public isInitialized: () => boolean; constructor() { // NOTE!: DON'T set default values here, instead set them in the _initDefaults() function as it is also called during teardown() let _isInitialized: boolean; let _eventQueue: ITelemetryItem[]; let _notificationManager: INotificationManager | null | undefined; let _perfManager: IPerfManager | null; let _cfgPerfManager: IPerfManager | null; let _cookieManager: ICookieMgr | null; let _pluginChain: ITelemetryPluginChain | null; let _configExtensions: IPlugin[]; let _coreExtensions: ITelemetryPlugin[] | null; let _channelControl: IChannelController | null; let _channelConfig: IChannelControls[][] | null | undefined; let _channelQueue: _IInternalChannels[] | null; let _isUnloading: boolean; let _telemetryInitializerPlugin: TelemetryInitializerPlugin; let _internalLogsEventName: string | null; let _evtNamespace: string; let _unloadHandlers: IUnloadHandlerContainer; let _debugListener: INotificationListener | null; let _traceCtx: IDistributedTraceContext | null; /** * Internal log poller */ let _internalLogPoller: number = 0; dynamicProto(BaseCore, this, (_self) => { // Set the default values (also called during teardown) _initDefaults(); _self.isInitialized = () => _isInitialized; _self.initialize = (config: IConfiguration, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void => { if (_isUnloading) { throwError(strSdkUnloadingError); } // Make sure core is only initialized once if (_self.isInitialized()) { throwError("Core should not be initialized more than once"); } if (!config || isNullOrUndefined(config.instrumentationKey)) { throwError("Please provide instrumentation key"); } _notificationManager = notificationManager; // For backward compatibility only _self[strNotificationManager] = notificationManager; _self.config = config || {}; _initDebugListener(config); _initPerfManager(config); config.extensions = isNullOrUndefined(config.extensions) ? [] : config.extensions; // add notification to the extensions in the config so other plugins can access it _initExtConfig(config); if (logger) { _self.logger = logger; } // Extension validation _configExtensions = []; _configExtensions.push(...extensions, ...config.extensions); _channelConfig = (config||{}).channels; _initPluginChain(config, null); if (!_channelQueue || _channelQueue.length === 0) { throwError("No channels available"); } _isInitialized = true; _self.releaseQueue(); }; _self.getTransmissionControls = (): IChannelControls[][] => { let controls: IChannelControls[][] = []; if (_channelQueue) { arrForEach(_channelQueue, (channels) => { controls.push(channels.queue); }); } return objFreeze(controls); }; _self.track = (telemetryItem: ITelemetryItem) => { // setup default iKey if not passed in setValue(telemetryItem, strIKey, _self.config.instrumentationKey, null, isNotTruthy); // add default timestamp if not passed in setValue(telemetryItem, "time", toISOString(new Date()), null, isNotTruthy); // Common Schema 4.0 setValue(telemetryItem, "ver", "4.0", null, isNullOrUndefined); if (!_isUnloading && _self.isInitialized()) { // Process the telemetry plugin chain _createTelCtx().processNext(telemetryItem); } else { // Queue events until all extensions are initialized _eventQueue.push(telemetryItem); } }; _self.getProcessTelContext = _createTelCtx; _self.getNotifyMgr = (): INotificationManager => { if (!_notificationManager) { // Create Dummy notification manager _notificationManager = _createDummyNotificationManager(); // For backward compatibility only _self[strNotificationManager] = _notificationManager; } return _notificationManager; }; /** * Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised. * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be * called. * @param {INotificationListener} listener - An INotificationListener object. */ _self[strAddNotificationListener] = (listener: INotificationListener): void => { if (_notificationManager) { _notificationManager[strAddNotificationListener](listener); } }; /** * Removes all instances of the listener. * @param {INotificationListener} listener - INotificationListener to remove. */ _self[strRemoveNotificationListener] = (listener: INotificationListener): void => { if (_notificationManager) { _notificationManager[strRemoveNotificationListener](listener); } } _self.getCookieMgr = (): ICookieMgr => { if (!_cookieManager) { _cookieManager = createCookieMgr(_self.config, _self.logger); } return _cookieManager; }; _self.setCookieMgr = (cookieMgr: ICookieMgr) => { _cookieManager = cookieMgr; }; _self.getPerfMgr = (): IPerfManager => { if (!_perfManager && !_cfgPerfManager) { if (_self.config && _self.config.enablePerfMgr && isFunction(_self.config.createPerfMgr)) { _cfgPerfManager = _self.config.createPerfMgr(_self, _self.getNotifyMgr()); } } return _perfManager || _cfgPerfManager || getGblPerfMgr(); }; _self.setPerfMgr = (perfMgr: IPerfManager) => { _perfManager = perfMgr; }; _self.eventCnt = (): number => { return _eventQueue.length; }; _self.releaseQueue = () => { if (_isInitialized && _eventQueue.length > 0) { let eventQueue = _eventQueue; _eventQueue = []; arrForEach(eventQueue, (event: ITelemetryItem) => { _createTelCtx().processNext(event); }); } }; /** * Periodically check logger.queue for log messages to be flushed */ _self.pollInternalLogs = (eventName?: string): number => { _internalLogsEventName = eventName || null; let interval = _self.config.diagnosticLogInterval; if (!interval || !(interval > 0)) { interval = 10000; } if(_internalLogPoller) { clearInterval(_internalLogPoller); } _internalLogPoller = setInterval(() => { _flushInternalLogs(); }, interval) as any; return _internalLogPoller; } /** * Stop polling log messages from logger.queue */ _self.stopPollingInternalLogs = (): void => { if(_internalLogPoller) { clearInterval(_internalLogPoller); _internalLogPoller = 0; _flushInternalLogs(); } } // Add addTelemetryInitializer proxyFunctions(_self, () => _telemetryInitializerPlugin, [ "addTelemetryInitializer" ]); _self.unload = (isAsync: boolean = true, unloadComplete?: (unloadState: ITelemetryUnloadState) => void, cbTimeout?: number): void => { if (!_isInitialized) { // The SDK is not initialized throwError(strSdkNotInitialized); } // Check if the SDK still unloading so throw if (_isUnloading) { // The SDK is already unloading throwError(strSdkUnloadingError); } let unloadState: ITelemetryUnloadState = { reason: TelemetryUnloadReason.SdkUnload, isAsync: isAsync, flushComplete: false } let processUnloadCtx = createProcessTelemetryUnloadContext(_getPluginChain(), _self); processUnloadCtx.onComplete(() => { _initDefaults(); unloadComplete && unloadComplete(unloadState); }, _self); function _doUnload(flushComplete: boolean) { unloadState.flushComplete = flushComplete; _isUnloading = true; // Run all of the unload handlers first (before unloading the plugins) _unloadHandlers.run(processUnloadCtx, unloadState); // Stop polling the internal logs _self.stopPollingInternalLogs(); // Start unloading the components, from this point onwards the SDK should be considered to be in an unstable state processUnloadCtx.processNext(unloadState); } if (!_flushChannels(isAsync, _doUnload, SendRequestReason.SdkUnload, cbTimeout)) { _doUnload(false); } }; _self.getPlugin = _getPlugin; _self.addPlugin = <T extends IPlugin = ITelemetryPlugin>(plugin: T, replaceExisting?: boolean, isAsync?: boolean, addCb?: (added?: boolean) => void): void => { if (!plugin) { addCb && addCb(false); _logOrThrowError(strValidationError); return; } let existingPlugin = _getPlugin(plugin.identifier); if (existingPlugin && !replaceExisting) { addCb && addCb(false); _logOrThrowError("Plugin [" + plugin.identifier + "] is already loaded!"); return; } let updateState: ITelemetryUpdateState = { reason: TelemetryUpdateReason.PluginAdded }; function _addPlugin(removed: boolean) { _configExtensions.push(plugin); updateState.added = [plugin]; // Re-Initialize the plugin chain _initPluginChain(_self.config, updateState); addCb && addCb(true); } if (existingPlugin) { let removedPlugins: IPlugin[] = [existingPlugin.plugin]; let unloadState: ITelemetryUnloadState = { reason: TelemetryUnloadReason.PluginReplace, isAsync: !!isAsync }; _removePlugins(removedPlugins, unloadState, (removed) => { if (!removed) { // Previous plugin was successfully removed or was not installed addCb && addCb(false); } else { updateState.removed = removedPlugins updateState.reason |= TelemetryUpdateReason.PluginRemoved; _addPlugin(true); } }); } else { _addPlugin(false); } }; _self.evtNamespace = (): string => { return _evtNamespace; }; _self.flush = _flushChannels; _self.getTraceCtx = (createNew?: boolean): IDistributedTraceContext | null => { if (!_traceCtx) { _traceCtx = createDistributedTraceContext(); } return _traceCtx; }; _self.setTraceCtx = (traceCtx: IDistributedTraceContext): void => { _traceCtx = traceCtx || null; }; // Create the addUnloadCb proxyFunctionAs(_self, "addUnloadCb", () => _unloadHandlers, "add"); function _initDefaults() { _isInitialized = false; // Use a default logger so initialization errors are not dropped on the floor with full logging _self.config = objExtend(true, {}, defaultInitConfig); _self.logger = new DiagnosticLogger(_self.config); _self._extensions = []; _telemetryInitializerPlugin = new TelemetryInitializerPlugin(); _eventQueue = []; _notificationManager = null; _perfManager = null; _cfgPerfManager = null; _cookieManager = null; _pluginChain = null; _coreExtensions = null; _configExtensions = []; _channelControl = null; _channelConfig = null; _channelQueue = null; _isUnloading = false; _internalLogsEventName = null; _evtNamespace = createUniqueNamespace("AIBaseCore", true); _unloadHandlers = createUnloadHandlerContainer(); _traceCtx = null; } function _createTelCtx(): IProcessTelemetryContext { return createProcessTelemetryContext(_getPluginChain(), _self.config, _self); } // Initialize or Re-initialize the plugins function _initPluginChain(config: IConfiguration, updateState: ITelemetryUpdateState | null) { // Extension validation let theExtensions = _validateExtensions(_self.logger, ChannelControllerPriority, _configExtensions); _coreExtensions = theExtensions.core; _pluginChain = null; // Sort the complete set of extensions by priority let allExtensions = theExtensions.all; // Initialize the Channel Queues and the channel plugins first _channelQueue = objFreeze(createChannelQueues(_channelConfig, allExtensions, config, _self)); if (_channelControl) { // During add / remove of a plugin this may get called again, so don't re-add if already present // But we also want the controller as the last, so remove if already present // And reusing the existing instance, just in case an installed plugin has a reference and // is using it. let idx = arrIndexOf(allExtensions, _channelControl); if (idx !== -1) { allExtensions.splice(idx, 1); } idx = arrIndexOf(_coreExtensions, _channelControl); if (idx !== -1) { _coreExtensions.splice(idx, 1); } (_channelControl as IInternalChannelController)._setQueue(_channelQueue); } else { _channelControl = createChannelControllerPlugin(_channelQueue, _self); } // Add on "channelController" as the last "plugin" allExtensions.push(_channelControl); _coreExtensions.push(_channelControl); // Required to allow plugins to call core.getPlugin() during their own initialization _self._extensions = sortPlugins(allExtensions); // Initialize the controls _channelControl.initialize(config, _self, allExtensions); initializePlugins(_createTelCtx(), allExtensions); // Now reset the extensions to just those being managed by Basecore _self._extensions = objFreeze(sortPlugins(_coreExtensions || [])).slice(); if (updateState) { _doUpdate(updateState); } } function _getPlugin<T extends IPlugin = IPlugin>(pluginIdentifier: string): ILoadedPlugin<T> { let theExt: ILoadedPlugin<T> = null; let thePlugin: IPlugin = null; arrForEach(_self._extensions, (ext: any) => { if (ext.identifier === pluginIdentifier && ext !== _channelControl && ext !== _telemetryInitializerPlugin) { thePlugin = ext; return -1; } }); if (!thePlugin && _channelControl) { // Check the channel Controller thePlugin = _channelControl.getChannel(pluginIdentifier); } if (thePlugin) { theExt = { plugin: thePlugin as T, setEnabled: (enabled: boolean) => { _getPluginState(thePlugin)[strDisabled] = !enabled; }, isEnabled: () => { let pluginState = _getPluginState(thePlugin); return !pluginState[strTeardown] && !pluginState[strDisabled]; }, remove: (isAsync: boolean = true, removeCb?: (removed?: boolean) => void): void => { let pluginsToRemove: IPlugin[] = [thePlugin]; let unloadState: ITelemetryUnloadState = { reason: TelemetryUnloadReason.PluginUnload, isAsync: isAsync }; _removePlugins(pluginsToRemove, unloadState, (removed) => { if (removed) { // Re-Initialize the plugin chain _initPluginChain(_self.config, { reason: TelemetryUpdateReason.PluginRemoved, removed: pluginsToRemove }); } removeCb && removeCb(removed); }); } } } return theExt; } function _getPluginChain() { if (!_pluginChain) { // copy the collection of extensions let extensions = (_coreExtensions || []).slice(); // During add / remove this may get called again, so don't readd if already present if (arrIndexOf(extensions, _telemetryInitializerPlugin) === -1) { extensions.push(_telemetryInitializerPlugin); } _pluginChain = createTelemetryProxyChain(sortPlugins(extensions), _self.config, _self); } return _pluginChain; } function _removePlugins(thePlugins: IPlugin[], unloadState: ITelemetryUnloadState, removeComplete: (removed: boolean) => void) { if (thePlugins && thePlugins.length > 0) { let unloadChain = createTelemetryProxyChain(thePlugins, _self.config, _self); let unloadCtx = createProcessTelemetryUnloadContext(unloadChain, _self); unloadCtx.onComplete(() => { let removed = false; // Remove the listed config extensions let newConfigExtensions: IPlugin[] = []; arrForEach(_configExtensions, (plugin, idx) => { if (!_isPluginPresent(plugin, thePlugins)) { newConfigExtensions.push(plugin); } else { removed = true; } }); _configExtensions = newConfigExtensions; // Re-Create the channel config let newChannelConfig: IChannelControls[][] = []; if (_channelConfig) { arrForEach(_channelConfig, (queue, idx) => { let newQueue: IChannelControls[] = []; arrForEach(queue, (channel) => { if (!_isPluginPresent(channel, thePlugins)) { newQueue.push(channel); } else { removed = true; } }); newChannelConfig.push(newQueue); }); _channelConfig = newChannelConfig; } removeComplete && removeComplete(removed); }); unloadCtx.processNext(unloadState); } else { removeComplete(false); } } function _flushInternalLogs() { let queue: _InternalLogMessage[] = _self.logger ? _self.logger.queue : []; if (queue) { arrForEach(queue, (logMessage: _InternalLogMessage) => { const item: ITelemetryItem = { name: _internalLogsEventName ? _internalLogsEventName : "InternalMessageId: " + logMessage.messageId, iKey: _self.config.instrumentationKey, time: toISOString(new Date()), baseType: _InternalLogMessage.dataType, baseData: { message: logMessage.message } }; _self.track(item); }); queue.length = 0; } } function _flushChannels(isAsync?: boolean, callBack?: (flushComplete?: boolean) => void, sendReason?: SendRequestReason, cbTimeout?: number) { if (_channelControl) { return _channelControl.flush(isAsync, callBack, sendReason || SendRequestReason.SdkUnload, cbTimeout); } callBack && callBack(false); return true; } function _initDebugListener(config: IConfiguration) { if (config.disableDbgExt === true && _debugListener) { // Remove any previously loaded debug listener _notificationManager[strRemoveNotificationListener](_debugListener); _debugListener = null; } if (_notificationManager && !_debugListener && config.disableDbgExt !== true) { _debugListener = getDebugListener(config); _notificationManager[strAddNotificationListener](_debugListener); } } function _initPerfManager(config: IConfiguration) { if (!config.enablePerfMgr && _cfgPerfManager) { // Remove any existing config based performance manager _cfgPerfManager = null; } if (config.enablePerfMgr) { // Set the performance manager creation function if not defined setValue(_self.config, "createPerfMgr", _createPerfManager); } } function _initExtConfig(config: IConfiguration) { let extConfig = getSetValue(config, strExtensionConfig); extConfig.NotificationManager = _notificationManager; } function _doUpdate(updateState: ITelemetryUpdateState): void { let updateCtx = createProcessTelemetryUpdateContext(_getPluginChain(), _self); if (!_self._updateHook || _self._updateHook(updateCtx, updateState) !== true) { updateCtx.processNext(updateState); } } function _logOrThrowError(message: string) { let logger = _self.logger; if (logger) { // there should always be a logger _throwInternal(logger, eLoggingSeverity.WARNING, _eInternalMessageId.PluginException, message); } else { throwError(message); } } }); } public initialize(config: IConfiguration, extensions: IPlugin[], logger?: IDiagnosticLogger, notificationManager?: INotificationManager): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } public getTransmissionControls(): IChannelControls[][] { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return null; } public track(telemetryItem: ITelemetryItem) { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } public getProcessTelContext(): IProcessTelemetryContext { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return null; } public getNotifyMgr(): INotificationManager { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return null; } /** * Adds a notification listener. The SDK calls methods on the listener when an appropriate notification is raised. * The added plugins must raise notifications. If the plugins do not implement the notifications, then no methods will be * called. * @param {INotificationListener} listener - An INotificationListener object. */ public addNotificationListener(listener: INotificationListener): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Removes all instances of the listener. * @param {INotificationListener} listener - INotificationListener to remove. */ public removeNotificationListener(listener: INotificationListener): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Get the current cookie manager for this instance */ public getCookieMgr(): ICookieMgr { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return null; } /** * Set the current cookie manager for this instance * @param cookieMgr - The manager, if set to null/undefined will cause the default to be created */ public setCookieMgr(cookieMgr: ICookieMgr) { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } public getPerfMgr(): IPerfManager { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return null; } public setPerfMgr(perfMgr: IPerfManager) { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } public eventCnt(): number { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return 0; } /** * Periodically check logger.queue for */ public pollInternalLogs(eventName?: string): number { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return 0; } /** * Periodically check logger.queue for */ public stopPollingInternalLogs(): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Add a telemetry processor to decorate or drop telemetry events. * @param telemetryInitializer - The Telemetry Initializer function * @returns - A ITelemetryInitializerHandler to enable the initializer to be removed */ public addTelemetryInitializer(telemetryInitializer: TelemetryInitializerFunction): ITelemetryInitializerHandler | void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Unload and Tear down the SDK and any initialized plugins, after calling this the SDK will be considered * to be un-initialized and non-operational, re-initializing the SDK should only be attempted if the previous * unload call return `true` stating that all plugins reported that they also unloaded, the recommended * approach is to create a new instance and initialize that instance. * This is due to possible unexpected side effects caused by plugins not supporting unload / teardown, unable * to successfully remove any global references or they may just be completing the unload process asynchronously. * @param isAsync - Can the unload be performed asynchronously (default) * @param unloadComplete - An optional callback that will be called once the unload has completed * @param cbTimeout - An optional timeout to wait for any flush operations to complete before proceeding with the unload. Defaults to 5 seconds. */ public unload(isAsync?: boolean, unloadComplete?: (unloadState: ITelemetryUnloadState) => void, cbTimeout?: number): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } public getPlugin<T extends IPlugin = IPlugin>(pluginIdentifier: string): ILoadedPlugin<T> { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return null; } /** * Add a new plugin to the installation * @param plugin - The new plugin to add * @param replaceExisting - should any existing plugin be replaced, default is false * @param doAsync - Should the add be performed asynchronously * @param addCb - [Optional] callback to call after the plugin has been added */ public addPlugin<T extends IPlugin = ITelemetryPlugin>(plugin: T, replaceExisting?: boolean, doAsync?: boolean, addCb?: (added?: boolean) => void): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Returns the unique event namespace that should be used */ public evtNamespace(): string { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return null; } /** * Add an unload handler that will be called when the SDK is being unloaded * @param handler - the handler */ public addUnloadCb(handler: UnloadHandler): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Flush and send any batched / cached data immediately * @param async - send data asynchronously when true (defaults to true) * @param callBack - if specified, notify caller when send is complete, the channel should return true to indicate to the caller that it will be called. * If the caller doesn't return true the caller should assume that it may never be called. * @param sendReason - specify the reason that you are calling "flush" defaults to ManualFlush (1) if not specified * @returns - true if the callback will be return after the flush is complete otherwise the caller should assume that any provided callback will never be called */ public flush(isAsync?: boolean, callBack?: (flushComplete?: boolean) => void, sendReason?: SendRequestReason): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Gets the current distributed trace context for this instance if available * @param createNew - Optional flag to create a new instance if one doesn't currently exist, defaults to true */ public getTraceCtx(createNew?: boolean): IDistributedTraceContext | null { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return null; } /** * Sets the current distributed trace context for this instance if available */ public setTraceCtx(newTracectx: IDistributedTraceContext): void { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } protected releaseQueue() { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging } /** * Hook for Core extensions to allow them to update their own configuration before updating all of the plugins. * @param updateCtx - The plugin update context * @param updateState - The Update State * @returns boolean - True means the extension class will call updateState otherwise the Core will */ protected _updateHook?(updateCtx: IProcessTelemetryUpdateContext, updateState: ITelemetryUpdateState): void | boolean { // @DynamicProtoStub -- DO NOT add any code as this will be removed during packaging return false; } }
the_stack
export declare var NewLine: string; /** * Describes a format provider context. */ export interface IFormatProviderContext { /** * The format expression. */ expression: string; /** * Gets if the expression has been handled or not. */ handled: boolean; /** * Gets the underlying value. */ value: any; } /** * Builds a string. */ export declare class StringBuilder { /** * Stores the internal buffer. */ protected _buffer: string; /** * Store the value for a "new line". */ protected _newLine: string; /** * Initializes a new instance of that class. * * @param any [initialVal] The initial value. */ constructor(initialVal?: any); /** * Appends a value. * * @chainable * * @param any value The value to append. */ append(value: any): StringBuilder; /** * Appends a formatted string. * * @chainable * * @param {String} formatStr The format string. * @param any ...args One or more argument for the format string. */ appendFormat(formatStr: string, ...args: any[]): StringBuilder; /** * Appends a formatted string. * * @chainable * * @param {String} formatStr The format string. * @param {Array} [args] One or more argument for the format string. */ appendFormatArray(formatStr: string, args?: any[]): StringBuilder; /** * Appends a new line by appending an optional value. * * @chainable * * @param any [value] The optional value to append. */ appendLine(value?: any): StringBuilder; /** * Resets the string. * * @chainable */ clear(): StringBuilder; /** * Checks if another string and the string of that builder are equal. * * @param any other The other string. * * @return {Boolean} Are equal or not. */ equals(other: string | StringBuilder): boolean; /** * Executes a search on a string using a regular expression pattern, * and returns an array containing the results of that search. * * @param RegExp regEx The rehular expression to use. * * @return {RegExpExecArray} The result of the search. */ exec(regEx: RegExp): RegExpExecArray; /** * Inserts a value. * * @chainable * * @param {Number} index The zero based index where to insert the value to. * @param any value The value to insert. */ insert(index: number, value: any): StringBuilder; /** * Inserts a formatted string. * * @chainable * * @param {Number} index The zero based index where to insert the formatted string to. * @param {String} formatStr The format string. * @param any ...args One or more argument for the format string. */ insertFormat(index: number, formatStr: string, ...args: any[]): StringBuilder; /** * Inserts a formatted string. * * @chainable * * @param {Number} index The zero based index where to insert the formatted string to. * @param {String} formatStr The format string. * @param {Array} [args] One or more argument for the format string. */ insertFormatArray(index: number, formatStr: string, args: any[]): StringBuilder; /** * Gets the current length of the current string. */ length: number; /** * Gets or sets the value for a "new line". */ newLine: string; /** * Prepends a value. * * @chainable * * @param any value The value to prepend. */ prepend(value: any): StringBuilder; /** * Prepends a formatted string. * * @chainable * * @param {String} formatStr The format string. * @param any ...args One or more argument for the format string. */ prependFormat(formatStr: string, ...args: any[]): StringBuilder; /** * Prepends a formatted string. * * @chainable * * @param {String} formatStr The format string. * @param {Array} [args] One or more argument for the format string. */ prependFormatArray(formatStr: string, args?: any[]): StringBuilder; /** * Prepends a new line by prepending an optional value. * * @chainable * * @param any [value] The optional value to prepend. */ prependLine(value?: any): StringBuilder; /** * Removes the specified range of characters from this instance. * * @chainable * * @param {Number} startIndex The zero-based position where removal begins. * @param {Number} [length] The number of characters to remove. * If NOT defined: Anything behind startIndex is removed. */ remove(startIndex: number, length?: number): StringBuilder; /** * Replaces parts of the string. * * @chainable * * @param {String|RegExp} searchValue The string or the regular expression to search for. * @param {String|RegExp} replacerOrValue The value or callback that replaces the matches. * @param {Number} startIndex The optional start index that defines where replacements starts. * @param {Number} count The optional number of chars (beginning at start index) that should be replaced. */ replace(searchValue: string | RegExp, replacerOrValue: string | ((substring: string, ...args: any[]) => string), startIndex?: number, count?: number): StringBuilder; /** * Checks if a pattern exists in a searched string. * * @param {RegExp} regEx The regular expression. * * @return {Boolean} Pattern exists or not. */ test(regEx: RegExp): boolean; /** * Returns that string as an char array. * * @return {Array} The array of chars. */ toCharArray(): string[]; /** * Creates the string representation of that builder. * * @return {String} The string representation. */ toString(): string; /** * Converts a value to a string. * * @param any value The input value. * * @return {String} The value as string. */ protected valueToString(value?: any): string; } /** * Adds a format provider. * * @function addFormatProvider * * @param {Function} providerCallback The provider callback. */ export declare function addFormatProvider(providerCallback: (ctx: IFormatProviderContext) => any): void; /** * Compares two strings. * * @function compare * * @param {String} x The left string. * @param {String} y The right string. * * @return {Number} The compare value (0: are equal; 1: x is greater than y; 2: x is less than y) */ export declare function compare(x: string, y: string): number; /** * Joins items to one string. * * @function concat * * @param {Array} itemList The list of items. * * @return {String} The joined string. */ export declare function concat(itemList: any[]): string; /** * Formats a string. * * @function format * * @param {String} formatStr The format string. * @param ...any args One or more argument for the format string. * * @return {String} The formatted string. */ export declare function format(formatStr: string, ...args: any[]): string; /** * Formats a string. * * @function formatArray * * @param {String} formatStr The format string. * @param {Array} args The list of arguments for the format string. * * @return {String} The formatted string. */ export declare function formatArray(formatStr: string, args: any[]): string; /** * Checks if a string is (null), undefined or empty. * * @function isEmpty * * @param {String} str The string to check. * * @return {Boolean} Is (null) / undefined / empty or not. */ export declare function isEmpty(str: string): boolean; /** * Checks if a string is (null), undefined, empty or contains whitespaces only. * * @function isEmptyOrWhitespace * * @param {String} str The string to check. * * @return {Boolean} Is (null) / undefined / empty / contains whitespaces only or not. */ export declare function isEmptyOrWhitespace(str: string): boolean; /** * Checks if a string is (null) or empty. * * @function isNullOrEmpty * * @param {String} str The string to check. * * @return {Boolean} Is (null) / empty or not. */ export declare function isNullOrEmpty(str: string): boolean; /** * Checks if a string is (null) or undefined. * * @function isNullOrUndefined * * @param {String} str The string to check. * * @return {Boolean} Is (null) / undefined or not. */ export declare function isNullOrUndefined(str: string): boolean; /** * Checks if a string is (null), empty or contains whitespaces only. * * @function isNullOrWhitespace * * @param {String} str The string to check. * * @return {Boolean} Is (null) / empty / contains whitespaces or not. */ export declare function isNullOrWhitespace(str: string): boolean; /** * Checks if a string is empty or contains whitespaces only. * * @function isWhitespace * * @param {String} str The string to check. * * @return {Boolean} Is empty / contains whitespaces only or not. */ export declare function isWhitespace(str: string): boolean; /** * Joins items to one string. * * @function join * * @param {String} separator The separator. * @param {Array} itemList The list of items. * * @return {String} The joined string. */ export declare function join(separator: string, itemList: any[]): string; /** * Returns the similarity of strings. * * @function similarity * * @param {string} left The "left" string. * @param {string} right The "right" string. * @param {boolean} [ignoreCase] Compare case insensitive or not. * @param {boolean} [trim] Trim both strings before comparison or not. * * @return {Number} The similarity between 0 (0 %) and 1 (100 %). */ export declare function similarity(left: string, right: string, ignoreCase?: boolean, trim?: boolean): number;
the_stack
import insertTextAtCursor from 'insert-text-at-cursor'; import { length } from 'stringz'; import { toASCII } from 'punycode'; import MkVisibilityChooser from '../views/components/visibility-chooser.vue'; import getFace from './get-face'; import { parse } from '../../../../mfm/parse'; import { host, url } from '../../config'; import i18n from '../../i18n'; import { erase, unique } from '../../../../prelude/array'; import extractMentions from '../../../../misc/extract-mentions'; export default (opts) => ({ i18n: i18n(), components: { XPostFormAttaches: () => import('../views/components/post-form-attaches.vue').then(m => m.default), XPollEditor: () => import('../views/components/poll-editor.vue').then(m => m.default) }, props: { reply: { type: Object, required: false }, renote: { type: Object, required: false }, mention: { type: Object, required: false }, initialText: { type: String, required: false }, instant: { type: Boolean, required: false, default: false } }, data() { return { posting: false, text: '', files: [], uploadings: [], poll: false, pollChoices: [], pollMultiple: false, pollExpiration: [], useCw: false, cw: null, geo: null, visibility: 'public', visibleUsers: [], localOnly: false, autocomplete: null, draghover: false, quoteId: null, recentHashtags: JSON.parse(localStorage.getItem('hashtags') || '[]'), maxNoteTextLength: 1000 }; }, computed: { draftId(): string { return this.renote ? `renote:${this.renote.id}` : this.reply ? `reply:${this.reply.id}` : 'note'; }, placeholder(): string { const xs = [ this.$t('@.note-placeholders.a'), this.$t('@.note-placeholders.b'), this.$t('@.note-placeholders.c'), this.$t('@.note-placeholders.d'), this.$t('@.note-placeholders.e'), this.$t('@.note-placeholders.f') ]; const x = xs[Math.floor(Math.random() * xs.length)]; return this.renote ? opts.mobile ? this.$t('@.post-form.option-quote-placeholder') : this.$t('@.post-form.quote-placeholder') : this.reply ? this.$t('@.post-form.reply-placeholder') : x; }, submitText(): string { return this.renote ? this.$t('@.post-form.renote') : this.reply ? this.$t('@.post-form.reply') : this.$t('@.post-form.submit'); }, canPost(): boolean { return !this.posting && (1 <= this.text.length || 1 <= this.files.length || this.poll || this.renote) && (length(this.text.trim()) <= this.maxNoteTextLength) && (!this.poll || this.pollChoices.length >= 2); } }, created() { this.$root.getMeta().then(meta => { this.maxNoteTextLength = meta.maxNoteTextLength; }); }, mounted() { if (this.initialText) { this.text = this.initialText; } if (this.mention) { this.text = this.mention.host ? `@${this.mention.username}@${toASCII(this.mention.host)}` : `@${this.mention.username}`; this.text += ' '; } if (this.reply && this.reply.user.host != null) { this.text = `@${this.reply.user.username}@${toASCII(this.reply.user.host)} `; } if (this.reply && this.reply.text != null) { const ast = parse(this.reply.text); for (const x of extractMentions(ast)) { const mention = x.host ? `@${x.username}@${toASCII(x.host)}` : `@${x.username}`; // 自分は除外 if (this.$store.state.i.username == x.username && x.host == null) continue; if (this.$store.state.i.username == x.username && x.host == host) continue; // 重複は除外 if (this.text.indexOf(`${mention} `) != -1) continue; this.text += `${mention} `; } } // デフォルト公開範囲 this.applyVisibility(this.$store.state.settings.rememberNoteVisibility ? (this.$store.state.device.visibility || this.$store.state.settings.defaultNoteVisibility) : this.$store.state.settings.defaultNoteVisibility); // 公開以外へのリプライ時は元の公開範囲を引き継ぐ if (this.reply && ['home', 'followers', 'specified'].includes(this.reply.visibility)) { this.visibility = this.reply.visibility; } if (this.reply) { this.$root.api('users/show', { userId: this.reply.userId }).then(user => { this.visibleUsers.push(user); }); } // keep cw when reply if (this.$store.state.settings.keepCw && this.reply && this.reply.cw) { this.useCw = true; this.cw = this.reply.cw; } this.focus(); this.$nextTick(() => { this.focus(); }); this.$nextTick(() => { // 書きかけの投稿を復元 if (!this.instant && !this.mention) { const draft = JSON.parse(localStorage.getItem('drafts') || '{}')[this.draftId]; if (draft) { this.text = draft.data.text; this.files = (draft.data.files || []).filter(e => e); if (draft.data.poll) { this.poll = true; this.$nextTick(() => { (this.$refs.poll as any).set(draft.data.poll); }); } this.$emit('change-attached-files', this.files); } } this.$nextTick(() => this.watch()); }); }, methods: { watch() { this.$watch('text', () => this.saveDraft()); this.$watch('poll', () => this.saveDraft()); this.$watch('files', () => this.saveDraft()); }, trimmedLength(text: string) { return length(text.trim()); }, addTag(tag: string) { insertTextAtCursor(this.$refs.text, ` #${tag} `); }, focus() { (this.$refs.text as any).focus(); }, chooseFile() { (this.$refs.file as any).click(); }, chooseFileFromDrive() { this.$chooseDriveFile({ multiple: true }).then(files => { for (const x of files) this.attachMedia(x); }); }, attachMedia(driveFile) { this.files.push(driveFile); this.$emit('change-attached-files', this.files); }, detachMedia(id) { this.files = this.files.filter(x => x.id != id); this.$emit('change-attached-files', this.files); }, onChangeFile() { for (const x of Array.from((this.$refs.file as any).files)) this.upload(x); }, upload(file) { (this.$refs.uploader as any).upload(file); }, onChangeUploadings(uploads) { this.$emit('change-uploadings', uploads); }, onPollUpdate() { const got = this.$refs.poll.get(); this.pollChoices = got.choices; this.pollMultiple = got.multiple; this.pollExpiration = [got.expiration, got.expiresAt || got.expiredAfter]; this.saveDraft(); }, setGeo() { if (navigator.geolocation == null) { this.$root.dialog({ type: 'warning', text: this.$t('@.post-form.geolocation-alert') }); return; } navigator.geolocation.getCurrentPosition(pos => { this.geo = pos.coords; this.$emit('geo-attached', this.geo); }, err => { this.$root.dialog({ type: 'error', title: this.$t('@.post-form.error'), text: err.message }); }, { enableHighAccuracy: true }); }, removeGeo() { this.geo = null; this.$emit('geo-dettached'); }, setVisibility() { const w = this.$root.new(MkVisibilityChooser, { source: this.$refs.visibilityButton, currentVisibility: this.visibility }); w.$once('chosen', v => { this.applyVisibility(v); }); }, applyVisibility(v: string) { const m = v.match(/^local-(.+)/); if (m) { this.localOnly = true; this.visibility = m[1]; } else { this.localOnly = false; this.visibility = v; } }, addVisibleUser() { this.$root.dialog({ title: this.$t('@.post-form.enter-username'), user: true }).then(({ canceled, result: user }) => { if (canceled) return; this.visibleUsers.push(user); }); }, removeVisibleUser(user) { this.visibleUsers = erase(user, this.visibleUsers); }, clear() { this.text = ''; this.files = []; this.poll = false; this.$emit('change-attached-files', this.files); }, onKeydown(e) { if ((e.which == 10 || e.which == 13) && (e.ctrlKey || e.metaKey) && this.canPost) this.post(); }, async onPaste(e) { for (const item of Array.from(e.clipboardData.items)) { if (item.kind == 'file') { this.upload(item.getAsFile()); } } const paste = e.clipboardData.getData('text'); if (paste.startsWith(url + '/notes/')) { e.preventDefault(); this.$root.dialog({ type: 'info', text: this.$t('@.post-form.quote-question'), showCancelButton: true }).then(({ canceled }) => { if (canceled) { insertTextAtCursor(this.$refs.text, paste); return; } this.quoteId = paste.substr(url.length).match(/^\/notes\/(.+?)\/?$/)[1]; }); } }, onDragover(e) { const isFile = e.dataTransfer.items[0].kind == 'file'; const isDriveFile = e.dataTransfer.types[0] == 'mk_drive_file'; if (isFile || isDriveFile) { e.preventDefault(); this.draghover = true; e.dataTransfer.dropEffect = e.dataTransfer.effectAllowed == 'all' ? 'copy' : 'move'; } }, onDragenter(e) { this.draghover = true; }, onDragleave(e) { this.draghover = false; }, onDrop(e): void { this.draghover = false; // ファイルだったら if (e.dataTransfer.files.length > 0) { e.preventDefault(); for (const x of Array.from(e.dataTransfer.files)) this.upload(x); return; } //#region ドライブのファイル const driveFile = e.dataTransfer.getData('mk_drive_file'); if (driveFile != null && driveFile != '') { const file = JSON.parse(driveFile); this.files.push(file); this.$emit('change-attached-files', this.files); e.preventDefault(); } //#endregion }, async emoji() { const Picker = await import('../../desktop/views/components/emoji-picker-dialog.vue').then(m => m.default); const button = this.$refs.emoji; const rect = button.getBoundingClientRect(); const vm = this.$root.new(Picker, { x: button.offsetWidth + rect.left + window.pageXOffset, y: rect.top + window.pageYOffset }); vm.$once('chosen', emoji => { insertTextAtCursor(this.$refs.text, emoji); }); }, saveDraft() { if (this.instant) return; const data = JSON.parse(localStorage.getItem('drafts') || '{}'); data[this.draftId] = { updatedAt: new Date(), data: { text: this.text, files: this.files, poll: this.poll && this.$refs.poll ? (this.$refs.poll as any).get() : undefined } }; localStorage.setItem('drafts', JSON.stringify(data)); }, deleteDraft() { const data = JSON.parse(localStorage.getItem('drafts') || '{}'); delete data[this.draftId]; localStorage.setItem('drafts', JSON.stringify(data)); }, kao() { this.text += getFace(); }, post() { this.posting = true; const viaMobile = opts.mobile && !this.$store.state.settings.disableViaMobile; this.$root.api('notes/create', { text: this.text == '' ? undefined : this.text, fileIds: this.files.length > 0 ? this.files.map(f => f.id) : undefined, replyId: this.reply ? this.reply.id : undefined, renoteId: this.renote ? this.renote.id : this.quoteId ? this.quoteId : undefined, poll: this.poll ? (this.$refs.poll as any).get() : undefined, cw: this.useCw ? this.cw || '' : undefined, visibility: this.visibility, visibleUserIds: this.visibility == 'specified' ? this.visibleUsers.map(u => u.id) : undefined, localOnly: this.localOnly, geo: this.geo ? { coordinates: [this.geo.longitude, this.geo.latitude], altitude: this.geo.altitude, accuracy: this.geo.accuracy, altitudeAccuracy: this.geo.altitudeAccuracy, heading: isNaN(this.geo.heading) ? null : this.geo.heading, speed: this.geo.speed, } : null, viaMobile: viaMobile }).then(data => { this.clear(); this.deleteDraft(); this.$emit('posted'); if (opts.onSuccess) opts.onSuccess(this); }).catch(err => { if (opts.onSuccess) opts.onFailure(this); }).then(() => { this.posting = false; }); if (this.text && this.text != '') { const hashtags = parse(this.text).filter(x => x.node.type === 'hashtag').map(x => x.node.props.hashtag); const history = JSON.parse(localStorage.getItem('hashtags') || '[]') as string[]; localStorage.setItem('hashtags', JSON.stringify(unique(hashtags.concat(history)))); } }, } });
the_stack
import { JsonConvert } from "../src/json2typescript/json-convert"; import { JsonObject, JsonProperty } from "../src/json2typescript/json-convert-decorators"; import { PropertyConvertingMode, ValueCheckingMode } from "../src/json2typescript/json-convert-enums"; describe("JsonConvert nullable type tests", () => { // <editor-fold desc="JSON CONVERT INSTANCES"> const jsonConvertAllowNull = new JsonConvert(); jsonConvertAllowNull.valueCheckingMode = ValueCheckingMode.ALLOW_NULL; const jsonConvertAllowObjectNull = new JsonConvert(); jsonConvertAllowObjectNull.valueCheckingMode = ValueCheckingMode.ALLOW_OBJECT_NULL; const jsonConvertNoNull = new JsonConvert(); jsonConvertNoNull.valueCheckingMode = ValueCheckingMode.DISALLOW_NULL; // </editor-fold> // <editor-fold desc="CLASSES"> @JsonObject("NullPropertyTest") class NullPropertyTest { @JsonProperty("a", Number) a: number | null = null; @JsonProperty("b", Number, PropertyConvertingMode.IGNORE_NULLABLE) b: number | null = null; @JsonProperty("c", Number, PropertyConvertingMode.PASS_NULLABLE) c: number | null = null; } @JsonObject("UndefinedPropertyTest") class UndefinedPropertyTest { @JsonProperty("a", Number) a: number | undefined = undefined; @JsonProperty("b", Number, PropertyConvertingMode.IGNORE_NULLABLE) b: number | undefined = undefined; @JsonProperty("c", Number, PropertyConvertingMode.PASS_NULLABLE) c: number | undefined = undefined; } // </editor-fold> // <editor-fold desc="TESTS"> describe("undefined property checks", () => { describe("serialize", () => { it("null allowed", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: undefined, throws: true, }, { data: undefined, mapUndefinedToNull: true, throws: true, }, { data: {}, throws: true, }, { data: {}, expected: {a: null, b: undefined, c: null}, mapUndefinedToNull: true, }, { data: {a: undefined, b: undefined, c: undefined}, throws: true, }, { data: {a: undefined, b: undefined, c: undefined}, expected: {a: null, b: undefined, c: null}, mapUndefinedToNull: true, }, { data: {a: 0, b: undefined, c: undefined}, expected: {a: 0, b: undefined, c: undefined}, }, { data: {a: 0, b: 0, c: undefined}, expected: {a: 0, b: 0, c: undefined}, }, { data: {a: 0, b: undefined, c: 0}, expected: {a: 0, b: undefined, c: 0}, }, ]; for (const test of tests) { serializeData( jsonConvertAllowNull, test.data, UndefinedPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); it("null objects allowed", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: undefined, throws: true, }, { data: undefined, mapUndefinedToNull: true, throws: true, }, { data: {}, throws: true, }, { data: {}, mapUndefinedToNull: true, throws: true, }, { data: {a: undefined, b: undefined, c: undefined}, throws: true, }, { data: {a: undefined, b: undefined, c: undefined}, mapUndefinedToNull: true, throws: true, }, { data: {a: 0, b: undefined, c: undefined}, expected: {a: 0, b: undefined, c: undefined}, }, { data: {a: 0, b: 0, c: undefined}, expected: {a: 0, b: 0, c: undefined}, }, { data: {a: 0, b: undefined, c: 0}, expected: {a: 0, b: undefined, c: 0}, }, ]; for (const test of tests) { serializeData( jsonConvertAllowObjectNull, test.data, UndefinedPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); it("null forbidden", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: undefined, throws: true, }, { data: undefined, mapUndefinedToNull: true, throws: true, }, { data: {}, throws: true, }, { data: {}, mapUndefinedToNull: true, throws: true, }, { data: {a: undefined, b: undefined, c: undefined}, throws: true, }, { data: {a: undefined, b: undefined, c: undefined}, mapUndefinedToNull: true, throws: true, }, { data: {a: 0, b: undefined, c: undefined}, expected: {a: 0, b: undefined, c: undefined}, }, { data: {a: 0, b: 0, c: undefined}, expected: {a: 0, b: 0, c: undefined}, }, { data: {a: 0, b: undefined, c: 0}, expected: {a: 0, b: undefined, c: 0}, }, ]; for (const test of tests) { serializeData( jsonConvertNoNull, test.data, UndefinedPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); }); describe("deserialize", () => { it("null allowed", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: undefined, throws: true, }, { data: undefined, mapUndefinedToNull: true, throws: true, }, { data: {}, throws: true, }, { data: {}, expected: {a: null, b: undefined, c: null}, mapUndefinedToNull: true, }, { data: {a: undefined, b: undefined, c: undefined}, throws: true, }, { data: {a: undefined, b: undefined, c: undefined}, expected: {a: null, b: undefined, c: null}, mapUndefinedToNull: true, }, { data: {a: 0, b: undefined, c: undefined}, expected: {a: 0, b: undefined, c: undefined}, }, { data: {a: 0, b: 0, c: undefined}, expected: {a: 0, b: 0, c: undefined}, }, { data: {a: 0, b: undefined, c: 0}, expected: {a: 0, b: undefined, c: 0}, }, ]; for (const test of tests) { deserializeData( jsonConvertAllowNull, test.data, UndefinedPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); it("null objects allowed", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: undefined, throws: true, }, { data: undefined, mapUndefinedToNull: true, throws: true, }, { data: {}, throws: true, }, { data: {}, mapUndefinedToNull: true, throws: true, }, { data: {a: undefined, b: undefined, c: undefined}, throws: true, }, { data: {a: undefined, b: undefined, c: undefined}, mapUndefinedToNull: true, throws: true, }, { data: {a: 0, b: undefined, c: undefined}, expected: {a: 0, b: undefined, c: undefined}, }, { data: {a: 0, b: 0, c: undefined}, expected: {a: 0, b: 0, c: undefined}, }, { data: {a: 0, b: undefined, c: 0}, expected: {a: 0, b: undefined, c: 0}, }, ]; for (const test of tests) { deserializeData( jsonConvertAllowObjectNull, test.data, UndefinedPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); it("null forbidden", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: undefined, throws: true, }, { data: undefined, mapUndefinedToNull: true, throws: true, }, { data: {}, throws: true, }, { data: {}, mapUndefinedToNull: true, throws: true, }, { data: {a: undefined, b: undefined, c: undefined}, throws: true, }, { data: {a: undefined, b: undefined, c: undefined}, mapUndefinedToNull: true, throws: true, }, { data: {a: 0, b: undefined, c: undefined}, expected: {a: 0, b: undefined, c: undefined}, }, { data: {a: 0, b: 0, c: undefined}, expected: {a: 0, b: 0, c: undefined}, }, { data: {a: 0, b: undefined, c: 0}, expected: {a: 0, b: undefined, c: 0}, }, ]; for (const test of tests) { deserializeData( jsonConvertNoNull, test.data, UndefinedPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); }); }); describe("null property checks", () => { describe("serialize", () => { it("null allowed", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: null, expected: null, }, { data: {}, throws: true, }, { data: {a: null, b: null, c: null}, expected: {a: null, b: undefined, c: null}, }, { data: {a: 0, b: null, c: null}, expected: {a: 0, b: undefined, c: null}, }, { data: {a: 0, b: 0, c: null}, expected: {a: 0, b: 0, c: null}, }, { data: {a: 0, b: null, c: 0}, expected: {a: 0, b: undefined, c: 0}, }, ]; for (const test of tests) { serializeData( jsonConvertAllowNull, test.data, NullPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); it("null object allowed", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: null, expected: null, }, { data: {}, throws: true, }, { data: {a: null, b: null, c: null}, throws: true, }, { data: {a: 0, b: null, c: null}, expected: {a: 0, b: undefined, c: null}, }, { data: {a: 0, b: 0, c: null}, expected: {a: 0, b: 0, c: null}, }, { data: {a: 0, b: null, c: 0}, expected: {a: 0, b: undefined, c: 0}, }, ]; for (const test of tests) { serializeData( jsonConvertAllowObjectNull, test.data, NullPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); it("null forbidden", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: null, throws: true, }, { data: {}, throws: true, }, { data: {a: null, b: null, c: null}, throws: true, }, { data: {a: 0, b: null, c: null}, expected: {a: 0, b: undefined, c: null}, }, { data: {a: 0, b: 0, c: null}, expected: {a: 0, b: 0, c: null}, }, { data: {a: 0, b: null, c: 0}, expected: {a: 0, b: undefined, c: 0}, }, ]; for (const test of tests) { serializeData( jsonConvertNoNull, test.data, NullPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); }); describe("deserialize", () => { it("null allowed", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: null, expected: null, }, { data: {}, throws: true, }, { data: {a: null, b: null, c: null}, expected: {a: null, b: null, c: null}, }, { data: {a: 0, b: null, c: null}, expected: {a: 0, b: null, c: null}, }, { data: {a: 0, b: 0, c: null}, expected: {a: 0, b: 0, c: null}, }, { data: {a: 0, b: null, c: 0}, expected: {a: 0, b: null, c: 0}, }, ]; for (const test of tests) { deserializeData( jsonConvertAllowNull, test.data, NullPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); it("null object allowed", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: null, expected: null, }, { data: {}, throws: true, }, { data: {a: null, b: null, c: null}, throws: true, }, { data: {a: 0, b: null, c: null}, expected: {a: 0, b: null, c: null}, }, { data: {a: 0, b: 0, c: null}, expected: {a: 0, b: 0, c: null}, }, { data: {a: 0, b: null, c: 0}, expected: {a: 0, b: null, c: 0}, }, ]; for (const test of tests) { deserializeData( jsonConvertAllowObjectNull, test.data, NullPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); it("null forbidden", () => { const tests: { data: any, expected?: any, mapUndefinedToNull?: boolean, throws?: boolean }[] = [ { data: null, throws: true, }, { data: {}, throws: true, }, { data: {a: null, b: null, c: null}, throws: true, }, { data: {a: 0, b: null, c: null}, expected: {a: 0, b: null, c: null}, }, { data: {a: 0, b: 0, c: null}, expected: {a: 0, b: 0, c: null}, }, { data: {a: 0, b: null, c: 0}, expected: {a: 0, b: null, c: 0}, }, ]; for (const test of tests) { deserializeData( jsonConvertNoNull, test.data, NullPropertyTest, test.expected, test.mapUndefinedToNull, test.throws, ); } }); }); }); // </editor-fold> // <editor-fold desc="TEST METHODS"> /** * Generic method for serializing data. */ function serializeData(jsonConvert: JsonConvert, data: any, classReference: any, expectedResult: any, mapUndefinedToNull: boolean = false, throws: boolean = false): void { jsonConvert.mapUndefinedToNull = mapUndefinedToNull === true; if (throws) { expect(() => jsonConvert.serialize(data, classReference)).toThrowError(); } else { const result: any = jsonConvert.serialize(data, classReference); if (result === undefined || result === null) { expect(result).toEqual(expectedResult); return; } Object.keys(result).forEach((key: string) => { const value = result[key]; expect(value).toEqual(expectedResult[key]); }); } jsonConvert.mapUndefinedToNull = false; } /** * Generic method for deserializing data. */ function deserializeData(jsonConvert: JsonConvert, data: any, classReference: any, expectedResult: any, mapUndefinedToNull: boolean = false, throws: boolean = false): void { jsonConvert.mapUndefinedToNull = mapUndefinedToNull === true; if (throws) { expect(() => jsonConvert.deserialize(data, classReference)).toThrowError(); } else { const result: any = jsonConvert.deserialize(data, classReference); if (result === undefined || result === null) { expect(result).toEqual(expectedResult); return; } Object.keys(result).forEach((key: string) => { const value = result[key]; expect(value).toEqual(expectedResult[key]); }); } jsonConvert.mapUndefinedToNull = false; } // </editor-fold> });
the_stack
import StateMachine from '../src/app/app' import LifecycleLogger from './helpers/lifecycle_logger' test('basic transition from state to state', () => { const fsm = new StateMachine({ init: 'A', transitions: [ { name: 'step1', from: 'A', to: 'B' }, { name: 'step2', from: 'B', to: 'C' }, { name: 'step3', from: 'C', to: 'D' } ] }); expect(fsm.state).toBe('A'); fsm.step1(); expect(fsm.state).toBe('B'); fsm.step2(); expect(fsm.state).toBe('C'); fsm.step3(); expect(fsm.state).toBe('D'); }); //----------------------------------------------------------------------------- test('multiple transitions with same name', () => { const fsm = new StateMachine({ init: 'hungry', transitions: [ { name: 'eat', from: 'hungry', to: 'satisfied' }, { name: 'eat', from: 'satisfied', to: 'full' }, { name: 'eat', from: 'full', to: 'sick' }, { name: 'rest', from: '*', to: 'hungry' } ] }); expect(fsm.state).toBe('hungry'); expect(fsm.can('eat')).toBe(true); expect(fsm.can('rest')).toBe(true); fsm.eat(); expect(fsm.state).toBe('satisfied'); expect(fsm.can('eat')).toBe(true); expect(fsm.can('rest')).toBe(true); fsm.eat(); expect(fsm.state).toBe('full'); expect(fsm.can('eat')).toBe(true); expect(fsm.can('rest')).toBe(true); fsm.eat(); expect(fsm.state).toBe('sick'); expect(fsm.can('eat')).toBe(false); expect(fsm.can('rest')).toBe(true); fsm.rest(); expect(fsm.state).toBe('hungry'); expect(fsm.can('eat')).toBe(true); expect(fsm.can('rest')).toBe(true); }); test('transitions with multiple from states', () => { const fsm = new StateMachine({ transitions: [ { name: 'start', from: 'none', to: 'green' }, { name: 'warn', from: ['green', 'red'], to: 'yellow' }, { name: 'panic', from: ['green', 'yellow'], to: 'red' }, { name: 'clear', from: ['red', 'yellow'], to: 'green' }, ], }); expect(fsm.allStates()).toEqual([ 'none', 'green', 'yellow', 'red' ]); expect(fsm.allTransitions()).toEqual([ 'start', 'warn', 'panic', 'clear' ]); expect(fsm.state).toBe('none'); expect(fsm.can('start')).toBe(true); expect(fsm.can('warn')).toBe(false); expect(fsm.can('panic')).toBe(false); expect(fsm.can('clear')).toBe(false); expect(fsm.transitions()).toEqual(['start']); fsm.start(); expect(fsm.state).toBe('green'); expect(fsm.can('start')).toBe(false); expect(fsm.can('warn')).toBe(true); expect(fsm.can('panic')).toBe(true); expect(fsm.can('clear')).toBe(false); expect(fsm.transitions()).toEqual(['warn', 'panic']); fsm.warn(); expect(fsm.state).toBe('yellow'); expect(fsm.can('start')).toBe(false); expect(fsm.can('warn')).toBe(false); expect(fsm.can('panic')).toBe(true); expect(fsm.can('clear')).toBe(true); expect(fsm.transitions()).toEqual(['panic', 'clear']); fsm.panic(); expect(fsm.state).toBe('red'); expect(fsm.can('start')).toBe(false); expect(fsm.can('warn')).toBe(true); expect(fsm.can('panic')).toBe(false); expect(fsm.can('clear')).toBe(true); expect(fsm.transitions()).toEqual(['warn', 'clear']); fsm.clear(); expect(fsm.state).toBe('green'); expect(fsm.can('start')).toBe(false); expect(fsm.can('warn')).toBe(true); expect(fsm.can('panic')).toBe(true); expect(fsm.can('clear')).toBe(false); expect(fsm.transitions()).toEqual(['warn', 'panic']); }); test("transitions that dont change state, dont trigger enter/leave lifecycle events", () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ transitions: [ { name: 'noop', from: 'none', to: 'none' } ], methods: { onBeforeTransition: logger, onBeforeNoop: logger, onLeaveState: logger, onLeaveNone: logger, onTransition: logger, onEnterState: logger, onEnterNone: logger, onNone: logger, onAfterTransition: logger, onAfterNoop: logger, onNoop: logger } }); expect(fsm.state).toBe('none'); expect(logger.log).toEqual([]); fsm.noop(); expect(fsm.state).toBe('none'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onBeforeNoop', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onTransition', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onAfterTransition', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onAfterNoop', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onNoop', transition: 'noop', from: 'none', to: 'none', current: 'none' } ]); }); test("transitions that dont change state, can be configured to trigger enter/leave lifecycle events", () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ observeUnchangedState: true, transitions: [ { name: 'noop', from: 'none', to: 'none' } ], methods: { onBeforeTransition: logger, onBeforeNoop: logger, onLeaveState: logger, onLeaveNone: logger, onTransition: logger, onEnterState: logger, onEnterNone: logger, onNone: logger, onAfterTransition: logger, onAfterNoop: logger, onNoop: logger } }); expect(fsm.state).toBe('none'); expect(logger.log).toEqual([]); fsm.noop(); expect(fsm.state).toBe('none'); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onBeforeNoop', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onLeaveState', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onLeaveNone', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onTransition', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onEnterState', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onEnterNone', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onNone', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onAfterTransition', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onAfterNoop', transition: 'noop', from: 'none', to: 'none', current: 'none' }, { event: 'onNoop', transition: 'noop', from: 'none', to: 'none', current: 'none' } ]); }); test("transition methods with dash or underscore are camelized", () => { const fsm = new StateMachine({ init: 'A', transitions: [ { name: 'do-with-dash', from: 'A', to: 'B' }, { name: 'do_with_underscore', from: 'B', to: 'C' }, { name: 'doAlreadyCamelized', from: 'C', to: 'D' } ] }); expect(fsm.state).toBe('A'); fsm.doWithDash(); expect(fsm.state).toBe('B'); fsm.doWithUnderscore(); expect(fsm.state).toBe('C'); fsm.doAlreadyCamelized(); expect(fsm.state).toBe('D'); }); test('conditional transitions', () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ init: 'A', transitions: [ // @ts-ignore { name: 'step', from: '*', to: function(n) { return this.skip(n); } }, ], methods: { skip: function(amount) { // @ts-ignore const code = this.state.charCodeAt(0); return String.fromCharCode(code + (amount || 1)); }, onBeforeTransition: logger, onBeforeInit: logger, onBeforeStep: logger, onLeaveState: logger, onLeaveNone: logger, onLeaveA: logger, onLeaveB: logger, onLeaveG: logger, onTransition: logger, onEnterState: logger, onEnterNone: logger, onEnterA: logger, onEnterB: logger, onEnterG: logger, onAfterTransition: logger, onAfterInit: logger, onAfterStep: logger } }); expect(fsm.state).toBe('A'); expect(fsm.allStates()).toEqual([ 'none', 'A' ]); fsm.step(); expect(fsm.state).toBe('B'); expect(fsm.allStates()).toEqual([ 'none', 'A', 'B' ]); fsm.step(5); expect(fsm.state).toBe('G'); expect(fsm.allStates()).toEqual([ 'none', 'A', 'B', 'G' ]); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onBeforeInit', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onLeaveState', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onLeaveNone', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onTransition', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onEnterState', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onEnterA', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onAfterTransition', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onAfterInit', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onBeforeTransition', transition: 'step', from: 'A', to: 'B', current: 'A' }, { event: 'onBeforeStep', transition: 'step', from: 'A', to: 'B', current: 'A' }, { event: 'onLeaveState', transition: 'step', from: 'A', to: 'B', current: 'A' }, { event: 'onLeaveA', transition: 'step', from: 'A', to: 'B', current: 'A' }, { event: 'onTransition', transition: 'step', from: 'A', to: 'B', current: 'A' }, { event: 'onEnterState', transition: 'step', from: 'A', to: 'B', current: 'B' }, { event: 'onEnterB', transition: 'step', from: 'A', to: 'B', current: 'B' }, { event: 'onAfterTransition', transition: 'step', from: 'A', to: 'B', current: 'B' }, { event: 'onAfterStep', transition: 'step', from: 'A', to: 'B', current: 'B' }, { event: 'onBeforeTransition', transition: 'step', from: 'B', to: 'G', current: 'B', args: [ 5 ] }, { event: 'onBeforeStep', transition: 'step', from: 'B', to: 'G', current: 'B', args: [ 5 ] }, { event: 'onLeaveState', transition: 'step', from: 'B', to: 'G', current: 'B', args: [ 5 ] }, { event: 'onLeaveB', transition: 'step', from: 'B', to: 'G', current: 'B', args: [ 5 ] }, { event: 'onTransition', transition: 'step', from: 'B', to: 'G', current: 'B', args: [ 5 ] }, { event: 'onEnterState', transition: 'step', from: 'B', to: 'G', current: 'G', args: [ 5 ] }, { event: 'onEnterG', transition: 'step', from: 'B', to: 'G', current: 'G', args: [ 5 ] }, { event: 'onAfterTransition', transition: 'step', from: 'B', to: 'G', current: 'G', args: [ 5 ] }, { event: 'onAfterStep', transition: 'step', from: 'B', to: 'G', current: 'G', args: [ 5 ] }, ]); }); test('async conditional transitions', async () => { // @ts-ignore const logger = new LifecycleLogger(); const fsm = new StateMachine({ init: 'A', transitions: [ // @ts-ignore { name: 'step', from: '*', to: async function(n) { // @ts-ignore return await this.skip(n); } }, ], methods: { skip: function(amount) { // @ts-ignore const code = this.state.charCodeAt(0); return String.fromCharCode(code + (amount || 1)); }, onBeforeTransition: logger, onBeforeInit: logger, onBeforeStep: logger, onLeaveState: logger, onLeaveNone: logger, onLeaveA: logger, onLeaveB: logger, onLeaveG: logger, onTransition: logger, onEnterState: logger, onEnterNone: logger, onEnterA: logger, onEnterB: logger, onEnterG: logger, onAfterTransition: logger, onAfterInit: logger, onAfterStep: logger } }); expect(fsm.state).toBe('A'); expect(fsm.allStates()).toEqual([ 'none', 'A' ]); await fsm.step(); expect(fsm.state).toBe('B'); expect(fsm.allStates()).toEqual([ 'none', 'A', 'B' ]); await fsm.step(5); expect(fsm.state).toBe('G'); expect(fsm.allStates()).toEqual([ 'none', 'A', 'B', 'G' ]); expect(logger.log).toEqual([ { event: 'onBeforeTransition', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onBeforeInit', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onLeaveState', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onLeaveNone', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onTransition', transition: 'init', from: 'none', to: 'A', current: 'none' }, { event: 'onEnterState', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onEnterA', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onAfterTransition', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onAfterInit', transition: 'init', from: 'none', to: 'A', current: 'A' }, { event: 'onBeforeTransition', transition: 'step', from: 'A', to: 'B', current: 'A' }, { event: 'onBeforeStep', transition: 'step', from: 'A', to: 'B', current: 'A' }, { event: 'onLeaveState', transition: 'step', from: 'A', to: 'B', current: 'A' }, { event: 'onLeaveA', transition: 'step', from: 'A', to: 'B', current: 'A' }, { event: 'onTransition', transition: 'step', from: 'A', to: 'B', current: 'A' }, { event: 'onEnterState', transition: 'step', from: 'A', to: 'B', current: 'B' }, { event: 'onEnterB', transition: 'step', from: 'A', to: 'B', current: 'B' }, { event: 'onAfterTransition', transition: 'step', from: 'A', to: 'B', current: 'B' }, { event: 'onAfterStep', transition: 'step', from: 'A', to: 'B', current: 'B' }, { event: 'onBeforeTransition', transition: 'step', from: 'B', to: 'G', current: 'B', args: [ 5 ] }, { event: 'onBeforeStep', transition: 'step', from: 'B', to: 'G', current: 'B', args: [ 5 ] }, { event: 'onLeaveState', transition: 'step', from: 'B', to: 'G', current: 'B', args: [ 5 ] }, { event: 'onLeaveB', transition: 'step', from: 'B', to: 'G', current: 'B', args: [ 5 ] }, { event: 'onTransition', transition: 'step', from: 'B', to: 'G', current: 'B', args: [ 5 ] }, { event: 'onEnterState', transition: 'step', from: 'B', to: 'G', current: 'G', args: [ 5 ] }, { event: 'onEnterG', transition: 'step', from: 'B', to: 'G', current: 'G', args: [ 5 ] }, { event: 'onAfterTransition', transition: 'step', from: 'B', to: 'G', current: 'G', args: [ 5 ] }, { event: 'onAfterStep', transition: 'step', from: 'B', to: 'G', current: 'G', args: [ 5 ] }, ]); }); export {}
the_stack
export const enum Enum { A = "A", B = "B", } export const encodeEnum: { [key: string]: number } = { A: 0, B: 1, }; export const decodeEnum: { [key: number]: Enum } = { 0: Enum.A, 1: Enum.B, }; export interface Nested { x?: number; y?: number; } export function encodeNested(message: Nested): Uint8Array { let bb = popByteBuffer(); _encodeNested(message, bb); return toUint8Array(bb); } function _encodeNested(message: Nested, bb: ByteBuffer): void { // optional float x = 1; let $x = message.x; if ($x !== undefined) { writeVarint32(bb, 13); writeFloat(bb, $x); } // optional float y = 2; let $y = message.y; if ($y !== undefined) { writeVarint32(bb, 21); writeFloat(bb, $y); } } export function decodeNested(binary: Uint8Array): Nested { return _decodeNested(wrapByteBuffer(binary)); } function _decodeNested(bb: ByteBuffer): Nested { let message: Nested = {} as any; end_of_message: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_message; // optional float x = 1; case 1: { message.x = readFloat(bb); break; } // optional float y = 2; case 2: { message.y = readFloat(bb); break; } default: skipUnknownField(bb, tag & 7); } } return message; } export interface Optional { field_int32?: number; field_int64?: Long; field_uint32?: number; field_uint64?: Long; field_sint32?: number; field_sint64?: Long; field_bool?: boolean; field_fixed64?: Long; field_sfixed64?: Long; field_double?: number; field_string?: string; field_bytes?: Uint8Array; field_fixed32?: number; field_sfixed32?: number; field_float?: number; field_nested?: Nested; } export function encodeOptional(message: Optional): Uint8Array { let bb = popByteBuffer(); _encodeOptional(message, bb); return toUint8Array(bb); } function _encodeOptional(message: Optional, bb: ByteBuffer): void { // optional int32 field_int32 = 1; let $field_int32 = message.field_int32; if ($field_int32 !== undefined) { writeVarint32(bb, 8); writeVarint64(bb, intToLong($field_int32)); } // optional int64 field_int64 = 2; let $field_int64 = message.field_int64; if ($field_int64 !== undefined) { writeVarint32(bb, 16); writeVarint64(bb, $field_int64); } // optional uint32 field_uint32 = 3; let $field_uint32 = message.field_uint32; if ($field_uint32 !== undefined) { writeVarint32(bb, 24); writeVarint32(bb, $field_uint32); } // optional uint64 field_uint64 = 4; let $field_uint64 = message.field_uint64; if ($field_uint64 !== undefined) { writeVarint32(bb, 32); writeVarint64(bb, $field_uint64); } // optional sint32 field_sint32 = 5; let $field_sint32 = message.field_sint32; if ($field_sint32 !== undefined) { writeVarint32(bb, 40); writeVarint32ZigZag(bb, $field_sint32); } // optional sint64 field_sint64 = 6; let $field_sint64 = message.field_sint64; if ($field_sint64 !== undefined) { writeVarint32(bb, 48); writeVarint64ZigZag(bb, $field_sint64); } // optional bool field_bool = 7; let $field_bool = message.field_bool; if ($field_bool !== undefined) { writeVarint32(bb, 56); writeByte(bb, $field_bool ? 1 : 0); } // optional fixed64 field_fixed64 = 8; let $field_fixed64 = message.field_fixed64; if ($field_fixed64 !== undefined) { writeVarint32(bb, 65); writeInt64(bb, $field_fixed64); } // optional sfixed64 field_sfixed64 = 9; let $field_sfixed64 = message.field_sfixed64; if ($field_sfixed64 !== undefined) { writeVarint32(bb, 73); writeInt64(bb, $field_sfixed64); } // optional double field_double = 10; let $field_double = message.field_double; if ($field_double !== undefined) { writeVarint32(bb, 81); writeDouble(bb, $field_double); } // optional string field_string = 11; let $field_string = message.field_string; if ($field_string !== undefined) { writeVarint32(bb, 90); writeString(bb, $field_string); } // optional bytes field_bytes = 12; let $field_bytes = message.field_bytes; if ($field_bytes !== undefined) { writeVarint32(bb, 98); writeVarint32(bb, $field_bytes.length), writeBytes(bb, $field_bytes); } // optional fixed32 field_fixed32 = 13; let $field_fixed32 = message.field_fixed32; if ($field_fixed32 !== undefined) { writeVarint32(bb, 109); writeInt32(bb, $field_fixed32); } // optional sfixed32 field_sfixed32 = 14; let $field_sfixed32 = message.field_sfixed32; if ($field_sfixed32 !== undefined) { writeVarint32(bb, 117); writeInt32(bb, $field_sfixed32); } // optional float field_float = 15; let $field_float = message.field_float; if ($field_float !== undefined) { writeVarint32(bb, 125); writeFloat(bb, $field_float); } // optional Nested field_nested = 16; let $field_nested = message.field_nested; if ($field_nested !== undefined) { writeVarint32(bb, 130); let nested = popByteBuffer(); _encodeNested($field_nested, nested); writeVarint32(bb, nested.limit); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } export function decodeOptional(binary: Uint8Array): Optional { return _decodeOptional(wrapByteBuffer(binary)); } function _decodeOptional(bb: ByteBuffer): Optional { let message: Optional = {} as any; end_of_message: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_message; // optional int32 field_int32 = 1; case 1: { message.field_int32 = readVarint32(bb); break; } // optional int64 field_int64 = 2; case 2: { message.field_int64 = readVarint64(bb, /* unsigned */ false); break; } // optional uint32 field_uint32 = 3; case 3: { message.field_uint32 = readVarint32(bb) >>> 0; break; } // optional uint64 field_uint64 = 4; case 4: { message.field_uint64 = readVarint64(bb, /* unsigned */ true); break; } // optional sint32 field_sint32 = 5; case 5: { message.field_sint32 = readVarint32ZigZag(bb); break; } // optional sint64 field_sint64 = 6; case 6: { message.field_sint64 = readVarint64ZigZag(bb); break; } // optional bool field_bool = 7; case 7: { message.field_bool = !!readByte(bb); break; } // optional fixed64 field_fixed64 = 8; case 8: { message.field_fixed64 = readInt64(bb, /* unsigned */ true); break; } // optional sfixed64 field_sfixed64 = 9; case 9: { message.field_sfixed64 = readInt64(bb, /* unsigned */ false); break; } // optional double field_double = 10; case 10: { message.field_double = readDouble(bb); break; } // optional string field_string = 11; case 11: { message.field_string = readString(bb, readVarint32(bb)); break; } // optional bytes field_bytes = 12; case 12: { message.field_bytes = readBytes(bb, readVarint32(bb)); break; } // optional fixed32 field_fixed32 = 13; case 13: { message.field_fixed32 = readInt32(bb) >>> 0; break; } // optional sfixed32 field_sfixed32 = 14; case 14: { message.field_sfixed32 = readInt32(bb); break; } // optional float field_float = 15; case 15: { message.field_float = readFloat(bb); break; } // optional Nested field_nested = 16; case 16: { let limit = pushTemporaryLength(bb); message.field_nested = _decodeNested(bb); bb.limit = limit; break; } default: skipUnknownField(bb, tag & 7); } } return message; } export interface RepeatedUnpacked { field_int32?: number[]; field_int64?: Long[]; field_uint32?: number[]; field_uint64?: Long[]; field_sint32?: number[]; field_sint64?: Long[]; field_bool?: boolean[]; field_fixed64?: Long[]; field_sfixed64?: Long[]; field_double?: number[]; field_string?: string[]; field_bytes?: Uint8Array[]; field_fixed32?: number[]; field_sfixed32?: number[]; field_float?: number[]; field_nested?: Nested[]; } export function encodeRepeatedUnpacked(message: RepeatedUnpacked): Uint8Array { let bb = popByteBuffer(); _encodeRepeatedUnpacked(message, bb); return toUint8Array(bb); } function _encodeRepeatedUnpacked(message: RepeatedUnpacked, bb: ByteBuffer): void { // repeated int32 field_int32 = 1; let array$field_int32 = message.field_int32; if (array$field_int32 !== undefined) { for (let value of array$field_int32) { writeVarint32(bb, 8); writeVarint64(bb, intToLong(value)); } } // repeated int64 field_int64 = 2; let array$field_int64 = message.field_int64; if (array$field_int64 !== undefined) { for (let value of array$field_int64) { writeVarint32(bb, 16); writeVarint64(bb, value); } } // repeated uint32 field_uint32 = 3; let array$field_uint32 = message.field_uint32; if (array$field_uint32 !== undefined) { for (let value of array$field_uint32) { writeVarint32(bb, 24); writeVarint32(bb, value); } } // repeated uint64 field_uint64 = 4; let array$field_uint64 = message.field_uint64; if (array$field_uint64 !== undefined) { for (let value of array$field_uint64) { writeVarint32(bb, 32); writeVarint64(bb, value); } } // repeated sint32 field_sint32 = 5; let array$field_sint32 = message.field_sint32; if (array$field_sint32 !== undefined) { for (let value of array$field_sint32) { writeVarint32(bb, 40); writeVarint32ZigZag(bb, value); } } // repeated sint64 field_sint64 = 6; let array$field_sint64 = message.field_sint64; if (array$field_sint64 !== undefined) { for (let value of array$field_sint64) { writeVarint32(bb, 48); writeVarint64ZigZag(bb, value); } } // repeated bool field_bool = 7; let array$field_bool = message.field_bool; if (array$field_bool !== undefined) { for (let value of array$field_bool) { writeVarint32(bb, 56); writeByte(bb, value ? 1 : 0); } } // repeated fixed64 field_fixed64 = 8; let array$field_fixed64 = message.field_fixed64; if (array$field_fixed64 !== undefined) { for (let value of array$field_fixed64) { writeVarint32(bb, 65); writeInt64(bb, value); } } // repeated sfixed64 field_sfixed64 = 9; let array$field_sfixed64 = message.field_sfixed64; if (array$field_sfixed64 !== undefined) { for (let value of array$field_sfixed64) { writeVarint32(bb, 73); writeInt64(bb, value); } } // repeated double field_double = 10; let array$field_double = message.field_double; if (array$field_double !== undefined) { for (let value of array$field_double) { writeVarint32(bb, 81); writeDouble(bb, value); } } // repeated string field_string = 11; let array$field_string = message.field_string; if (array$field_string !== undefined) { for (let value of array$field_string) { writeVarint32(bb, 90); writeString(bb, value); } } // repeated bytes field_bytes = 12; let array$field_bytes = message.field_bytes; if (array$field_bytes !== undefined) { for (let value of array$field_bytes) { writeVarint32(bb, 98); writeVarint32(bb, value.length), writeBytes(bb, value); } } // repeated fixed32 field_fixed32 = 13; let array$field_fixed32 = message.field_fixed32; if (array$field_fixed32 !== undefined) { for (let value of array$field_fixed32) { writeVarint32(bb, 109); writeInt32(bb, value); } } // repeated sfixed32 field_sfixed32 = 14; let array$field_sfixed32 = message.field_sfixed32; if (array$field_sfixed32 !== undefined) { for (let value of array$field_sfixed32) { writeVarint32(bb, 117); writeInt32(bb, value); } } // repeated float field_float = 15; let array$field_float = message.field_float; if (array$field_float !== undefined) { for (let value of array$field_float) { writeVarint32(bb, 125); writeFloat(bb, value); } } // repeated Nested field_nested = 16; let array$field_nested = message.field_nested; if (array$field_nested !== undefined) { for (let value of array$field_nested) { writeVarint32(bb, 130); let nested = popByteBuffer(); _encodeNested(value, nested); writeVarint32(bb, nested.limit); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } } export function decodeRepeatedUnpacked(binary: Uint8Array): RepeatedUnpacked { return _decodeRepeatedUnpacked(wrapByteBuffer(binary)); } function _decodeRepeatedUnpacked(bb: ByteBuffer): RepeatedUnpacked { let message: RepeatedUnpacked = {} as any; end_of_message: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_message; // repeated int32 field_int32 = 1; case 1: { let values = message.field_int32 || (message.field_int32 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint32(bb)); } bb.limit = outerLimit; } else { values.push(readVarint32(bb)); } break; } // repeated int64 field_int64 = 2; case 2: { let values = message.field_int64 || (message.field_int64 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint64(bb, /* unsigned */ false)); } bb.limit = outerLimit; } else { values.push(readVarint64(bb, /* unsigned */ false)); } break; } // repeated uint32 field_uint32 = 3; case 3: { let values = message.field_uint32 || (message.field_uint32 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint32(bb) >>> 0); } bb.limit = outerLimit; } else { values.push(readVarint32(bb) >>> 0); } break; } // repeated uint64 field_uint64 = 4; case 4: { let values = message.field_uint64 || (message.field_uint64 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint64(bb, /* unsigned */ true)); } bb.limit = outerLimit; } else { values.push(readVarint64(bb, /* unsigned */ true)); } break; } // repeated sint32 field_sint32 = 5; case 5: { let values = message.field_sint32 || (message.field_sint32 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint32ZigZag(bb)); } bb.limit = outerLimit; } else { values.push(readVarint32ZigZag(bb)); } break; } // repeated sint64 field_sint64 = 6; case 6: { let values = message.field_sint64 || (message.field_sint64 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint64ZigZag(bb)); } bb.limit = outerLimit; } else { values.push(readVarint64ZigZag(bb)); } break; } // repeated bool field_bool = 7; case 7: { let values = message.field_bool || (message.field_bool = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(!!readByte(bb)); } bb.limit = outerLimit; } else { values.push(!!readByte(bb)); } break; } // repeated fixed64 field_fixed64 = 8; case 8: { let values = message.field_fixed64 || (message.field_fixed64 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readInt64(bb, /* unsigned */ true)); } bb.limit = outerLimit; } else { values.push(readInt64(bb, /* unsigned */ true)); } break; } // repeated sfixed64 field_sfixed64 = 9; case 9: { let values = message.field_sfixed64 || (message.field_sfixed64 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readInt64(bb, /* unsigned */ false)); } bb.limit = outerLimit; } else { values.push(readInt64(bb, /* unsigned */ false)); } break; } // repeated double field_double = 10; case 10: { let values = message.field_double || (message.field_double = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readDouble(bb)); } bb.limit = outerLimit; } else { values.push(readDouble(bb)); } break; } // repeated string field_string = 11; case 11: { let values = message.field_string || (message.field_string = []); values.push(readString(bb, readVarint32(bb))); break; } // repeated bytes field_bytes = 12; case 12: { let values = message.field_bytes || (message.field_bytes = []); values.push(readBytes(bb, readVarint32(bb))); break; } // repeated fixed32 field_fixed32 = 13; case 13: { let values = message.field_fixed32 || (message.field_fixed32 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readInt32(bb) >>> 0); } bb.limit = outerLimit; } else { values.push(readInt32(bb) >>> 0); } break; } // repeated sfixed32 field_sfixed32 = 14; case 14: { let values = message.field_sfixed32 || (message.field_sfixed32 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readInt32(bb)); } bb.limit = outerLimit; } else { values.push(readInt32(bb)); } break; } // repeated float field_float = 15; case 15: { let values = message.field_float || (message.field_float = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readFloat(bb)); } bb.limit = outerLimit; } else { values.push(readFloat(bb)); } break; } // repeated Nested field_nested = 16; case 16: { let limit = pushTemporaryLength(bb); let values = message.field_nested || (message.field_nested = []); values.push(_decodeNested(bb)); bb.limit = limit; break; } default: skipUnknownField(bb, tag & 7); } } return message; } export interface RepeatedPacked { field_int32?: number[]; field_int64?: Long[]; field_uint32?: number[]; field_uint64?: Long[]; field_sint32?: number[]; field_sint64?: Long[]; field_bool?: boolean[]; field_fixed64?: Long[]; field_sfixed64?: Long[]; field_double?: number[]; field_string?: string[]; field_bytes?: Uint8Array[]; field_fixed32?: number[]; field_sfixed32?: number[]; field_float?: number[]; field_nested?: Nested[]; } export function encodeRepeatedPacked(message: RepeatedPacked): Uint8Array { let bb = popByteBuffer(); _encodeRepeatedPacked(message, bb); return toUint8Array(bb); } function _encodeRepeatedPacked(message: RepeatedPacked, bb: ByteBuffer): void { // repeated int32 field_int32 = 1; let array$field_int32 = message.field_int32; if (array$field_int32 !== undefined) { let packed = popByteBuffer(); for (let value of array$field_int32) { writeVarint64(packed, intToLong(value)); } writeVarint32(bb, 10); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated int64 field_int64 = 2; let array$field_int64 = message.field_int64; if (array$field_int64 !== undefined) { let packed = popByteBuffer(); for (let value of array$field_int64) { writeVarint64(packed, value); } writeVarint32(bb, 18); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated uint32 field_uint32 = 3; let array$field_uint32 = message.field_uint32; if (array$field_uint32 !== undefined) { let packed = popByteBuffer(); for (let value of array$field_uint32) { writeVarint32(packed, value); } writeVarint32(bb, 26); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated uint64 field_uint64 = 4; let array$field_uint64 = message.field_uint64; if (array$field_uint64 !== undefined) { let packed = popByteBuffer(); for (let value of array$field_uint64) { writeVarint64(packed, value); } writeVarint32(bb, 34); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated sint32 field_sint32 = 5; let array$field_sint32 = message.field_sint32; if (array$field_sint32 !== undefined) { let packed = popByteBuffer(); for (let value of array$field_sint32) { writeVarint32ZigZag(packed, value); } writeVarint32(bb, 42); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated sint64 field_sint64 = 6; let array$field_sint64 = message.field_sint64; if (array$field_sint64 !== undefined) { let packed = popByteBuffer(); for (let value of array$field_sint64) { writeVarint64ZigZag(packed, value); } writeVarint32(bb, 50); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated bool field_bool = 7; let array$field_bool = message.field_bool; if (array$field_bool !== undefined) { let packed = popByteBuffer(); for (let value of array$field_bool) { writeByte(packed, value ? 1 : 0); } writeVarint32(bb, 58); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated fixed64 field_fixed64 = 8; let array$field_fixed64 = message.field_fixed64; if (array$field_fixed64 !== undefined) { let packed = popByteBuffer(); for (let value of array$field_fixed64) { writeInt64(packed, value); } writeVarint32(bb, 66); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated sfixed64 field_sfixed64 = 9; let array$field_sfixed64 = message.field_sfixed64; if (array$field_sfixed64 !== undefined) { let packed = popByteBuffer(); for (let value of array$field_sfixed64) { writeInt64(packed, value); } writeVarint32(bb, 74); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated double field_double = 10; let array$field_double = message.field_double; if (array$field_double !== undefined) { let packed = popByteBuffer(); for (let value of array$field_double) { writeDouble(packed, value); } writeVarint32(bb, 82); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated string field_string = 11; let array$field_string = message.field_string; if (array$field_string !== undefined) { for (let value of array$field_string) { writeVarint32(bb, 90); writeString(bb, value); } } // repeated bytes field_bytes = 12; let array$field_bytes = message.field_bytes; if (array$field_bytes !== undefined) { for (let value of array$field_bytes) { writeVarint32(bb, 98); writeVarint32(bb, value.length), writeBytes(bb, value); } } // repeated fixed32 field_fixed32 = 13; let array$field_fixed32 = message.field_fixed32; if (array$field_fixed32 !== undefined) { let packed = popByteBuffer(); for (let value of array$field_fixed32) { writeInt32(packed, value); } writeVarint32(bb, 106); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated sfixed32 field_sfixed32 = 14; let array$field_sfixed32 = message.field_sfixed32; if (array$field_sfixed32 !== undefined) { let packed = popByteBuffer(); for (let value of array$field_sfixed32) { writeInt32(packed, value); } writeVarint32(bb, 114); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated float field_float = 15; let array$field_float = message.field_float; if (array$field_float !== undefined) { let packed = popByteBuffer(); for (let value of array$field_float) { writeFloat(packed, value); } writeVarint32(bb, 122); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } // repeated Nested field_nested = 16; let array$field_nested = message.field_nested; if (array$field_nested !== undefined) { for (let value of array$field_nested) { writeVarint32(bb, 130); let nested = popByteBuffer(); _encodeNested(value, nested); writeVarint32(bb, nested.limit); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } } export function decodeRepeatedPacked(binary: Uint8Array): RepeatedPacked { return _decodeRepeatedPacked(wrapByteBuffer(binary)); } function _decodeRepeatedPacked(bb: ByteBuffer): RepeatedPacked { let message: RepeatedPacked = {} as any; end_of_message: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_message; // repeated int32 field_int32 = 1; case 1: { let values = message.field_int32 || (message.field_int32 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint32(bb)); } bb.limit = outerLimit; } else { values.push(readVarint32(bb)); } break; } // repeated int64 field_int64 = 2; case 2: { let values = message.field_int64 || (message.field_int64 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint64(bb, /* unsigned */ false)); } bb.limit = outerLimit; } else { values.push(readVarint64(bb, /* unsigned */ false)); } break; } // repeated uint32 field_uint32 = 3; case 3: { let values = message.field_uint32 || (message.field_uint32 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint32(bb) >>> 0); } bb.limit = outerLimit; } else { values.push(readVarint32(bb) >>> 0); } break; } // repeated uint64 field_uint64 = 4; case 4: { let values = message.field_uint64 || (message.field_uint64 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint64(bb, /* unsigned */ true)); } bb.limit = outerLimit; } else { values.push(readVarint64(bb, /* unsigned */ true)); } break; } // repeated sint32 field_sint32 = 5; case 5: { let values = message.field_sint32 || (message.field_sint32 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint32ZigZag(bb)); } bb.limit = outerLimit; } else { values.push(readVarint32ZigZag(bb)); } break; } // repeated sint64 field_sint64 = 6; case 6: { let values = message.field_sint64 || (message.field_sint64 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readVarint64ZigZag(bb)); } bb.limit = outerLimit; } else { values.push(readVarint64ZigZag(bb)); } break; } // repeated bool field_bool = 7; case 7: { let values = message.field_bool || (message.field_bool = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(!!readByte(bb)); } bb.limit = outerLimit; } else { values.push(!!readByte(bb)); } break; } // repeated fixed64 field_fixed64 = 8; case 8: { let values = message.field_fixed64 || (message.field_fixed64 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readInt64(bb, /* unsigned */ true)); } bb.limit = outerLimit; } else { values.push(readInt64(bb, /* unsigned */ true)); } break; } // repeated sfixed64 field_sfixed64 = 9; case 9: { let values = message.field_sfixed64 || (message.field_sfixed64 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readInt64(bb, /* unsigned */ false)); } bb.limit = outerLimit; } else { values.push(readInt64(bb, /* unsigned */ false)); } break; } // repeated double field_double = 10; case 10: { let values = message.field_double || (message.field_double = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readDouble(bb)); } bb.limit = outerLimit; } else { values.push(readDouble(bb)); } break; } // repeated string field_string = 11; case 11: { let values = message.field_string || (message.field_string = []); values.push(readString(bb, readVarint32(bb))); break; } // repeated bytes field_bytes = 12; case 12: { let values = message.field_bytes || (message.field_bytes = []); values.push(readBytes(bb, readVarint32(bb))); break; } // repeated fixed32 field_fixed32 = 13; case 13: { let values = message.field_fixed32 || (message.field_fixed32 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readInt32(bb) >>> 0); } bb.limit = outerLimit; } else { values.push(readInt32(bb) >>> 0); } break; } // repeated sfixed32 field_sfixed32 = 14; case 14: { let values = message.field_sfixed32 || (message.field_sfixed32 = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readInt32(bb)); } bb.limit = outerLimit; } else { values.push(readInt32(bb)); } break; } // repeated float field_float = 15; case 15: { let values = message.field_float || (message.field_float = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(readFloat(bb)); } bb.limit = outerLimit; } else { values.push(readFloat(bb)); } break; } // repeated Nested field_nested = 16; case 16: { let limit = pushTemporaryLength(bb); let values = message.field_nested || (message.field_nested = []); values.push(_decodeNested(bb)); bb.limit = limit; break; } default: skipUnknownField(bb, tag & 7); } } return message; } export interface EnumTest { a?: Enum; b: Enum; c?: Enum[]; } export function encodeEnumTest(message: EnumTest): Uint8Array { let bb = popByteBuffer(); _encodeEnumTest(message, bb); return toUint8Array(bb); } function _encodeEnumTest(message: EnumTest, bb: ByteBuffer): void { // optional Enum a = 1; let $a = message.a; if ($a !== undefined) { writeVarint32(bb, 8); writeVarint32(bb, encodeEnum[$a]); } // required Enum b = 2; let $b = message.b; if ($b !== undefined) { writeVarint32(bb, 16); writeVarint32(bb, encodeEnum[$b]); } // repeated Enum c = 3; let array$c = message.c; if (array$c !== undefined) { let packed = popByteBuffer(); for (let value of array$c) { writeVarint32(packed, encodeEnum[value]); } writeVarint32(bb, 26); writeVarint32(bb, packed.offset); writeByteBuffer(bb, packed); pushByteBuffer(packed); } } export function decodeEnumTest(binary: Uint8Array): EnumTest { return _decodeEnumTest(wrapByteBuffer(binary)); } function _decodeEnumTest(bb: ByteBuffer): EnumTest { let message: EnumTest = {} as any; end_of_message: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_message; // optional Enum a = 1; case 1: { message.a = decodeEnum[readVarint32(bb)]; break; } // required Enum b = 2; case 2: { message.b = decodeEnum[readVarint32(bb)]; break; } // repeated Enum c = 3; case 3: { let values = message.c || (message.c = []); if ((tag & 7) === 2) { let outerLimit = pushTemporaryLength(bb); while (!isAtEnd(bb)) { values.push(decodeEnum[readVarint32(bb)]); } bb.limit = outerLimit; } else { values.push(decodeEnum[readVarint32(bb)]); } break; } default: skipUnknownField(bb, tag & 7); } } if (message.b === undefined) throw new Error("Missing required field: b"); return message; } export interface MapTestIntAndString { field_int32?: { [key: number]: string }; field_uint32?: { [key: number]: Uint8Array }; field_sint32?: { [key: number]: Long }; field_string?: { [key: string]: number }; field_fixed32?: { [key: number]: boolean }; field_sfixed32?: { [key: number]: Nested }; } export function encodeMapTestIntAndString(message: MapTestIntAndString): Uint8Array { let bb = popByteBuffer(); _encodeMapTestIntAndString(message, bb); return toUint8Array(bb); } function _encodeMapTestIntAndString(message: MapTestIntAndString, bb: ByteBuffer): void { // optional map<int32, string> field_int32 = 1; let map$field_int32 = message.field_int32; if (map$field_int32 !== undefined) { for (let key in map$field_int32) { let nested = popByteBuffer(); let value = map$field_int32[key]; writeVarint32(nested, 8); writeVarint64(nested, intToLong(+key)); writeVarint32(nested, 18); writeString(nested, value); writeVarint32(bb, 10); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } // optional map<uint32, bytes> field_uint32 = 2; let map$field_uint32 = message.field_uint32; if (map$field_uint32 !== undefined) { for (let key in map$field_uint32) { let nested = popByteBuffer(); let value = map$field_uint32[key]; writeVarint32(nested, 8); writeVarint32(nested, +key); writeVarint32(nested, 18); writeVarint32(nested, value.length), writeBytes(nested, value); writeVarint32(bb, 18); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } // optional map<sint32, int64> field_sint32 = 3; let map$field_sint32 = message.field_sint32; if (map$field_sint32 !== undefined) { for (let key in map$field_sint32) { let nested = popByteBuffer(); let value = map$field_sint32[key]; writeVarint32(nested, 8); writeVarint32ZigZag(nested, +key); writeVarint32(nested, 16); writeVarint64(nested, value); writeVarint32(bb, 26); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } // optional map<string, double> field_string = 5; let map$field_string = message.field_string; if (map$field_string !== undefined) { for (let key in map$field_string) { let nested = popByteBuffer(); let value = map$field_string[key]; writeVarint32(nested, 10); writeString(nested, key); writeVarint32(nested, 17); writeDouble(nested, value); writeVarint32(bb, 42); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } // optional map<fixed32, bool> field_fixed32 = 6; let map$field_fixed32 = message.field_fixed32; if (map$field_fixed32 !== undefined) { for (let key in map$field_fixed32) { let nested = popByteBuffer(); let value = map$field_fixed32[key]; writeVarint32(nested, 13); writeInt32(nested, +key); writeVarint32(nested, 16); writeByte(nested, value ? 1 : 0); writeVarint32(bb, 50); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } // optional map<sfixed32, Nested> field_sfixed32 = 7; let map$field_sfixed32 = message.field_sfixed32; if (map$field_sfixed32 !== undefined) { for (let key in map$field_sfixed32) { let nested = popByteBuffer(); let value = map$field_sfixed32[key]; writeVarint32(nested, 13); writeInt32(nested, +key); writeVarint32(nested, 18); let nestedValue = popByteBuffer(); _encodeNested(value, nestedValue); writeVarint32(nested, nestedValue.limit); writeByteBuffer(nested, nestedValue); pushByteBuffer(nestedValue); writeVarint32(bb, 58); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } } export function decodeMapTestIntAndString(binary: Uint8Array): MapTestIntAndString { return _decodeMapTestIntAndString(wrapByteBuffer(binary)); } function _decodeMapTestIntAndString(bb: ByteBuffer): MapTestIntAndString { let message: MapTestIntAndString = {} as any; end_of_message: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_message; // optional map<int32, string> field_int32 = 1; case 1: { let values = message.field_int32 || (message.field_int32 = {}); let outerLimit = pushTemporaryLength(bb); let key: number | undefined; let value: string | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readVarint32(bb); break; } case 2: { value = readString(bb, readVarint32(bb)); break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_int32"); values[key] = value; bb.limit = outerLimit; break; } // optional map<uint32, bytes> field_uint32 = 2; case 2: { let values = message.field_uint32 || (message.field_uint32 = {}); let outerLimit = pushTemporaryLength(bb); let key: number | undefined; let value: Uint8Array | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readVarint32(bb) >>> 0; break; } case 2: { value = readBytes(bb, readVarint32(bb)); break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_uint32"); values[key] = value; bb.limit = outerLimit; break; } // optional map<sint32, int64> field_sint32 = 3; case 3: { let values = message.field_sint32 || (message.field_sint32 = {}); let outerLimit = pushTemporaryLength(bb); let key: number | undefined; let value: Long | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readVarint32ZigZag(bb); break; } case 2: { value = readVarint64(bb, /* unsigned */ false); break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_sint32"); values[key] = value; bb.limit = outerLimit; break; } // optional map<string, double> field_string = 5; case 5: { let values = message.field_string || (message.field_string = {}); let outerLimit = pushTemporaryLength(bb); let key: string | undefined; let value: number | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readString(bb, readVarint32(bb)); break; } case 2: { value = readDouble(bb); break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_string"); values[key] = value; bb.limit = outerLimit; break; } // optional map<fixed32, bool> field_fixed32 = 6; case 6: { let values = message.field_fixed32 || (message.field_fixed32 = {}); let outerLimit = pushTemporaryLength(bb); let key: number | undefined; let value: boolean | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readInt32(bb) >>> 0; break; } case 2: { value = !!readByte(bb); break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_fixed32"); values[key] = value; bb.limit = outerLimit; break; } // optional map<sfixed32, Nested> field_sfixed32 = 7; case 7: { let values = message.field_sfixed32 || (message.field_sfixed32 = {}); let outerLimit = pushTemporaryLength(bb); let key: number | undefined; let value: Nested | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readInt32(bb); break; } case 2: { let valueLimit = pushTemporaryLength(bb); value = _decodeNested(bb); bb.limit = valueLimit; break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_sfixed32"); values[key] = value; bb.limit = outerLimit; break; } default: skipUnknownField(bb, tag & 7); } } return message; } export interface MapTestLongAndBool { field_int64?: { [key: string]: string }; field_uint64?: { [key: string]: Uint8Array }; field_sint64?: { [key: string]: Long }; field_fixed64?: { [key: string]: number }; field_sfixed64?: { [key: string]: boolean }; field_bool?: { [key: string]: Nested }; } export function encodeMapTestLongAndBool(message: MapTestLongAndBool): Uint8Array { let bb = popByteBuffer(); _encodeMapTestLongAndBool(message, bb); return toUint8Array(bb); } function _encodeMapTestLongAndBool(message: MapTestLongAndBool, bb: ByteBuffer): void { // optional map<int64, string> field_int64 = 1; let map$field_int64 = message.field_int64; if (map$field_int64 !== undefined) { for (let key in map$field_int64) { let nested = popByteBuffer(); let value = map$field_int64[key]; writeVarint32(nested, 8); writeVarint64(nested, stringToLong(key)); writeVarint32(nested, 18); writeString(nested, value); writeVarint32(bb, 10); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } // optional map<uint64, bytes> field_uint64 = 2; let map$field_uint64 = message.field_uint64; if (map$field_uint64 !== undefined) { for (let key in map$field_uint64) { let nested = popByteBuffer(); let value = map$field_uint64[key]; writeVarint32(nested, 8); writeVarint64(nested, stringToLong(key)); writeVarint32(nested, 18); writeVarint32(nested, value.length), writeBytes(nested, value); writeVarint32(bb, 18); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } // optional map<sint64, int64> field_sint64 = 3; let map$field_sint64 = message.field_sint64; if (map$field_sint64 !== undefined) { for (let key in map$field_sint64) { let nested = popByteBuffer(); let value = map$field_sint64[key]; writeVarint32(nested, 8); writeVarint64ZigZag(nested, stringToLong(key)); writeVarint32(nested, 16); writeVarint64(nested, value); writeVarint32(bb, 26); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } // optional map<fixed64, double> field_fixed64 = 4; let map$field_fixed64 = message.field_fixed64; if (map$field_fixed64 !== undefined) { for (let key in map$field_fixed64) { let nested = popByteBuffer(); let value = map$field_fixed64[key]; writeVarint32(nested, 9); writeInt64(nested, stringToLong(key)); writeVarint32(nested, 17); writeDouble(nested, value); writeVarint32(bb, 34); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } // optional map<sfixed64, bool> field_sfixed64 = 5; let map$field_sfixed64 = message.field_sfixed64; if (map$field_sfixed64 !== undefined) { for (let key in map$field_sfixed64) { let nested = popByteBuffer(); let value = map$field_sfixed64[key]; writeVarint32(nested, 9); writeInt64(nested, stringToLong(key)); writeVarint32(nested, 16); writeByte(nested, value ? 1 : 0); writeVarint32(bb, 42); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } // optional map<bool, Nested> field_bool = 6; let map$field_bool = message.field_bool; if (map$field_bool !== undefined) { for (let key in map$field_bool) { let nested = popByteBuffer(); let value = map$field_bool[key]; writeVarint32(nested, 8); writeByte(nested, key === "true" ? 1 : 0); writeVarint32(nested, 18); let nestedValue = popByteBuffer(); _encodeNested(value, nestedValue); writeVarint32(nested, nestedValue.limit); writeByteBuffer(nested, nestedValue); pushByteBuffer(nestedValue); writeVarint32(bb, 50); writeVarint32(bb, nested.offset); writeByteBuffer(bb, nested); pushByteBuffer(nested); } } } export function decodeMapTestLongAndBool(binary: Uint8Array): MapTestLongAndBool { return _decodeMapTestLongAndBool(wrapByteBuffer(binary)); } function _decodeMapTestLongAndBool(bb: ByteBuffer): MapTestLongAndBool { let message: MapTestLongAndBool = {} as any; end_of_message: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_message; // optional map<int64, string> field_int64 = 1; case 1: { let values = message.field_int64 || (message.field_int64 = {}); let outerLimit = pushTemporaryLength(bb); let key: Long | undefined; let value: string | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readVarint64(bb, /* unsigned */ false); break; } case 2: { value = readString(bb, readVarint32(bb)); break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_int64"); values[longToString(key)] = value; bb.limit = outerLimit; break; } // optional map<uint64, bytes> field_uint64 = 2; case 2: { let values = message.field_uint64 || (message.field_uint64 = {}); let outerLimit = pushTemporaryLength(bb); let key: Long | undefined; let value: Uint8Array | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readVarint64(bb, /* unsigned */ true); break; } case 2: { value = readBytes(bb, readVarint32(bb)); break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_uint64"); values[longToString(key)] = value; bb.limit = outerLimit; break; } // optional map<sint64, int64> field_sint64 = 3; case 3: { let values = message.field_sint64 || (message.field_sint64 = {}); let outerLimit = pushTemporaryLength(bb); let key: Long | undefined; let value: Long | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readVarint64ZigZag(bb); break; } case 2: { value = readVarint64(bb, /* unsigned */ false); break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_sint64"); values[longToString(key)] = value; bb.limit = outerLimit; break; } // optional map<fixed64, double> field_fixed64 = 4; case 4: { let values = message.field_fixed64 || (message.field_fixed64 = {}); let outerLimit = pushTemporaryLength(bb); let key: Long | undefined; let value: number | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readInt64(bb, /* unsigned */ true); break; } case 2: { value = readDouble(bb); break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_fixed64"); values[longToString(key)] = value; bb.limit = outerLimit; break; } // optional map<sfixed64, bool> field_sfixed64 = 5; case 5: { let values = message.field_sfixed64 || (message.field_sfixed64 = {}); let outerLimit = pushTemporaryLength(bb); let key: Long | undefined; let value: boolean | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = readInt64(bb, /* unsigned */ false); break; } case 2: { value = !!readByte(bb); break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_sfixed64"); values[longToString(key)] = value; bb.limit = outerLimit; break; } // optional map<bool, Nested> field_bool = 6; case 6: { let values = message.field_bool || (message.field_bool = {}); let outerLimit = pushTemporaryLength(bb); let key: boolean | undefined; let value: Nested | undefined; end_of_entry: while (!isAtEnd(bb)) { let tag = readVarint32(bb); switch (tag >>> 3) { case 0: break end_of_entry; case 1: { key = !!readByte(bb); break; } case 2: { let valueLimit = pushTemporaryLength(bb); value = _decodeNested(bb); bb.limit = valueLimit; break; } default: skipUnknownField(bb, tag & 7); } } if (key === undefined || value === undefined) throw new Error("Invalid data for map: field_bool"); values[key + ''] = value; bb.limit = outerLimit; break; } default: skipUnknownField(bb, tag & 7); } } return message; } export interface Long { low: number; high: number; unsigned: boolean; } interface ByteBuffer { bytes: Uint8Array; offset: number; limit: number; } function pushTemporaryLength(bb: ByteBuffer): number { let length = readVarint32(bb); let limit = bb.limit; bb.limit = bb.offset + length; return limit; } function skipUnknownField(bb: ByteBuffer, type: number): void { switch (type) { case 0: while (readByte(bb) & 0x80) { } break; case 2: skip(bb, readVarint32(bb)); break; case 5: skip(bb, 4); break; case 1: skip(bb, 8); break; default: throw new Error("Unimplemented type: " + type); } } function stringToLong(value: string): Long { return { low: value.charCodeAt(0) | (value.charCodeAt(1) << 16), high: value.charCodeAt(2) | (value.charCodeAt(3) << 16), unsigned: false, }; } function longToString(value: Long): string { let low = value.low; let high = value.high; return String.fromCharCode( low & 0xFFFF, low >>> 16, high & 0xFFFF, high >>> 16); } // The code below was modified from https://github.com/protobufjs/bytebuffer.js // which is under the Apache License 2.0. let f32 = new Float32Array(1); let f32_u8 = new Uint8Array(f32.buffer); let f64 = new Float64Array(1); let f64_u8 = new Uint8Array(f64.buffer); function intToLong(value: number): Long { value |= 0; return { low: value, high: value >> 31, unsigned: value >= 0, }; } let bbStack: ByteBuffer[] = []; function popByteBuffer(): ByteBuffer { const bb = bbStack.pop(); if (!bb) return { bytes: new Uint8Array(64), offset: 0, limit: 0 }; bb.offset = bb.limit = 0; return bb; } function pushByteBuffer(bb: ByteBuffer): void { bbStack.push(bb); } function wrapByteBuffer(bytes: Uint8Array): ByteBuffer { return { bytes, offset: 0, limit: bytes.length }; } function toUint8Array(bb: ByteBuffer): Uint8Array { let bytes = bb.bytes; let limit = bb.limit; return bytes.length === limit ? bytes : bytes.subarray(0, limit); } function skip(bb: ByteBuffer, offset: number): void { if (bb.offset + offset > bb.limit) { throw new Error('Skip past limit'); } bb.offset += offset; } function isAtEnd(bb: ByteBuffer): boolean { return bb.offset >= bb.limit; } function grow(bb: ByteBuffer, count: number): number { let bytes = bb.bytes; let offset = bb.offset; let limit = bb.limit; let finalOffset = offset + count; if (finalOffset > bytes.length) { let newBytes = new Uint8Array(finalOffset * 2); newBytes.set(bytes); bb.bytes = newBytes; } bb.offset = finalOffset; if (finalOffset > limit) { bb.limit = finalOffset; } return offset; } function advance(bb: ByteBuffer, count: number): number { let offset = bb.offset; if (offset + count > bb.limit) { throw new Error('Read past limit'); } bb.offset += count; return offset; } function readBytes(bb: ByteBuffer, count: number): Uint8Array { let offset = advance(bb, count); return bb.bytes.subarray(offset, offset + count); } function writeBytes(bb: ByteBuffer, buffer: Uint8Array): void { let offset = grow(bb, buffer.length); bb.bytes.set(buffer, offset); } function readString(bb: ByteBuffer, count: number): string { // Sadly a hand-coded UTF8 decoder is much faster than subarray+TextDecoder in V8 let offset = advance(bb, count); let fromCharCode = String.fromCharCode; let bytes = bb.bytes; let invalid = '\uFFFD'; let text = ''; for (let i = 0; i < count; i++) { let c1 = bytes[i + offset], c2: number, c3: number, c4: number, c: number; // 1 byte if ((c1 & 0x80) === 0) { text += fromCharCode(c1); } // 2 bytes else if ((c1 & 0xE0) === 0xC0) { if (i + 1 >= count) text += invalid; else { c2 = bytes[i + offset + 1]; if ((c2 & 0xC0) !== 0x80) text += invalid; else { c = ((c1 & 0x1F) << 6) | (c2 & 0x3F); if (c < 0x80) text += invalid; else { text += fromCharCode(c); i++; } } } } // 3 bytes else if ((c1 & 0xF0) == 0xE0) { if (i + 2 >= count) text += invalid; else { c2 = bytes[i + offset + 1]; c3 = bytes[i + offset + 2]; if (((c2 | (c3 << 8)) & 0xC0C0) !== 0x8080) text += invalid; else { c = ((c1 & 0x0F) << 12) | ((c2 & 0x3F) << 6) | (c3 & 0x3F); if (c < 0x0800 || (c >= 0xD800 && c <= 0xDFFF)) text += invalid; else { text += fromCharCode(c); i += 2; } } } } // 4 bytes else if ((c1 & 0xF8) == 0xF0) { if (i + 3 >= count) text += invalid; else { c2 = bytes[i + offset + 1]; c3 = bytes[i + offset + 2]; c4 = bytes[i + offset + 3]; if (((c2 | (c3 << 8) | (c4 << 16)) & 0xC0C0C0) !== 0x808080) text += invalid; else { c = ((c1 & 0x07) << 0x12) | ((c2 & 0x3F) << 0x0C) | ((c3 & 0x3F) << 0x06) | (c4 & 0x3F); if (c < 0x10000 || c > 0x10FFFF) text += invalid; else { c -= 0x10000; text += fromCharCode((c >> 10) + 0xD800, (c & 0x3FF) + 0xDC00); i += 3; } } } } else text += invalid; } return text; } function writeString(bb: ByteBuffer, text: string): void { // Sadly a hand-coded UTF8 encoder is much faster than TextEncoder+set in V8 let n = text.length; let byteCount = 0; // Write the byte count first for (let i = 0; i < n; i++) { let c = text.charCodeAt(i); if (c >= 0xD800 && c <= 0xDBFF && i + 1 < n) { c = (c << 10) + text.charCodeAt(++i) - 0x35FDC00; } byteCount += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } writeVarint32(bb, byteCount); let offset = grow(bb, byteCount); let bytes = bb.bytes; // Then write the bytes for (let i = 0; i < n; i++) { let c = text.charCodeAt(i); if (c >= 0xD800 && c <= 0xDBFF && i + 1 < n) { c = (c << 10) + text.charCodeAt(++i) - 0x35FDC00; } if (c < 0x80) { bytes[offset++] = c; } else { if (c < 0x800) { bytes[offset++] = ((c >> 6) & 0x1F) | 0xC0; } else { if (c < 0x10000) { bytes[offset++] = ((c >> 12) & 0x0F) | 0xE0; } else { bytes[offset++] = ((c >> 18) & 0x07) | 0xF0; bytes[offset++] = ((c >> 12) & 0x3F) | 0x80; } bytes[offset++] = ((c >> 6) & 0x3F) | 0x80; } bytes[offset++] = (c & 0x3F) | 0x80; } } } function writeByteBuffer(bb: ByteBuffer, buffer: ByteBuffer): void { let offset = grow(bb, buffer.limit); let from = bb.bytes; let to = buffer.bytes; // This for loop is much faster than subarray+set on V8 for (let i = 0, n = buffer.limit; i < n; i++) { from[i + offset] = to[i]; } } function readByte(bb: ByteBuffer): number { return bb.bytes[advance(bb, 1)]; } function writeByte(bb: ByteBuffer, value: number): void { let offset = grow(bb, 1); bb.bytes[offset] = value; } function readFloat(bb: ByteBuffer): number { let offset = advance(bb, 4); let bytes = bb.bytes; // Manual copying is much faster than subarray+set in V8 f32_u8[0] = bytes[offset++]; f32_u8[1] = bytes[offset++]; f32_u8[2] = bytes[offset++]; f32_u8[3] = bytes[offset++]; return f32[0]; } function writeFloat(bb: ByteBuffer, value: number): void { let offset = grow(bb, 4); let bytes = bb.bytes; f32[0] = value; // Manual copying is much faster than subarray+set in V8 bytes[offset++] = f32_u8[0]; bytes[offset++] = f32_u8[1]; bytes[offset++] = f32_u8[2]; bytes[offset++] = f32_u8[3]; } function readDouble(bb: ByteBuffer): number { let offset = advance(bb, 8); let bytes = bb.bytes; // Manual copying is much faster than subarray+set in V8 f64_u8[0] = bytes[offset++]; f64_u8[1] = bytes[offset++]; f64_u8[2] = bytes[offset++]; f64_u8[3] = bytes[offset++]; f64_u8[4] = bytes[offset++]; f64_u8[5] = bytes[offset++]; f64_u8[6] = bytes[offset++]; f64_u8[7] = bytes[offset++]; return f64[0]; } function writeDouble(bb: ByteBuffer, value: number): void { let offset = grow(bb, 8); let bytes = bb.bytes; f64[0] = value; // Manual copying is much faster than subarray+set in V8 bytes[offset++] = f64_u8[0]; bytes[offset++] = f64_u8[1]; bytes[offset++] = f64_u8[2]; bytes[offset++] = f64_u8[3]; bytes[offset++] = f64_u8[4]; bytes[offset++] = f64_u8[5]; bytes[offset++] = f64_u8[6]; bytes[offset++] = f64_u8[7]; } function readInt32(bb: ByteBuffer): number { let offset = advance(bb, 4); let bytes = bb.bytes; return ( bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16) | (bytes[offset + 3] << 24) ); } function writeInt32(bb: ByteBuffer, value: number): void { let offset = grow(bb, 4); let bytes = bb.bytes; bytes[offset] = value; bytes[offset + 1] = value >> 8; bytes[offset + 2] = value >> 16; bytes[offset + 3] = value >> 24; } function readInt64(bb: ByteBuffer, unsigned: boolean): Long { return { low: readInt32(bb), high: readInt32(bb), unsigned, }; } function writeInt64(bb: ByteBuffer, value: Long): void { writeInt32(bb, value.low); writeInt32(bb, value.high); } function readVarint32(bb: ByteBuffer): number { let c = 0; let value = 0; let b: number; do { b = readByte(bb); if (c < 32) value |= (b & 0x7F) << c; c += 7; } while (b & 0x80); return value; } function writeVarint32(bb: ByteBuffer, value: number): void { value >>>= 0; while (value >= 0x80) { writeByte(bb, (value & 0x7f) | 0x80); value >>>= 7; } writeByte(bb, value); } function readVarint64(bb: ByteBuffer, unsigned: boolean): Long { let part0 = 0; let part1 = 0; let part2 = 0; let b: number; b = readByte(bb); part0 = (b & 0x7F); if (b & 0x80) { b = readByte(bb); part0 |= (b & 0x7F) << 7; if (b & 0x80) { b = readByte(bb); part0 |= (b & 0x7F) << 14; if (b & 0x80) { b = readByte(bb); part0 |= (b & 0x7F) << 21; if (b & 0x80) { b = readByte(bb); part1 = (b & 0x7F); if (b & 0x80) { b = readByte(bb); part1 |= (b & 0x7F) << 7; if (b & 0x80) { b = readByte(bb); part1 |= (b & 0x7F) << 14; if (b & 0x80) { b = readByte(bb); part1 |= (b & 0x7F) << 21; if (b & 0x80) { b = readByte(bb); part2 = (b & 0x7F); if (b & 0x80) { b = readByte(bb); part2 |= (b & 0x7F) << 7; } } } } } } } } } return { low: part0 | (part1 << 28), high: (part1 >>> 4) | (part2 << 24), unsigned, }; } function writeVarint64(bb: ByteBuffer, value: Long): void { let part0 = value.low >>> 0; let part1 = ((value.low >>> 28) | (value.high << 4)) >>> 0; let part2 = value.high >>> 24; // ref: src/google/protobuf/io/coded_stream.cc let size = part2 === 0 ? part1 === 0 ? part0 < 1 << 14 ? part0 < 1 << 7 ? 1 : 2 : part0 < 1 << 21 ? 3 : 4 : part1 < 1 << 14 ? part1 < 1 << 7 ? 5 : 6 : part1 < 1 << 21 ? 7 : 8 : part2 < 1 << 7 ? 9 : 10; let offset = grow(bb, size); let bytes = bb.bytes; switch (size) { case 10: bytes[offset + 9] = (part2 >>> 7) & 0x01; case 9: bytes[offset + 8] = size !== 9 ? part2 | 0x80 : part2 & 0x7F; case 8: bytes[offset + 7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F; case 7: bytes[offset + 6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F; case 6: bytes[offset + 5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F; case 5: bytes[offset + 4] = size !== 5 ? part1 | 0x80 : part1 & 0x7F; case 4: bytes[offset + 3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F; case 3: bytes[offset + 2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F; case 2: bytes[offset + 1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F; case 1: bytes[offset] = size !== 1 ? part0 | 0x80 : part0 & 0x7F; } } function readVarint32ZigZag(bb: ByteBuffer): number { let value = readVarint32(bb); // ref: src/google/protobuf/wire_format_lite.h return (value >>> 1) ^ -(value & 1); } function writeVarint32ZigZag(bb: ByteBuffer, value: number): void { // ref: src/google/protobuf/wire_format_lite.h writeVarint32(bb, (value << 1) ^ (value >> 31)); } function readVarint64ZigZag(bb: ByteBuffer): Long { let value = readVarint64(bb, /* unsigned */ false); let low = value.low; let high = value.high; let flip = -(low & 1); // ref: src/google/protobuf/wire_format_lite.h return { low: ((low >>> 1) | (high << 31)) ^ flip, high: (high >>> 1) ^ flip, unsigned: false, }; } function writeVarint64ZigZag(bb: ByteBuffer, value: Long): void { let low = value.low; let high = value.high; let flip = high >> 31; // ref: src/google/protobuf/wire_format_lite.h writeVarint64(bb, { low: (low << 1) ^ flip, high: ((high << 1) | (low >>> 31)) ^ flip, unsigned: false, }); }
the_stack
/// <reference path="../Primitives/DateTime.ts" /> /// <reference path="Format.ts" /> module Fayde.Localization { RegisterFormattable(DateTime, (obj: any, format: string, provider?: any): string => { if (!format) return undefined; if (obj == null) return null; if (obj.constructor !== DateTime) return null; var res = tryStandardFormat(<DateTime>obj, format); if (res != undefined) return res; return tryCustomFormat(<DateTime>obj, format, TimeSpan.MinValue); }); // Standard Formats // d Short date // D Long date // f Full date/time (short time) // F Full date/time (long time) // g General date/time (short time) // G General date/time (long time) // M, m Month/day // R, r RFC1123 // s Sortable date/time // t Short time // T Long time // u Universal sortable date/time // U Universal full date/time // Y, y Year month function tryStandardFormat(obj: DateTime, format: string): string { if (format.length !== 1) return undefined; var ch = format[0]; if (!ch) return undefined; var f = standardFormatters[ch]; if (!f) return undefined; return f(obj); } interface IStandardFormatter { (obj: DateTime): string; } var standardFormatters: IStandardFormatter[] = []; standardFormatters["d"] = function (obj: DateTime): string { return [ obj.Month.toString(), obj.Day.toString(), obj.Year.toString() ].join("/"); }; standardFormatters["D"] = function (obj: DateTime): string { var info = DateTimeFormatInfo.Instance; return [ info.DayNames[obj.DayOfWeek], ", ", info.MonthNames[obj.Month - 1], " ", obj.Day.toString(), ", ", obj.Year.toString() ].join(""); }; standardFormatters["f"] = function (obj: DateTime): string { return [ standardFormatters["D"](obj), standardFormatters["t"](obj) ].join(" "); }; standardFormatters["F"] = function (obj: DateTime): string { return [ standardFormatters["D"](obj), standardFormatters["T"](obj) ].join(" "); }; standardFormatters["g"] = function (obj: DateTime): string { return [ standardFormatters["d"](obj), standardFormatters["t"](obj) ].join(" "); }; standardFormatters["G"] = function (obj: DateTime): string { return [ standardFormatters["d"](obj), standardFormatters["T"](obj) ].join(" "); }; standardFormatters["m"] = standardFormatters["M"] = function (obj: DateTime): string { var info = DateTimeFormatInfo.Instance; return [ info.MonthNames[obj.Month - 1], obj.Day ].join(" "); }; standardFormatters["r"] = standardFormatters["R"] = function (obj: DateTime): string { var utc = obj.ToUniversalTime(); var info = DateTimeFormatInfo.Instance; return [ info.AbbreviatedDayNames[utc.DayOfWeek], ", ", utc.Day, " ", info.AbbreviatedMonthNames[utc.Month-1], " ", utc.Year, " ", utc.Hour, ":", utc.Minute, ":", utc.Second, " GMT" ].join(""); }; standardFormatters["s"] = function (obj: DateTime): string { return [ obj.Year, "-", padded(obj.Month), "-", padded(obj.Day), "T", padded(obj.Hour), ":", padded(obj.Minute), ":", padded(obj.Second) ].join(""); }; standardFormatters["t"] = function (obj: DateTime): string { var info = DateTimeFormatInfo.Instance; var hour = obj.Hour; var desig = info.AMDesignator; if (hour > 12) { hour -= 12; desig = info.PMDesignator; } return [ hour.toString(), ":", obj.Minute.toString(), " ", desig ].join(""); }; standardFormatters["T"] = function (obj: DateTime): string { var info = DateTimeFormatInfo.Instance; var hour = obj.Hour; var desig = info.AMDesignator; if (hour > 12) { hour -= 12; desig = info.PMDesignator; } return [ hour.toString(), ":", obj.Minute.toString(), ":", obj.Second.toString(), " ", desig ].join(""); }; standardFormatters["u"] = function (obj: DateTime): string { return [ obj.Year.toString(), "-", padded(obj.Month), "-", padded(obj.Day), " ", padded(obj.Hour), ":", padded(obj.Minute), ":", padded(obj.Second), "Z" ].join(""); }; standardFormatters["U"] = function (obj: DateTime): string { var info = DateTimeFormatInfo.Instance; var hour = obj.Hour; var desig = info.AMDesignator; if (hour > 12) { hour -= 12; desig = info.PMDesignator; } return [ info.DayNames[obj.DayOfWeek], ", ", info.MonthNames[obj.Month-1], " ", obj.Day.toString(), ", ", obj.Year.toString(), " ", hour.toString(), ":", obj.Minute.toString(), ":", obj.Second.toString(), " ", desig ].join(""); }; standardFormatters["y"] = standardFormatters["Y"] = function (obj: DateTime): string { var info = DateTimeFormatInfo.Instance; return [ info.MonthNames[obj.Month - 1], obj.Year ].join(", "); }; function padded(num: number): string { return num < 10 ? "0" + num.toString() : num.toString(); } function tryCustomFormat(obj: DateTime, format: string, offset: TimeSpan): string { var info = DateTimeFormatInfo.Instance; var calendar = info.Calendar; var stringBuilder: string[] = []; var flag = calendar.ID === 8; var timeOnly = true; var index = 0; var len: number; while (index < format.length) { var patternChar = format[index]; switch (patternChar) { case 'm': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); DateTimeFormatInfo.FormatDigits(stringBuilder, obj.Minute, len); break; case 's': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); DateTimeFormatInfo.FormatDigits(stringBuilder, obj.Second, len); break; case 't': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); if (len === 1) { if (obj.Hour < 12) { if (info.AMDesignator.length >= 1) { stringBuilder.push(info.AMDesignator[0]); break; } else break; } else if (info.PMDesignator.length >= 1) { stringBuilder.push(info.PMDesignator[0]); break; } else break; } else { stringBuilder.push(obj.Hour < 12 ? info.AMDesignator : info.PMDesignator); break; } case 'y': var year = obj.Year; len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); if (info.HasForceTwoDigitYears) DateTimeFormatInfo.FormatDigits(stringBuilder, year, len <= 2 ? len : 2); else if (calendar.ID === 8) DateTimeFormatInfo.HebrewFormatDigits(stringBuilder, year); else if (len <= 2) { DateTimeFormatInfo.FormatDigits(stringBuilder, year % 100, len); } else { stringBuilder.push(FormatSingle(year, "D" + len.toString())); } timeOnly = false; break; case 'z': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); //DateTimeFormatInfo.FormatCustomizedTimeZone(obj, offset, format, len, timeOnly, stringBuilder); console.warn("DateTime 'z' not implemented"); break; case 'K': len = 1; //DateTimeFormatInfo.FormatCustomizedRoundripTimeZone(obj, offset, stringBuilder); console.warn("DateTime 'K' not implemented"); break; case 'M': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); var month = obj.Month; if (len <= 2) { if (flag) DateTimeFormatInfo.HebrewFormatDigits(stringBuilder, month); else DateTimeFormatInfo.FormatDigits(stringBuilder, month, len); } else if (flag) stringBuilder.push(DateTimeFormatInfo.FormatHebrewMonthName(obj, month, len, info)); /*else if ((info.FormatFlags & DateTimeFormatFlags.UseGenitiveMonth) !== DateTimeFormatFlags.None && len >= 4) stringBuilder.push(info.internalGetMonthName(month, DateTimeFormat.IsUseGenitiveForm(format, index, len, 'd') ? MonthNameStyles.Genitive : MonthNameStyles.Regular, false));*/ else stringBuilder.push(DateTimeFormatInfo.FormatMonth(month, len, info)); timeOnly = false; break; case '\\': var num2 = DateTimeFormatInfo.ParseNextChar(format, index); if (num2 < 0) throw formatError(); stringBuilder.push(String.fromCharCode(num2)); len = 2; break; case 'd': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); if (len <= 2) { var dayOfMonth = obj.Day; if (flag) DateTimeFormatInfo.HebrewFormatDigits(stringBuilder, dayOfMonth); else DateTimeFormatInfo.FormatDigits(stringBuilder, dayOfMonth, len); } else { var dayOfWeek = obj.DayOfWeek; stringBuilder.push(DateTimeFormatInfo.FormatDayOfWeek(dayOfWeek, len, info)); } timeOnly = false; break; case 'f': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); if (len > 7) throw formatError(); stringBuilder.push(msf(obj.Millisecond, len)); break; case 'F': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); if (len > 7) throw formatError(); stringBuilder.push(msF(obj.Millisecond, len)); break; case 'g': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); stringBuilder.push(info.GetEraName(1)); break; case 'h': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); var num5 = obj.Hour % 12; if (num5 === 0) num5 = 12; DateTimeFormatInfo.FormatDigits(stringBuilder, num5, len); break; case '/': stringBuilder.push(info.DateSeparator); len = 1; break; case ':': stringBuilder.push(info.TimeSeparator); len = 1; break; case 'H': len = DateTimeFormatInfo.ParseRepeatPattern(format, index, patternChar); DateTimeFormatInfo.FormatDigits(stringBuilder, obj.Hour, len); break; case '"': case '\'': len = DateTimeFormatInfo.ParseQuoteString(format, index, stringBuilder); break; case '%': var num6 = DateTimeFormatInfo.ParseNextChar(format, index); if (num6 < 0 || num6 === 37) throw formatError(); stringBuilder.push(tryCustomFormat(obj, String.fromCharCode(num6), offset)); len = 2; break; default: stringBuilder.push(patternChar); len = 1; break; } index += len; } return stringBuilder.join(""); } function msf(ms: number, len: number): string { var s = Math.abs(ms).toString(); while (s.length < 3) s = "0" + s; s += "0000"; return s.substr(0, len); } function msF(ms: number, len: number): string { var f = msf(ms, len); var end = f.length - 1; for (; end >= 0; end--) { if (f[end] !== "0") break; } return f.slice(0, end + 1); } function formatError(): FormatException { return new FormatException("Invalid format string."); } }
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview Code that is common to all condition-based filtering of lists. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.filterLabelWidth = VRS.globalOptions.filterLabelWidth !== undefined ? VRS.globalOptions.filterLabelWidth : VRS.LabelWidth.Short; // The default width for labels in the filter options UI. /** * Options that can be applied when matching values in a filter. */ export interface Filter_Options { caseInsensitive?: boolean; } export interface IValueCondition { getCondition() : FilterConditionEnum; setCondition(filter: FilterConditionEnum); getReverseCondition() : boolean; setReverseCondition(reverseCondition: boolean); equals(other: IValueCondition) : boolean; clone() : IValueCondition; toSerialisableObject() : ISerialisedCondition; applySerialisedObject(obj: ISerialisedCondition); } /** * The base for all value conditions. */ export abstract class ValueCondition implements IValueCondition { protected _Condition: FilterConditionEnum; protected _ReverseCondition: boolean; constructor(condition: FilterConditionEnum, reverseCondition?: boolean) { this._Condition = condition; this._ReverseCondition = reverseCondition; } getCondition() : FilterConditionEnum { return this._Condition; } setCondition(value: FilterConditionEnum) { this._Condition = value; } getReverseCondition() : boolean { return this._ReverseCondition; } setReverseCondition(value: boolean) { this._ReverseCondition = value; } abstract equals(other: ValueCondition) : boolean; abstract clone() : ValueCondition; abstract toSerialisableObject() : ISerialisedCondition; abstract applySerialisedObject(obj: ISerialisedCondition); } /** * Describes a condition with single parameter that can be tested against a value. */ export class OneValueCondition extends ValueCondition { private _Value: any; constructor(condition: FilterConditionEnum, reverseCondition?: boolean, value?: any) { super(condition, reverseCondition); this._Value = value; } getValue() : any { return this._Value; } setValue(value: any) { this._Value = value; } equals(obj: OneValueCondition) : boolean { return this.getCondition() === obj.getCondition() && this.getReverseCondition() === obj.getReverseCondition() && this.getValue() === obj.getValue(); } clone() : OneValueCondition { return new OneValueCondition(this.getCondition(), this.getReverseCondition(), this.getValue()); } toSerialisableObject() : ISerialisedOneValueCondition { return { condition: this._Condition, reversed: this._ReverseCondition, value: this._Value }; } applySerialisedObject(settings: ISerialisedOneValueCondition) { this.setCondition(settings.condition); this.setReverseCondition(settings.reversed); this.setValue(settings.value); } } /** * Describes a condition that takes two parameters to be tested against a value. */ export class TwoValueCondition extends ValueCondition { private _Value1: any; private _Value2: any; private _Value1IsLow: boolean; constructor(condition: FilterConditionEnum, reverseCondition?: boolean, value1?: any, value2?: any) { super(condition, reverseCondition); this._Value1 = value1; this._Value2 = value2; } getValue1() : any { return this._Value1; } setValue1(value: any) { if(value !== this._Value1) { this._Value1 = value; this.orderValues(); } } getValue2() : any { return this._Value2; } setValue2(value: any) { if(value !== this._Value2) { this._Value2 = value; this.orderValues(); } } getLowValue() : any { return this._Value1IsLow ? this._Value1 : this._Value2; } getHighValue() : any { return this._Value1IsLow ? this._Value2 : this._Value1; } private orderValues() { if(this._Value1 === undefined || this._Value2 === undefined) this._Value1IsLow = true; else this._Value1IsLow = this._Value1 <= this._Value2; } equals(obj: TwoValueCondition) : boolean { return this.getCondition() === obj.getCondition() && this.getReverseCondition() === obj.getReverseCondition() && this.getValue1() === obj.getValue1() && this.getValue2() === obj.getValue2(); } clone() : TwoValueCondition { return new VRS.TwoValueCondition(this.getCondition(), this.getReverseCondition(), this.getValue1(), this.getValue2()); } toSerialisableObject() : ISerialisedTwoValueCondition { return { condition: this._Condition, reversed: this._ReverseCondition, value1: this._Value1, value2: this._Value2 } } applySerialisedObject(settings: ISerialisedTwoValueCondition) { this.setCondition(settings.condition); this.setReverseCondition(settings.reversed); this.setValue1(settings.value1); this.setValue2(settings.value2); } } /** * Describes a condition without a value. */ export interface Condition { condition: FilterConditionEnum; reverseCondition: boolean; labelKey: string; } /** * The settings to use when creating a new FilterPropertyTypeHandler. */ export interface FilterPropertyTypeHandler_Settings { /** * The VRS.FilterPropertyType that this object handles. */ type: FilterPropertyTypeEnum; /** * Returns an array of condition enum values and their text keys. */ getConditions?: () => Condition[]; /** * Returns a new condition and values object. */ createValueCondition: () => ValueCondition; /** * Mandatory if useSingleValueEquals is false, takes a value and a value/condition object and returns true if the value passes the filter. */ valuePassesCallback?: (value: any, valueCondition: ValueCondition, options?: Filter_Options) => boolean; /** * True if the aircraft property is just compared as equal to the filter. Pre-fills 'valuePassesCallback'. */ useSingleValueEquals?: boolean; /** * True if the aircraft property is to lie between a range of values. Pre-fills 'valuePassesCallback'. */ useValueBetweenRange?: boolean; /** * Takes a label key, a value/condition object, a filter property handler and a saveState callback and returns an array of option fields. */ createOptionFieldsCallback: (labelKey: string, valueCondition: ValueCondition, handler: FilterPropertyHandler, saveState: () => void) => OptionField[]; /** * Parses a string into the correct type. Returns undefined or null if the string is unparseable. */ parseString: (str: string) => any; /** * Formats a value into a query string value. Returns null or undefined if the value is empty / missing. */ toQueryString: (value: any) => string; /** * Returns true if empty values are to be passed to the server. Defaults to function that returns false. */ passEmptyValues?: (valueCondition: ValueCondition) => boolean; } /** * An object that matches a filter property type (boolean, numeric etc.) with the value filter required to test the * a property of this type and details of the UI required to collect those filter's parameters from the user. */ export class FilterPropertyTypeHandler { // Keeping these as public fields for backwards compatibility type: FilterPropertyTypeEnum; getConditions: () => Condition[]; createValueCondition: () => ValueCondition; createOptionFieldsCallback: (labelKey: string, valueCondition: ValueCondition, handler: FilterPropertyHandler, saveState: () => void) => OptionField[]; valuePassesCallback: (value: any, valueCondition: ValueCondition, options?: Filter_Options) => boolean; parseString: (str: string) => any; passEmptyValues: (valueCondition: ValueCondition) => boolean; toQueryString: (value: any) => string; constructor(settings: FilterPropertyTypeHandler_Settings) { if(!settings) throw 'You must supply a settings object'; if(settings.useSingleValueEquals) settings.valuePassesCallback = this.singleValueEquals; if(settings.useValueBetweenRange) settings.valuePassesCallback = this.valueBetweenRange; if(!settings.type || !VRS.enumHelper.getEnumName(VRS.FilterPropertyType, settings.type)) throw 'You must supply a property type'; if(!settings.createValueCondition) throw 'You must supply a createValueCondition'; if(!settings.valuePassesCallback) throw 'You must supply an valuePassesCallback'; if(!settings.createOptionFieldsCallback) throw 'You must supply a createOptionFieldsCallback'; this.type = settings.type; this.getConditions = settings.getConditions; this.createValueCondition = settings.createValueCondition; this.createOptionFieldsCallback = settings.createOptionFieldsCallback; this.valuePassesCallback = settings.valuePassesCallback; this.parseString = settings.parseString; this.passEmptyValues = settings.passEmptyValues || function() { return false; }; this.toQueryString = settings.toQueryString; } /** * Returns true if a value is equal to the value held by the parameters. */ private singleValueEquals(value: any, valueCondition: OneValueCondition) : boolean { var filterValue = valueCondition.getValue(); var result = filterValue === undefined; if(!result) { switch(valueCondition.getCondition()) { case VRS.FilterCondition.Equals: result = filterValue === value; break; default: throw 'Invalid condition ' + valueCondition.getCondition() + ' for a ' + this.type + ' filter type'; } if(valueCondition.getReverseCondition()) result = !result; } return result; } /** * Returns true if the value is between the values held by the parameters. */ private valueBetweenRange(value: any, valueCondition: TwoValueCondition) : boolean { var filterLowValue = valueCondition.getLowValue(); var filterHighValue = valueCondition.getHighValue(); var result = filterLowValue === undefined && filterHighValue === undefined; if(!result) { switch(valueCondition.getCondition()) { case VRS.FilterCondition.Between: if(filterLowValue === undefined) result = value <= filterHighValue; else if(filterHighValue === undefined) result = value >= filterLowValue; else result = value >= filterLowValue && value <= filterHighValue; break; default: throw 'Invalid condition ' + valueCondition.getCondition() + ' for range property types'; } if(valueCondition.getReverseCondition()) result = !result; } return result; } /** * Returns an array of objects describing all of the filter conditions ready for use in a combo box drop-down. */ getConditionComboBoxValues() : ValueText[] { var result = []; var self = this; $.each(this.getConditions(), function(idx, condition) { result.push(new VRS.ValueText({ value: self.encodeConditionAndReverseCondition(condition.condition, condition.reverseCondition), textKey: condition.labelKey })); }); return result; } /** * Returns the condition and, if reverseCondition is true, a suffix to distinguish it as the reverse condition. */ encodeConditionAndReverseCondition(condition: FilterConditionEnum, reverseCondition: boolean) : string { return condition + (reverseCondition ? '_reversed' : ''); } /** * Takes a string encoded by encodeConditionAndReverseCondition and returns the original condition and reverseCondition flag. */ decodeConditionAndReverseCondition(encodedConditionAndReverse: string) : Condition { var markerPosn = encodedConditionAndReverse.indexOf('_reversed'); var condition: FilterConditionEnum = markerPosn === -1 ? encodedConditionAndReverse : encodedConditionAndReverse.substr(0, markerPosn); var reversed = markerPosn !== -1; return <Condition>{ condition: condition, reverseCondition: reversed }; } /** * Takes a value/condition and returns the condition and reverse condition values encoded as a single string. */ encodeCondition(valueCondition: ValueCondition) : string { return this.encodeConditionAndReverseCondition(valueCondition.getCondition(), valueCondition.getReverseCondition()); } /** * Takes a string that holds an encoded condition and the reverse condition flag and applies them to a value/condition object. */ applyEncodedCondition(valueCondition: ValueCondition, encodedCondition: string) { var decodedCondition = this.decodeConditionAndReverseCondition(encodedCondition); valueCondition.setCondition(decodedCondition.condition); valueCondition.setReverseCondition(decodedCondition.reverseCondition); } } /** * This is the list of pre-built (and potentially 3rd party) handlers for filter property types that describe how to * ask for the filter parameters used to test a property of a given type. */ export var filterPropertyTypeHandlers: { [index: string]: FilterPropertyTypeHandler } = VRS.filterPropertyTypeHandlers || {}; VRS.filterPropertyTypeHandlers[VRS.FilterPropertyType.DateRange] = new VRS.FilterPropertyTypeHandler({ type: VRS.FilterPropertyType.DateRange, createValueCondition: function() { return new VRS.TwoValueCondition(VRS.FilterCondition.Between); }, getConditions: function() { return [ { condition: VRS.FilterCondition.Between, reverseCondition: false, labelKey: 'Between' }, { condition: VRS.FilterCondition.Between, reverseCondition: true, labelKey: 'NotBetween' } ]}, useValueBetweenRange: true, createOptionFieldsCallback: function(labelKey: string, twoValueCondition: TwoValueCondition, handler: FilterPropertyHandler, saveState: () => void) { var self = this; var conditionValues = self.getConditionComboBoxValues(); return [ new VRS.OptionFieldLabel({ name: 'label', labelKey: labelKey, keepWithNext: true, labelWidth: VRS.globalOptions.filterLabelWidth }), new VRS.OptionFieldComboBox({ name: 'condition', getValue: function() { return self.encodeCondition(twoValueCondition); }, setValue: function(value) { self.applyEncodedCondition(twoValueCondition, value); }, saveState: saveState, values: conditionValues, keepWithNext: true }), new VRS.OptionFieldDate({ name: 'value1', getValue: function() { return twoValueCondition.getValue1(); }, setValue: function(value) { twoValueCondition.setValue1(value); }, inputWidth: handler.inputWidth, saveState: saveState, keepWithNext: true }), new VRS.OptionFieldLabel({ name: 'valueSeparator', labelKey: 'SeparateTwoValues', keepWithNext: true }), new VRS.OptionFieldDate({ name: 'value2', getValue: function() { return twoValueCondition.getValue2(); }, setValue: function(value) { twoValueCondition.setValue2(value); }, inputWidth: handler.inputWidth, saveState: saveState }) ]; }, parseString: function(text) { return VRS.dateHelper.parse(text); }, toQueryString: function(value) { return value ? VRS.dateHelper.toIsoFormatString(value, true, true) : null; } }); VRS.filterPropertyTypeHandlers[VRS.FilterPropertyType.EnumMatch] = new VRS.FilterPropertyTypeHandler({ type: VRS.FilterPropertyType.EnumMatch, createValueCondition: function() { return new VRS.OneValueCondition(VRS.FilterCondition.Equals); }, getConditions: function() { return [ { condition: VRS.FilterCondition.Equals, reverseCondition: false, labelKey: 'Equal' }, { condition: VRS.FilterCondition.Equals, reverseCondition: true, labelKey: 'NotEquals' } ]}, useSingleValueEquals: true, createOptionFieldsCallback: function(labelKey: string, oneValueCondition: OneValueCondition, handler: FilterPropertyHandler, saveState: () => void) { var self = this; var comboBoxValues = handler.getEnumValues(); if(!comboBoxValues) throw 'Property type handlers for enum types must supply a getEnumValues callback'; var conditionValues = self.getConditionComboBoxValues(); return [ new VRS.OptionFieldLabel({ name: 'label', labelKey: labelKey, keepWithNext: true, labelWidth: VRS.globalOptions.filterLabelWidth }), new VRS.OptionFieldComboBox({ name: 'condition', getValue: function() { return self.encodeCondition(oneValueCondition); }, setValue: function(value) { self.applyEncodedCondition(oneValueCondition, value); }, saveState: saveState, values: conditionValues, keepWithNext: true }), new VRS.OptionFieldComboBox({ name: 'value', getValue: function() { return oneValueCondition.getValue(); }, setValue: function(value) { oneValueCondition.setValue(value); }, saveState: saveState, values: comboBoxValues }) ]; }, parseString: function(text) { return text !== undefined && text !== null ? text : undefined; }, toQueryString: function(value) { return value; } }); VRS.filterPropertyTypeHandlers[VRS.FilterPropertyType.NumberRange] = new VRS.FilterPropertyTypeHandler({ type: VRS.FilterPropertyType.NumberRange, createValueCondition: function() { return new VRS.TwoValueCondition(VRS.FilterCondition.Between); }, getConditions: function() { return [ { condition: VRS.FilterCondition.Between, reverseCondition: false, labelKey: 'Between' }, { condition: VRS.FilterCondition.Between, reverseCondition: true, labelKey: 'NotBetween' } ]}, useValueBetweenRange: true, createOptionFieldsCallback: function(labelKey: string, twoValueCondition: TwoValueCondition, handler: FilterPropertyHandler, saveState: () => void) { var self = this; var conditionValues = self.getConditionComboBoxValues(); return [ new VRS.OptionFieldLabel({ name: 'label', labelKey: labelKey, keepWithNext: true, labelWidth: VRS.globalOptions.filterLabelWidth }), new VRS.OptionFieldComboBox({ name: 'condition', getValue: function() { return self.encodeCondition(twoValueCondition); }, setValue: function(value) { self.applyEncodedCondition(twoValueCondition, value); }, saveState: saveState, values: conditionValues, keepWithNext: true }), new VRS.OptionFieldNumeric({ name: 'value1', getValue: function() { return twoValueCondition.getValue1(); }, setValue: function(value) { twoValueCondition.setValue1(value); }, inputWidth: handler.inputWidth, saveState: saveState, min: handler.minimumValue, max: handler.maximumValue, decimals: handler.decimalPlaces, keepWithNext: true, allowNullValue: true }), new VRS.OptionFieldLabel({ name: 'valueSeparator', labelKey: 'SeparateTwoValues', keepWithNext: true }), new VRS.OptionFieldNumeric({ name: 'value2', getValue: function() { return twoValueCondition.getValue2(); }, setValue: function(value) { twoValueCondition.setValue2(value); }, inputWidth: handler.inputWidth, saveState: saveState, min: handler.minimumValue, max: handler.maximumValue, decimals: handler.decimalPlaces, allowNullValue: true }) ]; }, parseString: function(text) { var result; try { if(text !== null && text !== undefined) { result = parseFloat(text); if(isNaN(result)) result = undefined; } } catch(ex) { result = undefined; } return result; }, toQueryString: function(value) { return value || value === 0 ? value.toString() : null; } }); VRS.filterPropertyTypeHandlers[VRS.FilterPropertyType.OnOff] = new VRS.FilterPropertyTypeHandler({ type: VRS.FilterPropertyType.OnOff, createValueCondition: function() { return new VRS.OneValueCondition(VRS.FilterCondition.Equals, false, true); }, // Preset the option to true. getConditions: function() { return [ { condition: VRS.FilterCondition.Equals, reverseCondition: false, labelKey: 'Equal' } ]}, useSingleValueEquals: true, createOptionFieldsCallback: function(labelKey: string, oneValueCondition: OneValueCondition, handler: FilterPropertyHandler, saveState: () => void) { return [ new VRS.OptionFieldCheckBox({ name: 'onOff', labelKey: labelKey, getValue: function() { return oneValueCondition.getValue(); }, setValue: function(value) { oneValueCondition.setValue(value); }, saveState: saveState }) ];}, parseString: function(text) { var result; if(text) { switch(text.toUpperCase()) { case 'TRUE': case 'YES': case 'ON': case '1': result = true; break; case 'FALSE': case 'NO': case 'OFF': case '0': result = false; break; } } return result; }, toQueryString: function(value) { return value !== undefined && value !== null ? value ? '1' : '0' : null; } }); var filterTextMatchSettings: FilterPropertyTypeHandler_Settings = { type: VRS.FilterPropertyType.TextMatch, createValueCondition: function() { return new VRS.OneValueCondition(VRS.FilterCondition.Contains); }, getConditions: function() { return [ { condition: VRS.FilterCondition.Contains, reverseCondition: false, labelKey: 'Contains' }, { condition: VRS.FilterCondition.Contains, reverseCondition: true, labelKey: 'NotContains' }, { condition: VRS.FilterCondition.Equals, reverseCondition: false, labelKey: 'Equal' }, { condition: VRS.FilterCondition.Equals, reverseCondition: true, labelKey: 'NotEquals' }, { condition: VRS.FilterCondition.Starts, reverseCondition: false, labelKey: 'StartsWith' }, { condition: VRS.FilterCondition.Starts, reverseCondition: true, labelKey: 'NotStartsWith' }, { condition: VRS.FilterCondition.Ends, reverseCondition: false, labelKey: 'EndsWith' }, { condition: VRS.FilterCondition.Ends, reverseCondition: true, labelKey: 'NotEndsWith' } ]}, valuePassesCallback: function(value: any, oneValueCondition: OneValueCondition, options: Filter_Options) { var conditionValue = oneValueCondition.getValue(); var result = conditionValue === undefined; if(!result) { var ignoreCase = options && options.caseInsensitive; switch(oneValueCondition.getCondition()) { case VRS.FilterCondition.Contains: result = VRS.stringUtility.contains(value, conditionValue, ignoreCase); break; case VRS.FilterCondition.Equals: result = VRS.stringUtility.equals(value, conditionValue, ignoreCase); break; case VRS.FilterCondition.Starts: result = VRS.stringUtility.startsWith(value, conditionValue, ignoreCase); break; case VRS.FilterCondition.Ends: result = VRS.stringUtility.endsWith(value, conditionValue, ignoreCase); break; default: throw 'Invalid condition ' + oneValueCondition.getCondition() + ' for text match filters'; } if(oneValueCondition.getReverseCondition()) result = !result; } return result; }, createOptionFieldsCallback: function(labelKey: string, oneValueCondition: OneValueCondition, handler: FilterPropertyHandler, saveState: () => void) { var self = this; var conditionValues = self.getConditionComboBoxValues(); return [ new VRS.OptionFieldLabel({ name: 'label', labelKey: labelKey, keepWithNext: true, labelWidth: VRS.globalOptions.filterLabelWidth }), new VRS.OptionFieldComboBox({ name: 'condition', getValue: function() { return self.encodeCondition(oneValueCondition); }, setValue: function(value) { self.applyEncodedCondition(oneValueCondition, value); }, saveState: saveState, values: conditionValues, keepWithNext: true }), new VRS.OptionFieldTextBox({ name: 'value', getValue: function() { return oneValueCondition.getValue(); }, setValue: function(value) { oneValueCondition.setValue(value); }, inputWidth: handler.inputWidth, saveState: saveState, upperCase: handler.isUpperCase, lowerCase: handler.isLowerCase }) ]; }, parseString: function(text) { return text !== null ? text : undefined; }, toQueryString: function(value) { return value; }, passEmptyValues: function(valueCondition) { // We want to pass empty strings if they're searching for null/empty strings return valueCondition.getCondition() === VRS.FilterCondition.Equals; } }; VRS.filterPropertyTypeHandlers[VRS.FilterPropertyType.TextMatch] = new VRS.FilterPropertyTypeHandler(filterTextMatchSettings); VRS.filterPropertyTypeHandlers[VRS.FilterPropertyType.TextListMatch] = new VRS.FilterPropertyTypeHandler({ type: VRS.FilterPropertyType.TextListMatch, valuePassesCallback: function(value: string[], oneValueCondition: OneValueCondition, options: Filter_Options) { var conditionValue: string = oneValueCondition.getValue(); var result = conditionValue === undefined; if(!result) { var ignoreCase = options && options.caseInsensitive; var condition = oneValueCondition.getCondition(); var length = value.length; for(var i = 0;!result && i < length;++i) { var item = value[i]; switch(condition) { case VRS.FilterCondition.Contains: result = VRS.stringUtility.contains(item, conditionValue, ignoreCase); break; case VRS.FilterCondition.Equals: result = VRS.stringUtility.equals(item, conditionValue, ignoreCase); break; case VRS.FilterCondition.Starts: result = VRS.stringUtility.startsWith(item, conditionValue, ignoreCase); break; case VRS.FilterCondition.Ends: result = VRS.stringUtility.endsWith(item, conditionValue, ignoreCase); break; default: throw 'Invalid condition ' + condition + ' for text match filters'; } } if(oneValueCondition.getReverseCondition()) result = !result; } return result; }, createValueCondition: filterTextMatchSettings.createValueCondition, getConditions: filterTextMatchSettings.getConditions, createOptionFieldsCallback: filterTextMatchSettings.createOptionFieldsCallback, parseString: filterTextMatchSettings.parseString, toQueryString: filterTextMatchSettings.toQueryString, passEmptyValues: filterTextMatchSettings.passEmptyValues }); /** * The settings to pass when creating a new instance of a FilterPropertyHandler. */ export interface FilterPropertyHandler_Settings { /** * The property that this object handles. */ property: AircraftFilterPropertyEnum | ReportFilterPropertyEnum; /** * The property is expected to be an enum value - this is the enum object that holds all possible values of the property. */ propertyEnumObject?: Object; /** * The VRS.FilterPropertyType of the filter used by this object. */ type: FilterPropertyTypeEnum; /** * The key of the translated text for the filter's label. */ labelKey: string; /** * A method that returns the value being filtered. */ getValueCallback?: (parameter: any) => any; /** * The callback (mandatory for enum types) that returns the list of all possible enum values and their descriptions. */ getEnumValues?: () => ValueText[]; /** * True if string values are to be converted to upper-case on data-entry. */ isUpperCase?: boolean; /** * True if string values are to be converted to lower-case on data-entry. */ isLowerCase?: boolean; /** * The minimum value for numeric range fields. */ minimumValue?: number; /** * The maximum value for numeric range fields. */ maximumValue?: number; /** * The number of decimals for numeric range fields. */ decimalPlaces?: number; /** * The optional width to use on input fields. */ inputWidth?: InputWidthEnum; /** * Returns true if the filter is supported server-side, false if it is not. Default returns true if serverFilterName is present, false if it is not. */ isServerFilter?: (valueCondition: ValueCondition) => boolean; /** * The name to use when representing the filter in a query to the server. */ serverFilterName?: string; /** * A method that takes a value and a unit display preferences and converts it from the user's preferred unit to the unit expected by the server. * The default just returns the value unchanged. */ normaliseValue?: (value: any, unitDisplayPrefs: UnitDisplayPreferences) => any; /** * The initial condition to offer when the filter is added to the user interface. */ defaultCondition?: FilterConditionEnum; } /** * The base for objects that bring together a property and its type, and describe the ranges that the filters can be * set to, its on-screen description and so on. */ export class FilterPropertyHandler { // Kept as public fields for backwards compatibility property: AircraftFilterPropertyEnum | ReportFilterPropertyEnum; type: FilterPropertyTypeEnum; labelKey: string; getValueCallback: (parameter: any) => any; getEnumValues: () => ValueText[]; isUpperCase: boolean; isLowerCase: boolean; minimumValue: number; maximumValue: number; decimalPlaces: number; inputWidth: InputWidthEnum; serverFilterName: string; isServerFilter: (valueCondition: ValueCondition) => boolean; normaliseValue: (value: any, unitDisplayPrefs: UnitDisplayPreferences) => any; defaultCondition: FilterConditionEnum; constructor(settings: FilterPropertyHandler_Settings) { if(!settings) throw 'You must supply a settings object'; if(!settings.property || !VRS.enumHelper.getEnumName(settings.propertyEnumObject, settings.property)) throw 'You must supply a valid property'; if(!settings.type || !VRS.enumHelper.getEnumName(VRS.FilterPropertyType, settings.type)) throw 'You must supply a property type'; if(!settings.labelKey) throw 'You must supply a labelKey'; this.property = settings.property; this.type = settings.type; this.labelKey = settings.labelKey; this.getValueCallback = settings.getValueCallback; this.getEnumValues = settings.getEnumValues; this.isUpperCase = settings.isUpperCase; this.isLowerCase = settings.isLowerCase; this.minimumValue = settings.minimumValue; this.maximumValue = settings.maximumValue; this.decimalPlaces = settings.decimalPlaces; this.inputWidth = settings.inputWidth === undefined ? VRS.InputWidth.Auto : settings.inputWidth; this.serverFilterName = settings.serverFilterName; this.isServerFilter = settings.isServerFilter || function() { return !!settings.serverFilterName; }; this.normaliseValue = settings.normaliseValue || function(value) { return value; }; this.defaultCondition = settings.defaultCondition; } /** * Returns the handler for the property's type. */ getFilterPropertyTypeHandler() : FilterPropertyTypeHandler { return filterPropertyTypeHandlers[this.type]; } } /** * Describes the settings to pass when creating a new instance of Filter. */ export interface Filter_Settings { /** * The property that is to be associated with the filter. */ property: AircraftFilterPropertyEnum | ReportFilterPropertyEnum; /** * The object that describes the condition and values to compare against a property. */ valueCondition: ValueCondition; /** * The property is expected to belong to an enum - this is the enum object that holds all possible values of property. */ propertyEnumObject: Object; /** * An associative array of property values and their associated FilterPropertyHandler-based objects. The index is either * an AircraftFilterPropertyEnum or a ReportFilterPropertyEnum. */ filterPropertyHandlers: { [index: string]: FilterPropertyHandler }; /** * A method that can create a clone of the filter derivee. */ cloneCallback: (obj: AircraftFilterPropertyEnum | ReportFilterPropertyEnum, valueCondition: ValueCondition) => Filter; } /** * The base for more specialised filters. A filter joins together a property identifier and an object that carries a * condition and values to use with the condition in the filter test. The classes derived from this one specialise * the property but they all share the concept of joining a property and a value/condition together. */ export class Filter { protected _Settings: Filter_Settings; constructor(settings: Filter_Settings) { if(!settings) throw 'The derivee must supply a subclassSettings object'; if(!settings.property || !VRS.enumHelper.getEnumName(settings.propertyEnumObject, settings.property)) throw 'You must supply a valid property'; if(!settings.valueCondition) throw 'You must supply a filter'; this._Settings = settings; } getProperty() : AircraftFilterPropertyEnum | ReportFilterPropertyEnum { return this._Settings.property; } setProperty(value: AircraftFilterPropertyEnum | ReportFilterPropertyEnum) { if(!value || !VRS.enumHelper.getEnumName(this._Settings.propertyEnumObject, value)) { throw 'Cannot set property of "' + value + '", it is not a valid property'; } this._Settings.property = value; } getValueCondition() : ValueCondition { return this._Settings.valueCondition; } setValueCondition(value: ValueCondition) { if(!value) throw 'You cannot set the value/condition to null or undefined'; this._Settings.valueCondition = value; } getPropertyHandler() : FilterPropertyHandler { return this._Settings.filterPropertyHandlers[this._Settings.property]; } /** * Returns true if this object has the same property values as another object. */ equals(obj: Filter) : boolean { return this.getProperty() === obj.getProperty() && this.getValueCondition().equals(obj.getValueCondition()); } /** * Returns a copy of this object. */ clone() : Filter { return this._Settings.cloneCallback(this._Settings.property, this._Settings.valueCondition.clone()); } /** * Creates a serialisable copy of the filter. */ toSerialisableObject() : ISerialisedFilter { return { property: this._Settings.property, valueCondition: this._Settings.valueCondition.toSerialisableObject() }; } /** * Applies serialised settings to this object. */ applySerialisedObject(settings: ISerialisedFilter) { this.setProperty(settings.property); this._Settings.valueCondition.applySerialisedObject(settings.valueCondition); } /** * Creates an object pane for the condition and parameters to the condition. */ createOptionPane(saveState: () => any) : OptionPane { var propertyHandler = this.getPropertyHandler(); var typeHandler = propertyHandler.getFilterPropertyTypeHandler(); var labelKey = propertyHandler.labelKey; return new VRS.OptionPane({ name: 'filter', fields: typeHandler.createOptionFieldsCallback(labelKey, this.getValueCondition(), propertyHandler, saveState) }); } /** * Adds parameters to a query string parameters object to represent the filter property, condition and values. */ addToQueryParameters(query: Object, unitDisplayPreferences: UnitDisplayPreferences) { var valueCondition = this.getValueCondition(); var propertyHandler = this._Settings.filterPropertyHandlers[this.getProperty()]; if(propertyHandler && propertyHandler.isServerFilter(valueCondition)) { var typeHandler = propertyHandler.getFilterPropertyTypeHandler(); var filterName = propertyHandler.serverFilterName; var reverse = valueCondition.getReverseCondition() ? 'N' : ''; var passEmptyValue = typeHandler.passEmptyValues(valueCondition); var addQueryString = function(suffix, value) { if(passEmptyValue || value !== undefined) { value = propertyHandler.normaliseValue(value, unitDisplayPreferences); if(propertyHandler.decimalPlaces === 0) value = Math.round(value); var textValue = typeHandler.toQueryString(value); if(passEmptyValue || textValue) query[filterName + suffix + reverse] = textValue || ''; } }; switch(valueCondition.getCondition()) { case VRS.FilterCondition.Between: addQueryString('L', (<TwoValueCondition>valueCondition).getLowValue()); addQueryString('U', (<TwoValueCondition>valueCondition).getHighValue()); break; case VRS.FilterCondition.Contains: addQueryString('C', (<OneValueCondition>valueCondition).getValue()); break; case VRS.FilterCondition.Ends: addQueryString('E', (<OneValueCondition>valueCondition).getValue()); break; case VRS.FilterCondition.Equals: addQueryString('Q', (<OneValueCondition>valueCondition).getValue()); break; case VRS.FilterCondition.Starts: addQueryString('S', (<OneValueCondition>valueCondition).getValue()); break; default: throw 'Unknown condition ' + valueCondition.getCondition(); } } } } /** * The settings that are passed as parameters to FilterHelper.addConfigureFiltersListToPane */ export interface FilterHelper_AddConfigureSettings { /** * The pane that the field holding the filters will be added to. */ pane: OptionPane; /** * The array of filters to pre-fill the field with. These are the ones already set up by the user. */ filters: Filter[]; /** * The name to assign to the field, defaults to 'filters'. */ fieldName?: string; /** * The callback that will save the state when the filters list is changed. */ saveState: () => any; /** * The maximum number of filters that the user can have. */ maxFilters?: number; /** * An array of properties that the user can choose from. If not supplied then the user cannot add new filters. */ allowableProperties?: AircraftFilterPropertyEnum[] | ReportFilterPropertyEnum[]; /** * The property to show when adding a new filter. If not supplied then the first allowableProperties value is used. */ defaultProperty?: AircraftFilterPropertyEnum | ReportFilterPropertyEnum; /** * Mandatory if settings.allowableProperties is provided - called when the user creates a new filter, expected to * add the filter to a list of user-created filters. */ addFilter?: (property: AircraftFilterPropertyEnum | ReportFilterPropertyEnum, paneListField: OptionFieldPaneList) => void; /** * The labelKey into VRS.$$ for the 'add a new filter' button. */ addFilterButtonLabel?: string; /** * True if the user must be prohibited from adding filters for the same property twice. Defaults to false. */ onlyUniqueFilters?: boolean; /** * A method that takes a property and returns true if it is already in use. Must be supplied if onlyUniqueFilters is true. */ isAlreadyInUse?: (property: AircraftFilterPropertyEnum | ReportFilterPropertyEnum) => boolean; } /** * The settings to use when creating a new instance of FilterHelper. */ export interface FilterHelper_Settings { /** * The enum object from which all filter properties are obtained. */ propertyEnumObject: Object; /** * An associative array of property enum values against the handler for the property. The index is either an * AircraftFilterPropertyEnum or a ReportFilterPropertyEnum. */ filterPropertyHandlers: { [index: string]: FilterPropertyHandler }; /** * A method that creates a filter of the correct type. */ createFilterCallback: (filterPropertyHandler: FilterPropertyHandler, valueCondition: ValueCondition) => Filter; /** * A method that adds query string parameters for a fetch from the server to a query string object. */ addToQueryParameters?: (filters: Filter[], query: Object) => void; } /** * The base for helper objects that can deal with common routine tasks when working with filters. */ export class FilterHelper { private _Settings: FilterHelper_Settings; constructor(settings: FilterHelper_Settings) { if(!settings) throw 'You must supply the subclass settings'; this._Settings = settings; } /** * Creates a new Filter for the property passed across. */ createFilter(property: AircraftFilterPropertyEnum | ReportFilterPropertyEnum) : Filter { var propertyHandler = this._Settings.filterPropertyHandlers[property]; if(!propertyHandler) throw 'There is no property handler for ' + property + ' properties'; var typeHandler = propertyHandler.getFilterPropertyTypeHandler(); if(!typeHandler) throw 'There is no type handler of ' + propertyHandler.type + ' for ' + property + ' properties'; var valueCondition = typeHandler.createValueCondition(); if(propertyHandler.defaultCondition) valueCondition.setCondition(propertyHandler.defaultCondition); return this._Settings.createFilterCallback(propertyHandler, valueCondition); } /** * Converts a list of filters to an array of serialised objects that can be saved in an object's state. */ serialiseFiltersList(filters: Filter[]) : ISerialisedFilter[] { var result = []; $.each(filters, function(idx, filter) { result.push(filter.toSerialisableObject()); }); return result; } /** * Removes invalid serialised filters from a list of serialised filters, presumably from a previous session's state. */ buildValidFiltersList(serialisedFilters: ISerialisedFilter[], maximumFilters: number = -1) : ISerialisedFilter[] { maximumFilters = maximumFilters === undefined ? -1 : maximumFilters; var validFilters = []; var self = this; $.each(serialisedFilters, function(idx, serialisedFilter) { if(maximumFilters === -1 || validFilters.length <= maximumFilters) { if(VRS.enumHelper.getEnumName(self._Settings.propertyEnumObject, serialisedFilter.property) && serialisedFilter.valueCondition) { validFilters.push(serialisedFilter); } } }); return validFilters; } /** * Adds a paneList option field (an option field that shows a list of option panes) to a pane where the content * of the field is a set of panes, each pane representing a single filter and its parameters. The field allows * the user to add and remove filters. */ addConfigureFiltersListToPane(settings: FilterHelper_AddConfigureSettings) : OptionFieldPaneList { var pane = settings.pane; var filters = settings.filters; var fieldName = settings.fieldName || 'filters'; var saveState = settings.saveState; var maxFilters = settings.maxFilters; var allowableProperties = settings.allowableProperties; var defaultProperty = settings.defaultProperty; var addFilter = settings.addFilter; var addFilterButtonLabel = settings.addFilterButtonLabel; var onlyUniqueFilters = settings.onlyUniqueFilters === undefined ? true : settings.onlyUniqueFilters; var isAlreadyInUse = settings.isAlreadyInUse || function() { return false; }; var length = filters.length; var panes = []; for(var i = 0;i < length;++i) { var filter = filters[i]; panes.push(filter.createOptionPane(saveState)); } var paneListField = new VRS.OptionFieldPaneList({ name: fieldName, labelKey: 'Filters', saveState: saveState, maxPanes: maxFilters, panes: panes }); if(allowableProperties && allowableProperties.length) { var addPropertyComboBoxValues = []; length = allowableProperties.length; for(i = 0;i < length;++i) { var allowableProperty = allowableProperties[i]; var handler = this._Settings.filterPropertyHandlers[allowableProperty]; if(!handler) throw 'No handler defined for the "' + allowableProperty + '" property'; addPropertyComboBoxValues.push(new VRS.ValueText({ value: allowableProperty, textKey: handler.labelKey })); } var newProperty = defaultProperty || allowableProperties[0]; var addFieldButton = new VRS.OptionFieldButton({ name: 'addComparer', labelKey: addFilterButtonLabel, saveState: function() { addFilter(newProperty, paneListField); }, icon: 'plusthick' }); var addPane = new VRS.OptionPane({ name: 'vrsAddNewEntryPane', fields: [ new VRS.OptionFieldComboBox({ name: 'newComparerCombo', getValue: function() { return newProperty; }, setValue: function(value) { newProperty = value; }, saveState: saveState, keepWithNext: true, values: addPropertyComboBoxValues, changed: function(newValue) { if(onlyUniqueFilters) addFieldButton.setEnabled(!isAlreadyInUse(newValue)); } }), addFieldButton ] }); paneListField.setRefreshAddControls((disabled: boolean, addParentJQ: JQuery) => { if(!disabled && onlyUniqueFilters && isAlreadyInUse(newProperty)) disabled = true; addFieldButton.setEnabled(!disabled); }); paneListField.setAddPane(addPane); } pane.addField(paneListField); return paneListField; } /** * Returns true if any of the filters in the array passed across have the property passed across, otherwise returns false. */ isFilterInUse(filters: Filter[], property: AircraftFilterPropertyEnum | ReportFilterPropertyEnum) : boolean { return this.getIndexForFilterProperty(filters, property) !== -1; } /** * Returns the filter with the filter property passed across or null if no such filter exists. */ getFilterForFilterProperty(filters: Filter[], property: AircraftFilterPropertyEnum | ReportFilterPropertyEnum) : Filter { var index = this.getIndexForFilterProperty(filters, property); return index === -1 ? null : filters[index]; } /** * Returns the index of the filter with the filter property passed across or -1 if no such filter exists. */ getIndexForFilterProperty(filters: Filter[], property: AircraftFilterPropertyEnum | ReportFilterPropertyEnum) : number { var result = -1; var length = filters.length; for(var i = 0;i < length;++i) { if(filters[i].getProperty() === property) { result = i; break; } } return result; } /** * Adds filter parameters to an object that collects together query string parameters for server fetch. */ addToQueryParameters(filters: Filter[], query: Object, unitDisplayPreferences: UnitDisplayPreferences) { if(this._Settings.addToQueryParameters) { this._Settings.addToQueryParameters(filters, query); } if(filters && filters.length) { var length = filters.length; for(var i = 0;i < length;++i) { var filter = filters[i]; filter.addToQueryParameters(query, unitDisplayPreferences); } } } } }
the_stack
import fs from 'fs'; import path from 'path'; import tachPkg from 'tachometer/lib/cli.js'; const {main: tachometer} = tachPkg; import tablePkg from 'table'; const {table, getBorderCharacters} = tablePkg; import rimraf from 'rimraf'; import cliArgs from 'command-line-args'; import {getOptions, OptionKey, OptionValues} from './options.js'; import {getRenderers, TemplateRenderer} from './renderers.js'; import {deoptigate, deoptigateFolderForUrl} from './deoptigate.js'; import { nextLevel, depthForLevel, levelForTemplate, templateNameForLevel, parseRenderer, } from './utils.js'; // Options and renderers are circular, so pass a dummy options // so we can change it once we parse the command line args const prettyOptions = {pretty: false}; const renderers = getRenderers(prettyOptions); const { optionsDesc, options, reportOptions, variedOptions, variations, rendererForName, } = getOptions(renderers); prettyOptions.pretty = options.pretty; // Generates a full benchmark html page + js script for a given set of options const generateBenchmark = ( opts: OptionValues, outputPath: string, name: string ) => { console.log(`Generating variant ${name}`); const renderer = rendererForName(parseRenderer(opts.renderers).base)!; const generatedTemplates = new Set(); // Generates a template for a given level const generateTemplate = (s = '', templateLevel = '', tag = 'div') => { // "Static" nodes/attrs mean there is no binding (i.e. not "dynamic") const staticAttrPerNode = Math.floor( (1 - opts.dynAttrPct) * opts.attrPerNode ); const staticNodesPerNode = Math.floor((1 - opts.dynNodePct) * opts.width); // "Constant" nodes/attrs mean there is a binding, but it shouldn't change // between updates (i.e. not "updatable") const constantAttrPerNode = Math.floor( (1 - opts.updateAttrPct) * (opts.attrPerNode - staticAttrPerNode) ); const constantNodesPerNode = Math.floor( (1 - opts.updateNodePct) * (opts.width - staticNodesPerNode) ); // Generates a tree of either static or dynamic nodes (template calls) at a // given level const generateTree = ( s: string, renderer: TemplateRenderer, parentLevel = '' ) => { // Generate `width` nodes (or template calls) for this level of the tree for (let i = 0; i < opts.width; i++) { // Moniker for this position in the tree, based on parent level & node // index (i.e. if parent was position 0_2_3 and this is node 3 inside // it, the current level will be 0_2_3_3); the level is used for // generating unique text at a given position in the tree, and for // naming templates corresponding to a given level in the tree const level = nextLevel(parentLevel, i); // Open tag start s = renderer.openTagStart( s, level, tag, opts.attrPerNode, staticAttrPerNode ); // Attributes for (let j = 0; j < opts.attrPerNode; j++) { const isStatic = j < staticAttrPerNode; const isConstant = isStatic || j - staticAttrPerNode < constantAttrPerNode; const name = nextLevel(level, j); s = renderer.setAttr( s, level, name, isStatic, isConstant, Math.max(opts.valPerDynAttr, 1) ); } // Open tag end s = renderer.openTagEnd(s, level, tag, opts.attrPerNode); // Text s = renderer.textNode(s, level, false, level); // Generate next level of tree, until we've reached the max depth if (depthForLevel(level) < opts.depth) { if (i < staticNodesPerNode) { // Recurse to continue generating static DOM in the tree s = generateTree(s, renderer, level); } else { // Recurse by way of a dynamic template call const isConstant = i - staticNodesPerNode < constantNodesPerNode; const name = templateNameForLevel( level, !!opts.uniqueTemplates, isConstant ? '' : 'A' ); // Generate new template(s) for the given depth if we haven't yet or // for the given level (unique position) if we're using // uniqueTemplates if (opts.uniqueTemplates || !generatedTemplates.has(name)) { generatedTemplates.add(name); // Prepend generated templates to the start of the script s = generateTemplate(s, level + (isConstant ? '' : 'A'), 'div'); if (!isConstant) { // If this template call is updatable, generate a "B" version of // the template const name = levelForTemplate( level, !!opts.uniqueTemplates, 'B' ); if (opts.uniqueTemplates || !generatedTemplates.has(name)) { generatedTemplates.add(name); s = generateTemplate(s, level + 'B', 'p'); } } } // Emit a call to the generated/prepended template s = renderer.callTemplate( s, level, templateNameForLevel(level, !!opts.uniqueTemplates), isConstant ); } } // Close tag s = renderer.closeTag(s, level, tag); } return s; }; let t = ''; t = renderer.startTemplate( t, templateNameForLevel(templateLevel, !!opts.uniqueTemplates) ); t = generateTree(t, renderer, templateLevel); t = renderer.endTemplate(t); return t + s; }; const generatedByComment = `Benchmark generated via the following invocation:\n` + `node generator/build/index.js ${process.argv.slice(2).join(' ')}\n\n` + `Parameters:\n${Object.entries(opts) .filter(([p]) => !optionsDesc[p as keyof typeof optionsDesc].noReport) .map(([p, v]) => ` ${p}: ${v}`) .join('\n')}`; // Output benchmark script file const script = ` /*\n${generatedByComment}\n*/ ${renderer.startBenchmark(parseRenderer(opts.renderers).base)} ${generateTemplate()} const container = document.getElementById('container'); let updateId = 0; let useTemplateA = true; window.update = () => { ${renderer.render()} updateId++; useTemplateA = !useTemplateA; } performance.mark('initial-render-start'); window.update(); performance.mark('initial-render-end'); for (let i=0; i<${opts.updateCount}; i++) { window.update(); } performance.mark('updates-end'); performance.measure('render', 'initial-render-start', 'initial-render-end'); performance.measure('update', 'initial-render-end', 'updates-end'); performance.measure('time', 'initial-render-start', 'updates-end'); ${ opts.measure === 'memory' ? `window.tachometerResult = performance.memory.usedJSHeapSize/1024;` : `window.tachometerResult = performance.getEntriesByName('render')[0].duration + performance.getEntriesByName('update')[0].duration;` } document.title = window.tachometerResult.toFixed(2) + 'ms'; `; fs.writeFileSync(path.join(outputPath, name + '.js'), script, 'utf-8'); // Output benchmark html file const html = `<!DOCTYPE html> <!--\n${generatedByComment}\n--> <html> <head> </head> <body> <div id="container"></div> ${ renderer.legacyScripts ? renderer.legacyScripts .map((s) => `<script src="${s}"></script>`) .join('\n') : '' } <script type="module" src="${name + '.js'}"></script> </body> </html>`; fs.writeFileSync(path.join(outputPath, name + '.html'), html, 'utf-8'); }; // Pretty printing of option values for reporting // eslint-disable-next-line @typescript-eslint/no-explicit-any const formatOptionValue = (v: any) => { v = Array.isArray(v) ? v[0] : v; // For logging constant options if (typeof v === 'number' && v % 1 !== 0) { return v.toFixed(1); } else if (typeof v === 'boolean') { return v.toString()[0]; } else { return String(v); } }; // Use CLI alias for each option that differed to construct a terse // moniker for the unique variation, used in filename & reporting const nameForVariation = (variation: OptionValues) => { return reportOptions .map((option) => { if (option === 'renderers') { return parseRenderer(variation.renderers).base; } else { return `${optionsDesc[option].alias}${formatOptionValue( variation[option] )}`; } }) .join('-'); }; // Similar to nameForVariation, but includes options that varied const shortNameForVariation = (variation: OptionValues) => { return variedOptions .map((option) => { if (option === 'renderers') { return parseRenderer(variation.renderers).base; } else { return `${optionsDesc[option].alias}${formatOptionValue( variation[option] )}`; } }) .join('-'); }; // Log the options that were held constant along with the benchmark results so // it's easy to capture what the run was testing (only the varied options are // included in the benchmark name itself, to keep the table columns as narrow as // possible) const printConstantOptions = (options: cliArgs.CommandLineOptions) => { const keys = reportOptions.filter((arg) => variedOptions.indexOf(arg) < 0); console.log('Held constant between variations:'); console.log( table([keys, keys.map((arg) => formatOptionValue(options[arg]))], { border: getBorderCharacters('norc'), }) ); }; const outputPath = path.join(process.cwd(), options.output); // Create the output folder if it does not exist if (fs.existsSync(outputPath)) { if (options.clean) { // Remove all generated HTML files from the generated folder rimraf.sync(outputPath); fs.mkdirSync(outputPath); } } else { fs.mkdirSync(outputPath); } // Main routine to generate all benchmarks, index.html, & tachometer.json async function generateAll() { let measurement; if (options.measure === 'memory') { measurement = 'global'; } else { measurement = options.measure.split(',').map((m: string) => ({ mode: 'performance', entryName: m.trim(), })); } const tach = { $schema: 'https://raw.githubusercontent.com/Polymer/tachometer/master/config.schema.json', timeout: 0, sampleSize: options.runDeoptigate ? 2 : options.sampleSize, benchmarks: [ { measurement: measurement, browser: { headless: true, name: 'chrome', addArguments: [], }, expand: [], }, ], }; // Pointer into tachometer.json object to add benchmarks to // eslint-disable-next-line @typescript-eslint/no-explicit-any const tachList = tach.benchmarks[0].expand as any; // eslint-disable-next-line @typescript-eslint/no-explicit-any const browserArguments = (tach.benchmarks[0].browser as any).addArguments; // Note `performance.memory.usedJSHeapSize` does not actually change without // this flag if (options.measure === 'memory') { browserArguments.push('--enable-precise-memory-info'); } // index.html preamble let index = `<style>table,th,td { padding: 3px; border: 1px solid black; border-collapse: collapse;}</style><table>`; index += `<tr>${reportOptions .map((arg) => `<td>${arg}</td>`) .join('')}<td>URL</td>${ options.runDeoptigate ? `<td>Deopt</td>` : '' }</tr>`; // Loop over cartesian product of all options and output benchmarks const urls = []; const files = new Set(); const urlPath = path.relative(process.cwd(), outputPath); for (const variation of variations) { const variant = (Object.keys(options) as OptionKey[]).reduce( // eslint-disable-next-line @typescript-eslint/no-explicit-any (v: any, arg: OptionKey, i: number) => ((v[arg] = variation[i]), v), {} ); const fullName = nameForVariation(variant); const shortName = shortNameForVariation(variant); const name = options.shortname ? `${options.shortname}${shortName ? `-${shortName}` : ''}` : `benchmark-${fullName}`; const filename = `${name}.html`; const {query, packageVersions} = parseRenderer(variant.renderers); const url = filename + (query ? '?' + query : ''); urls.push(url); index += `<tr>${reportOptions .map((opt) => `<td>${formatOptionValue(variant[opt])}</td>`) .join('')}`; index += `<td><a href="${url}">${url}</a></td>`; index += `${ options.runDeoptigate ? `<td><a href="${deoptigateFolderForUrl( `${urlPath}/${url}` )}/index.html">Deopt</a></td>` : '' }`; index += `</tr>`; const tachInfo = { name: shortName || options.shortname || '(single)', url: `${urlPath}/${url}`, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any; if (packageVersions) { tachInfo.packageVersions = packageVersions; } tachList.push(tachInfo); // Dedupe files called with differing query strings if (!files.has(filename)) { files.add(filename); generateBenchmark(variant, outputPath, name); } } if (!options.generateOnlyBenchmarks || options.runTachometer) { console.log(`Generating tachometer.json...`); fs.writeFileSync( path.join(outputPath, 'tachometer.json'), JSON.stringify(tach, null, ' '), 'utf-8' ); } if (options.generateIndex) { console.log(`Generating index.html...`); fs.writeFileSync( path.join(outputPath, 'index.html'), index + '</table>', 'utf-8' ); } console.log('Done.'); // Run the benchmarks! if (options.runDeoptigate) { for (const url of urls) { await deoptigate(options.output, `${urlPath}/${url}`); } } else if (options.runTachometer) { await tachometer([ '--config', path.join(outputPath, 'tachometer.json'), '--csv-file', path.join(outputPath, 'results.csv'), '--json-file', path.join(outputPath, 'results.json'), ]); printConstantOptions(options); } } generateAll();
the_stack
import { Dispatch, Store, Reducer, Middleware, StoreEnhancer } from 'redux'; import { History } from 'history'; export type Nullable<T> = T | null | undefined; export type StateGetter<TState = any> = () => TState; export type RouteString = string; export type ConfirmLeave = (state: object, action: object) => Nullable<string>; export type RouteThunk<TState = any> = ( dispatch: Dispatch<any>, getState: StateGetter<TState>, ) => any | Promise<any>; export type RouteObject<TKeys = {}, TState = any> = TKeys & { capitalizedWords?: boolean | undefined; navKey?: string | undefined; path?: string | undefined; thunk?: RouteThunk<TState> | undefined; fromPath?(path: string, key?: string): string; toPath?(param: string, key?: string): string; coerceNumbers?: boolean | undefined; confirmLeave?: ConfirmLeave | undefined; meta?: Meta | undefined; }; export type Route<TKeys = {}, TState = any> = RouteString | RouteObject<TKeys, TState>; export interface RoutesMap<TKeys = {}, TState = any> { [key: string]: Route<TKeys, TState>; } export interface ReceivedAction { type: string; payload: Payload; meta?: object | undefined; query?: Query | undefined; search?: string | undefined; navKey?: Nullable<string> | undefined; } export interface ReceivedActionMeta { type: string; payload: Payload; query?: Query | undefined; navKey?: Nullable<string> | undefined; meta: { notFoundPath?: string | undefined; query?: Query | undefined; search?: string | undefined; }; } export type HistoryEntries = Array<{ pathname: string }>; export interface HistoryData { entries: HistoryEntries; index: number; length: number; } export interface Location { pathname: string; type: string; payload: Payload; query?: Query | undefined; search?: string | undefined; } export interface LocationState<TKeys = {}, TState = any> { pathname: string; type: string; payload: Payload; query?: Query | undefined; search?: string | undefined; prev: Location; kind: Nullable<string>; history: Nullable<HistoryData>; routesMap: RoutesMap<TKeys, TState>; hasSSR?: boolean | undefined; } export interface ActionMetaLocation { current: Location; prev: Location; kind: Nullable<string>; history: Nullable<HistoryData>; } export interface NavigationAction { type: string; key?: Nullable<string> | undefined; navKey?: Nullable<string> | undefined; routeName?: string | undefined; actions?: NavigationAction[] | undefined; action?: NavigationAction | undefined; params?: Params | undefined; meta?: object | undefined; } export interface Meta { location: ActionMetaLocation; notFoundPath?: string | undefined; navigation?: NavigationAction | undefined; query?: Query | undefined; search?: string | undefined; } export interface Action { type: string; payload?: Payload | undefined; meta?: Meta | undefined; query?: Query | undefined; navKey?: Nullable<string> | undefined; } export interface HistoryLocation { pathname: string; search?: string | undefined; } export type HistoryAction = string; export type Listener = ( location: HistoryLocation, action: HistoryAction ) => void; export type ScrollBehavior = object; export interface Router<TState = any> { getStateForActionOriginal( action: object, state: Nullable<TState> ): Nullable<TState>; getStateForAction( action: object, state: Nullable<TState> ): Nullable<TState>; getPathAndParamsForState( state: TState ): { path: Nullable<string>; params: Nullable<Params> }; getActionForPathAndParams(path: string): Nullable<object>; } export interface Navigator<TState = any> { router: Router<TState>; } export interface Navigators<TState = any> { [key: string]: Navigator<TState>; } export type SelectLocationState<TKeys = {}, TState = any> = (state: TState) => LocationState<TKeys, TState>; export type SelectTitleState<TState = any> = (state: TState) => string; export interface QuerySerializer { stringify(params: Params): string; parse(queryString: string): object; } export interface NavigatorsConfig<TKeys = {}, TState = any> { navigators: Navigators<TState>; patchNavigators(navigators: Navigators<TState>): void; actionToNavigation( navigators: Navigators<TState>, action: object, // TODO check this navigationAction: Nullable<NavigationAction>, route: Nullable<Route<TKeys, TState>> ): object; navigationToAction( navigators: Navigators<TState>, store: Store<TState>, routesMap: RoutesMap<TKeys, TState>, action: object ): { action: object; navigationAction: Nullable<NavigationAction>; }; } export interface Bag { action: ReceivedAction | Action; extra: any; } export interface Options<TKeys = {}, TState = any> { /** * A prefix that will be prepended to the URL. For example, using a basename of '/playground', * a route with the path '/home' would correspond to the URL path '/playground/home'. */ basename?: string | undefined; /** * Whether or not a trailing delimiter is allowed when matching path. */ strict?: boolean | undefined; /** * The name of the state key or a selector function to specify where in your Redux state tree * Redux First Router should expect your page location reducer to be attached to. */ location?: string | SelectLocationState<TKeys, TState> | undefined; /** * The name of the state key or a selector function to specify where in your Redux state tree * Redux First Router should expect your page title reducer to be attached to. * This can be omitted if you attach the reducer at state.title. */ title?: string | SelectTitleState<TState> | undefined; /** * Can be set to false to bypass the initial dispatch, so you can do it manually, perhaps after running sagas. */ initialDispatch?: boolean | undefined; /** * An array of entries to initialise history object. Useful for server side rendering and tests. */ initialEntries?: HistoryEntries | undefined; /** * An object with parse and stringify methods, such as the `query-string` or `qs` libraries (or anything handmade). * This will be used to handle querystrings. Without this option, query strings are ignored silently. */ querySerializer?: QuerySerializer | undefined; /** * The path where users may be redirected in 2 situations: when you dispatch an action with no matching path, * or if you manually call dispatch(redirect({ type: NOT_FOUND })), where NOT_FOUND is an export from this package. * The type in actions and state will be NOT_FOUND, which you can use to show a 404 page. */ notFoundPath?: string | undefined; /** * Whether or not window.scrollTo(0, 0) should be run on route changes so the user starts each page at the top. */ scrollTop?: boolean | undefined; /** * A function to update window/elements scroll position. */ restoreScroll?(history: History): ScrollBehavior; /** * A simple function that will be called before the routes change. * It's passed your standard `dispatch` and `getState` arguments like a thunk, * as well as the `bag` object as a third parameter, which contains the dispatched `action` and the configured `extra` value. */ onBeforeChange?(dispatch: Dispatch<any>, getState: StateGetter<TState>, bag: Bag): void; /** * A simple function that will be called after the routes change. * It's passed your standard `dispatch` and `getState` arguments like a thunk, * as well as the `bag` object as a third parameter, which contains the dispatched `action` and the configured `extra` value. */ onAfterChange?(dispatch: Dispatch<any>, getState: StateGetter<TState>, bag: Bag): void; /** * A simple function that will be called whenever the user uses the browser back/next buttons. * It's passed your standard `dispatch` and `getState` arguments like a thunk, * as well as the `bag` object as a third parameter, which contains the dispatched `action` * and the configured `extra` value. Actions with kinds `back`, `next`, and `pop` trigger this. */ onBackNext?(dispatch: Dispatch<any>, getState: StateGetter<TState>, bag: Bag): void; /** * A function receiving `message` and `callback` when navigation is blocked with `confirmLeave`. * The message is the return value from `confirmLeave`. * The callback can be called with `true` to unblock the navigation, or with `false` to cancel the navigation. */ displayConfirmLeave?: DisplayConfirmLeave | undefined; /** * A function returning a history object compatible with the popular `history` package. */ createHistory?(): History; /** * A map of of your Redux state keys to _React Navigation_ navigators. */ navigators?: NavigatorsConfig<TKeys, TState> | undefined; /** * An optional value that will be passed as part of the third `bag` argument to all options callbacks and routes thunk. * It works much like the `withExtraArgument` feature of `redux-thunk` or the `context` argument of GraphQL resolvers. * You can use it to pass any required context to your thunks without having to tightly couple them to it. * For example, you could pass an instance of an API client initialised with authentication cookies, * or a function `addReducer` to inject new code split reducers into the store. */ extra?: any; } export interface Query { [key: string]: string | undefined; } export interface Params { [key: string]: any; } export interface Payload { query?: Query | undefined; [key: string]: any; } export type DisplayConfirmLeave = (message: string, callback: (unblock: boolean) => void) => void; export type ScrollUpdater = (performedByUser: boolean) => void; export const NOT_FOUND: '@@redux-first-router/NOT_FOUND'; export function actionToPath<TKeys = {}, TState = any>( action: ReceivedAction, routesMap: RoutesMap<TKeys, TState>, querySerializer?: QuerySerializer ): string; export function back(): void; export function canGo(n: number): boolean; export function canGoBack(): boolean; export function canGoForward(): boolean; export function connectRoutes<TKeys = {}, TState = any>( routesMap: RoutesMap<TKeys, TState>, options?: Options<TKeys, TState>, ): { reducer: Reducer<LocationState<TKeys, TState>>; middleware: Middleware; thunk(store: Store<TState>): Promise<Nullable<RouteThunk<TState>>>; enhancer: StoreEnhancer; initialDispatch?(): void; }; export function go(n: number): void; export function history(): History; export function isLocationAction(action: any): boolean; export function next(): void; export function nextPath(): string | void; export function pathToAction<TKeys = {}, TState = any>( pathname: string, routesMap: RoutesMap<TKeys, TState>, querySerializer?: QuerySerializer ): ReceivedAction; export function prevPath(): string | void; export function push(pathname: string): void; export function redirect(action: Action): Action; export function replace(pathname: string): void; export function scrollBehavior(): ScrollBehavior | void; export function setKind(action: Action, kind: string): Action; export function updateScroll(): void; export function selectLocationState<TState = any>(state: TState): LocationState;
the_stack
import app from '../../forum/app'; import Component, { ComponentAttrs } from '../../common/Component'; import LoadingIndicator from '../../common/components/LoadingIndicator'; import ItemList from '../../common/utils/ItemList'; import classList from '../../common/utils/classList'; import extractText from '../../common/utils/extractText'; import KeyboardNavigatable from '../utils/KeyboardNavigatable'; import icon from '../../common/helpers/icon'; import SearchState from '../states/SearchState'; import DiscussionsSearchSource from './DiscussionsSearchSource'; import UsersSearchSource from './UsersSearchSource'; import { fireDeprecationWarning } from '../../common/helpers/fireDebugWarning'; import type Mithril from 'mithril'; /** * The `SearchSource` interface defines a section of search results in the * search dropdown. * * Search sources should be registered with the `Search` component class * by extending the `sourceItems` method. When the user types a * query, each search source will be prompted to load search results via the * `search` method. When the dropdown is redrawn, it will be constructed by * putting together the output from the `view` method of each source. */ export interface SearchSource { /** * Make a request to get results for the given query. * The results will be updated internally in the search source, not exposed. */ search(query: string): Promise<void>; /** * Get an array of virtual <li>s that list the search results for the given * query. */ view(query: string): Array<Mithril.Vnode>; } export interface SearchAttrs extends ComponentAttrs { /** The type of alert this is. Will be used to give the alert a class name of `Alert--{type}`. */ state: SearchState; } /** * The `Search` component displays a menu of as-you-type results from a variety * of sources. * * The search box will be 'activated' if the app's search state's * getInitialSearch() value is a truthy value. If this is the case, an 'x' * button will be shown next to the search field, and clicking it will clear the search. * * ATTRS: * * - state: SearchState instance. */ export default class Search<T extends SearchAttrs = SearchAttrs> extends Component<T, SearchState> { /** * The minimum query length before sources are searched. */ protected static MIN_SEARCH_LEN = 3; /** * The instance of `SearchState` for this component. */ protected searchState!: SearchState; /** * The instance of `SearchState` for this component. * * @deprecated Replace with`this.searchState` instead. */ // TODO: [Flarum 2.0] Remove this. // @ts-expect-error This is a get accessor, while superclass defines this as a property. This is needed to prevent breaking changes, however. protected get state() { fireDeprecationWarning('`state` property of the Search component is deprecated', '3212'); return this.searchState; } protected set state(state: SearchState) { // Workaround to prevent triggering deprecation warnings due to Mithril // setting state to undefined when creating components state !== undefined && fireDeprecationWarning('`state` property of the Search component is deprecated', '3212'); this.searchState = state; } /** * Whether or not the search input has focus. */ protected hasFocus = false; /** * An array of SearchSources. */ protected sources?: SearchSource[]; /** * The number of sources that are still loading results. */ protected loadingSources = 0; /** * The index of the currently-selected <li> in the results list. This can be * a unique string (to account for the fact that an item's position may jump * around as new results load), but otherwise it will be numeric (the * sequential position within the list). */ protected index: number = 0; protected navigator!: KeyboardNavigatable; protected searchTimeout?: NodeJS.Timeout; private updateMaxHeightHandler?: () => void; oninit(vnode: Mithril.Vnode<T, this>) { super.oninit(vnode); this.searchState = this.attrs.state; } view() { const currentSearch = this.searchState.getInitialSearch(); // Initialize search sources in the view rather than the constructor so // that we have access to app.forum. if (!this.sources) this.sources = this.sourceItems().toArray(); // Hide the search view if no sources were loaded if (!this.sources.length) return <div></div>; const searchLabel = extractText(app.translator.trans('core.forum.header.search_placeholder')); const isActive = !!currentSearch; const shouldShowResults = !!(!this.loadingSources && this.searchState.getValue() && this.hasFocus); const shouldShowClearButton = !!(!this.loadingSources && this.searchState.getValue()); return ( <div role="search" aria-label={app.translator.trans('core.forum.header.search_role_label')} className={classList('Search', { open: this.searchState.getValue() && this.hasFocus, focused: this.hasFocus, active: isActive, loading: !!this.loadingSources, })} > <div className="Search-input"> <input aria-label={searchLabel} className="FormControl" type="search" placeholder={searchLabel} value={this.searchState.getValue()} oninput={(e: InputEvent) => this.searchState.setValue((e?.target as HTMLInputElement)?.value)} onfocus={() => (this.hasFocus = true)} onblur={() => (this.hasFocus = false)} /> {!!this.loadingSources && <LoadingIndicator size="small" display="inline" containerClassName="Button Button--icon Button--link" />} {shouldShowClearButton && ( <button className="Search-clear Button Button--icon Button--link" onclick={this.clear.bind(this)} aria-label={app.translator.trans('core.forum.header.search_clear_button_accessible_label')} > {icon('fas fa-times-circle')} </button> )} </div> <ul className="Dropdown-menu Search-results" aria-hidden={!shouldShowResults || undefined} aria-live={shouldShowResults ? 'polite' : undefined} > {shouldShowResults && this.sources.map((source) => source.view(this.searchState.getValue()))} </ul> </div> ); } updateMaxHeight() { // Since extensions might add elements above the search box on mobile, // we need to calculate and set the max height dynamically. const resultsElementMargin = 14; const maxHeight = window.innerHeight - this.element.querySelector('.Search-input>.FormControl')!.getBoundingClientRect().bottom - resultsElementMargin; this.element.querySelector<HTMLElement>('.Search-results')?.style?.setProperty('max-height', `${maxHeight}px`); } onupdate(vnode: Mithril.VnodeDOM<T, this>) { super.onupdate(vnode); // Highlight the item that is currently selected. this.setIndex(this.getCurrentNumericIndex()); // If there are no sources, the search view is not shown. if (!this.sources?.length) return; this.updateMaxHeight(); } oncreate(vnode: Mithril.VnodeDOM<T, this>) { super.oncreate(vnode); // If there are no sources, we shouldn't initialize logic for // search elements, as they will not be shown. if (!this.sources?.length) return; const search = this; const state = this.searchState; // Highlight the item that is currently selected. this.setIndex(this.getCurrentNumericIndex()); this.$('.Search-results') .on('mousedown', (e) => e.preventDefault()) .on('click', () => this.$('input').trigger('blur')) // Whenever the mouse is hovered over a search result, highlight it. .on('mouseenter', '> li:not(.Dropdown-header)', function () { search.setIndex(search.selectableItems().index(this)); }); const $input = this.$('input') as JQuery<HTMLInputElement>; this.navigator = new KeyboardNavigatable(); this.navigator .onUp(() => this.setIndex(this.getCurrentNumericIndex() - 1, true)) .onDown(() => this.setIndex(this.getCurrentNumericIndex() + 1, true)) .onSelect(this.selectResult.bind(this), true) .onCancel(this.clear.bind(this)) .bindTo($input); // Handle input key events on the search input, triggering results to load. $input .on('input focus', function () { const query = this.value.toLowerCase(); if (!query) return; if (search.searchTimeout) clearTimeout(search.searchTimeout); search.searchTimeout = setTimeout(() => { if (state.isCached(query)) return; if (query.length >= (search.constructor as typeof Search).MIN_SEARCH_LEN) { search.sources?.map((source) => { if (!source.search) return; search.loadingSources++; source.search(query).then(() => { search.loadingSources = Math.max(0, search.loadingSources - 1); m.redraw(); }); }); } state.cache(query); m.redraw(); }, 250); }) .on('focus', function () { $(this) .one('mouseup', (e) => e.preventDefault()) .trigger('select'); }); this.updateMaxHeightHandler = this.updateMaxHeight.bind(this); window.addEventListener('resize', this.updateMaxHeightHandler); } onremove(vnode: Mithril.VnodeDOM<T, this>) { super.onremove(vnode); if (this.updateMaxHeightHandler) { window.removeEventListener('resize', this.updateMaxHeightHandler); } } /** * Navigate to the currently selected search result and close the list. */ selectResult() { if (this.searchTimeout) clearTimeout(this.searchTimeout); this.loadingSources = 0; const selectedUrl = this.getItem(this.index).find('a').attr('href'); if (this.searchState.getValue() && selectedUrl) { m.route.set(selectedUrl); } else { this.clear(); } this.$('input').blur(); } /** * Clear the search */ clear() { this.searchState.clear(); } /** * Build an item list of SearchSources. */ sourceItems(): ItemList<SearchSource> { const items = new ItemList<SearchSource>(); if (app.forum.attribute('canViewForum')) items.add('discussions', new DiscussionsSearchSource()); if (app.forum.attribute('canSearchUsers')) items.add('users', new UsersSearchSource()); return items; } /** * Get all of the search result items that are selectable. */ selectableItems(): JQuery { return this.$('.Search-results > li:not(.Dropdown-header)'); } /** * Get the position of the currently selected search result item. */ getCurrentNumericIndex(): number { return this.selectableItems().index(this.getItem(this.index)); } /** * Get the <li> in the search results with the given index (numeric or named). */ getItem(index: number): JQuery { const $items = this.selectableItems(); let $item = $items.filter(`[data-index="${index}"]`); if (!$item.length) { $item = $items.eq(index); } return $item; } /** * Set the currently-selected search result item to the one with the given * index. */ setIndex(index: number, scrollToItem: boolean = false) { const $items = this.selectableItems(); const $dropdown = $items.parent(); let fixedIndex = index; if (index < 0) { fixedIndex = $items.length - 1; } else if (index >= $items.length) { fixedIndex = 0; } const $item = $items.removeClass('active').eq(fixedIndex).addClass('active'); this.index = parseInt($item.attr('data-index') as string) || fixedIndex; if (scrollToItem) { const dropdownScroll = $dropdown.scrollTop()!; const dropdownTop = $dropdown.offset()!.top; const dropdownBottom = dropdownTop + $dropdown.outerHeight()!; const itemTop = $item.offset()!.top; const itemBottom = itemTop + $item.outerHeight()!; let scrollTop; if (itemTop < dropdownTop) { scrollTop = dropdownScroll - dropdownTop + itemTop - parseInt($dropdown.css('padding-top'), 10); } else if (itemBottom > dropdownBottom) { scrollTop = dropdownScroll - dropdownBottom + itemBottom + parseInt($dropdown.css('padding-bottom'), 10); } if (typeof scrollTop !== 'undefined') { $dropdown.stop(true).animate({ scrollTop }, 100); } } } }
the_stack
import * as React from "react"; import { PlaybackSettings, TimelineComponent, TimelinePausePlayAction, TimelinePausePlayArgs } from "@itwin/imodel-components-react"; import { ActionItemButton, CommandItemDef, ContentGroup, ContentLayoutDef, ContentLayoutManager, CoreTools, Frontstage, FrontstageDef, FrontstageManager, FrontstageProps, FrontstageProvider, GroupButton, ModalDialogManager, NavigationWidget, StagePanel, ToolButton, ToolWidget, useWidgetDirection, Widget, WidgetStateChangedEventArgs, Zone, ZoneLocation, ZoneState, } from "@itwin/appui-react"; import { Direction, Toolbar } from "@itwin/appui-layout-react"; import { AppTools } from "../../tools/ToolSpecifications"; import { SmallStatusBarWidgetControl } from "../statusbars/SmallStatusBar"; import { HorizontalPropertyGridWidgetControl, VerticalPropertyGridWidgetControl } from "../widgets/PropertyGridDemoWidget"; import { TableDemoWidgetControl } from "../widgets/TableDemoWidget"; import { NestedFrontstage1 } from "./NestedFrontstage1"; import { StandardContentLayouts, UiAdmin, WidgetState } from "@itwin/appui-abstract"; import { AppUi } from "../AppUi"; import { TestModalDialog } from "../dialogs/TestModalDialog"; /* eslint-disable react/jsx-key, deprecation/deprecation */ function RightPanel() { const direction = useWidgetDirection(); const [state, setState] = React.useState(() => { const frontstageDef = FrontstageManager.activeFrontstageDef!; const widgetDef = frontstageDef.findWidgetDef("VerticalPropertyGrid")!; return WidgetState[widgetDef.state]; }); React.useEffect(() => { const listener = (args: WidgetStateChangedEventArgs) => { if (args.widgetDef.id === "VerticalPropertyGrid") setState(WidgetState[args.widgetState]); }; FrontstageManager.onWidgetStateChangedEvent.addListener(listener); return () => { FrontstageManager.onWidgetStateChangedEvent.removeListener(listener); }; }); return ( <> <h2>Right panel</h2> <p>{state}</p> <p>{direction}</p> </> ); } function SampleTimelineComponent() { const duration = 20 * 1000; const startDate = new Date(2014, 6, 6); const endDate = new Date(2016, 8, 12); const [loop, setLoop] = React.useState<boolean>(false); const handleOnSettingsChange = (settings: PlaybackSettings) => { if (settings.loop !== undefined) { setLoop(settings.loop); } }; return ( <div> <TimelineComponent startDate={startDate} endDate={endDate} initialDuration={0} totalDuration={duration} minimized={true} showDuration={true} repeat={loop} onSettingsChange={handleOnSettingsChange} alwaysMinimized={true} componentId={"sampleApp-sampleTimeline"} // qualify id with "<appName>-" to ensure uniqueness /> </div> ); } export class Frontstage1 extends FrontstageProvider { public static stageId = "ui-test-app:Test1"; public get id(): string { return Frontstage1.stageId; } private _topMostPanel = { widgets: [ <Widget element={<> <h2>TopMost panel</h2> <span>BottomMost panel:</span> &nbsp; <button onClick={() => { const frontstageDef = FrontstageManager.activeFrontstageDef; const widgetDef = frontstageDef?.findWidgetDef("BottomMostPanelWidget"); widgetDef?.setWidgetState(WidgetState.Open); }}>show</button> &nbsp; <button onClick={() => { const frontstageDef = FrontstageManager.activeFrontstageDef; const widgetDef = frontstageDef?.findWidgetDef("BottomMostPanelWidget"); widgetDef?.setWidgetState(WidgetState.Hidden); }}>hide</button> </>} />, ], }; private _topPanel = { widgets: [ <Widget element={<h2>Top panel</h2>} />, ], }; private _leftPanel = { allowedZones: [2, 4, 7, 9], }; private _rightPanel = { allowedZones: [2, 9], widgets: [ <Widget element={<RightPanel />} />, ], }; private _bottomPanel = { widgets: [ <Widget element={<SampleTimelineComponent />} />, ], }; private _bottomMostPanel = { allowedZones: [2, 4, 9], widgets: [ <Widget id="BottomMostPanelWidget" element={<h2>BottomMost panel</h2>} />, ], }; public get frontstage(): React.ReactElement<FrontstageProps> { const contentGroup = new ContentGroup(AppUi.TestContentGroup1); return ( <Frontstage id={this.id} version={1} defaultTool={CoreTools.selectElementCommand} contentGroup={contentGroup} defaultContentId="TestContent1" isInFooterMode={true} topLeft={ <Zone widgets={[ <Widget isFreeform={true} element={<FrontstageToolWidget />} />, ]} /> } topCenter={ <Zone allowsMerging widgets={[ <Widget isToolSettings={true} />, ]} /> } topRight={ <Zone widgets={[ <Widget isFreeform={true} element={<FrontstageNavigationWidget />} />, ]} /> } centerLeft={ <Zone allowsMerging={true} defaultState={ZoneState.Minimized} widgets={[ <Widget id="VerticalPropertyGrid" iconSpec="icon-placeholder" labelKey="SampleApp:widgets.VerticalPropertyGrid" control={VerticalPropertyGridWidgetControl} />, ]} /> } bottomLeft={ <Zone allowsMerging={true} defaultState={ZoneState.Minimized} widgets={[ <Widget iconSpec="icon-placeholder" labelKey="SampleApp:widgets.TableDemo" control={TableDemoWidgetControl} />, ]} /> } /** The HorizontalPropertyGrid in zone 9 should be merged across zones 6 & 9 and take up the height of both zones initially. * The zones can be resized manually to take up the full height. */ centerRight={ <Zone defaultState={ZoneState.Open} allowsMerging={true} mergeWithZone={ZoneLocation.BottomRight} /> } bottomCenter={ <Zone defaultState={ZoneState.Open} widgets={[ <Widget isStatusBar={true} control={SmallStatusBarWidgetControl} />, ]} /> } bottomRight={ <Zone defaultState={ZoneState.Open} allowsMerging={true} widgets={[ <Widget defaultState={WidgetState.Open} iconSpec="icon-placeholder" labelKey="SampleApp:widgets.HorizontalPropertyGrid" control={HorizontalPropertyGridWidgetControl} fillZone={true} />, <Widget id="VerticalPropertyGrid1" defaultState={WidgetState.Hidden} iconSpec="icon-placeholder" labelKey="SampleApp:widgets.VerticalPropertyGrid" control={VerticalPropertyGridWidgetControl} />, ]} /> } topMostPanel={ <StagePanel widgets={this._topMostPanel.widgets} /> } topPanel={ <StagePanel resizable={false} widgets={this._topPanel.widgets} /> } leftPanel={ <StagePanel allowedZones={this._leftPanel.allowedZones} /> } rightPanel={ <StagePanel allowedZones={this._rightPanel.allowedZones} resizable={false} size={200} widgets={this._rightPanel.widgets} /> } bottomPanel={ <StagePanel widgets={this._bottomPanel.widgets} /> } bottomMostPanel={ <StagePanel allowedZones={this._bottomMostPanel.allowedZones} size={100} widgets={this._bottomMostPanel.widgets} /> } /> ); } } /** Define a ToolWidget with Buttons to display in the TopLeft zone. */ class FrontstageToolWidget extends React.Component { private static _frontstage1Def: FrontstageDef | undefined; private static async getFrontstage1Def() { if (!this._frontstage1Def) { const frontstageProvider = new NestedFrontstage1(); this._frontstage1Def = await FrontstageDef.create(frontstageProvider); } return this._frontstage1Def; } /** Command that opens a nested Frontstage */ private get _openNestedFrontstage1() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.openNestedFrontstage1", execute: async () => { const frontstage1Def = await FrontstageToolWidget.getFrontstage1Def(); await FrontstageManager.openNestedFrontstage(frontstage1Def); }, }); } /** Command that opens switches the content layout - TODO Review */ private get _switchLayout() { return new CommandItemDef({ iconSpec: "icon-placeholder", labelKey: "SampleApp:buttons.switchLayout", execute: async () => { const activeFrontstageDef = FrontstageManager.activeFrontstageDef; if (activeFrontstageDef) { const contentLayout = new ContentLayoutDef(StandardContentLayouts.twoHorizontalSplit); if (contentLayout && activeFrontstageDef.contentGroup) { await ContentLayoutManager.setActiveLayout(contentLayout, activeFrontstageDef.contentGroup); } } }, }); } /** Command to send pause/play toggle to the SampleTimelineComponent */ private get _pausePlayTimeline() { return new CommandItemDef({ iconSpec: "icon-snow", labelKey: "SampleApp:buttons.toggleTimelinePlay", execute: async () => { const eventArgs: TimelinePausePlayArgs = { uiComponentId: "sampleApp-sampleTimeline", timelineAction: TimelinePausePlayAction.Toggle }; UiAdmin.sendUiEvent(eventArgs); }, }); } private get _openPopupWindow() { return new CommandItemDef({ iconSpec: "icon-smiley-sad", label: "Open Popup Window", execute: () => location.href = "pw://imodelbridges-qa-us-pw.bentley.com:imodelbridges-qa-us-pw-01/Documents/D{8e708119-4aef-49f0-b412-d9b5615ba928}", // execute: () => window.open("pw://imodelbridges-qa-us-pw.bentley.com:imodelbridges-qa-us-pw-01/Documents/D{8e708119-4aef-49f0-b412-d9b5615ba928}"), }); } private get _openModal() { return new CommandItemDef({ iconSpec: "icon-smiley-happy", label: "Open Modal Dialog", execute: () => ModalDialogManager.openDialog(<TestModalDialog />), }); } private _horizontalToolbar = ( <Toolbar expandsTo={Direction.Bottom} items={ <> <ActionItemButton actionItem={this._openPopupWindow} /> <ActionItemButton actionItem={CoreTools.selectElementCommand} /> <ActionItemButton actionItem={AppTools.item1} /> <ActionItemButton actionItem={AppTools.item2} /> <ActionItemButton actionItem={this._openNestedFrontstage1} /> <ActionItemButton actionItem={this._switchLayout} /> <ActionItemButton actionItem={this._pausePlayTimeline} /> <ActionItemButton actionItem={this._openModal} /> </> } /> ); private _verticalToolbar = ( <Toolbar expandsTo={Direction.Right} items={ <> <ActionItemButton actionItem={CoreTools.rotateViewCommand} /> <ToolButton toolId={AppTools.tool1.id} iconSpec={AppTools.tool1.iconSpec} labelKey={AppTools.tool1.label} execute={AppTools.tool1.execute} /> <ToolButton toolId={AppTools.tool2.id} iconSpec={AppTools.tool2.iconSpec} labelKey={AppTools.tool2.label} execute={AppTools.tool2.execute} /> <GroupButton labelKey="SampleApp:buttons.anotherGroup" iconSpec="icon-placeholder" items={ [ AppTools.tool1, AppTools.tool2, AppTools.item3, AppTools.item4, AppTools.item5, AppTools.item6, AppTools.item7, AppTools.item8, ] } /> </> } /> ); public override render() { return ( <ToolWidget appButton={AppTools.backstageToggleCommand} horizontalToolbar={this._horizontalToolbar} verticalToolbar={this._verticalToolbar} /> ); } } /** Define a NavigationWidget with Buttons to display in the TopRight zone. */ class FrontstageNavigationWidget extends React.Component { private _horizontalToolbar = ( <Toolbar expandsTo={Direction.Bottom} items={ <> <ToolButton toolId={AppTools.item5.id} iconSpec={AppTools.item5.iconSpec} labelKey={AppTools.item5.label} execute={AppTools.item5.execute} /> <ToolButton toolId={AppTools.item6.id} iconSpec={AppTools.item6.iconSpec} labelKey={AppTools.item6.label} execute={AppTools.item6.execute} /> </> } /> ); private _verticalToolbar = ( <Toolbar expandsTo={Direction.Right} items={ <> <ToolButton toolId={AppTools.item7.id} iconSpec={AppTools.item7.iconSpec} labelKey={AppTools.item7.label} execute={AppTools.item7.execute} /> <ToolButton toolId={AppTools.item8.id} iconSpec={AppTools.item8.iconSpec} labelKey={AppTools.item8.label} execute={AppTools.item8.execute} /> </> } /> ); public override render() { return ( <NavigationWidget navigationAidId="StandardRotationNavigationAid" horizontalToolbar={this._horizontalToolbar} verticalToolbar={this._verticalToolbar} /> ); } }
the_stack
import { getActiveOrgGraphObjects, getDeletedOrgGraphObjects } from "./db"; import * as graphKey from "./graph_key"; import { Graph, Rbac, Model, Api, Auth } from "@core/types"; import { env } from "./env"; import { verifySignedLicense } from "./auth"; import { getOrgBillingId } from "./billing"; import * as R from "ramda"; import { pick } from "@core/lib/utils/pick"; import produce, { Draft } from "immer"; import { graphTypes, getUserGraph, getOrgAccessSet, getOrgUserDevicesByUserId, getAppUserGrantsByUserId, getLocalKeysByUserId, getLocalKeysByDeviceId, getActiveRecoveryKeysByUserId, getGroupMembershipsByObjectId, getActiveOrExpiredDeviceGrantsByGrantedByUserId, getActiveOrExpiredInvitesByInviteeId, getActiveOrExpiredDeviceGrantsByGranteeId, getUserIsImmediatelyDeletable, getDeviceIsImmediatelyDeletable, deleteGraphObjects, getEnvParentPermissions, getOrgPermissions, getOrg, getActiveInvitesByInviteeId, getActiveDeviceGrantsByGranteeId, } from "@core/lib/graph"; import { v4 as uuid } from "uuid"; import { objectDifference } from "@core/lib/utils/object"; import { PoolConnection } from "mysql2/promise"; import { log } from "@core/lib/utils/logger"; import { indexBy } from "@core/lib/utils/array"; import { asyncify } from "@core/lib/async"; export const getOrgGraph = async ( orgId: string, readOpts: Api.Db.DbReadOpts, nonBaseScopes?: string[] ): Promise<Api.Graph.OrgGraph> => { // query for active graph items, add to graph const graphObjects = await getActiveOrgGraphObjects( orgId, readOpts, nonBaseScopes ); return indexBy(R.prop("id"), graphObjects); }, getDeletedOrgGraph = async ( orgId: string, startsAt: number, endsAt: number, transactionConn: PoolConnection | undefined ): Promise<Api.Graph.OrgGraph> => { const graphObjects = await getDeletedOrgGraphObjects( orgId, startsAt, endsAt, transactionConn ); return indexBy(R.prop("id"), graphObjects); }, getApiUserGraph = ( orgGraph: Api.Graph.OrgGraph, orgId: string, userId: string, deviceId: string | undefined, now: number, includeDeleted = false ) => { const org = orgGraph[orgId] as Api.Db.Org; let userGraph = getUserGraph(orgGraph, userId, deviceId, includeDeleted); const billingId = getOrgBillingId(org.id); const license = verifySignedLicense(orgId, org.signedLicense, now, false); if (env.IS_CLOUD) { return { ...userGraph, [org.id]: { ...org, billingId, ssoEnabled: true, teamsEnabled: true, }, [license.id]: license, }; } if (env.IS_ENTERPRISE) { return { ...userGraph, [org.id]: { ...org, billingId, selfHostedVersions: { api: env.API_VERSION_NUMBER!, infra: env.INFRA_VERSION_NUMBER!, }, ssoEnabled: true, teamsEnabled: true, }, [license.id]: license, }; } // community return { ...userGraph, [org.id]: { ...org, billingId, }, [license.id]: license, }; }, getAccessUpdated = async ( previousGraph: Graph.Graph, nextGraph: Graph.Graph, scope: Rbac.OrgAccessScope ): Promise<Rbac.OrgAccessUpdated> => { const getOrgAccessSetAsync = asyncify("getOrgAccessSet", getOrgAccessSet); const getObjectDifferenceAsync = asyncify( "objectDifference", objectDifference ); const [nextSet, prevSet] = await Promise.all([ getOrgAccessSetAsync(nextGraph, scope), getOrgAccessSetAsync(previousGraph, scope), ]); const [granted, removed] = await Promise.all([ getObjectDifferenceAsync(nextSet, prevSet), getObjectDifferenceAsync(prevSet, nextSet), ]); return { granted, removed }; }, setEnvsUpdatedFields = ( auth: Auth.UserAuthContext, orgGraph: Api.Graph.OrgGraph, blobs: Api.Net.EnvParams["blobs"], now: number ) => { const encryptedById = auth.type == "tokenAuthContext" ? auth.orgUserDevice.id : auth.user.id; const updatingEnvironmentIds = new Set<string>(); const updatingEnvParentIds = new Set<string>(); const updatedGraph = produce(orgGraph, (draft) => { for (let envParentId in blobs) { const envParent = draft[envParentId] as Model.App | Model.Block; updatingEnvParentIds.add(envParentId); const { environments, locals } = blobs[envParentId]; for (let environmentId in environments) { updatingEnvironmentIds.add(environmentId); const environment = draft[environmentId] as Model.Environment; environment.envUpdatedAt = now; environment.encryptedById = encryptedById; environment.updatedAt = now; envParent.envsUpdatedAt = now; envParent.envsOrLocalsUpdatedAt = now; envParent.updatedAt = now; } for (let localsUserId in locals) { envParent.localsUpdatedAtByUserId[localsUserId] = now; envParent.localsUpdatedAt = now; envParent.envsOrLocalsUpdatedAt = now; envParent.localsEncryptedBy[localsUserId] = encryptedById; envParent.updatedAt = now; } } }); return { updatedGraph, updatingEnvironmentIds, updatingEnvParentIds, }; }, getGraphTransactionItems = ( previousGraph: Api.Graph.OrgGraph, nextGraph: Api.Graph.OrgGraph, now: number ) => { const transactionItems: Api.Db.ObjectTransactionItems = {}, toPut: { [id: string]: Api.Graph.GraphObject } = {}, toDelete: Api.Graph.GraphObject[] = []; // compare each item in graph, checking equality / newly created / deleted for (let id in nextGraph) { const previous = previousGraph[id], next = nextGraph[id]; if (next.deletedAt) { toDelete.push({ ...next, updatedAt: now, }); } else if (!previous || next.updatedAt == now) { toPut[next.id] = next; } // uncomment below to debug missing `updatedAt` timestamps // else if ( // env.NODE_ENV == "development" && // stableStringify(previous) != stableStringify(next) // ) { // const msg = // "Development-only error: graph object was updated but is missing updatedAt timestamp"; // log(msg, { previous, next, now }); // throw new Error(msg); // } } for (let obj of toDelete) { if (obj.id in toPut) { delete toPut[obj.id]; } if (!transactionItems.softDeleteKeys) { transactionItems.softDeleteKeys = []; } transactionItems.softDeleteKeys.push(pick(["pkey", "skey"], obj)); } for (let id in toPut) { const obj = toPut[id]; if (!transactionItems.puts) { transactionItems.puts = []; } transactionItems.puts.push(obj); } return transactionItems; }, deleteUser = ( orgGraph: Api.Graph.OrgGraph, userId: string, auth: Auth.DefaultAuthContext | Auth.ProvisioningBearerAuthContext, now: number ): Api.Graph.OrgGraph => { const target = orgGraph[userId] as Api.Db.OrgUser | Api.Db.CliUser, byType = graphTypes(orgGraph), orgUserDevices = getOrgUserDevicesByUserId(orgGraph)[userId] ?? [], appUserGrants = getAppUserGrantsByUserId(orgGraph)[userId] ?? [], localKeys = getLocalKeysByUserId(orgGraph)[userId] ?? [], localKeyIds = localKeys.map(R.prop("id")), localKeyIdsSet = new Set(localKeyIds), generatedEnvkeys = byType.generatedEnvkeys.filter(({ keyableParentId }) => localKeyIdsSet.has(keyableParentId) ), groupMemberships = getGroupMembershipsByObjectId(orgGraph)[userId] ?? [], appGroupUsers = byType.appGroupUsers.filter(R.propEq("userId", userId)), recoveryKey = getActiveRecoveryKeysByUserId(orgGraph)[userId], pendingOrExpiredGranterDeviceGrants = getActiveOrExpiredDeviceGrantsByGrantedByUserId(orgGraph)[userId] ?? []; let deleteIds: string[] = ( [ appUserGrants, generatedEnvkeys, groupMemberships, appGroupUsers, recoveryKey ? [recoveryKey] : [], pendingOrExpiredGranterDeviceGrants, ] as Api.Graph.GraphObject[][] ).flatMap((objects) => objects.map(R.prop("id"))); let updatedGraph = produce(orgGraph, (draft) => { // clear out localsUpdatedAtByUserId / localsEncryptedBy entries const { apps, blocks } = byType; for (let envParents of [apps, blocks]) { for (let envParent of envParents) { const envParentDraft = draft[envParent.id] as Draft<Api.Db.EnvParent>; if ( envParentDraft.localsUpdatedAtByUserId[userId] || envParentDraft.localsEncryptedBy[userId] ) { delete envParentDraft.localsUpdatedAtByUserId[userId]; delete envParentDraft.localsEncryptedBy[userId]; envParentDraft.updatedAt = now; } } } // clear out any pending rootPubkeyReplacements for user + user's local keys const rootPubkeyReplacements = byType.rootPubkeyReplacements as Api.Db.RootPubkeyReplacement[]; for (let replacement of rootPubkeyReplacements) { const replacementDraft = draft[ replacement.id ] as Draft<Api.Db.RootPubkeyReplacement>; for (let objs of [orgUserDevices, generatedEnvkeys]) { for (let { id } of objs) { if (replacementDraft.processedAtById[id]) { delete replacementDraft.processedAtById[id]; replacementDraft.updatedAt = now; } } } const replacementProcessedAll = R.all( Boolean, Object.values(replacementDraft.processedAtById) ); if (replacementProcessedAll) { deleteIds.push(replacementDraft.id); } } }); const canImmediatelyDelete = getUserIsImmediatelyDeletable( orgGraph, userId ); let deletedDeviceLike = 0; let deletedUserOrInvite = 0; if (canImmediatelyDelete) { deleteIds.push(userId); if (target.type == "cliUser") { deletedDeviceLike++; } else { deletedUserOrInvite++; for (let { id } of orgUserDevices) { deleteIds.push(id); deletedDeviceLike++; } } const invites = getActiveOrExpiredInvitesByInviteeId(orgGraph)[userId] ?? [], deviceGrants = getActiveOrExpiredDeviceGrantsByGranteeId(orgGraph)[userId] ?? []; for (let objs of [invites, deviceGrants]) { for (let { id } of objs) { deleteIds.push(id); deletedDeviceLike++; } } deletedUserOrInvite += invites.length; } else { updatedGraph = produce(updatedGraph, (draft) => { (draft[target.id] as Api.Db.OrgUser | Api.Db.CliUser).deactivatedAt = now; (draft[target.id] as Api.Db.OrgUser | Api.Db.CliUser).updatedAt = now; if (target.type == "cliUser") { deletedDeviceLike++; const pubkeyRevocationRequest = getPubkeyRevocationRequest( auth, target, now ); draft[pubkeyRevocationRequest.id] = pubkeyRevocationRequest; } else { for (let orgUserDevice of orgUserDevices) { deletedDeviceLike++; (draft[orgUserDevice.id] as Api.Db.OrgUserDevice).deactivatedAt = now; (draft[orgUserDevice.id] as Api.Db.OrgUserDevice).updatedAt = now; const pubkeyRevocationRequest = getPubkeyRevocationRequest( auth, orgUserDevice, now ); draft[pubkeyRevocationRequest.id] = pubkeyRevocationRequest; } } }); } deleteIds = deleteIds.concat(localKeyIds); updatedGraph = deleteGraphObjects(updatedGraph, deleteIds, now); if (deletedDeviceLike > 0 || deletedUserOrInvite > 0) { const org = getOrg(updatedGraph) as Api.Db.Org; updatedGraph = { ...updatedGraph, [org.id]: { ...org, deviceLikeCount: org.deviceLikeCount - deletedDeviceLike, activeUserOrInviteCount: org.activeUserOrInviteCount! - deletedUserOrInvite, updatedAt: now, }, }; } return updatedGraph; }, deleteDevice = ( orgGraph: Api.Graph.OrgGraph, deviceId: string, auth: Auth.DefaultAuthContext, now: number ): Api.Graph.OrgGraph => { const orgUserDevice = orgGraph[deviceId] as Api.Db.OrgUserDevice; const localKeys = getLocalKeysByDeviceId(orgGraph)[deviceId] ?? [], localKeyIds = localKeys.map(R.prop("id")), localKeyIdsSet = new Set(localKeyIds), generatedEnvkeys = graphTypes(orgGraph).generatedEnvkeys.filter( ({ keyableParentId }) => localKeyIdsSet.has(keyableParentId) ); let deleteIds = [...localKeyIds, ...generatedEnvkeys.map(R.prop("id"))]; let updatedGraph = produce(orgGraph, (draft) => { const draftsByType = graphTypes(draft); // clear out any pending rootPubkeyReplacements for this device const rootPubkeyReplacementDrafts = draftsByType.rootPubkeyReplacements as Api.Db.RootPubkeyReplacement[]; for (let replacementDraft of rootPubkeyReplacementDrafts) { if (replacementDraft.processedAtById[deviceId]) { delete replacementDraft.processedAtById[deviceId]; replacementDraft.updatedAt = now; const replacementProcessedAll = R.all( Boolean, Object.values(replacementDraft.processedAtById) ); if (replacementProcessedAll) { deleteIds.push(replacementDraft.id); } } } }); const canImmediatelyDelete = getDeviceIsImmediatelyDeletable( orgGraph, deviceId ); if (canImmediatelyDelete) { deleteIds.push(deviceId); } else { updatedGraph = produce(updatedGraph, (draft) => { (draft[orgUserDevice.id] as Api.Db.OrgUserDevice).deactivatedAt = now; (draft[orgUserDevice.id] as Api.Db.OrgUserDevice).updatedAt = now; const pubkeyRevocationRequest = getPubkeyRevocationRequest( auth, orgUserDevice, now ); draft[pubkeyRevocationRequest.id] = pubkeyRevocationRequest; }); } if (deleteIds.length > 0) { updatedGraph = deleteGraphObjects(updatedGraph, deleteIds, now); } return updatedGraph; }, clearOrphanedLocals = ( orgGraph: Api.Graph.OrgGraph, now: number ): [Api.Graph.OrgGraph, Api.Db.ObjectTransactionItems] => { // delete blobs and clear localsUpdatedAt for any users that previously had access and no longer do const hardDeleteEncryptedBlobParams: Api.Db.ObjectTransactionItems["hardDeleteEncryptedBlobParams"] = []; const { apps, blocks, org } = graphTypes(orgGraph); const updatedOrgGraph = produce(orgGraph, (draft) => { for (let envParent of (apps as Model.EnvParent[]).concat(blocks)) { if (envParent.deletedAt) { continue; } for (let localsUserId in envParent.localsUpdatedAtByUserId) { const localsUser = orgGraph[localsUserId] as | Model.OrgUser | Model.CliUser | undefined; let shouldClear = false; if (localsUser && !localsUser.deletedAt) { const orgPermissions = getOrgPermissions( orgGraph, localsUser.orgRoleId ); const envParentPermissions = getEnvParentPermissions( orgGraph, envParent.id, localsUserId ); if ( !orgPermissions.has("blocks_read_all") && !envParentPermissions.has("app_read_own_locals") ) { shouldClear = true; } } else { shouldClear = true; } if (shouldClear) { const envParentDraft = draft[ envParent.id ] as Draft<Api.Db.EnvParent>; delete envParentDraft.localsUpdatedAtByUserId[localsUserId]; delete envParentDraft.localsEncryptedBy[localsUserId]; envParentDraft.updatedAt = now; hardDeleteEncryptedBlobParams.push({ orgId: org.id, envParentId: envParent.id, blobType: "env", environmentId: envParent.id + "|" + localsUserId, }); } } } }); return [updatedOrgGraph, { hardDeleteEncryptedBlobParams }]; }; const getPubkeyRevocationRequest = ( auth: Auth.DefaultAuthContext | Auth.ProvisioningBearerAuthContext, revocationTarget: Model.OrgUserDevice | Model.CliUser, now: number ) => { const pubkeyRevocationRequestId = uuid(), pubkeyRevocationRequest: Api.Db.PubkeyRevocationRequest = { type: "pubkeyRevocationRequest", id: pubkeyRevocationRequestId, ...graphKey.pubkeyRevocationRequest( auth.org.id, pubkeyRevocationRequestId ), targetId: revocationTarget.id, // OrgUser.id or ProvisioningProvider.id. Informational prop only (?) creatorId: "provisioningProvider" in auth ? auth.provisioningProvider.id : auth.user.id, excludeFromDeletedGraph: true, createdAt: now, updatedAt: now, }; return pubkeyRevocationRequest; };
the_stack
import React from "react"; import { Room } from "matrix-js-sdk/src/models/room"; import { MatrixError } from "matrix-js-sdk/src/http-api"; import { EventType, RoomType } from "matrix-js-sdk/src/@types/event"; import { IJoinRuleEventContent, JoinRule } from "matrix-js-sdk/src/@types/partials"; import { RoomMember } from "matrix-js-sdk/src/models/room-member"; import classNames from 'classnames'; import { MatrixClientPeg } from '../../../MatrixClientPeg'; import dis from '../../../dispatcher/dispatcher'; import { _t } from '../../../languageHandler'; import SdkConfig from "../../../SdkConfig"; import IdentityAuthClient from '../../../IdentityAuthClient'; import { CommunityPrototypeStore } from "../../../stores/CommunityPrototypeStore"; import { UPDATE_EVENT } from "../../../stores/AsyncStore"; import { replaceableComponent } from "../../../utils/replaceableComponent"; import InviteReason from "../elements/InviteReason"; import { IOOBData } from "../../../stores/ThreepidInviteStore"; import Spinner from "../elements/Spinner"; import AccessibleButton from "../elements/AccessibleButton"; import { UIFeature } from "../../../settings/UIFeature"; import SettingsStore from "../../../settings/SettingsStore"; import RoomAvatar from "../avatars/RoomAvatar"; const MemberEventHtmlReasonField = "io.element.html_reason"; enum MessageCase { NotLoggedIn = "NotLoggedIn", Joining = "Joining", Loading = "Loading", Rejecting = "Rejecting", Kicked = "Kicked", Banned = "Banned", OtherThreePIDError = "OtherThreePIDError", InvitedEmailNotFoundInAccount = "InvitedEmailNotFoundInAccount", InvitedEmailNoIdentityServer = "InvitedEmailNoIdentityServer", InvitedEmailMismatch = "InvitedEmailMismatch", Invite = "Invite", ViewingRoom = "ViewingRoom", RoomNotFound = "RoomNotFound", OtherError = "OtherError", } interface IProps { // if inviterName is specified, the preview bar will shown an invite to the room. // You should also specify onRejectClick if specifying inviterName inviterName?: string; // If invited by 3rd party invite, the email address the invite was sent to invitedEmail?: string; // For third party invites, information passed about the room out-of-band oobData?: IOOBData; // For third party invites, a URL for a 3pid invite signing service signUrl?: string; // A standard client/server API error object. If supplied, indicates that the // caller was unable to fetch details about the room for the given reason. error?: MatrixError; canPreview?: boolean; previewLoading?: boolean; room?: Room; loading?: boolean; joining?: boolean; rejecting?: boolean; // The alias that was used to access this room, if appropriate // If given, this will be how the room is referred to (eg. // in error messages). roomAlias?: string; onJoinClick?(): void; onRejectClick?(): void; onRejectAndIgnoreClick?(): void; onForgetClick?(): void; } interface IState { busy: boolean; accountEmails?: string[]; invitedEmailMxid?: string; threePidFetchError?: MatrixError; } @replaceableComponent("views.rooms.RoomPreviewBar") export default class RoomPreviewBar extends React.Component<IProps, IState> { static defaultProps = { onJoinClick() {}, }; constructor(props) { super(props); this.state = { busy: false, }; } componentDidMount() { this.checkInvitedEmail(); CommunityPrototypeStore.instance.on(UPDATE_EVENT, this.onCommunityUpdate); } componentDidUpdate(prevProps, prevState) { if (this.props.invitedEmail !== prevProps.invitedEmail || this.props.inviterName !== prevProps.inviterName) { this.checkInvitedEmail(); } } componentWillUnmount() { CommunityPrototypeStore.instance.off(UPDATE_EVENT, this.onCommunityUpdate); } private async checkInvitedEmail() { // If this is an invite and we've been told what email address was // invited, fetch the user's account emails and discovery bindings so we // can check them against the email that was invited. if (this.props.inviterName && this.props.invitedEmail) { this.setState({ busy: true }); try { // Gather the account 3PIDs const account3pids = await MatrixClientPeg.get().getThreePids(); this.setState({ accountEmails: account3pids.threepids.filter(b => b.medium === 'email').map(b => b.address), }); // If we have an IS connected, use that to lookup the email and // check the bound MXID. if (!MatrixClientPeg.get().getIdentityServerUrl()) { this.setState({ busy: false }); return; } const authClient = new IdentityAuthClient(); const identityAccessToken = await authClient.getAccessToken(); const result = await MatrixClientPeg.get().lookupThreePid( 'email', this.props.invitedEmail, undefined /* callback */, identityAccessToken, ); this.setState({ invitedEmailMxid: result.mxid }); } catch (err) { this.setState({ threePidFetchError: err }); } this.setState({ busy: false }); } } private onCommunityUpdate = (roomId: string): void => { if (this.props.room && this.props.room.roomId !== roomId) { return; } this.forceUpdate(); // we have nothing to update }; private getMessageCase(): MessageCase { const isGuest = MatrixClientPeg.get().isGuest(); if (isGuest) { return MessageCase.NotLoggedIn; } const myMember = this.getMyMember(); if (myMember) { if (myMember.isKicked()) { return MessageCase.Kicked; } else if (myMember.membership === "ban") { return MessageCase.Banned; } } if (this.props.joining) { return MessageCase.Joining; } else if (this.props.rejecting) { return MessageCase.Rejecting; } else if (this.props.loading || this.state.busy) { return MessageCase.Loading; } if (this.props.inviterName) { if (this.props.invitedEmail) { if (this.state.threePidFetchError) { return MessageCase.OtherThreePIDError; } else if ( this.state.accountEmails && !this.state.accountEmails.includes(this.props.invitedEmail) ) { return MessageCase.InvitedEmailNotFoundInAccount; } else if (!MatrixClientPeg.get().getIdentityServerUrl()) { return MessageCase.InvitedEmailNoIdentityServer; } else if (this.state.invitedEmailMxid != MatrixClientPeg.get().getUserId()) { return MessageCase.InvitedEmailMismatch; } } return MessageCase.Invite; } else if (this.props.error) { if ((this.props.error as MatrixError).errcode == 'M_NOT_FOUND') { return MessageCase.RoomNotFound; } else { return MessageCase.OtherError; } } else { return MessageCase.ViewingRoom; } } private getKickOrBanInfo(): { memberName?: string, reason?: string } { const myMember = this.getMyMember(); if (!myMember) { return {}; } const kickerMember = this.props.room.currentState.getMember( myMember.events.member.getSender(), ); const memberName = kickerMember ? kickerMember.name : myMember.events.member.getSender(); const reason = myMember.events.member.getContent().reason; return { memberName, reason }; } private joinRule(): JoinRule { return this.props.room?.currentState .getStateEvents(EventType.RoomJoinRules, "")?.getContent<IJoinRuleEventContent>().join_rule; } private communityProfile(): { displayName?: string, avatarMxc?: string } { if (this.props.room) return CommunityPrototypeStore.instance.getInviteProfile(this.props.room.roomId); return { displayName: null, avatarMxc: null }; } private roomName(atStart = false): string { let name = this.props.room ? this.props.room.name : this.props.roomAlias; const profile = this.communityProfile(); if (profile.displayName) name = profile.displayName; if (name) { return name; } else if (atStart) { return _t("This room"); } else { return _t("this room"); } } private getMyMember(): RoomMember { return this.props.room?.getMember(MatrixClientPeg.get().getUserId()); } private getInviteMember(): RoomMember { const { room } = this.props; if (!room) { return; } const myUserId = MatrixClientPeg.get().getUserId(); const inviteEvent = room.currentState.getMember(myUserId); if (!inviteEvent) { return; } const inviterUserId = inviteEvent.events.member.getSender(); return room.currentState.getMember(inviterUserId); } private isDMInvite(): boolean { const myMember = this.getMyMember(); if (!myMember) { return false; } const memberEvent = myMember.events.member; const memberContent = memberEvent.getContent(); return memberContent.membership === "invite" && memberContent.is_direct; } private makeScreenAfterLogin(): { screen: string, params: Record<string, any> } { return { screen: 'room', params: { email: this.props.invitedEmail, signurl: this.props.signUrl, room_name: this.props.oobData ? this.props.oobData.room_name : null, room_avatar_url: this.props.oobData ? this.props.oobData.avatarUrl : null, inviter_name: this.props.oobData ? this.props.oobData.inviterName : null, }, }; } private onLoginClick = () => { dis.dispatch({ action: 'start_login', screenAfterLogin: this.makeScreenAfterLogin() }); }; private onRegisterClick = () => { dis.dispatch({ action: 'start_registration', screenAfterLogin: this.makeScreenAfterLogin() }); }; render() { const brand = SdkConfig.get().brand; let showSpinner = false; let title; let subTitle; let reasonElement; let primaryActionHandler; let primaryActionLabel; let secondaryActionHandler; let secondaryActionLabel; let footer; const extraComponents = []; const messageCase = this.getMessageCase(); switch (messageCase) { case MessageCase.Joining: { title = this.props.oobData?.roomType === RoomType.Space ? _t("Joining space …") : _t("Joining room …"); showSpinner = true; break; } case MessageCase.Loading: { title = _t("Loading …"); showSpinner = true; break; } case MessageCase.Rejecting: { title = _t("Rejecting invite …"); showSpinner = true; break; } case MessageCase.NotLoggedIn: { title = _t("Join the conversation with an account"); if (SettingsStore.getValue(UIFeature.Registration)) { primaryActionLabel = _t("Sign Up"); primaryActionHandler = this.onRegisterClick; } secondaryActionLabel = _t("Sign In"); secondaryActionHandler = this.onLoginClick; if (this.props.previewLoading) { footer = ( <div> <Spinner w={20} h={20} /> { _t("Loading room preview") } </div> ); } break; } case MessageCase.Kicked: { const { memberName, reason } = this.getKickOrBanInfo(); title = _t("You were kicked from %(roomName)s by %(memberName)s", { memberName, roomName: this.roomName() }); subTitle = reason ? _t("Reason: %(reason)s", { reason }) : null; if (this.joinRule() === "invite") { primaryActionLabel = _t("Forget this room"); primaryActionHandler = this.props.onForgetClick; } else { primaryActionLabel = _t("Re-join"); primaryActionHandler = this.props.onJoinClick; secondaryActionLabel = _t("Forget this room"); secondaryActionHandler = this.props.onForgetClick; } break; } case MessageCase.Banned: { const { memberName, reason } = this.getKickOrBanInfo(); title = _t("You were banned from %(roomName)s by %(memberName)s", { memberName, roomName: this.roomName() }); subTitle = reason ? _t("Reason: %(reason)s", { reason }) : null; primaryActionLabel = _t("Forget this room"); primaryActionHandler = this.props.onForgetClick; break; } case MessageCase.OtherThreePIDError: { title = _t("Something went wrong with your invite to %(roomName)s", { roomName: this.roomName() }); const joinRule = this.joinRule(); const errCodeMessage = _t( "An error (%(errcode)s) was returned while trying to validate your " + "invite. You could try to pass this information on to a room admin.", { errcode: this.state.threePidFetchError.errcode || _t("unknown error code") }, ); switch (joinRule) { case "invite": subTitle = [ _t("You can only join it with a working invite."), errCodeMessage, ]; primaryActionLabel = _t("Try to join anyway"); primaryActionHandler = this.props.onJoinClick; break; case "public": subTitle = _t("You can still join it because this is a public room."); primaryActionLabel = _t("Join the discussion"); primaryActionHandler = this.props.onJoinClick; break; default: subTitle = errCodeMessage; primaryActionLabel = _t("Try to join anyway"); primaryActionHandler = this.props.onJoinClick; break; } break; } case MessageCase.InvitedEmailNotFoundInAccount: { title = _t( "This invite to %(roomName)s was sent to %(email)s which is not " + "associated with your account", { roomName: this.roomName(), email: this.props.invitedEmail, }, ); subTitle = _t( "Link this email with your account in Settings to receive invites " + "directly in %(brand)s.", { brand }, ); primaryActionLabel = _t("Join the discussion"); primaryActionHandler = this.props.onJoinClick; break; } case MessageCase.InvitedEmailNoIdentityServer: { title = _t( "This invite to %(roomName)s was sent to %(email)s", { roomName: this.roomName(), email: this.props.invitedEmail, }, ); subTitle = _t( "Use an identity server in Settings to receive invites directly in %(brand)s.", { brand }, ); primaryActionLabel = _t("Join the discussion"); primaryActionHandler = this.props.onJoinClick; break; } case MessageCase.InvitedEmailMismatch: { title = _t( "This invite to %(roomName)s was sent to %(email)s", { roomName: this.roomName(), email: this.props.invitedEmail, }, ); subTitle = _t( "Share this email in Settings to receive invites directly in %(brand)s.", { brand }, ); primaryActionLabel = _t("Join the discussion"); primaryActionHandler = this.props.onJoinClick; break; } case MessageCase.Invite: { const oobData = Object.assign({}, this.props.oobData, { avatarUrl: this.communityProfile().avatarMxc, }); const avatar = <RoomAvatar room={this.props.room} oobData={oobData} />; const inviteMember = this.getInviteMember(); let inviterElement; if (inviteMember) { inviterElement = <span> <span className="mx_RoomPreviewBar_inviter"> { inviteMember.rawDisplayName } </span> ({ inviteMember.userId }) </span>; } else { inviterElement = (<span className="mx_RoomPreviewBar_inviter">{ this.props.inviterName }</span>); } const isDM = this.isDMInvite(); if (isDM) { title = _t("Do you want to chat with %(user)s?", { user: inviteMember.name }); subTitle = [ avatar, _t("<userName/> wants to chat", {}, { userName: () => inviterElement }), ]; primaryActionLabel = _t("Start chatting"); } else { title = _t("Do you want to join %(roomName)s?", { roomName: this.roomName() }); subTitle = [ avatar, _t("<userName/> invited you", {}, { userName: () => inviterElement }), ]; primaryActionLabel = _t("Accept"); } const myUserId = MatrixClientPeg.get().getUserId(); const memberEventContent = this.props.room.currentState.getMember(myUserId).events.member.getContent(); if (memberEventContent.reason) { reasonElement = <InviteReason reason={memberEventContent.reason} htmlReason={memberEventContent[MemberEventHtmlReasonField]} />; } primaryActionHandler = this.props.onJoinClick; secondaryActionLabel = _t("Reject"); secondaryActionHandler = this.props.onRejectClick; if (this.props.onRejectAndIgnoreClick) { extraComponents.push( <AccessibleButton kind="secondary" onClick={this.props.onRejectAndIgnoreClick} key="ignore"> { _t("Reject & Ignore user") } </AccessibleButton>, ); } break; } case MessageCase.ViewingRoom: { if (this.props.canPreview) { title = _t("You're previewing %(roomName)s. Want to join it?", { roomName: this.roomName() }); } else { title = _t("%(roomName)s can't be previewed. Do you want to join it?", { roomName: this.roomName(true) }); } primaryActionLabel = _t("Join the discussion"); primaryActionHandler = this.props.onJoinClick; break; } case MessageCase.RoomNotFound: { title = _t("%(roomName)s does not exist.", { roomName: this.roomName(true) }); subTitle = _t("This room doesn't exist. Are you sure you're at the right place?"); break; } case MessageCase.OtherError: { title = _t("%(roomName)s is not accessible at this time.", { roomName: this.roomName(true) }); subTitle = [ _t("Try again later, or ask a room admin to check if you have access."), _t( "%(errcode)s was returned while trying to access the room. " + "If you think you're seeing this message in error, please " + "<issueLink>submit a bug report</issueLink>.", { errcode: this.props.error.errcode }, { issueLink: label => <a href="https://github.com/vector-im/element-web/issues/new/choose" target="_blank" rel="noreferrer noopener">{ label }</a> }, ), ]; break; } } let subTitleElements; if (subTitle) { if (!Array.isArray(subTitle)) { subTitle = [subTitle]; } subTitleElements = subTitle.map((t, i) => <p key={`subTitle${i}`}>{ t }</p>); } let titleElement; if (showSpinner) { titleElement = <h3 className="mx_RoomPreviewBar_spinnerTitle"><Spinner />{ title }</h3>; } else { titleElement = <h3>{ title }</h3>; } let primaryButton; if (primaryActionHandler) { primaryButton = ( <AccessibleButton kind="primary" onClick={primaryActionHandler}> { primaryActionLabel } </AccessibleButton> ); } let secondaryButton; if (secondaryActionHandler) { secondaryButton = ( <AccessibleButton kind="secondary" onClick={secondaryActionHandler}> { secondaryActionLabel } </AccessibleButton> ); } const isPanel = this.props.canPreview; const classes = classNames("mx_RoomPreviewBar", "dark-panel", `mx_RoomPreviewBar_${messageCase}`, { "mx_RoomPreviewBar_panel": isPanel, "mx_RoomPreviewBar_dialog": !isPanel, }); // ensure correct tab order for both views const actions = isPanel ? <> { secondaryButton } { extraComponents } { primaryButton } </> : <> { primaryButton } { extraComponents } { secondaryButton } </>; return ( <div className={classes}> <div className="mx_RoomPreviewBar_message"> { titleElement } { subTitleElements } </div> { reasonElement } <div className="mx_RoomPreviewBar_actions"> { actions } </div> <div className="mx_RoomPreviewBar_footer"> { footer } </div> </div> ); } }
the_stack
import substrings from '@udondan/common-substrings'; import RegexParser = require('regex-parser'); import { AccessLevel } from '../access-level'; import { AccessLevelList } from '../access-level'; import { PolicyStatementWithCondition } from './2-conditions'; export interface Action { url: string; description: string; accessLevel: string; resourceTypes?: any; conditions?: string[]; dependentActions?: string[]; } /** * Adds "action" functionality to the Policy Statement */ export class PolicyStatementWithActions extends PolicyStatementWithCondition { protected accessLevelList: AccessLevelList = {}; private useNotActions = false; protected actions: string[] = []; private cdkActionsApplied = false; private isCompact = false; /** * Injects actions into the statement. * * Only relevant for the main package. In CDK mode this only calls super. */ public toJSON(): any { // @ts-ignore only available after swapping 1-base if (typeof this.addResources == 'function') { this.cdkApplyActions(); return super.toJSON(); } const mode = this.useNotActions ? 'NotAction' : 'Action'; const statement = super.toJSON(); const self = this; if (this.hasActions()) { if (this.isCompact) { this.compactActions(); } const actions = this.actions .filter((elem, pos) => { return self.actions.indexOf(elem) == pos; }) .sort(); statement[mode] = actions.length > 1 ? actions : actions[0]; } return statement; } public toStatementJson(): any { this.cdkApplyActions(); // @ts-ignore only available after swapping 1-base return super.toStatementJson(); } private cdkApplyActions() { if (!this.cdkActionsApplied) { const mode = this.useNotActions ? 'addNotActions' : 'addActions'; const self = this; if (this.isCompact) { this.compactActions(); } const uniqueActions = this.actions .filter((elem, pos) => { return self.actions.indexOf(elem) == pos; }) .sort(); // @ts-ignore only available after swapping 1-base this[mode](...uniqueActions); } this.cdkActionsApplied = true; } /** * Switches the statement to use [`NotAction`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html). */ public notActions() { this.useNotActions = true; return this; } /** * Checks weather actions have been applied to the policy. */ public hasActions(): boolean { return this.actions.length > 0; } /** * Adds actions by name. * * Depending on the "mode", actions will be either added to the list of [`Actions`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html) or [`NotActions`](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_notaction.html). * * The mode can be switched by calling `notActions()`. * * If the action does not contain a colon, the action will be prefixed with the service prefix of the class, e.g. `ec2:` * * @param action Actions that will be added to the statement. */ public to(action: string) { if (this.servicePrefix.length && action.indexOf(':') < 0) { action = this.servicePrefix + ':' + action; } this.actions.push(action); return this; } /** * Adds all actions of the statement provider to the statement, e.g. `actions: 'ec2:*'` */ public allActions() { if (this.servicePrefix.length) { this.to(`${this.servicePrefix}:*`); } else { this.to('*'); } return this; } /** * Adds all actions that match one of the given regular expressions. * * @param expressions One or more regular expressions. The regular expressions need to be in [Perl/JavaScript literal style](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) and need to be passed as strings, * For example: * ```typescript * allMatchingActions('/vpn/i') * ``` */ public allMatchingActions(...expressions: string[]) { expressions.forEach((expression) => { for (const [_, actions] of Object.entries(this.accessLevelList)) { actions.forEach((action) => { if (action.match(RegexParser(expression))) { this.to(`${this.servicePrefix}:${action}`); } }); } }); return this; } /** * Adds all actions with [access level](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_understand-policy-summary-access-level-summaries.html#access_policies_access-level) LIST to the statement * * Permission to list resources within the service to determine whether an object exists. * * Actions with this level of access can list objects but cannot see the contents of a resource. * * For example, the Amazon S3 action `ListBucket` has the List access level. */ public allListActions() { return this.addAccessLevel(AccessLevel.LIST); } /** * Adds all actions with [access level](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_understand-policy-summary-access-level-summaries.html#access_policies_access-level) READ to the statement * * Permission to read but not edit the contents and attributes of resources in the service. * * For example, the Amazon S3 actions `GetObject` and `GetBucketLocation` have the Read access level. */ public allReadActions() { return this.addAccessLevel(AccessLevel.READ); } /** * Adds all actions with [access level](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_understand-policy-summary-access-level-summaries.html#access_policies_access-level) WRITE to the statement * * Permission to create, delete, or modify resources in the service. * * For example, the Amazon S3 actions `CreateBucket`, `DeleteBucket` and `PutObject` have the Write access level. * * Write actions might also allow modifying a resource tag. However, an action that allows only changes to tags has the Tagging access level. */ public allWriteActions() { return this.addAccessLevel(AccessLevel.WRITE); } /** * Adds all actions with [access level](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_understand-policy-summary-access-level-summaries.html#access_policies_access-level) PERMISSION MANAGEMENT to the statement * * Permission to grant or modify resource permissions in the service. * * For example, most IAM and AWS Organizations actions, as well as actions like the Amazon S3 actions `PutBucketPolicy` and `DeleteBucketPolicy` have the Permissions management access level. */ public allPermissionManagementActions() { return this.addAccessLevel(AccessLevel.PERMISSION_MANAGEMENT); } /** * Adds all actions with [access level](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_understand-policy-summary-access-level-summaries.html#access_policies_access-level) TAGGING to the statement * * Permission to perform actions that only change the state of resource tags. * * For example, the IAM actions `TagRole` and `UntagRole` have the Tagging access level because they allow only tagging or untagging a role. However, the `CreateRole` action allows tagging a role resource when you create that role. Because the action does not only add a tag, it has the Write access level. */ public allTaggingActions() { return this.addAccessLevel(AccessLevel.TAGGING); } private addAccessLevel(accessLevel: AccessLevel) { if (accessLevel in this.accessLevelList) { this.accessLevelList[accessLevel].forEach((action) => { this.to(`${this.servicePrefix}:${action}`); }); } return this; } /** * Condense action list down to a list of patterns. * * Using this method can help to reduce the policy size. * * For example, all actions with access level `list` could be reduced to a small pattern `List*`. */ public compact() { this.isCompact = true; return this; } private compactActions() { // actions that will be included, service prefix is removed const includeActions = this.actions.map((elem) => { return elem.substr(elem.indexOf(':') + 1); }); // actions that will not be included, the opposite of includeActions const excludeActions: string[] = []; for (const [_, actions] of Object.entries(this.accessLevelList)) { actions.forEach((action) => { if (!includeActions.includes(action)) { excludeActions.push(`^${action}$`); } }); } // will contain the index of elements that are covered by substrings let covered: number[] = []; const subs = substrings( includeActions.map((action) => { return `^${action}$`; }), { minLength: 3, minOccurrence: 2, } ) .filter((sub) => { // remove all substrings, that match an action we have not selected for (let action of excludeActions) { if (action.includes(sub.name)) { return false; } } return true; }) .sort((a, b) => { // sort list by the number of matches if (a.source.length < b.source.length) return 1; if (a.source.length > b.source.length) return -1; return 0; }) .filter((sub) => { // removes substrings, that have already been covered by other substrings const sources = sub.source.filter((source) => { return !covered.includes(source); }); if (sources.length > 1) { //add list of sources to the global list of covered actions covered = covered.concat(sources); return true; } return false; }); // stores the list of patterns const compactActionList: string[] = []; subs.forEach((sub) => { compactActionList.push( `${this.servicePrefix}:*${sub.name}*` .replace('*^', '') .replace('$*', '') ); sub.source.forEach((source) => { includeActions[source] = ''; // invalidate, will be filtered later }); }); includeActions .filter((action) => { // remove elements that have been covered by patterns, we invalidated them above return action.length > 0; }) .forEach((action) => { // add actions that have not been covered by patterns to the new action list compactActionList.push(`${this.servicePrefix}:${action}`); }); // we're done. override action list this.actions = compactActionList; } }
the_stack
import { StudentExamDetailComponent } from 'app/exam/manage/student-exams/student-exam-detail.component'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { Course } from 'app/entities/course.model'; import { User } from 'app/core/user/user.model'; import { StudentExam } from 'app/entities/student-exam.model'; import { ArtemisDurationFromSecondsPipe } from 'app/shared/pipes/artemis-duration-from-seconds.pipe'; import { ArtemisDatePipe } from 'app/shared/pipes/artemis-date.pipe'; import { MockComponent, MockDirective, MockPipe, MockProvider } from 'ng-mocks'; import { StudentExamService } from 'app/exam/manage/student-exams/student-exam.service'; import { HttpResponse } from '@angular/common/http'; import { of } from 'rxjs'; import { ActivatedRoute, convertToParamMap, Params } from '@angular/router'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { NgxDatatableModule } from '@swimlane/ngx-datatable'; import { FontAwesomeTestingModule } from '@fortawesome/angular-fontawesome/testing'; import { TranslateModule } from '@ngx-translate/core'; import { RouterTestingModule } from '@angular/router/testing'; import { NgForm, NgModel, ReactiveFormsModule } from '@angular/forms'; import { Exercise } from 'app/entities/exercise.model'; import { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model'; import { ExerciseGroup } from 'app/entities/exercise-group.model'; import { Exam } from 'app/entities/exam.model'; import dayjs from 'dayjs/esm'; import { StudentParticipation } from 'app/entities/participation/student-participation.model'; import { ParticipationType } from 'app/entities/participation/participation.model'; import { Result } from 'app/entities/result.model'; import { ArtemisTranslatePipe } from 'app/shared/pipes/artemis-translate.pipe'; import { StudentExamDetailTableRowComponent } from 'app/exam/manage/student-exams/student-exam-detail-table-row/student-exam-detail-table-row.component'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { GradingSystemService } from 'app/grading-system/grading-system.service'; import { DataTableComponent } from 'app/shared/data-table/data-table.component'; import { AlertService } from 'app/core/util/alert.service'; import { TranslateDirective } from 'app/shared/language/translate.directive'; import { MockTranslateValuesDirective } from '../../../../helpers/mocks/directive/mock-translate-values.directive'; import { StudentExamWorkingTimeComponent } from 'app/exam/shared/student-exam-working-time.component'; describe('StudentExamDetailComponent', () => { let studentExamDetailComponentFixture: ComponentFixture<StudentExamDetailComponent>; let studentExamDetailComponent: StudentExamDetailComponent; let course: Course; let student: User; let studentExam: StudentExam; let studentExam2: StudentExam; let exercise: Exercise; let exam: Exam; let studentParticipation: StudentParticipation; let result: Result; let studentExamService: any; let gradingSystemService: GradingSystemService; beforeEach(() => { course = { id: 1 }; student = { internal: true, guidedTourSettings: [], name: 'name', login: 'login', email: 'email', visibleRegistrationNumber: 'visibleRegistrationNumber', }; exam = { course, id: 1, registeredUsers: [student], visibleDate: dayjs().add(120, 'seconds'), startDate: dayjs().add(200, 'seconds'), endDate: dayjs().add(7400, 'seconds'), }; result = { score: 40 }; studentParticipation = new StudentParticipation(ParticipationType.STUDENT); studentParticipation.results = [result]; exercise = new ModelingExercise(UMLDiagramType.ActivityDiagram, course, new ExerciseGroup()); exercise.maxPoints = 100; exercise.studentParticipations = [studentParticipation]; studentExam = { id: 1, workingTime: 7200, exam, user: student, exercises: [exercise], }; studentExam2 = { id: 2, workingTime: 3600, exam, user: student, submitted: true, submissionDate: dayjs(), exercises: [exercise], }; return TestBed.configureTestingModule({ imports: [ RouterTestingModule.withRoutes([]), NgbModule, NgxDatatableModule, FontAwesomeTestingModule, ReactiveFormsModule, TranslateModule.forRoot(), HttpClientTestingModule, ], declarations: [ StudentExamDetailComponent, MockComponent(DataTableComponent), MockComponent(StudentExamWorkingTimeComponent), MockDirective(NgForm), MockDirective(NgModel), MockPipe(ArtemisDurationFromSecondsPipe), MockPipe(ArtemisDatePipe), MockTranslateValuesDirective, MockPipe(ArtemisTranslatePipe), StudentExamDetailTableRowComponent, ], providers: [ MockProvider(StudentExamService, { updateWorkingTime: () => { return of( new HttpResponse({ body: studentExam, status: 200, }), ); }, toggleSubmittedState: () => { return of( new HttpResponse({ body: studentExam2, status: 200, }), ); }, }), MockPipe(ArtemisDurationFromSecondsPipe), MockProvider(AlertService), MockDirective(TranslateDirective), { provide: ActivatedRoute, useValue: { params: { subscribe: (fn: (value: Params) => void) => fn({ courseId: 1, }), }, data: { subscribe: (fn: (value: any) => void) => fn({ studentExam, }), }, snapshot: { paramMap: convertToParamMap({ courseId: '1', }), url: [], }, }, }, ], }) .compileComponents() .then(() => { studentExamDetailComponentFixture = TestBed.createComponent(StudentExamDetailComponent); studentExamDetailComponent = studentExamDetailComponentFixture.componentInstance; studentExamService = TestBed.inject(StudentExamService); gradingSystemService = TestBed.inject(GradingSystemService); }); }); afterEach(() => { jest.restoreAllMocks(); }); const expectDuration = (hours: number, minutes: number, seconds: number) => { expect(studentExamDetailComponent.workingTimeFormValues.hours).toBe(hours); expect(studentExamDetailComponent.workingTimeFormValues.minutes).toBe(minutes); expect(studentExamDetailComponent.workingTimeFormValues.seconds).toBe(seconds); }; it('initialize', () => { const gradeSpy = jest.spyOn(gradingSystemService, 'matchPercentageToGradeStepForExam'); studentExamDetailComponentFixture.detectChanges(); expect(gradeSpy).toHaveBeenCalledOnce(); expect(course.id).toBe(1); expect(studentExamDetailComponent.achievedTotalPoints).toBe(40); expectDuration(2, 0, 0); expect(studentExamDetailComponent.workingTimeFormValues.percent).toBe(0); }); it('should save working time', () => { const studentExamSpy = jest.spyOn(studentExamService, 'updateWorkingTime'); studentExamDetailComponentFixture.detectChanges(); studentExamDetailComponent.saveWorkingTime(); expect(studentExamSpy).toHaveBeenCalledOnce(); expect(studentExamDetailComponent.isSavingWorkingTime).toBeFalse(); expect(course.id).toBe(1); expect(studentExamDetailComponent.achievedTotalPoints).toBe(40); expect(studentExamDetailComponent.maxTotalPoints).toBe(100); }); it('should not increase points when save working time is called more than once', () => { const studentExamSpy = jest.spyOn(studentExamService, 'updateWorkingTime'); studentExamDetailComponentFixture.detectChanges(); studentExamDetailComponent.saveWorkingTime(); studentExamDetailComponent.saveWorkingTime(); studentExamDetailComponent.saveWorkingTime(); expect(studentExamSpy).toHaveBeenCalledTimes(3); expect(studentExamDetailComponent.isSavingWorkingTime).toBeFalse(); expect(course.id).toBe(1); expect(studentExamDetailComponent.achievedTotalPoints).toBe(40); expect(studentExamDetailComponent.maxTotalPoints).toBe(100); }); it('should disable the working time form while saving', () => { studentExamDetailComponent.isSavingWorkingTime = true; expect(studentExamDetailComponent.isFormDisabled()).toBeTrue(); }); it('should disable the working time form after a test run is submitted', () => { studentExamDetailComponent.isTestRun = true; studentExamDetailComponent.studentExam = studentExam; studentExamDetailComponent.studentExam.submitted = false; expect(studentExamDetailComponent.isFormDisabled()).toBeFalse(); studentExamDetailComponent.studentExam.submitted = true; expect(studentExamDetailComponent.isFormDisabled()).toBeTrue(); }); it('should disable the working time form after the exam is visible to a student', () => { studentExamDetailComponent.isTestRun = false; studentExamDetailComponent.studentExam = studentExam; studentExamDetailComponent.studentExam.exam!.visibleDate = dayjs().add(1, 'hour'); expect(studentExamDetailComponent.isFormDisabled()).toBeFalse(); studentExamDetailComponent.studentExam.exam!.visibleDate = dayjs().subtract(1, 'hour'); expect(studentExamDetailComponent.isFormDisabled()).toBeTrue(); }); it('should disable the working time form if there is no exam', () => { studentExamDetailComponent.isTestRun = false; studentExamDetailComponent.studentExam = studentExam; studentExamDetailComponent.studentExam.exam = undefined; expect(studentExamDetailComponent.isFormDisabled()).toBeTrue(); }); it('should get examIsOver', () => { studentExamDetailComponent.studentExam = studentExam; studentExam.exam!.gracePeriod = 100; expect(studentExamDetailComponent.examIsOver()).toBeFalse(); studentExam.exam!.endDate = dayjs().add(-20, 'seconds'); expect(studentExamDetailComponent.examIsOver()).toBeFalse(); studentExam.exam!.endDate = dayjs().add(-200, 'seconds'); expect(studentExamDetailComponent.examIsOver()).toBeTrue(); studentExam.exam = undefined; expect(studentExamDetailComponent.examIsOver()).toBeFalse(); }); it('should toggle to unsubmitted', () => { const toggleSubmittedStateSpy = jest.spyOn(studentExamService, 'toggleSubmittedState'); studentExamDetailComponentFixture.detectChanges(); expect(studentExamDetailComponent.studentExam.submitted).toBe(undefined); expect(studentExamDetailComponent.studentExam.submissionDate).toBe(undefined); studentExamDetailComponent.toggle(); expect(toggleSubmittedStateSpy).toHaveBeenCalledOnce(); expect(studentExamDetailComponent.studentExam.submitted).toBeTrue(); // the toggle uses the current time as submission date, // therefore no useful assertion about a concrete value is possible here expect(studentExamDetailComponent.studentExam.submissionDate).not.toBe(undefined); }); it('should update the percent difference when the absolute working time changes', () => { studentExamDetailComponent.ngOnInit(); studentExamDetailComponent.workingTimeFormValues.hours = 4; studentExamDetailComponent.updateWorkingTimePercent(); expect(studentExamDetailComponent.workingTimeFormValues.percent).toBe(100); studentExamDetailComponent.workingTimeFormValues.hours = 3; studentExamDetailComponent.updateWorkingTimePercent(); expect(studentExamDetailComponent.workingTimeFormValues.percent).toBe(50); studentExamDetailComponent.workingTimeFormValues.hours = 0; studentExamDetailComponent.updateWorkingTimePercent(); expect(studentExamDetailComponent.workingTimeFormValues.percent).toBe(-100); // small change, not a full percent studentExamDetailComponent.workingTimeFormValues.hours = 2; studentExamDetailComponent.workingTimeFormValues.seconds = 12; studentExamDetailComponent.updateWorkingTimePercent(); expect(studentExamDetailComponent.workingTimeFormValues.percent).toBe(0.17); }); it('should update the absolute working time when changing the percent difference', () => { studentExamDetailComponent.ngOnInit(); studentExamDetailComponent.workingTimeFormValues.percent = 26; studentExamDetailComponent.updateWorkingTimeDuration(); expectDuration(2, 31, 12); studentExamDetailComponent.workingTimeFormValues.percent = -100; studentExamDetailComponent.updateWorkingTimeDuration(); expectDuration(0, 0, 0); }); });
the_stack
import * as zrUtil from 'zrender/src/core/util'; import SymbolDraw, { ListForSymbolDraw } from '../helper/SymbolDraw'; import LineDraw from '../helper/LineDraw'; import RoamController, { RoamControllerHost } from '../../component/helper/RoamController'; import * as roamHelper from '../../component/helper/roamHelper'; import {onIrrelevantElement} from '../../component/helper/cursorHelper'; import * as graphic from '../../util/graphic'; import adjustEdge from './adjustEdge'; import {getNodeGlobalScale} from './graphHelper'; import ChartView from '../../view/Chart'; import GlobalModel from '../../model/Global'; import ExtensionAPI from '../../core/ExtensionAPI'; import GraphSeriesModel, { GraphNodeItemOption, GraphEdgeItemOption } from './GraphSeries'; import { CoordinateSystem } from '../../coord/CoordinateSystem'; import View from '../../coord/View'; import Symbol from '../helper/Symbol'; import SeriesData from '../../data/SeriesData'; import Line from '../helper/Line'; import { getECData } from '../../util/innerStore'; function isViewCoordSys(coordSys: CoordinateSystem): coordSys is View { return coordSys.type === 'view'; } class GraphView extends ChartView { static readonly type = 'graph'; readonly type = GraphView.type; private _symbolDraw: SymbolDraw; private _lineDraw: LineDraw; private _controller: RoamController; private _controllerHost: RoamControllerHost; private _firstRender: boolean; private _model: GraphSeriesModel; private _layoutTimeout: number; private _layouting: boolean; init(ecModel: GlobalModel, api: ExtensionAPI) { const symbolDraw = new SymbolDraw(); const lineDraw = new LineDraw(); const group = this.group; this._controller = new RoamController(api.getZr()); this._controllerHost = { target: group } as RoamControllerHost; group.add(symbolDraw.group); group.add(lineDraw.group); this._symbolDraw = symbolDraw; this._lineDraw = lineDraw; this._firstRender = true; } render(seriesModel: GraphSeriesModel, ecModel: GlobalModel, api: ExtensionAPI) { const coordSys = seriesModel.coordinateSystem; this._model = seriesModel; const symbolDraw = this._symbolDraw; const lineDraw = this._lineDraw; const group = this.group; if (isViewCoordSys(coordSys)) { const groupNewProp = { x: coordSys.x, y: coordSys.y, scaleX: coordSys.scaleX, scaleY: coordSys.scaleY }; if (this._firstRender) { group.attr(groupNewProp); } else { graphic.updateProps(group, groupNewProp, seriesModel); } } // Fix edge contact point with node adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel)); const data = seriesModel.getData(); symbolDraw.updateData(data as ListForSymbolDraw); const edgeData = seriesModel.getEdgeData(); // TODO: TYPE lineDraw.updateData(edgeData as SeriesData); this._updateNodeAndLinkScale(); this._updateController(seriesModel, ecModel, api); clearTimeout(this._layoutTimeout); const forceLayout = seriesModel.forceLayout; const layoutAnimation = seriesModel.get(['force', 'layoutAnimation']); if (forceLayout) { this._startForceLayoutIteration(forceLayout, layoutAnimation); } data.graph.eachNode((node) => { const idx = node.dataIndex; const el = node.getGraphicEl() as Symbol; const itemModel = node.getModel<GraphNodeItemOption>(); // Update draggable el.off('drag').off('dragend'); const draggable = itemModel.get('draggable'); if (draggable) { el.on('drag', () => { if (forceLayout) { forceLayout.warmUp(); !this._layouting && this._startForceLayoutIteration(forceLayout, layoutAnimation); forceLayout.setFixed(idx); // Write position back to layout data.setItemLayout(idx, [el.x, el.y]); } }).on('dragend', () => { if (forceLayout) { forceLayout.setUnfixed(idx); } }); } el.setDraggable(draggable && !!forceLayout); const focus = itemModel.get(['emphasis', 'focus']); if (focus === 'adjacency') { getECData(el).focus = node.getAdjacentDataIndices(); } }); data.graph.eachEdge(function (edge) { const el = edge.getGraphicEl() as Line; const focus = edge.getModel<GraphEdgeItemOption>().get(['emphasis', 'focus']); if (focus === 'adjacency') { getECData(el).focus = { edge: [edge.dataIndex], node: [edge.node1.dataIndex, edge.node2.dataIndex] }; } }); const circularRotateLabel = seriesModel.get('layout') === 'circular' && seriesModel.get(['circular', 'rotateLabel']); const cx = data.getLayout('cx'); const cy = data.getLayout('cy'); data.eachItemGraphicEl(function (el: Symbol, idx) { const itemModel = data.getItemModel<GraphNodeItemOption>(idx); let labelRotate = itemModel.get(['label', 'rotate']) || 0; const symbolPath = el.getSymbolPath(); if (circularRotateLabel) { const pos = data.getItemLayout(idx); let rad = Math.atan2(pos[1] - cy, pos[0] - cx); if (rad < 0) { rad = Math.PI * 2 + rad; } const isLeft = pos[0] < cx; if (isLeft) { rad = rad - Math.PI; } const textPosition = isLeft ? 'left' as const : 'right' as const; symbolPath.setTextConfig({ rotation: -rad, position: textPosition, origin: 'center' }); const emphasisState = symbolPath.ensureState('emphasis'); zrUtil.extend(emphasisState.textConfig || (emphasisState.textConfig = {}), { position: textPosition }); } else { symbolPath.setTextConfig({ rotation: labelRotate *= Math.PI / 180 }); } }); this._firstRender = false; } dispose() { this._controller && this._controller.dispose(); this._controllerHost = null; } _startForceLayoutIteration( forceLayout: GraphSeriesModel['forceLayout'], layoutAnimation?: boolean ) { const self = this; (function step() { forceLayout.step(function (stopped) { self.updateLayout(self._model); (self._layouting = !stopped) && ( layoutAnimation ? (self._layoutTimeout = setTimeout(step, 16) as any) : step() ); }); })(); } _updateController( seriesModel: GraphSeriesModel, ecModel: GlobalModel, api: ExtensionAPI ) { const controller = this._controller; const controllerHost = this._controllerHost; const group = this.group; controller.setPointerChecker(function (e, x, y) { const rect = group.getBoundingRect(); rect.applyTransform(group.transform); return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel); }); if (!isViewCoordSys(seriesModel.coordinateSystem)) { controller.disable(); return; } controller.enable(seriesModel.get('roam')); controllerHost.zoomLimit = seriesModel.get('scaleLimit'); controllerHost.zoom = seriesModel.coordinateSystem.getZoom(); controller .off('pan') .off('zoom') .on('pan', (e) => { roamHelper.updateViewOnPan(controllerHost, e.dx, e.dy); api.dispatchAction({ seriesId: seriesModel.id, type: 'graphRoam', dx: e.dx, dy: e.dy }); }) .on('zoom', (e) => { roamHelper.updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY); api.dispatchAction({ seriesId: seriesModel.id, type: 'graphRoam', zoom: e.scale, originX: e.originX, originY: e.originY }); this._updateNodeAndLinkScale(); adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel)); this._lineDraw.updateLayout(); // Only update label layout on zoom api.updateLabelLayout(); }); } _updateNodeAndLinkScale() { const seriesModel = this._model; const data = seriesModel.getData(); const nodeScale = getNodeGlobalScale(seriesModel); data.eachItemGraphicEl(function (el: Symbol, idx) { el.setSymbolScale(nodeScale); }); } updateLayout(seriesModel: GraphSeriesModel) { adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel)); this._symbolDraw.updateLayout(); this._lineDraw.updateLayout(); } remove(ecModel: GlobalModel, api: ExtensionAPI) { this._symbolDraw && this._symbolDraw.remove(); this._lineDraw && this._lineDraw.remove(); } } export default GraphView;
the_stack
import { Component, OnInit } from '@angular/core'; import { Location } from '@angular/common'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { CardConfig } from 'patternfly-ng/card/basic-card/card-config'; import { NotificationService } from 'patternfly-ng/notification/notification-service/notification.service'; import { NotificationType } from 'patternfly-ng/notification/notification-type'; import { AuthService } from '../auth/auth.service'; import { Email } from '../resources/emails/email'; import { EmailService } from '../resources/emails/email.service'; import { PreferencesService } from '../resources/preferences/preferences.service'; import { UserPreferences } from '../resources/preferences/user-preferences'; import { UserService } from '../resources/users/user.service'; @Component({ selector: 'app-preferences', templateUrl: './preferences.component.html', styleUrls: ['./preferences.component.less'], }) export class PreferencesComponent implements OnInit { // Used to track which component is being loaded componentName = 'PreferencesComponent'; constructor( private notificationService: NotificationService, private authService: AuthService, private preferencesService: PreferencesService, private userService: UserService, private router: Router, private emailService: EmailService, private activatedRoute: ActivatedRoute, private location: Location, ) {} emailCard: CardConfig; notificationsCard: CardConfig; apiKeyCard: CardConfig; authorsFollowedCard: CardConfig; collectionsFollowedCard: CardConfig; rolesFollowedCard: CardConfig; emails: Email[]; notificationSettings: any; apiKey: string; userId: number; preferences: UserPreferences; followed: any; ngOnInit() { this.authService.me().subscribe(me => { if (!me.authenticated) { this.router.navigate(['/', 'login'], { queryParams: { next: '/me/preferences' }, }); } else { this.userId = me.id; this.getEmails(); this.getPreferences(); } }); this.emailCard = { title: 'Email Settings', } as CardConfig; this.notificationsCard = { title: 'Notification Settings', } as CardConfig; this.apiKeyCard = { title: 'API Key', } as CardConfig; this.authorsFollowedCard = { title: 'Authors Followed', } as CardConfig; this.rolesFollowedCard = { title: 'Roles Followed', } as CardConfig; this.collectionsFollowedCard = { title: 'Collections Followed', } as CardConfig; } private getPreferences() { this.preferencesService.get().subscribe(response => { this.preferences = response; // Copy the follower information into a new variable so that we can // remember what someone was following in case the accidentally // unfollow and want to re follow this.followed = JSON.parse( JSON.stringify(this.preferences.summary_fields), ); for (const x of this.followed.repositories_followed) { x['hasFollowed'] = true; x['iconClass'] = 'fa fa-user-times'; } for (const x of this.followed.collections_followed) { x['hasFollowed'] = true; x['iconClass'] = 'fa fa-user-times'; } for (const x of this.followed.namespaces_followed) { x['hasFollowed'] = true; x['iconClass'] = 'fa fa-user-times'; } this.notificationSettings = [ { key: 'notify_survey', description: 'Someone submits a new survey for one of your repos or collections', }, { key: 'notify_content_release', description: 'There is a new release of a repo or collection you follow', }, { key: 'notify_author_release', description: 'An author you follow releases a new repo or collection', }, { key: 'notify_import_fail', description: 'One of your imports fails', }, { key: 'notify_import_success', description: 'One of your imports succeeds', }, { key: 'notify_galaxy_announce', description: 'There is an anouncement from the galaxy team', }, ]; }); } private getEmails() { this.emailService.query({ user_id: this.userId }).subscribe(emails => { this.emails = emails; this.activatedRoute.queryParams.subscribe((params: Params) => { if (params.verify) { this.checkVerification(params); } }); }); } private checkVerification(params: Params) { this.emailService.verifyEmail(params.verify).subscribe(result => { const updateEmail = this.emails.find(obj => { return obj.id === result.email_address; }); updateEmail.verified = result.verified; if (result.verified) { this.notificationService.message( NotificationType.SUCCESS, 'Verification', `${updateEmail.email} is now verified.`, false, null, null, ); } // remove code from URL this.location.replaceState(this.location.path().split('?')[0], ''); }); } private deleteEmail(email: Email) { this.emailService.deleteEmail(email).subscribe(response => { if (response === null) { const index = this.emails.findIndex(i => i.id === email.id); this.emails.splice(index, 1); } }); } followToggle(type: string, objIndex) { let index = this.preferences[type].findIndex(x => { return x === this.followed[type][objIndex].id; }); this.followed[type][objIndex].iconClass = 'fa fa-spin fa-spinner'; if (index > -1) { this.preferences[type].splice(index, 1); } else { this.preferences[type].push(this.followed[type][objIndex].id); } this.preferencesService.save(this.preferences).subscribe(result => { if (result) { this.preferences = result; index = this.preferences[type].findIndex(x => { return x === this.followed[type][objIndex].id; }); if (index > -1) { // We are following the object this.followed[type][objIndex].hasFollowed = true; this.followed[type][objIndex].iconClass = 'fa fa-user-times'; } else { // Not following the object this.followed[type][objIndex].hasFollowed = false; this.followed[type][objIndex].iconClass = 'fa fa-user-plus'; } } }); } setPrimary(email: Email) { let currentPrimary = -1; let newPrimary = -1; currentPrimary = this.emails.findIndex(i => i.primary === true); newPrimary = this.emails.findIndex(i => i.id === email.id); const newCopy = JSON.parse(JSON.stringify(this.emails[newPrimary])); newCopy.primary = true; this.emailService.save(newCopy).subscribe(result => { if (result) { this.emails[newPrimary] = result; } }); if (currentPrimary !== -1) { const currentCopy = JSON.parse( JSON.stringify(this.emails[currentPrimary]), ); currentCopy.primary = false; this.emailService.save(currentCopy).subscribe(result => { if (result) { this.emails[currentPrimary] = result; } }); } } verifyEmail(email: Email) { this.emailService.sendVerification(email).subscribe(result => { if (result) { this.notificationService.message( NotificationType.SUCCESS, 'Sending Verification', `We've sent your verification code to to ${email.email}`, false, null, null, ); } }); } showApiKey() { this.userService.getToken(this.userId).subscribe(token => { return (this.apiKey = token); }); } resetApiKey() { if ( confirm( 'Resetting your key will remove access to all applications that might rely on it. Do you wish to continue?', ) ) { this.userService.resetToken(this.userId).subscribe(token => { return (this.apiKey = token); }); } } addNewEmail() { const email = { email: '', verified: false, primary: false, summary_fields: { new: true }, } as Email; this.emails.push(email); } saveEmail(email) { email.user = this.userId; this.emailService.save(email).subscribe(response => { if (response) { const i = this.emails.findIndex( val => val.email === email.email, ); this.emails[i] = response; this.verifyEmail(response); } }); } handleEmailAction($event) { if ($event.id === 'edit') { $event.email.summary_fields.new = true; } else if ($event.id === 'delete') { this.deleteEmail($event.email); } } cancelAddEmail(index: number) { this.emails.splice(index, 1); } updateNotifications() { // Slow the update to prevent race condition with ngModel; // otherwise, the saved value won't match the UI value. setTimeout(() => { this.preferencesService.save(this.preferences).subscribe(); }, 500); } }
the_stack
import CLASS from './class' import { ChartInternal } from './core' import { isFunction } from './util' ChartInternal.prototype.initBrush = function(scale) { var $$ = this, d3 = $$.d3 // TODO: dynamically change brushY/brushX according to axis_rotated. $$.brush = ($$.config.axis_rotated ? d3.brushY() : d3.brushX()) .on('brush', function() { var event = d3.event.sourceEvent if (event && event.type === 'zoom') { return } $$.redrawForBrush() }) .on('end', function() { var event = d3.event.sourceEvent if (event && event.type === 'zoom') { return } if ($$.brush.empty() && event && event.type !== 'end') { $$.brush.clear() } }) $$.brush.updateExtent = function() { var range = this.scale.range(), extent if ($$.config.axis_rotated) { extent = [ [0, range[0]], [$$.width2, range[1]] ] } else { extent = [ [range[0], 0], [range[1], $$.height2] ] } this.extent(extent) return this } $$.brush.updateScale = function(scale) { this.scale = scale return this } $$.brush.update = function(scale) { this.updateScale(scale || $$.subX).updateExtent() $$.context.select('.' + CLASS.brush).call(this) } $$.brush.clear = function() { $$.context.select('.' + CLASS.brush).call($$.brush.move, null) } $$.brush.selection = function() { return d3.brushSelection($$.context.select('.' + CLASS.brush).node()) } $$.brush.selectionAsValue = function(selectionAsValue, withTransition) { var selection, brush if (selectionAsValue) { if ($$.context) { selection = [ this.scale(selectionAsValue[0]), this.scale(selectionAsValue[1]) ] brush = $$.context.select('.' + CLASS.brush) if (withTransition) { brush = brush.transition() } $$.brush.move(brush, selection) } return [] } selection = $$.brush.selection() || [0, 0] return [this.scale.invert(selection[0]), this.scale.invert(selection[1])] } $$.brush.empty = function() { var selection = $$.brush.selection() return !selection || selection[0] === selection[1] } return $$.brush.updateScale(scale) } ChartInternal.prototype.initSubchart = function() { var $$ = this, config = $$.config, context = ($$.context = $$.svg .append('g') .attr('transform', $$.getTranslate('context'))) // set style context.style('visibility', 'visible') // Define g for chart area context .append('g') .attr('clip-path', $$.clipPathForSubchart) .attr('class', CLASS.chart) // Define g for bar chart area context .select('.' + CLASS.chart) .append('g') .attr('class', CLASS.chartBars) // Define g for line chart area context .select('.' + CLASS.chart) .append('g') .attr('class', CLASS.chartLines) // Add extent rect for Brush context .append('g') .attr('clip-path', $$.clipPath) .attr('class', CLASS.brush) // ATTENTION: This must be called AFTER chart added // Add Axis $$.axes.subx = context .append('g') .attr('class', CLASS.axisX) .attr('transform', $$.getTranslate('subx')) .attr('clip-path', config.axis_rotated ? '' : $$.clipPathForXAxis) .style('visibility', config.subchart_axis_x_show ? 'visible' : 'hidden'); } ChartInternal.prototype.initSubchartBrush = function() { var $$ = this // Add extent rect for Brush $$.initBrush($$.subX).updateExtent() $$.context.select('.' + CLASS.brush).call($$.brush) } ChartInternal.prototype.updateTargetsForSubchart = function(targets) { var $$ = this, context = $$.context, config = $$.config, contextLineEnter, contextLine, contextBarEnter, contextBar, classChartBar = $$.classChartBar.bind($$), classBars = $$.classBars.bind($$), classChartLine = $$.classChartLine.bind($$), classLines = $$.classLines.bind($$), classAreas = $$.classAreas.bind($$) //-- Bar --// contextBar = context .select('.' + CLASS.chartBars) .selectAll('.' + CLASS.chartBar) .data(targets) contextBarEnter = contextBar .enter() .append('g') .style('opacity', 0) contextBarEnter.merge(contextBar).attr('class', classChartBar) // Bars for each data contextBarEnter.append('g').attr('class', classBars) //-- Line --// contextLine = context .select('.' + CLASS.chartLines) .selectAll('.' + CLASS.chartLine) .data(targets) contextLineEnter = contextLine .enter() .append('g') .style('opacity', 0) contextLineEnter.merge(contextLine).attr('class', classChartLine) // Lines for each data contextLineEnter.append('g').attr('class', classLines) // Area contextLineEnter.append('g').attr('class', classAreas) //-- Brush --// context .selectAll('.' + CLASS.brush + ' rect') .attr( config.axis_rotated ? 'width' : 'height', config.axis_rotated ? $$.width2 : $$.height2 ) } ChartInternal.prototype.updateBarForSubchart = function(durationForExit) { var $$ = this var contextBar = $$.context .selectAll('.' + CLASS.bars) .selectAll('.' + CLASS.bar) .data($$.barData.bind($$)) var contextBarEnter = contextBar .enter() .append('path') .attr('class', $$.classBar.bind($$)) .style('stroke', 'none') .style('fill', $$.color) contextBar .exit() .transition() .duration(durationForExit) .style('opacity', 0) .remove() $$.contextBar = contextBarEnter .merge(contextBar) .style('opacity', $$.initialOpacity.bind($$)) } ChartInternal.prototype.redrawBarForSubchart = function( drawBarOnSub, withTransition, duration ) { ;(withTransition ? this.contextBar.transition(Math.random().toString()).duration(duration) : this.contextBar ) .attr('d', drawBarOnSub) .style('opacity', 1) } ChartInternal.prototype.updateLineForSubchart = function(durationForExit) { var $$ = this var contextLine = $$.context .selectAll('.' + CLASS.lines) .selectAll('.' + CLASS.line) .data($$.lineData.bind($$)) var contextLineEnter = contextLine .enter() .append('path') .attr('class', $$.classLine.bind($$)) .style('stroke', $$.color) contextLine .exit() .transition() .duration(durationForExit) .style('opacity', 0) .remove() $$.contextLine = contextLineEnter .merge(contextLine) .style('opacity', $$.initialOpacity.bind($$)) } ChartInternal.prototype.redrawLineForSubchart = function( drawLineOnSub, withTransition, duration ) { ;(withTransition ? this.contextLine.transition(Math.random().toString()).duration(duration) : this.contextLine ) .attr('d', drawLineOnSub) .style('opacity', 1) } ChartInternal.prototype.updateAreaForSubchart = function(durationForExit) { var $$ = this, d3 = $$.d3 var contextArea = $$.context .selectAll('.' + CLASS.areas) .selectAll('.' + CLASS.area) .data($$.lineData.bind($$)) var contextAreaEnter = contextArea .enter() .append('path') .attr('class', $$.classArea.bind($$)) .style('fill', $$.color) .style('opacity', function() { $$.orgAreaOpacity = +d3.select(this).style('opacity') return 0 }) contextArea .exit() .transition() .duration(durationForExit) .style('opacity', 0) .remove() $$.contextArea = contextAreaEnter.merge(contextArea).style('opacity', 0) } ChartInternal.prototype.redrawAreaForSubchart = function( drawAreaOnSub, withTransition, duration ) { ;(withTransition ? this.contextArea.transition(Math.random().toString()).duration(duration) : this.contextArea ) .attr('d', drawAreaOnSub) .style('fill', this.color) .style('opacity', this.orgAreaOpacity) } ChartInternal.prototype.redrawSubchart = function( withSubchart, transitions, duration, durationForExit, areaIndices, barIndices, lineIndices ) { var $$ = this, d3 = $$.d3, drawAreaOnSub, drawBarOnSub, drawLineOnSub // reflect main chart to extent on subchart if zoomed if (d3.event && d3.event.type === 'zoom') { $$.brush.selectionAsValue($$.x.orgDomain()) } // update subchart elements if needed if (withSubchart) { // extent rect if (!$$.brush.empty()) { $$.brush.selectionAsValue($$.x.orgDomain()) } // setup drawer - MEMO: this must be called after axis updated drawAreaOnSub = $$.generateDrawArea(areaIndices, true) drawBarOnSub = $$.generateDrawBar(barIndices, true) drawLineOnSub = $$.generateDrawLine(lineIndices, true) $$.updateBarForSubchart(duration) $$.updateLineForSubchart(duration) $$.updateAreaForSubchart(duration) $$.redrawBarForSubchart(drawBarOnSub, duration, duration) $$.redrawLineForSubchart(drawLineOnSub, duration, duration) $$.redrawAreaForSubchart(drawAreaOnSub, duration, duration) } } ChartInternal.prototype.redrawForBrush = function() { var $$ = this, x = $$.x, d3 = $$.d3, s $$.redraw({ withTransition: false, withY: $$.config.zoom_rescale, withSubchart: false, withUpdateXDomain: true, withEventRect: false, withDimension: false }) // update zoom transation binded to event rect s = d3.event.selection || $$.brush.scale.range() $$.main .select('.' + CLASS.eventRect) .call( $$.zoom.transform, d3.zoomIdentity.scale($$.width / (s[1] - s[0])).translate(-s[0], 0) ) $$.config.subchart_onbrush.call($$.api, x.orgDomain()) } ChartInternal.prototype.transformContext = function( withTransition, transitions ) { var $$ = this, subXAxis if (transitions && transitions.axisSubX) { subXAxis = transitions.axisSubX } else { subXAxis = $$.context.select('.' + CLASS.axisX) if (withTransition) { subXAxis = subXAxis.transition() } } $$.context.attr('transform', $$.getTranslate('context')) subXAxis.attr('transform', $$.getTranslate('subx')) } ChartInternal.prototype.getDefaultSelection = function() { var $$ = this, config = $$.config, selection = isFunction(config.axis_x_selection) ? config.axis_x_selection($$.getXDomain($$.data.targets)) : config.axis_x_selection if ($$.isTimeSeries()) { selection = [$$.parseDate(selection[0]), $$.parseDate(selection[1])] } return selection } ChartInternal.prototype.removeSubchart = function() { const $$ = this $$.brush = null $$.context.remove() $$.context = null }
the_stack
import * as Recorder from 'opus-recorder'; import encoderPath from 'opus-recorder/dist/encoderWorker.min.js'; import { MatrixClient } from "matrix-js-sdk/src/client"; import { SimpleObservable } from "matrix-widget-api"; import EventEmitter from "events"; import { IEncryptedFile } from "matrix-js-sdk/src/@types/event"; import { logger } from "matrix-js-sdk/src/logger"; import MediaDeviceHandler from "../MediaDeviceHandler"; import { IDestroyable } from "../utils/IDestroyable"; import { Singleflight } from "../utils/Singleflight"; import { PayloadEvent, WORKLET_NAME } from "./consts"; import { UPDATE_EVENT } from "../stores/AsyncStore"; import { Playback } from "./Playback"; import { createAudioContext } from "./compat"; import { uploadFile } from "../ContentMessages"; import { FixedRollingArray } from "../utils/FixedRollingArray"; import { clamp } from "../utils/numbers"; import mxRecorderWorkletPath from "./RecorderWorklet"; const CHANNELS = 1; // stereo isn't important export const SAMPLE_RATE = 48000; // 48khz is what WebRTC uses. 12khz is where we lose quality. const BITRATE = 24000; // 24kbps is pretty high quality for our use case in opus. const TARGET_MAX_LENGTH = 120; // 2 minutes in seconds. Somewhat arbitrary, though longer == larger files. const TARGET_WARN_TIME_LEFT = 10; // 10 seconds, also somewhat arbitrary. export const RECORDING_PLAYBACK_SAMPLES = 44; export interface IRecordingUpdate { waveform: number[]; // floating points between 0 (low) and 1 (high). timeSeconds: number; // float } export enum RecordingState { Started = "started", EndingSoon = "ending_soon", // emits an object with a single numerical value: secondsLeft Ended = "ended", Uploading = "uploading", Uploaded = "uploaded", } export interface IUpload { mxc?: string; // for unencrypted uploads encrypted?: IEncryptedFile; } export class VoiceRecording extends EventEmitter implements IDestroyable { private recorder: Recorder; private recorderContext: AudioContext; private recorderSource: MediaStreamAudioSourceNode; private recorderStream: MediaStream; private recorderWorklet: AudioWorkletNode; private recorderProcessor: ScriptProcessorNode; private buffer = new Uint8Array(0); // use this.audioBuffer to access private lastUpload: IUpload; private recording = false; private observable: SimpleObservable<IRecordingUpdate>; private amplitudes: number[] = []; // at each second mark, generated private playback: Playback; private liveWaveform = new FixedRollingArray(RECORDING_PLAYBACK_SAMPLES, 0); public constructor(private client: MatrixClient) { super(); } public get contentType(): string { return "audio/ogg"; } public get contentLength(): number { return this.buffer.length; } public get durationSeconds(): number { if (!this.recorder) throw new Error("Duration not available without a recording"); return this.recorderContext.currentTime; } public get isRecording(): boolean { return this.recording; } public emit(event: string, ...args: any[]): boolean { super.emit(event, ...args); super.emit(UPDATE_EVENT, event, ...args); return true; // we don't ever care if the event had listeners, so just return "yes" } private async makeRecorder() { try { this.recorderStream = await navigator.mediaDevices.getUserMedia({ audio: { channelCount: CHANNELS, noiseSuppression: true, // browsers ignore constraints they can't honour deviceId: MediaDeviceHandler.getAudioInput(), }, }); this.recorderContext = createAudioContext({ // latencyHint: "interactive", // we don't want a latency hint (this causes data smoothing) }); this.recorderSource = this.recorderContext.createMediaStreamSource(this.recorderStream); // Connect our inputs and outputs if (this.recorderContext.audioWorklet) { // Set up our worklet. We use this for timing information and waveform analysis: the // web audio API prefers this be done async to avoid holding the main thread with math. await this.recorderContext.audioWorklet.addModule(mxRecorderWorkletPath); this.recorderWorklet = new AudioWorkletNode(this.recorderContext, WORKLET_NAME); this.recorderSource.connect(this.recorderWorklet); this.recorderWorklet.connect(this.recorderContext.destination); // Dev note: we can't use `addEventListener` for some reason. It just doesn't work. this.recorderWorklet.port.onmessage = (ev) => { switch (ev.data['ev']) { case PayloadEvent.Timekeep: this.processAudioUpdate(ev.data['timeSeconds']); break; case PayloadEvent.AmplitudeMark: // Sanity check to make sure we're adding about one sample per second if (ev.data['forIndex'] === this.amplitudes.length) { this.amplitudes.push(ev.data['amplitude']); this.liveWaveform.pushValue(ev.data['amplitude']); } break; } }; } else { // Safari fallback: use a processor node instead, buffered to 1024 bytes of data // like the worklet is. this.recorderProcessor = this.recorderContext.createScriptProcessor(1024, CHANNELS, CHANNELS); this.recorderSource.connect(this.recorderProcessor); this.recorderProcessor.connect(this.recorderContext.destination); this.recorderProcessor.addEventListener("audioprocess", this.onAudioProcess); } this.recorder = new Recorder({ encoderPath, // magic from webpack encoderSampleRate: SAMPLE_RATE, encoderApplication: 2048, // voice (default is "audio") streamPages: true, // this speeds up the encoding process by using CPU over time encoderFrameSize: 20, // ms, arbitrary frame size we send to the encoder numberOfChannels: CHANNELS, sourceNode: this.recorderSource, encoderBitRate: BITRATE, // We use low values for the following to ease CPU usage - the resulting waveform // is indistinguishable for a voice message. Note that the underlying library will // pick defaults which prefer the highest possible quality, CPU be damned. encoderComplexity: 3, // 0-10, 10 is slow and high quality. resampleQuality: 3, // 0-10, 10 is slow and high quality }); this.recorder.ondataavailable = (a: ArrayBuffer) => { const buf = new Uint8Array(a); const newBuf = new Uint8Array(this.buffer.length + buf.length); newBuf.set(this.buffer, 0); newBuf.set(buf, this.buffer.length); this.buffer = newBuf; }; } catch (e) { logger.error("Error starting recording: ", e); if (e instanceof DOMException) { // Unhelpful DOMExceptions are common - parse them sanely logger.error(`${e.name} (${e.code}): ${e.message}`); } // Clean up as best as possible if (this.recorderStream) this.recorderStream.getTracks().forEach(t => t.stop()); if (this.recorderSource) this.recorderSource.disconnect(); if (this.recorder) this.recorder.close(); if (this.recorderContext) { // noinspection ES6MissingAwait - not important that we wait this.recorderContext.close(); } throw e; // rethrow so upstream can handle it } } private get audioBuffer(): Uint8Array { // We need a clone of the buffer to avoid accidentally changing the position // on the real thing. return this.buffer.slice(0); } public get liveData(): SimpleObservable<IRecordingUpdate> { if (!this.recording) throw new Error("No observable when not recording"); return this.observable; } public get isSupported(): boolean { return !!Recorder.isRecordingSupported(); } public get hasRecording(): boolean { return this.buffer.length > 0; } private onAudioProcess = (ev: AudioProcessingEvent) => { this.processAudioUpdate(ev.playbackTime); // We skip the functionality of the worklet regarding waveform calculations: we // should get that information pretty quick during the playback info. }; private processAudioUpdate = (timeSeconds: number) => { if (!this.recording) return; this.observable.update({ waveform: this.liveWaveform.value.map(v => clamp(v, 0, 1)), timeSeconds: timeSeconds, }); // Now that we've updated the data/waveform, let's do a time check. We don't want to // go horribly over the limit. We also emit a warning state if needed. // // We use the recorder's perspective of time to make sure we don't cut off the last // frame of audio, otherwise we end up with a 1:59 clip (119.68 seconds). This extra // safety can allow us to overshoot the target a bit, but at least when we say 2min // maximum we actually mean it. // // In testing, recorder time and worker time lag by about 400ms, which is roughly the // time needed to encode a sample/frame. // // Ref for recorderSeconds: https://github.com/chris-rudmin/opus-recorder#instance-fields const recorderSeconds = this.recorder.encodedSamplePosition / 48000; const secondsLeft = TARGET_MAX_LENGTH - recorderSeconds; if (secondsLeft < 0) { // go over to make sure we definitely capture that last frame // noinspection JSIgnoredPromiseFromCall - we aren't concerned with it overlapping this.stop(); } else if (secondsLeft <= TARGET_WARN_TIME_LEFT) { Singleflight.for(this, "ending_soon").do(() => { this.emit(RecordingState.EndingSoon, { secondsLeft }); return Singleflight.Void; }); } }; public async start(): Promise<void> { if (this.lastUpload || this.hasRecording) { throw new Error("Recording already prepared"); } if (this.recording) { throw new Error("Recording already in progress"); } if (this.observable) { this.observable.close(); } this.observable = new SimpleObservable<IRecordingUpdate>(); await this.makeRecorder(); await this.recorder.start(); this.recording = true; this.emit(RecordingState.Started); } public async stop(): Promise<Uint8Array> { return Singleflight.for(this, "stop").do(async () => { if (!this.recording) { throw new Error("No recording to stop"); } // Disconnect the source early to start shutting down resources await this.recorder.stop(); // stop first to flush the last frame this.recorderSource.disconnect(); if (this.recorderWorklet) this.recorderWorklet.disconnect(); if (this.recorderProcessor) { this.recorderProcessor.disconnect(); this.recorderProcessor.removeEventListener("audioprocess", this.onAudioProcess); } // close the context after the recorder so the recorder doesn't try to // connect anything to the context (this would generate a warning) await this.recorderContext.close(); // Now stop all the media tracks so we can release them back to the user/OS this.recorderStream.getTracks().forEach(t => t.stop()); // Finally do our post-processing and clean up this.recording = false; await this.recorder.close(); this.emit(RecordingState.Ended); return this.audioBuffer; }); } /** * Gets a playback instance for this voice recording. Note that the playback will not * have been prepared fully, meaning the `prepare()` function needs to be called on it. * * The same playback instance is returned each time. * * @returns {Playback} The playback instance. */ public getPlayback(): Playback { this.playback = Singleflight.for(this, "playback").do(() => { return new Playback(this.audioBuffer.buffer, this.amplitudes); // cast to ArrayBuffer proper; }); return this.playback; } public destroy() { // noinspection JSIgnoredPromiseFromCall - not concerned about stop() being called async here this.stop(); this.removeAllListeners(); Singleflight.forgetAllFor(this); // noinspection JSIgnoredPromiseFromCall - not concerned about being called async here this.playback?.destroy(); this.observable.close(); } public async upload(inRoomId: string): Promise<IUpload> { if (!this.hasRecording) { throw new Error("No recording available to upload"); } if (this.lastUpload) return this.lastUpload; try { this.emit(RecordingState.Uploading); const { url: mxc, file: encrypted } = await uploadFile(this.client, inRoomId, new Blob([this.audioBuffer], { type: this.contentType, })); this.lastUpload = { mxc, encrypted }; this.emit(RecordingState.Uploaded); } catch (e) { this.emit(RecordingState.Ended); throw e; } return this.lastUpload; } }
the_stack
import { PageCollection } from './Collection/PageCollection'; import { ImagePageCollection } from './Collection/ImagePageCollection'; import { HTMLPageCollection } from './Collection/HTMLPageCollection'; import { PageRect, Point } from './BasicTypes'; import { Flip, FlipCorner, FlippingState } from './Flip/Flip'; import { Orientation, Render } from './Render/Render'; import { CanvasRender } from './Render/CanvasRender'; import { HTMLUI } from './UI/HTMLUI'; import { CanvasUI } from './UI/CanvasUI'; import { Helper } from './Helper'; import { Page } from './Page/Page'; import { EventObject } from './Event/EventObject'; import { HTMLRender } from './Render/HTMLRender'; import { FlipSetting, Settings } from './Settings'; import { UI } from './UI/UI'; import './Style/stPageFlip.css'; /** * Class representing a main PageFlip object * * @extends EventObject */ export class PageFlip extends EventObject { private mousePosition: Point; private isUserTouch = false; private isUserMove = false; private readonly setting: FlipSetting = null; private readonly block: HTMLElement; // Root HTML Element private pages: PageCollection = null; private flipController: Flip; private render: Render; private ui: UI; /** * Create a new PageFlip instance * * @constructor * @param {HTMLElement} inBlock - Root HTML Element * @param {Object} setting - Configuration object */ constructor(inBlock: HTMLElement, setting: Partial<FlipSetting>) { super(); this.setting = new Settings().getSettings(setting); this.block = inBlock; } /** * Destructor. Remove a root HTML element and all event handlers */ public destroy(): void { this.ui.destroy(); this.block.remove(); } /** * Update the render area. Re-show current page. */ public update(): void { this.render.update(); this.pages.show(); } /** * Load pages from images on the Canvas mode * * @param {string[]} imagesHref - List of paths to images */ public loadFromImages(imagesHref: string[]): void { this.ui = new CanvasUI(this.block, this, this.setting); const canvas = (this.ui as CanvasUI).getCanvas(); this.render = new CanvasRender(this, this.setting, canvas); this.flipController = new Flip(this.render, this); this.pages = new ImagePageCollection(this, this.render, imagesHref); this.pages.load(); this.render.start(); this.pages.show(this.setting.startPage); // safari fix setTimeout(() => { this.ui.update(); this.trigger('init', this, { page: this.setting.startPage, mode: this.render.getOrientation(), }); }, 1); } /** * Load pages from HTML elements on the HTML mode * * @param {(NodeListOf<HTMLElement>|HTMLElement[])} items - List of pages as HTML Element */ public loadFromHTML(items: NodeListOf<HTMLElement> | HTMLElement[]): void { this.ui = new HTMLUI(this.block, this, this.setting, items); this.render = new HTMLRender(this, this.setting, this.ui.getDistElement()); this.flipController = new Flip(this.render, this); this.pages = new HTMLPageCollection(this, this.render, this.ui.getDistElement(), items); this.pages.load(); this.render.start(); this.pages.show(this.setting.startPage); // safari fix setTimeout(() => { this.ui.update(); this.trigger('init', this, { page: this.setting.startPage, mode: this.render.getOrientation(), }); }, 1); } /** * Update current pages from images * * @param {string[]} imagesHref - List of paths to images */ public updateFromImages(imagesHref: string[]): void { const current = this.pages.getCurrentPageIndex(); this.pages.destroy(); this.pages = new ImagePageCollection(this, this.render, imagesHref); this.pages.load(); this.pages.show(current); this.trigger('update', this, { page: current, mode: this.render.getOrientation(), }); } /** * Update current pages from HTML * * @param {(NodeListOf<HTMLElement>|HTMLElement[])} items - List of pages as HTML Element */ public updateFromHtml(items: NodeListOf<HTMLElement> | HTMLElement[]): void { const current = this.pages.getCurrentPageIndex(); this.pages.destroy(); this.pages = new HTMLPageCollection(this, this.render, this.ui.getDistElement(), items); this.pages.load(); (this.ui as HTMLUI).updateItems(items); this.render.reload(); this.pages.show(current); this.trigger('update', this, { page: current, mode: this.render.getOrientation(), }); } /** * Clear pages from HTML (remove to initinalState) */ public clear(): void { this.pages.destroy(); (this.ui as HTMLUI).clear(); } /** * Turn to the previous page (without animation) */ public turnToPrevPage(): void { this.pages.showPrev(); } /** * Turn to the next page (without animation) */ public turnToNextPage(): void { this.pages.showNext(); } /** * Turn to the specified page number (without animation) * * @param {number} page - New page number */ public turnToPage(page: number): void { this.pages.show(page); } /** * Turn to the next page (with animation) * * @param {FlipCorner} corner - Active page corner when turning */ public flipNext(corner: FlipCorner = FlipCorner.TOP): void { this.flipController.flipNext(corner); } /** * Turn to the prev page (with animation) * * @param {FlipCorner} corner - Active page corner when turning */ public flipPrev(corner: FlipCorner = FlipCorner.TOP): void { this.flipController.flipPrev(corner); } /** * Turn to the specified page number (with animation) * * @param {number} page - New page number * @param {FlipCorner} corner - Active page corner when turning */ public flip(page: number, corner: FlipCorner = FlipCorner.TOP): void { this.flipController.flipToPage(page, corner); } /** * Call a state change event trigger * * @param {FlippingState} newState - New state of the object */ public updateState(newState: FlippingState): void { this.trigger('changeState', this, newState); } /** * Call a page number change event trigger * * @param {number} newPage - New page Number */ public updatePageIndex(newPage: number): void { this.trigger('flip', this, newPage); } /** * Call a page orientation change event trigger. Update UI and rendering area * * @param {Orientation} newOrientation - New page orientation (portrait, landscape) */ public updateOrientation(newOrientation: Orientation): void { this.ui.setOrientationStyle(newOrientation); this.update(); this.trigger('changeOrientation', this, newOrientation); } /** * Get the total number of pages in a book * * @returns {number} */ public getPageCount(): number { return this.pages.getPageCount(); } /** * Get the index of the current page in the page list (starts at 0) * * @returns {number} */ public getCurrentPageIndex(): number { return this.pages.getCurrentPageIndex(); } /** * Get page from collection by number * * @param {number} pageIndex * @returns {Page} */ public getPage(pageIndex: number): Page { return this.pages.getPage(pageIndex); } /** * Get the current rendering object * * @returns {Render} */ public getRender(): Render { return this.render; } /** * Get current object responsible for flipping * * @returns {Flip} */ public getFlipController(): Flip { return this.flipController; } /** * Get current page orientation * * @returns {Orientation} Сurrent orientation: portrait or landscape */ public getOrientation(): Orientation { return this.render.getOrientation(); } /** * Get current book sizes and position * * @returns {PageRect} */ public getBoundsRect(): PageRect { return this.render.getRect(); } /** * Get configuration object * * @returns {FlipSetting} */ public getSettings(): FlipSetting { return this.setting; } /** * Get UI object * * @returns {UI} */ public getUI(): UI { return this.ui; } /** * Get current flipping state * * @returns {FlippingState} */ public getState(): FlippingState { return this.flipController.getState(); } /** * Get page collection * * @returns {PageCollection} */ public getPageCollection(): PageCollection { return this.pages; } /** * Start page turning. Called when a user clicks or touches * * @param {Point} pos - Touch position in coordinates relative to the book */ public startUserTouch(pos: Point): void { this.mousePosition = pos; // Save touch position this.isUserTouch = true; this.isUserMove = false; } /** * Called when a finger / mouse moves * * @param {Point} pos - Touch position in coordinates relative to the book * @param {boolean} isTouch - True if there was a touch event, not a mouse click */ public userMove(pos: Point, isTouch: boolean): void { if (!this.isUserTouch && !isTouch && this.setting.showPageCorners) { this.flipController.showCorner(pos); // fold Page Corner } else if (this.isUserTouch) { if (Helper.GetDistanceBetweenTwoPoint(this.mousePosition, pos) > 5) { this.isUserMove = true; this.flipController.fold(pos); } } } /** * Сalled when the user has stopped touching * * @param {Point} pos - Touch end position in coordinates relative to the book * @param {boolean} isSwipe - true if there was a mobile swipe event */ public userStop(pos: Point, isSwipe = false): void { if (this.isUserTouch) { this.isUserTouch = false; if (!isSwipe) { if (!this.isUserMove) this.flipController.flip(pos); else this.flipController.stopMove(); } } } }
the_stack
namespace ergometer.csafe { //----------------------------- get the stoke state ------------------------------------ export interface ICommandStrokeState extends ICommandParamsBase { onDataReceived: (state: StrokeState) => void; } export interface IBuffer { getStrokeState(params: ICommandStrokeState): IBuffer; } commandManager.register((buffer: IBuffer, monitor: PerformanceMonitorBase) => { buffer.getStrokeState = function (params: ICommandStrokeState): IBuffer { buffer.addRawCommand({ waitForResponse: true, command: csafe.defs.LONG_CFG_CMDS.SETUSERCFG1_CMD, detailCommand: csafe.defs.PM_SHORT_PULL_DATA_CMDS.PM_GET_STROKESTATE, onDataReceived: (data: DataView) => { if (params.onDataReceived) params.onDataReceived(data.getUint8(0)) }, onError: params.onError }); return buffer; } }) //----------------------------- get the drag factor ------------------------------------ export interface ICommandDragFactor extends ICommandParamsBase { onDataReceived: (state: number) => void; } export interface IBuffer { getDragFactor(params: ICommandDragFactor): IBuffer; } commandManager.register((buffer: IBuffer, monitor: PerformanceMonitorBase) => { buffer.getDragFactor = function (params: ICommandStrokeState): IBuffer { buffer.addRawCommand({ waitForResponse: true, command: csafe.defs.LONG_CFG_CMDS.SETUSERCFG1_CMD, detailCommand: csafe.defs.PM_SHORT_PULL_DATA_CMDS.PM_GET_DRAGFACTOR, onDataReceived: (data: DataView) => { if (params.onDataReceived) params.onDataReceived(data.getUint8(0)) }, onError: params.onError }); return buffer; } }) //----------------------------- get the work distance ------------------------------------ export interface ICommandWorkDistance extends ICommandParamsBase { onDataReceived: (value: number) => void; } export interface IBuffer { getWorkDistance(params: ICommandWorkDistance): IBuffer; } commandManager.register((buffer: IBuffer, monitor: PerformanceMonitorBase) => { buffer.getWorkDistance = function (params: ICommandWorkDistance): IBuffer { buffer.addRawCommand({ waitForResponse: true, command: csafe.defs.LONG_CFG_CMDS.SETUSERCFG1_CMD, detailCommand: csafe.defs.PM_SHORT_PULL_DATA_CMDS.PM_GET_WORKDISTANCE, onDataReceived: (data: DataView) => { if (params.onDataReceived) { var distance = (data.getUint8(0) + (data.getUint8(1) << 8) + (data.getUint8(2) << 16) + (data.getUint8(3) << 24)) / 10; var fraction = (data.getUint8(4) / 10.0); var workDistance = distance + fraction; params.onDataReceived(workDistance) } }, onError: params.onError }); return buffer; } }) //----------------------------- get the work time ------------------------------------ export interface ICommandWorkTime extends ICommandParamsBase { onDataReceived: (value: number) => void; } export interface IBuffer { getWorkTime(params: ICommandWorkTime): IBuffer; } commandManager.register((buffer: IBuffer, monitor: PerformanceMonitorBase) => { buffer.getWorkTime = function (params: ICommandWorkDistance): IBuffer { buffer.addRawCommand({ waitForResponse: true, command: csafe.defs.LONG_CFG_CMDS.SETUSERCFG1_CMD, detailCommand: csafe.defs.PM_SHORT_PULL_DATA_CMDS.PM_GET_WORKTIME, onDataReceived: (data: DataView) => { if (params.onDataReceived) { var timeInSeconds = ((data.getUint8(0) + (data.getUint8(1) << 8) + (data.getUint8(2) << 16) + (data.getUint8(3) << 24))) / 100; var fraction = data.getUint8(4) / 100; var workTimeMs = (timeInSeconds + fraction) * 1000; params.onDataReceived(workTimeMs); } }, onError: params.onError }); return buffer; } }) //----------------------------- get power curve ------------------------------------ export interface ICommandPowerCurve { onDataReceived: (curve: number[]) => void; onError?: ErrorHandler; } export interface IBuffer { getPowerCurve(params: ICommandPowerCurve): IBuffer; } var receivePowerCurvePart = []; var currentPowerCurve = []; var peekValue=0; commandManager.register((buffer: IBuffer, monitor: PerformanceMonitorBase) => { buffer.getPowerCurve = function (params: ICommandPowerCurve): IBuffer { buffer.addRawCommand({ waitForResponse: true, command: csafe.defs.LONG_CFG_CMDS.SETUSERCFG1_CMD, detailCommand: csafe.defs.PM_LONG_PULL_DATA_CMDS.PM_GET_FORCEPLOTDATA, data: [20], onError: params.onError, onDataReceived: function (data) { if (params.onDataReceived) { var bytesReturned = data.getUint8(0); //first byte monitor.traceInfo("received power curve count " + bytesReturned); var endFound = false; if (bytesReturned > 0) { //when it is going down we are near the end var value = 0; var lastValue=0; if (receivePowerCurvePart.length>0 ) lastValue=receivePowerCurvePart[receivePowerCurvePart.length-1]; for (var i = 1; i < bytesReturned + 1; i += 2) { value = data.getUint16(i, true); //in ltile endian format //console.log("receive curve "+value+" peek value "+peekValue); //work around the problem that since the last update we can not detect the end //when going up again near to the end it is a new curve (25% of the Peek value) //so directly send it if (receivePowerCurvePart.length > 20 && lastValue<(peekValue/4) && value > lastValue) { //console.log("going up again , split!"); //console.log("Curve:" + JSON.stringify(currentPowerCurve)); monitor.traceInfo("Curve:" + JSON.stringify(currentPowerCurve)); currentPowerCurve = receivePowerCurvePart; receivePowerCurvePart = []; peekValue=0; if (params.onDataReceived && currentPowerCurve.length > 4) params.onDataReceived(currentPowerCurve); } receivePowerCurvePart.push(value); if (value>peekValue) peekValue=value; lastValue=value; } //sometimes the last value is 0 in that case it is the end of the curve if (receivePowerCurvePart.length > 10 && value === 0) { endFound = true; //console.log("end found") } if (!endFound) { monitor.traceInfo("received part :" + JSON.stringify(receivePowerCurvePart)); //console.log("wait for next") monitor.newCsafeBuffer() .getPowerCurve({ onDataReceived: params.onDataReceived }) .send(); } } else endFound = true; if (endFound) { //console.log("send received"); //console.log("Curve:" + JSON.stringify(currentPowerCurve)); peekValue=0; currentPowerCurve = receivePowerCurvePart; receivePowerCurvePart = []; monitor.traceInfo("Curve:" + JSON.stringify(currentPowerCurve)); if (params.onDataReceived && currentPowerCurve.length > 4) params.onDataReceived(currentPowerCurve); } } } }); return buffer; }; }); //----------------------------- get power curve ------------------------------------ export interface ICommandStrokeStats { onDataReceived: (driveTime : number,strokeRecoveryTime : number) => void; onError?: ErrorHandler; } export interface IBuffer { getStrokeStats(params: ICommandStrokeStats): IBuffer; } commandManager.register((buffer: IBuffer, monitor: PerformanceMonitorBase) => { buffer.getStrokeStats = function (params: ICommandStrokeStats): IBuffer { buffer.addRawCommand({ waitForResponse: true, command: csafe.defs.LONG_CFG_CMDS.SETUSERCFG1_CMD, detailCommand: csafe.defs.PM_LONG_PULL_DATA_CMDS.CSAFE_PM_GET_STROKESTATS, data: [], onError: params.onError, onDataReceived: (data: DataView) => { if (params.onDataReceived && data.byteLength>=3) { var driveTime=data.getUint8(0); var strokeRecoveryTime= data.getUint8(1) + data.getUint8(2)*256; params.onDataReceived(driveTime,strokeRecoveryTime); } } }); return buffer; } }); //----------------------------- get workout type ------------------------------------ export interface ICommandGetWorkoutType extends ICommandParamsBase { onDataReceived: (value: WorkoutType) => void; } export interface IBuffer { getWorkoutType(params: ICommandParamsBase): IBuffer; } registerStandardLongGet<ICommandGetWorkoutType, WorkoutType>("getWorkoutType", csafe.defs.PM_SHORT_PULL_CFG_CMDS.PM_GET_WORKOUTTYPE, data=>data.getUint8(0)); //----------------------------- get workout state ------------------------------------ export interface ICommandGetWorkoutState extends ICommandParamsBase { onDataReceived: (value: WorkoutState) => void; } export interface IBuffer { getWorkoutState(params: ICommandParamsBase): IBuffer; } registerStandardLongGet<ICommandGetWorkoutState, WorkoutState>("getWorkoutState", csafe.defs.PM_SHORT_PULL_CFG_CMDS.PM_GET_WORKOUTSTATE, data=>data.getUint8(0)); //----------------------------- get workout interval count ------------------------------------ export interface ICommandGetWorkoutIntervalCount extends ICommandParamsBase { onDataReceived: (value: number) => void; } export interface IBuffer { getWorkoutIntervalCount(params: ICommandParamsBase): IBuffer; } registerStandardLongGet<ICommandGetWorkoutIntervalCount, number>("getWorkoutIntervalCount", csafe.defs.PM_SHORT_PULL_CFG_CMDS.PM_GET_WORKOUTINTERVALCOUNT, data=>data.getUint8(0)); //----------------------------- get workout interval type ------------------------------------ export interface ICommandGetWorkoutIntervalType extends ICommandParamsBase { onDataReceived: (value: IntervalType) => void; } export interface IBuffer { getWorkoutIntervalType(params: ICommandParamsBase): IBuffer; } registerStandardLongGet<ICommandGetWorkoutIntervalType, IntervalType>("getWorkoutIntervalType", csafe.defs.PM_SHORT_PULL_CFG_CMDS.PM_GET_INTERVALTYPE, data=>data.getUint8(0)); //----------------------------- get workout rest time ------------------------------------ export interface ICommandGetWorkoutIntervalRestTime extends ICommandParamsBase { onDataReceived: (value: number) => void; } export interface IBuffer { getWorkoutIntervalRestTime(params: ICommandParamsBase): IBuffer; } registerStandardLongGet<ICommandGetWorkoutIntervalCount, number>("getWorkoutIntervalRestTime", csafe.defs.PM_SHORT_PULL_DATA_CMDS.PM_GET_RESTTIME, data=>data.getUint16(0,true)); //----------------------------- get workout work ------------------------------------ export interface ICommandGetWork extends ICommandParamsBase { onDataReceived: (value: number) => void; } export interface IBuffer { getWork(params: ICommandParamsBase): IBuffer; } registerStandardLongGet<ICommandGetWork, number>("getWork", csafe.defs.SHORT_DATA_CMDS.GETTWORK_CMD, data=>{ var result=data.getUint8(0)*60*60+ data.getUint8(1)*60+ data.getUint8(2); return result*1000; }); //----------------------------- set program ------------------------------------ export interface ICommandProgramParams extends ICommandParamsBase { value: Program } export interface IBuffer { setProgram(params: ICommandProgramParams): IBuffer; } registerStandardSet<ICommandProgramParams>("setProgram", csafe.defs.LONG_DATA_CMDS.SETPROGRAM_CMD, (params) => { return [utils.getByte(params.value, 0), 0]; }); //----------------------------- set time ------------------------------------ export interface ICommandTimeParams extends ICommandParamsBase { hour: number; minute: number; second: number; } export interface IBuffer { setTime(params: ICommandTimeParams): IBuffer; } registerStandardSet<ICommandTimeParams>("setTime", csafe.defs.LONG_CFG_CMDS.SETTIME_CMD, (params) => { return [params.hour, params.minute, params.second]; }); //----------------------------- set date ------------------------------------ export interface ICommandDateParams extends ICommandParamsBase { year: number; month: number; day: number; } export interface IBuffer { setDate(params: ICommandDateParams): IBuffer; } registerStandardSet<ICommandDateParams>("setDate", csafe.defs.LONG_CFG_CMDS.SETDATE_CMD, (params) => { return [utils.getByte(params.year, 0), params.month, params.day]; }); //----------------------------- set timeout ------------------------------------ export interface IBuffer { setTimeout(params: ICommandSetStandardValue): IBuffer; } registerStandardSet<ICommandSetStandardValue>("setTimeout", csafe.defs.LONG_CFG_CMDS.SETTIMEOUT_CMD, (params) => { return [params.value]; }); //----------------------------- set work ------------------------------------ export interface IBuffer { setWork(params: ICommandTimeParams): IBuffer; } registerStandardSet<ICommandTimeParams>("setWork", csafe.defs.LONG_DATA_CMDS.SETTWORK_CMD, (params) => { return [params.hour, params.minute, params.second]; }); //----------------------------- set horizontal distance ------------------------------------ export interface ICommandDistanceParams extends ICommandSetStandardValue { unit: Unit; } export interface IBuffer { setDistance(params: ICommandDistanceParams): IBuffer; } registerStandardSet<ICommandDistanceParams>("setDistance", csafe.defs.LONG_DATA_CMDS.SETHORIZONTAL_CMD, (params) => { return [utils.getByte(params.value, 0), utils.getByte(params.value, 1), params.unit]; }); //----------------------------- set total calories ------------------------------------ export interface IBuffer { setTotalCalories(params: ICommandSetStandardValue): IBuffer; } registerStandardSet<ICommandSetStandardValue>("setTotalCalories", csafe.defs.LONG_DATA_CMDS.SETCALORIES_CMD, (params) => { return [utils.getByte(params.value, 0), utils.getByte(params.value, 1)]; }); //----------------------------- set power ------------------------------------ export interface ICommandPowerParams extends ICommandSetStandardValue { unit: Unit; } export interface IBuffer { setPower(params: ICommandPowerParams): IBuffer; } registerStandardSet<ICommandPowerParams>("setPower", csafe.defs.LONG_DATA_CMDS.SETPOWER_CMD, (params) => { return [utils.getByte(params.value, 0), utils.getByte(params.value, 1), params.unit]; }); }
the_stack
import { AssertTrue as Assert, IsExact, AssertFalse } from "conditional-type-checks"; import { assert, Buildable, DeepNonNullable, DeepNullable, DeepReadonly, DeepRequired, DeepWritable, StrictExtract, Dictionary, DictionaryValues, MarkOptional, MarkRequired, Merge, MergeN, NonEmptyObject, NonNever, noop, PickProperties, ReadonlyKeys, SafeDictionary, Tuple, WritableKeys, XOR, Head, Tail, Exact, ElementOf, DeepUndefinable, OptionalKeys, RequiredKeys, Opaque, AsyncOrSyncType, AsyncOrSync, Awaited, Newable, IsTuple, Writable, OmitProperties, isExact, IsUnknown, IsNever, ArrayOrSingle, IsAny, NonEmptyArray, } from "../lib"; import { TsVersion } from "./ts-version"; import { ComplexNestedPartial, ComplexNestedRequired } from "./types"; function testDictionary() { type cases = [ Assert<IsExact<Dictionary<number>[string], number>>, Assert<IsExact<Dictionary<number>[number], number>>, // @ts-expect-error cannot use boolean as dictionary key Dictionary<number>[boolean], // @ts-expect-error cannot use bigint as dictionary key Dictionary<number>[bigint], // @ts-expect-error cannot use symbol as dictionary key Dictionary<number>[symbol], // @ts-expect-error cannot use undefined as dictionary key Dictionary<number>[undefined], // @ts-expect-error cannot use null as dictionary key Dictionary<number>[null], // @ts-expect-error cannot use string as only 'a' | 'b' allowed Assert<IsExact<Dictionary<number, "a" | "b">[string], number>>, Assert<IsExact<Dictionary<number, "a" | "b">["a"], number>>, Assert<IsExact<Dictionary<number, "a" | "b">["b"], number>>, ]; } function testDictionaryValues() { type cases = [ Assert<IsExact<DictionaryValues<Dictionary<string>>, string>>, Assert<IsExact<DictionaryValues<Dictionary<number>>, number>>, Assert<IsExact<DictionaryValues<Dictionary<boolean>>, boolean>>, Assert<IsExact<DictionaryValues<Dictionary<bigint>>, bigint>>, Assert<IsExact<DictionaryValues<Dictionary<symbol>>, symbol>>, Assert<IsExact<DictionaryValues<Dictionary<undefined>>, undefined>>, Assert<IsExact<DictionaryValues<Dictionary<null>>, null>>, Assert<IsExact<DictionaryValues<Dictionary<string, "a" | "b">>, string>>, Assert<IsExact<DictionaryValues<Dictionary<number, "a" | "b">>, number>>, Assert<IsExact<DictionaryValues<Dictionary<boolean, "a" | "b">>, boolean>>, Assert<IsExact<DictionaryValues<Dictionary<bigint, "a" | "b">>, bigint>>, Assert<IsExact<DictionaryValues<Dictionary<symbol, "a" | "b">>, symbol>>, Assert<IsExact<DictionaryValues<Dictionary<undefined, "a" | "b">>, undefined>>, Assert<IsExact<DictionaryValues<Dictionary<null, "a" | "b">>, null>>, Assert<IsExact<DictionaryValues<Dictionary<string, 1 | 2>>, string>>, Assert<IsExact<DictionaryValues<Dictionary<number, 1 | 2>>, number>>, Assert<IsExact<DictionaryValues<Dictionary<boolean, 1 | 2>>, boolean>>, Assert<IsExact<DictionaryValues<Dictionary<bigint, 1 | 2>>, bigint>>, Assert<IsExact<DictionaryValues<Dictionary<symbol, 1 | 2>>, symbol>>, Assert<IsExact<DictionaryValues<Dictionary<undefined, 1 | 2>>, undefined>>, Assert<IsExact<DictionaryValues<Dictionary<null, 1 | 2>>, null>>, Assert<IsExact<DictionaryValues<SafeDictionary<string>>, string | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<number>>, number | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<boolean>>, boolean | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<bigint>>, bigint | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<symbol>>, symbol | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<undefined>>, undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<null>>, null | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<string, "a" | "b">>, string | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<number, "a" | "b">>, number | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<boolean, "a" | "b">>, boolean | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<bigint, "a" | "b">>, bigint | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<symbol, "a" | "b">>, symbol | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<undefined, "a" | "b">>, undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<null, "a" | "b">>, null | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<string, 1 | 2>>, string | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<number, 1 | 2>>, number | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<boolean, 1 | 2>>, boolean | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<bigint, 1 | 2>>, bigint | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<symbol, 1 | 2>>, symbol | undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<undefined, 1 | 2>>, undefined>>, Assert<IsExact<DictionaryValues<SafeDictionary<null, 1 | 2>>, null | undefined>>, ]; } function testSafeDictionary() { type cases = [ Assert<IsExact<SafeDictionary<number>, { [x: string]: number | undefined }>>, Assert<IsExact<Pick<SafeDictionary<number>, "foo">, { foo: number | undefined }>>, Assert<IsExact<SafeDictionary<number>["foo"], number | undefined>>, Assert<IsExact<SafeDictionary<boolean, number>[42], boolean | undefined>>, ]; const testingSafeDictionary: SafeDictionary<number> = {}; delete testingSafeDictionary.unexistingField; testingSafeDictionary.existingField = 1; delete testingSafeDictionary.existingField; // non exhaustiveness const safeDict: SafeDictionary<string, "A" | "B"> = { A: "OK" }; } type ComplexNestedNullable = { simple: number | null; nested: { date: Date | null; func: (() => string) | null; array: { bar: number | null }[]; tuple: [string | null, number | null, { good: boolean | null } | null]; set: Set<{ name: string | null }>; map: Map<string | null, { name: string | null }>; promise: Promise<{ foo: string | null; bar: number | null }>; }; }; type ComplexNestedUndefinable = { simple: number | undefined; nested: { date: Date | undefined; func: (() => string) | undefined; array: { bar: number | undefined }[]; tuple: [string | undefined, number | undefined, { good: boolean | undefined } | undefined]; set: Set<{ name: string | undefined }>; map: Map<string | undefined, { name: string | undefined }>; promise: Promise<{ foo: string | undefined; bar: number | undefined }>; }; }; type ComplexNestedNullableOrUndefined = { simple: number | null | undefined; nested: { date: Date | null | undefined; func: (() => string) | null | undefined; array: ({ bar: number | null | undefined } | null | undefined)[] | null | undefined; tuple: | [string | null | undefined, number | null | undefined, { good: boolean | null | undefined } | null | undefined] | null | undefined; set: | Set< | { name: string | null | undefined; } | null | undefined > | null | undefined; map: | Map< string | null | undefined, | { name: string | null | undefined; } | null | undefined > | null | undefined; promise: | Promise< | { foo: string | null | undefined; bar: number | null | undefined; } | null | undefined > | null | undefined; }; }; type ComplexNestedReadonly = { readonly simple: number; readonly nested: { readonly date: Date; readonly func: () => string; readonly array: readonly { readonly bar: number }[]; readonly tuple: readonly [string, number, { readonly good: boolean }]; readonly set: ReadonlySet<{ readonly name: string; }>; readonly map: ReadonlyMap< string, { readonly name: string; } >; readonly promise: Promise<{ readonly foo: string; readonly bar: number }>; }; }; function testDeepNullable() { type cases = [ Assert<IsExact<DeepNullable<number>, number | null>>, Assert<IsExact<DeepNullable<string>, string | null>>, Assert<IsExact<DeepNullable<boolean>, boolean | null>>, Assert<IsExact<DeepNullable<bigint>, bigint | null>>, Assert<IsExact<DeepNullable<symbol>, symbol | null>>, Assert<IsExact<DeepNullable<undefined>, undefined | null>>, Assert<IsExact<DeepNullable<null>, null>>, Assert<IsExact<DeepNullable<Function>, Function | null>>, Assert<IsExact<DeepNullable<Date>, Date | null>>, Assert<IsExact<DeepNullable<Error>, Error | null>>, Assert<IsExact<DeepNullable<RegExp>, RegExp | null>>, Assert<IsExact<DeepNullable<Map<string, boolean>>, Map<string | null, boolean | null>>>, Assert<IsExact<DeepNullable<Map<string, { a: number }>>, Map<string | null, { a: number | null }>>>, Assert<IsExact<DeepNullable<ReadonlyMap<string, boolean>>, ReadonlyMap<string | null, boolean | null>>>, Assert< IsExact< DeepNullable<ReadonlyMap<string, { checked: boolean }>>, ReadonlyMap<string | null, { checked: boolean | null }> > >, Assert<IsExact<DeepNullable<WeakMap<{ key: string }, boolean>>, WeakMap<{ key: string | null }, boolean | null>>>, Assert< IsExact< DeepNullable<WeakMap<{ key: string }, { value: boolean }>>, WeakMap<{ key: string | null }, { value: boolean | null }> > >, Assert<IsExact<DeepNullable<Set<string>>, Set<string | null>>>, Assert<IsExact<DeepNullable<Set<number[]>>, Set<(number | null)[]>>>, Assert<IsExact<DeepNullable<ReadonlySet<string>>, ReadonlySet<string | null>>>, Assert<IsExact<DeepNullable<[]>, []>>, Assert<IsExact<DeepNullable<never[]>, null[]>>, Assert<IsExact<DeepNullable<[1, 2, 3]>, [1 | null, 2 | null, 3 | null]>>, Assert<IsExact<DeepNullable<readonly number[]>, readonly (number | null)[]>>, Assert<IsExact<DeepNullable<Array<number>>, Array<number | null>>>, Assert<IsExact<DeepNullable<Promise<number>>, Promise<number | null>>>, Assert< IsExact< DeepNullable<Promise<{ api: () => { play: () => void; pause: () => void } }>>, Promise<{ api: (() => { play: () => void; pause: () => void }) | null }> > >, Assert<IsExact<DeepNullable<{ a: 1; b: 2; c: 3 }>, { a: 1 | null; b: 2 | null; c: 3 | null }>>, Assert<IsExact<DeepNullable<{ foo: () => void }>, { foo: (() => void) | null }>>, Assert<IsExact<DeepNullable<ComplexNestedRequired>, ComplexNestedNullable>>, ]; } function testDeepReadonly() { type cases = [ Assert<IsExact<DeepReadonly<number>, number>>, Assert<IsExact<DeepReadonly<string>, string>>, Assert<IsExact<DeepReadonly<boolean>, boolean>>, Assert<IsExact<DeepReadonly<bigint>, bigint>>, Assert<IsExact<DeepReadonly<symbol>, symbol>>, Assert<IsExact<DeepReadonly<undefined>, undefined>>, Assert<IsExact<DeepReadonly<null>, null>>, Assert<IsExact<DeepReadonly<Function>, Function>>, Assert<IsExact<DeepReadonly<Date>, Date>>, Assert<IsExact<DeepReadonly<Error>, Error>>, Assert<IsExact<DeepReadonly<RegExp>, RegExp>>, Assert<IsExact<DeepReadonly<Map<string, boolean>>, ReadonlyMap<string, boolean>>>, Assert<IsExact<DeepReadonly<ReadonlyMap<string, boolean>>, ReadonlyMap<string, boolean>>>, Assert<IsExact<DeepReadonly<WeakMap<{ key: string }, boolean>>, WeakMap<{ key: string }, boolean>>>, Assert< IsExact<DeepReadonly<WeakMap<{ key: string }, { value: boolean }>>, WeakMap<{ key: string }, { value: boolean }>> >, Assert<IsExact<DeepReadonly<Set<string>>, ReadonlySet<string>>>, Assert<IsExact<DeepReadonly<ReadonlySet<string>>, ReadonlySet<string>>>, Assert<IsExact<DeepReadonly<[]>, readonly []>>, Assert<IsExact<DeepReadonly<[1, 2, 3]>, readonly [1, 2, 3]>>, Assert<IsExact<DeepReadonly<readonly number[]>, readonly number[]>>, Assert<IsExact<DeepReadonly<Array<number>>, ReadonlyArray<number>>>, Assert<IsExact<DeepReadonly<Promise<number>>, Promise<number>>>, Assert<IsExact<DeepReadonly<{ a: 1; b: 2; c: 3 }>, { a: 1; b: 2; c: 3 }>>, Assert<IsExact<DeepReadonly<{ foo: () => void }>, { foo: () => void }>>, Assert< IsExact< DeepReadonly<{ obj: unknown; arr: unknown[] }>, { readonly obj: unknown; readonly arr: readonly unknown[] } > >, Assert<IsExact<DeepReadonly<ComplexNestedRequired>, ComplexNestedReadonly>>, ]; // Build-time test to ensure the fix for // https://github.com/krzkaczor/ts-essentials/issues/17 remains in place. { interface TestObject extends DeepReadonly<{ field: string[] }> {} let a: DeepReadonly<TestObject> = { field: ["lala"], }; let b: TestObject = { field: ["lala"], }; b = a; } { interface TestObject { obj: unknown; arr: unknown[]; } // @ts-expect-error const obj: TestObject = null; let readonlyObj: DeepReadonly<TestObject>; readonlyObj = obj; const readonlyObj2: DeepReadonly<TestObject> = obj; } } function testDeepUndefinable() { type cases = [ Assert<IsExact<DeepUndefinable<number>, number | undefined>>, Assert<IsExact<DeepUndefinable<string>, string | undefined>>, Assert<IsExact<DeepUndefinable<boolean>, boolean | undefined>>, Assert<IsExact<DeepUndefinable<bigint>, bigint | undefined>>, Assert<IsExact<DeepUndefinable<symbol>, symbol | undefined>>, Assert<IsExact<DeepUndefinable<undefined>, undefined>>, Assert<IsExact<DeepUndefinable<null>, null | undefined>>, Assert<IsExact<DeepUndefinable<Function>, Function | undefined>>, Assert<IsExact<DeepUndefinable<Date>, Date | undefined>>, Assert<IsExact<DeepUndefinable<Error>, Error | undefined>>, Assert<IsExact<DeepUndefinable<RegExp>, RegExp | undefined>>, Assert<IsExact<DeepUndefinable<Map<string, boolean>>, Map<string | undefined, boolean | undefined>>>, Assert<IsExact<DeepUndefinable<Map<string, { a: number }>>, Map<string | undefined, { a: number | undefined }>>>, Assert< IsExact<DeepUndefinable<ReadonlyMap<string, boolean>>, ReadonlyMap<string | undefined, boolean | undefined>> >, Assert< IsExact< DeepUndefinable<ReadonlyMap<string, { checked: boolean }>>, ReadonlyMap<string | undefined, { checked: boolean | undefined }> > >, Assert< IsExact< DeepUndefinable<WeakMap<{ key: string }, boolean>>, WeakMap<{ key: string | undefined }, boolean | undefined> > >, Assert< IsExact< DeepUndefinable<WeakMap<{ key: string }, { value: boolean }>>, WeakMap<{ key: string | undefined }, { value: boolean | undefined }> > >, Assert<IsExact<DeepUndefinable<Set<string>>, Set<string | undefined>>>, Assert<IsExact<DeepUndefinable<Set<number[]>>, Set<(number | undefined)[]>>>, Assert<IsExact<DeepUndefinable<ReadonlySet<string>>, ReadonlySet<string | undefined>>>, Assert<IsExact<DeepUndefinable<[]>, []>>, Assert<IsExact<DeepUndefinable<never[]>, undefined[]>>, Assert<IsExact<DeepUndefinable<[1, 2, 3]>, [1 | undefined, 2 | undefined, 3 | undefined]>>, Assert<IsExact<DeepUndefinable<readonly number[]>, readonly (number | undefined)[]>>, Assert<IsExact<DeepUndefinable<Array<number>>, Array<number | undefined>>>, Assert<IsExact<DeepUndefinable<Promise<number>>, Promise<number | undefined>>>, Assert< IsExact< DeepUndefinable<Promise<{ api: () => { play: () => void; pause: () => void } }>>, Promise<{ api: (() => { play: () => void; pause: () => void }) | undefined }> > >, Assert<IsExact<DeepUndefinable<{ a: 1; b: 2; c: 3 }>, { a: 1 | undefined; b: 2 | undefined; c: 3 | undefined }>>, Assert<IsExact<DeepUndefinable<{ foo: () => void }>, { foo: (() => void) | undefined }>>, Assert<IsExact<DeepUndefinable<ComplexNestedRequired>, ComplexNestedUndefinable>>, ]; } function testDeepNonNullable() { type cases = [ Assert<IsExact<DeepNonNullable<number | null | undefined>, number>>, Assert<IsExact<DeepNonNullable<string | null | undefined>, string>>, Assert<IsExact<DeepNonNullable<boolean | null | undefined>, boolean>>, Assert<IsExact<DeepNonNullable<bigint | null | undefined>, bigint>>, Assert<IsExact<DeepNonNullable<symbol | null | undefined>, symbol>>, Assert<IsExact<DeepNonNullable<undefined | null>, never>>, Assert<IsExact<DeepNonNullable<Function | null | undefined>, Function>>, Assert<IsExact<DeepNonNullable<Date | null | undefined>, Date>>, Assert<IsExact<DeepNonNullable<Error | null | undefined>, Error>>, Assert<IsExact<DeepNonNullable<RegExp | null | undefined>, RegExp>>, Assert<IsExact<DeepNonNullable<Map<string | null | undefined, boolean | null | undefined>>, Map<string, boolean>>>, Assert< IsExact< DeepNonNullable<Map<string | null | undefined, { a: number | null | undefined }>>, Map<string, { a: number }> > >, Assert< IsExact< DeepNonNullable<ReadonlyMap<string | null | undefined, boolean | null | undefined>>, ReadonlyMap<string, boolean> > >, Assert< IsExact< DeepNonNullable<ReadonlyMap<string | null | undefined, { checked: boolean | null | undefined }>>, ReadonlyMap<string, { checked: boolean }> > >, Assert< IsExact< DeepNonNullable<WeakMap<{ key: string | null | undefined }, boolean | null | undefined>>, WeakMap<{ key: string }, boolean> > >, Assert< IsExact< DeepNonNullable<WeakMap<{ key: string | null | undefined }, { value: boolean | null | undefined }>>, WeakMap<{ key: string }, { value: boolean }> > >, Assert<IsExact<DeepNonNullable<Set<string | null | undefined>>, Set<string>>>, Assert<IsExact<DeepNonNullable<Set<(number | null | undefined)[]>>, Set<number[]>>>, Assert<IsExact<DeepNonNullable<ReadonlySet<string | null | undefined>>, ReadonlySet<string>>>, Assert<IsExact<DeepNonNullable<[] | null | undefined>, []>>, Assert<IsExact<DeepNonNullable<(null | undefined)[]>, never[]>>, Assert<IsExact<DeepNonNullable<[1 | null | undefined, 2 | null | undefined, 3 | null | undefined]>, [1, 2, 3]>>, Assert<IsExact<DeepNonNullable<readonly (number | null | undefined)[]>, readonly number[]>>, Assert<IsExact<DeepNonNullable<Array<number | null | undefined>>, Array<number>>>, Assert<IsExact<DeepNonNullable<Promise<number | null | undefined>>, Promise<number>>>, Assert< IsExact< DeepNonNullable<Promise<{ api: (() => { play: () => void; pause: () => void }) | null | undefined }>>, Promise<{ api: () => { play: () => void; pause: () => void } }> > >, Assert< IsExact< DeepNonNullable<{ a: 1 | null | undefined; b: 2 | null | undefined; c: 3 | null | undefined }>, { a: 1; b: 2; c: 3 } > >, Assert<IsExact<DeepNonNullable<{ foo: (() => void) | null | undefined }>, { foo: () => void }>>, Assert<IsExact<DeepNonNullable<{ a?: 1; b?: 2 }>, { a?: 1 | undefined; b?: 2 | undefined }>>, Assert<IsExact<DeepNonNullable<ComplexNestedNullableOrUndefined>, ComplexNestedRequired>>, ]; } function testDeepRequired() { type cases = [ Assert<IsExact<DeepRequired<number | null | undefined>, number | null | undefined>>, Assert<IsExact<DeepRequired<string | null | undefined>, string | null | undefined>>, Assert<IsExact<DeepRequired<boolean | null | undefined>, boolean | null | undefined>>, Assert<IsExact<DeepRequired<bigint | null | undefined>, bigint | null | undefined>>, Assert<IsExact<DeepRequired<symbol | null | undefined>, symbol | null | undefined>>, Assert<IsExact<DeepRequired<undefined | null>, undefined | null>>, Assert<IsExact<DeepRequired<Function | null | undefined>, Function | null | undefined>>, Assert<IsExact<DeepRequired<Date | null | undefined>, Date | null | undefined>>, Assert<IsExact<DeepRequired<Error | null | undefined>, Required<Error> | null | undefined>>, Assert<IsExact<DeepRequired<RegExp | null | undefined>, RegExp | null | undefined>>, Assert< IsExact< DeepRequired<Map<string | null | undefined, boolean | null | undefined>>, Map<string | null | undefined, boolean | null | undefined> > >, Assert< IsExact< DeepRequired<Map<string | null | undefined, { a: number | null | undefined }>>, Map<string | null | undefined, { a: number | null | undefined }> > >, Assert< IsExact< DeepRequired<ReadonlyMap<string | null | undefined, boolean | null | undefined>>, ReadonlyMap<string | null | undefined, boolean | null | undefined> > >, Assert< IsExact< DeepRequired<ReadonlyMap<string | null | undefined, { checked: boolean | null | undefined }>>, ReadonlyMap<string | null | undefined, { checked: boolean | null | undefined }> > >, Assert< IsExact< DeepRequired<WeakMap<{ key: string | null | undefined }, boolean | null | undefined>>, WeakMap<{ key: string | null | undefined }, boolean | null | undefined> > >, Assert< IsExact< DeepRequired<WeakMap<{ key: string | null | undefined }, { value: boolean | null | undefined }>>, WeakMap<{ key: string | null | undefined }, { value: boolean | null | undefined }> > >, Assert<IsExact<DeepRequired<Set<string | null | undefined>>, Set<string | null | undefined>>>, Assert<IsExact<DeepRequired<Set<(number | null | undefined)[]>>, Set<(number | null)[]>>>, Assert<IsExact<DeepRequired<ReadonlySet<string | null | undefined>>, ReadonlySet<string | null | undefined>>>, Assert<IsExact<DeepRequired<[] | null | undefined>, [] | null | undefined>>, Assert<IsExact<DeepRequired<(null | undefined)[]>, null[]>>, Assert< IsExact< DeepRequired<[1 | null | undefined, 2 | null | undefined, 3 | null | undefined]>, [1 | null | undefined, 2 | null | undefined, 3 | null | undefined] > >, Assert< IsExact< DeepRequired<[(1 | null | undefined)?, (2 | null | undefined)?, (3 | null | undefined)?]>, [1 | null, 2 | null, 3 | null] > >, Assert<IsExact<DeepRequired<readonly (number | null | undefined)[]>, readonly (number | null)[]>>, Assert<IsExact<DeepRequired<Array<number | null | undefined>>, Array<number | null>>>, Assert<IsExact<DeepRequired<Promise<number | null | undefined>>, Promise<number | null | undefined>>>, Assert< IsExact< DeepRequired<Promise<{ api: (() => { play: () => void; pause: () => void }) | null | undefined }>>, Promise<{ api: | (() => { play: () => void; pause: () => void; }) | null | undefined; }> > >, Assert< IsExact< DeepRequired<{ a: 1 | null | undefined; b: 2 | null | undefined; c: 3 | null | undefined }>, { a: 1 | null | undefined; b: 2 | null | undefined; c: 3 | null | undefined } > >, Assert<IsExact<DeepRequired<{ foo: (() => void) | null | undefined }>, { foo: (() => void) | null | undefined }>>, Assert<IsExact<DeepRequired<{ a?: 1; b?: 2 }>, { a: 1; b: 2 }>>, Assert<IsExact<DeepRequired<ComplexNestedPartial>, ComplexNestedRequired>>, ]; } function testWritable() { type cases = [ Assert<IsExact<Writable<{}>, {}>>, Assert<IsExact<Writable<{ readonly a: number }>, { a: number }>>, Assert<IsExact<Writable<{ a: number }>, { a: number }>>, Assert<IsExact<Writable<[1, 2, 3]>, [1, 2, 3]>>, Assert<IsExact<Writable<readonly [1, 2, 3]>, [1, 2, 3]>>, Assert<IsExact<Writable<number[]>, number[]>>, Assert<IsExact<Writable<readonly number[]>, number[]>>, ]; } function testDeepWritable() { type cases = [ Assert<IsExact<DeepWritable<number>, number>>, Assert<IsExact<DeepWritable<string>, string>>, Assert<IsExact<DeepWritable<boolean>, boolean>>, Assert<IsExact<DeepWritable<bigint>, bigint>>, Assert<IsExact<DeepWritable<symbol>, symbol>>, Assert<IsExact<DeepWritable<undefined>, undefined>>, Assert<IsExact<DeepWritable<null>, null>>, Assert<IsExact<DeepWritable<Function>, Function>>, Assert<IsExact<DeepWritable<Date>, Date>>, Assert<IsExact<DeepWritable<Error>, Error>>, Assert<IsExact<DeepWritable<RegExp>, RegExp>>, Assert<IsExact<DeepWritable<Map<string, boolean>>, Map<string, boolean>>>, Assert<IsExact<DeepWritable<ReadonlyMap<string, boolean>>, Map<string, boolean>>>, Assert<IsExact<DeepWritable<WeakMap<{ key: string }, boolean>>, WeakMap<{ key: string }, boolean>>>, Assert< IsExact<DeepWritable<WeakMap<{ key: string }, { value: boolean }>>, WeakMap<{ key: string }, { value: boolean }>> >, Assert<IsExact<DeepWritable<Set<string>>, Set<string>>>, Assert<IsExact<DeepWritable<ReadonlySet<string>>, Set<string>>>, Assert<IsExact<DeepWritable<readonly []>, []>>, Assert<IsExact<DeepWritable<readonly [1, 2, 3]>, [1, 2, 3]>>, Assert<IsExact<DeepWritable<readonly number[]>, number[]>>, Assert<IsExact<DeepWritable<ReadonlyArray<number>>, Array<number>>>, Assert<IsExact<DeepWritable<Promise<number>>, Promise<number>>>, Assert<IsExact<DeepWritable<{ readonly a: 1; readonly b: 2; readonly c: 3 }>, { a: 1; b: 2; c: 3 }>>, Assert<IsExact<DeepWritable<{ foo: () => void }>, { foo: () => void }>>, Assert< IsExact< DeepWritable<{ readonly obj: unknown; readonly arr: readonly unknown[] }>, { obj: unknown; arr: unknown[] } > >, Assert<IsExact<DeepWritable<ComplexNestedReadonly>, ComplexNestedRequired>>, Assert<IsExact<DeepWritable<DeepReadonly<ComplexNestedRequired>>, ComplexNestedRequired>>, Assert<IsExact<DeepWritable<ComplexNestedRequired>, ComplexNestedRequired>>, ]; { type Test = { readonly foo: string; bar: { readonly x: number } }[]; const test: DeepWritable<Test> = [ { foo: "a", bar: { x: 5, }, }, ]; test[0].foo = "b"; test[0].bar.x = 2; } } function testBuildable() { type cases = [ Assert<IsExact<Buildable<number>, number>>, Assert<IsExact<Buildable<string>, string>>, Assert<IsExact<Buildable<boolean>, boolean>>, Assert<IsExact<Buildable<bigint>, bigint>>, Assert<IsExact<Buildable<symbol>, symbol>>, Assert<IsExact<Buildable<undefined>, undefined>>, Assert<IsExact<Buildable<null>, null>>, Assert<IsExact<Buildable<Function>, Function>>, Assert<IsExact<Buildable<Date>, Date>>, Assert<IsExact<Buildable<Error>, Error>>, Assert<IsExact<Buildable<RegExp>, RegExp>>, Assert<IsExact<Buildable<Map<string, boolean>>, Map<string, boolean>>>, Assert<IsExact<Buildable<ReadonlyMap<string, boolean>>, Map<string, boolean>>>, Assert<IsExact<Buildable<WeakMap<{ key: string }, boolean>>, WeakMap<{ key: string }, boolean>>>, Assert< IsExact<Buildable<WeakMap<{ key: string }, { value: boolean }>>, WeakMap<{ key?: string }, { value?: boolean }>> >, Assert<IsExact<Buildable<Set<string>>, Set<string>>>, Assert<IsExact<Buildable<ReadonlySet<string>>, Set<string>>>, Assert<IsExact<Buildable<readonly []>, []>>, Assert<IsExact<Buildable<readonly [1, 2, 3]>, [(1 | undefined)?, (2 | undefined)?, (3 | undefined)?]>>, Assert<IsExact<Buildable<readonly number[]>, (number | undefined)[]>>, Assert<IsExact<Buildable<ReadonlyArray<number>>, Array<number | undefined>>>, Assert<IsExact<Buildable<Promise<number>>, Promise<number>>>, Assert<IsExact<Buildable<{ readonly a: 1; readonly b: 2; readonly c: 3 }>, { a?: 1; b?: 2; c?: 3 }>>, Assert<IsExact<Buildable<{ foo: () => void }>, { foo?: () => void }>>, Assert< IsExact< Buildable<{ readonly obj: unknown; readonly arr: readonly unknown[] }>, { obj?: unknown | undefined; arr?: unknown[] | undefined; } > >, Assert<IsExact<Buildable<DeepReadonly<ComplexNestedRequired>>, ComplexNestedPartial>>, Assert<IsExact<Buildable<ComplexNestedRequired>, ComplexNestedPartial>>, Assert<IsExact<Buildable<ComplexNestedReadonly>, ComplexNestedPartial>>, ]; } function testOmitProperties() { type cases = [ Assert<IsExact<OmitProperties<{}, never>, {}>>, Assert<IsExact<OmitProperties<{ a: 1 }, never>, { a: 1 }>>, Assert<IsExact<OmitProperties<{ a?: 1 }, never>, { a?: 1 }>>, Assert<IsExact<OmitProperties<{ a: 1; b?: "2"; c: false }, number>, { b?: "2"; c: false }>>, Assert<IsExact<OmitProperties<{ a: 1; b?: "2"; c: false }, number | undefined>, { b?: "2"; c: false }>>, Assert<IsExact<OmitProperties<{ a: 1; b?: "2"; c: false }, string>, { a: 1; b?: "2"; c: false }>>, Assert<IsExact<OmitProperties<{ a: 1; b?: "2"; c: false }, string | undefined>, { a: 1; c: false }>>, Assert<IsExact<OmitProperties<{ a: 1; b?: "2"; c: false }, boolean>, { a: 1; b?: "2" }>>, Assert<IsExact<OmitProperties<{ a: 1; b?: "2"; c: false }, boolean | undefined>, { a: 1; b?: "2" }>>, Assert<IsExact<OmitProperties<{ a: 1; b?: "2"; c: false }, undefined>, { a: 1; b?: "2"; c: false }>>, Assert<IsExact<OmitProperties<{ a: 1; b?: "2"; c: false }, boolean | string>, { a: 1; b?: "2" }>>, Assert<IsExact<OmitProperties<{ a: 1; b?: "2"; c: false }, number | boolean>, { b?: "2" }>>, Assert<IsExact<OmitProperties<{ a: 1; b?: "2"; c: false }, number | string>, { b?: "2"; c: false }>>, Assert<IsExact<OmitProperties<{ a: string; b: number[] }, any[]>, { a: string }>>, Assert<IsExact<OmitProperties<{ a: string; b: number }, any[]>, { a: string; b: number }>>, ]; } function testPickProperties() { type cases = [ Assert<IsExact<PickProperties<{}, never>, {}>>, Assert<IsExact<PickProperties<{ a: 1 }, never>, {}>>, Assert<IsExact<PickProperties<{ a?: 1 }, never>, {}>>, Assert<IsExact<PickProperties<{ a: 1; b?: "2"; c: false }, number>, { a: 1 }>>, Assert<IsExact<PickProperties<{ a: 1; b?: "2"; c: false }, number | undefined>, { a: 1 }>>, Assert<IsExact<PickProperties<{ a: 1; b?: "2"; c: false }, string>, {}>>, Assert<IsExact<PickProperties<{ a: 1; b?: "2"; c: false }, string | undefined>, { b?: "2" }>>, Assert<IsExact<PickProperties<{ a: 1; b?: "2"; c: false }, boolean>, { c: false }>>, Assert<IsExact<PickProperties<{ a: 1; b?: "2"; c: false }, boolean | undefined>, { c: false }>>, Assert<IsExact<PickProperties<{ a: 1; b?: "2"; c: false }, undefined>, {}>>, Assert<IsExact<PickProperties<{ a: 1; b?: "2"; c: false }, boolean | string>, { c: false }>>, Assert<IsExact<PickProperties<{ a: 1; b?: "2"; c: false }, number | boolean>, { a: 1; c: false }>>, Assert<IsExact<PickProperties<{ a: 1; b?: "2"; c: false }, number | string>, { a: 1 }>>, Assert<IsExact<PickProperties<{ a: string; b: number[] }, any[]>, { b: number[] }>>, Assert<IsExact<PickProperties<{ a: string; b: number }, any[]>, {}>>, ]; } function testOptionalKeys() { type cases = [ // @ts-expect-error converts to Number and gets its optional keys Assert<IsExact<OptionalKeys<number>, never>>, // @ts-expect-error converts to String and gets its optional keys Assert<IsExact<OptionalKeys<string>, never>>, // wtf? Assert<IsExact<OptionalKeys<boolean>, () => boolean>>, // @ts-expect-error converts to BigInt and gets its optional keys Assert<IsExact<OptionalKeys<bigint>, never>>, // wtf? Assert< IsExact< OptionalKeys<symbol>, TsVersion extends "4.1" | "4.2" ? (() => string) | (() => symbol) : string | ((hint: string) => symbol) | (() => string) | (() => symbol) > >, Assert<IsExact<OptionalKeys<undefined>, never>>, Assert<IsExact<OptionalKeys<null>, never>>, Assert<IsExact<OptionalKeys<Function>, never>>, Assert<IsExact<OptionalKeys<Date>, never>>, Assert<IsExact<OptionalKeys<Error>, "stack">>, Assert<IsExact<OptionalKeys<RegExp>, never>>, Assert<IsExact<OptionalKeys<{}>, never>>, Assert<IsExact<OptionalKeys<{ a: 1 }>, never>>, Assert<IsExact<OptionalKeys<{ a?: 1 }>, "a">>, Assert<IsExact<OptionalKeys<{ a: 1 | undefined }>, never>>, Assert<IsExact<OptionalKeys<{ a: 1 | null }>, never>>, Assert<IsExact<OptionalKeys<{ a?: 1 } | { b: 2 }>, "a">>, Assert<IsExact<OptionalKeys<{ a?: 1 } | { b?: 2 }>, "a" | "b">>, Assert<IsExact<OptionalKeys<{ a?: 1 } | { b: 2 | undefined }>, "a">>, Assert<IsExact<OptionalKeys<{ a?: 1 } | { b: 2 | null }>, "a">>, Assert<IsExact<OptionalKeys<{ a: 1 } | { b: 2 }>, never>>, Assert<IsExact<OptionalKeys<{ a: 1 } | { b?: 2 }>, "b">>, Assert<IsExact<OptionalKeys<{ a: 1 } | { b: 2 | undefined }>, never>>, Assert<IsExact<OptionalKeys<{ a: 1 } | { b: 2 | null }>, never>>, ]; } function testRequiredKeys() { type cases = [ Assert<IsExact<RequiredKeys<number>, keyof Number>>, Assert<IsExact<RequiredKeys<string>, TsVersion extends "4.1" | "4.2" ? never : SymbolConstructor["iterator"]>>, Assert<IsExact<RequiredKeys<boolean>, keyof Boolean>>, Assert<IsExact<RequiredKeys<bigint>, keyof BigInt>>, Assert< IsExact< RequiredKeys<symbol>, TsVersion extends "4.1" | "4.2" ? "toString" | "valueOf" : typeof Symbol.toPrimitive | typeof Symbol.toStringTag > >, Assert<IsExact<RequiredKeys<undefined>, never>>, Assert<IsExact<RequiredKeys<null>, never>>, Assert<IsExact<RequiredKeys<Function>, keyof Function>>, Assert<IsExact<RequiredKeys<Date>, keyof Date>>, Assert<IsExact<RequiredKeys<Error>, "name" | "message">>, Assert<IsExact<RequiredKeys<RegExp>, keyof RegExp>>, Assert<IsExact<RequiredKeys<{}>, never>>, Assert<IsExact<RequiredKeys<{ a: 1 }>, "a">>, Assert<IsExact<RequiredKeys<{ a?: 1 }>, never>>, Assert<IsExact<RequiredKeys<{ a: 1 | undefined }>, "a">>, Assert<IsExact<RequiredKeys<{ a: 1 | null }>, "a">>, Assert<IsExact<RequiredKeys<{ a?: 1 } | { b: 2 }>, "b">>, Assert<IsExact<RequiredKeys<{ a?: 1 } | { b?: 2 }>, never>>, Assert<IsExact<RequiredKeys<{ a?: 1 } | { b: 2 | undefined }>, "b">>, Assert<IsExact<RequiredKeys<{ a?: 1 } | { b: 2 | null }>, "b">>, Assert<IsExact<RequiredKeys<{ a: 1 } | { b: 2 }>, "a" | "b">>, Assert<IsExact<RequiredKeys<{ a: 1 } | { b?: 2 }>, "a">>, Assert<IsExact<RequiredKeys<{ a: 1 } | { b: 2 | undefined }>, "a" | "b">>, Assert<IsExact<RequiredKeys<{ a: 1 } | { b: 2 | null }>, "a" | "b">>, ]; } function testTupleInference() { type Expected = [number, string]; function returnTuple<T extends Tuple>(tuple: T) { return tuple; } const ret = returnTuple([1, "s"]); type Test = Assert<IsExact<typeof ret, Expected>>; } function testParametrizedTuple() { function acceptsCertainTuple<T extends Tuple<number | string>>(tuple: T) { return tuple; } acceptsCertainTuple([42, "foo"]); } function testNonNever() { type TypesMap = { foo: string; bar: number; xyz: undefined }; type Mapped = { [K in keyof TypesMap]: TypesMap[K] extends undefined ? never : TypesMap[K]; }; type TestA = Assert<IsExact<keyof Mapped, "foo" | "bar" | "xyz">>; type TestB = Assert<IsExact<keyof NonNever<Mapped>, "foo" | "bar">>; } function testNonEmptyObject() { type ObjectWithKeys = { foo: string; bar: number; xyz: undefined }; type EmptyObject = {}; type TestA = Assert<IsExact<NonEmptyObject<ObjectWithKeys>, ObjectWithKeys>>; type TestB = Assert<IsExact<NonEmptyObject<EmptyObject>, never>>; } function testNonEmptyArray() { type Cases<T> = [ Assert<IsExact<NonEmptyArray<T>, [T, ...T[]]>>, AssertFalse<IsExact<NonEmptyArray<T>, []>>, AssertFalse<Assignable<NonEmptyArray<T>, []>>, Assert<Assignable<NonEmptyArray<T>, [T]>>, Assert<Assignable<NonEmptyArray<T>, [T, ...T[]]>>, ]; } function testMarkOptional() { type TestType = { required1: number; required2: string; optional1?: null; optional2?: boolean; }; type ExpectedType = { required1?: number; required2: string; optional1?: null; optional2?: boolean; }; type Test = Assert<IsExact<MarkOptional<TestType, "required1">, ExpectedType>>; } function testMerge() { type cases = [ Assert<IsExact<Merge<{}, { a: string }>, { a: string }>>, Assert<IsExact<Merge<{ a: string }, {}>, { a: string }>>, Assert<IsExact<Merge<{ a: number; b: string }, { a: string }>, { a: string; b: string }>>, ]; } function testMergeN() { type cases = [ Assert<IsExact<MergeN<[{ a: number; b: string; c: boolean }]>, { a: number; b: string; c: boolean }>>, Assert< IsExact< MergeN<[{ a: number; b: string; c: boolean }, { b: number; c: string; d: boolean }]>, { a: number; b: number; c: string; d: boolean } > >, Assert<IsExact<MergeN<[{ a: number }, { a: string }, { a: boolean }]>, { a: boolean }>>, ]; } function testReadonlyKeys() { type T = { readonly a: number; b: string }; type Actual = ReadonlyKeys<T>; type Expected = "a"; type Test = Assert<IsExact<Actual, Expected>>; } function testWritableKeys() { type T = { readonly a: number; b: string }; type Actual = WritableKeys<T>; type Expected = "b"; type Test = Assert<IsExact<Actual, Expected>>; } function testAssert() { type TestType1 = string | undefined; type Expected = string; const anything = undefined as any as TestType1; assert(anything); type Actual = typeof anything; type Test = Assert<IsExact<Actual, string>>; } function testXOR() { type TestType1 = { a: string }; type TestType2 = { a: number; b: boolean }; type TestType3 = { c: number; d: boolean }; type Actual1 = XOR<TestType1, TestType2>; type Expected1 = { a: string; b?: never } | { a: number; b: boolean }; type Actual2 = XOR<TestType1, TestType3>; type Expected2 = { a: string; c?: never; d?: never } | { a?: never; c: number; d: boolean }; type Test1 = Assert<IsExact<Actual1, Expected1>>; type Test2 = Assert<IsExact<Actual2, Expected2>>; } function testNoop() { const x: void = noop(); const y: void = noop(false, 0, "", {}, [], null, undefined, Promise.resolve(), new Error(), noop); const z: Promise<void> = Promise.resolve("foo").then(noop); const callback: (_: number) => void = noop; } function testHeadTail() { type List1 = [number, string, boolean, "a" | "b"]; type TestHead = Assert<IsExact<Head<List1>, number>>; type TestHeadOnEmpty = Assert<IsExact<Head<[]>, never>>; type TestTail = Assert<IsExact<Tail<List1>, [string, boolean, "a" | "b"]>>; type TestTailOnEmpty = Assert<IsExact<Tail<[]>, never>>; type TestTailOn1Elem = Assert<IsExact<Tail<[number]>, []>>; } function testExact() { type ABC = { a: number; b: number; c: number }; type BC = { b: number; c: number }; type C = { c: number }; type a1 = Assert<IsExact<Exact<ABC, C>, never>>; type a2 = Assert<IsExact<Exact<BC, C>, never>>; type a3 = Assert<IsExact<Exact<C, C>, C>>; } function testElementOf() { const t1 = [1, 2, true, false]; type a1 = Assert<IsExact<ElementOf<typeof t1>, number | boolean>>; const t2 = ["one"] as const; type a2 = Assert<IsExact<ElementOf<typeof t2>, "one">>; } // T = U type Assignable<T, U> = U extends T ? true : false; function testOpaque() { type t1 = Assert<IsExact<Assignable<number, Opaque<number, "a">>, true>>; type t2 = Assert<IsExact<Assignable<Opaque<number, "a">, number>, false>>; type t3 = Assert<IsExact<Assignable<Opaque<number, "a">, Opaque<number, "b">>, false>>; type t4 = Assert<IsExact<Assignable<Opaque<number, "a">, Opaque<number, "a">>, true>>; type t5 = Assert<IsExact<Opaque<"a", string>, never>>; // should blow on mismatched order } function testAsyncOrSyncType() { type t1 = Assert<IsExact<AsyncOrSyncType<AsyncOrSync<number>>, number>>; } function testAwaitedType() { type t1 = Assert<IsExact<Awaited<Promise<number>>, number>>; } function testNewable() { class TestCls { constructor(arg1: string) {} } const t1: Newable<any> = TestCls; } function testIsTuple() { type cases = [ Assert<IsExact<IsTuple<string>, never>>, Assert<IsExact<IsTuple<number>, never>>, Assert<IsExact<IsTuple<boolean>, never>>, Assert<IsExact<IsTuple<undefined>, never>>, Assert<IsExact<IsTuple<null>, never>>, Assert<IsExact<IsTuple<{ a: 1 }>, never>>, Assert<IsExact<IsTuple<[1]>, [1]>>, Assert<IsExact<IsTuple<[1, 2]>, [1, 2]>>, Assert<IsExact<IsTuple<[1, 2, 3]>, [1, 2, 3]>>, Assert<IsExact<IsTuple<[1, 2, 3, 4]>, [1, 2, 3, 4]>>, Assert<IsExact<IsTuple<[1, 2, 3, 4, 5]>, [1, 2, 3, 4, 5]>>, Assert<IsExact<IsTuple<[1, 2, 3, 4, 5, 6]>, [1, 2, 3, 4, 5, 6]>>, Assert<IsExact<IsTuple<[1, 2, 3, 4, 5, 6, 7]>, [1, 2, 3, 4, 5, 6, 7]>>, Assert<IsExact<IsTuple<[1, 2, 3, 4, 5, 6, 7, 8]>, [1, 2, 3, 4, 5, 6, 7, 8]>>, Assert<IsExact<IsTuple<[1, 2, 3, 4, 5, 6, 7, 8, 9]>, [1, 2, 3, 4, 5, 6, 7, 8, 9]>>, Assert<IsExact<IsTuple<[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]>>, Assert<IsExact<IsTuple<readonly number[]>, never>>, Assert<IsExact<IsTuple<{ length: 3 }>, never>>, ]; } function testIsExact() { type ABC = { a: number; b: number; c: number }; type BC = { b: number; c: number }; type BC2 = { b: number; c: string }; type C = { c: number }; let abc: ABC = { a: 1, b: 2, c: 3 }; let abc2 = { a: 1, b: 2, c: 3 } as const; let bc: BC = { b: 2, c: 3 }; let bc2: BC2 = { b: 2, c: "3" }; let bc3 = { b: 2, c: 3 } as const; let bc4 = { b: 2, c: "3" } as const; let c: C = { c: 3 }; let c2 = { c: 3 } as const; const isBC = isExact<BC>(); // @ts-expect-error has different structure from BC (excessive property a) isBC(abc); // @ts-expect-error has different structure from BC (excessive property a) isBC(abc2); // has the same structure as BC isBC(bc); // @ts-expect-error has different structure from BC (c has different type) isBC(bc2); // has the same structure as BC isBC(bc3); // @ts-expect-error has different structure from BC (c has different type) isBC(bc4); // @ts-expect-error has different structure from BC (missing property b) isBC(c); // @ts-expect-error has different structure from BC (missing property b) isBC(c2); } function testIsUnknown() { type cases = [ Assert<IsExact<IsUnknown<string>, false>>, Assert<IsExact<IsUnknown<number>, false>>, Assert<IsExact<IsUnknown<boolean>, false>>, Assert<IsExact<IsUnknown<bigint>, false>>, Assert<IsExact<IsUnknown<symbol>, false>>, Assert<IsExact<IsUnknown<undefined>, false>>, Assert<IsExact<IsUnknown<null>, false>>, Assert<IsExact<IsUnknown<Function>, false>>, Assert<IsExact<IsUnknown<Date>, false>>, Assert<IsExact<IsUnknown<Error>, false>>, Assert<IsExact<IsUnknown<RegExp>, false>>, Assert<IsExact<IsUnknown<Map<string, unknown>>, false>>, Assert<IsExact<IsUnknown<ReadonlyMap<string, unknown>>, false>>, Assert<IsExact<IsUnknown<WeakMap<{ a: 1 }, unknown>>, false>>, Assert<IsExact<IsUnknown<Set<string>>, false>>, Assert<IsExact<IsUnknown<ReadonlySet<string>>, false>>, Assert<IsExact<IsUnknown<WeakSet<{ a: 1 }>>, false>>, Assert<IsExact<IsUnknown<{ a: 1 }>, false>>, Assert<IsExact<IsUnknown<[]>, false>>, Assert<IsExact<IsUnknown<[1]>, false>>, Assert<IsExact<IsUnknown<readonly [1]>, false>>, Assert<IsExact<IsUnknown<readonly number[]>, false>>, Assert<IsExact<IsUnknown<number[]>, false>>, Assert<IsExact<IsUnknown<Promise<number>>, false>>, Assert<IsExact<IsUnknown<unknown>, true>>, Assert<IsExact<IsUnknown<never>, false>>, Assert<IsExact<IsUnknown<any>, false>>, ]; } function testIsNever() { type cases = [ Assert<IsExact<IsNever<string>, false>>, Assert<IsExact<IsNever<number>, false>>, Assert<IsExact<IsNever<boolean>, false>>, Assert<IsExact<IsNever<bigint>, false>>, Assert<IsExact<IsNever<symbol>, false>>, Assert<IsExact<IsNever<undefined>, false>>, Assert<IsExact<IsNever<null>, false>>, Assert<IsExact<IsNever<Function>, false>>, Assert<IsExact<IsNever<Date>, false>>, Assert<IsExact<IsNever<Error>, false>>, Assert<IsExact<IsNever<RegExp>, false>>, Assert<IsExact<IsNever<Map<string, unknown>>, false>>, Assert<IsExact<IsNever<ReadonlyMap<string, unknown>>, false>>, Assert<IsExact<IsNever<WeakMap<{ a: 1 }, unknown>>, false>>, Assert<IsExact<IsNever<Set<string>>, false>>, Assert<IsExact<IsNever<ReadonlySet<string>>, false>>, Assert<IsExact<IsNever<WeakSet<{ a: 1 }>>, false>>, Assert<IsExact<IsNever<{ a: 1 }>, false>>, Assert<IsExact<IsNever<[]>, false>>, Assert<IsExact<IsNever<[1]>, false>>, Assert<IsExact<IsNever<readonly [1]>, false>>, Assert<IsExact<IsNever<readonly number[]>, false>>, Assert<IsExact<IsNever<number[]>, false>>, Assert<IsExact<IsNever<Promise<number>>, false>>, Assert<IsExact<IsNever<unknown>, false>>, Assert<IsExact<IsNever<never>, true>>, Assert<IsExact<IsNever<any>, false>>, ]; } function testArrayOrSingle() { const castArray = <T extends any>(value: ArrayOrSingle<T>): T[] => { if (Array.isArray(value)) { return value; } return [value]; }; const numbers1 = castArray(1); const numbers2 = castArray([1]); const strings1 = castArray("hello"); const strings2 = castArray(["hello"]); const booleans1 = castArray(false); const booleans2 = castArray([false]); const nulls1 = castArray(null); const nulls2 = castArray([null]); const undefined1 = castArray(undefined); const undefined2 = castArray([undefined]); type cases = [ Assert<IsExact<ArrayOrSingle<never>, never | never[]>>, Assert<IsExact<ArrayOrSingle<string>, string | string[]>>, Assert<IsExact<ArrayOrSingle<1>, 1 | 1[]>>, Assert<IsExact<ArrayOrSingle<"1">, "1" | "1"[]>>, Assert<IsExact<ArrayOrSingle<string | number>, string | number | (string | number)[]>>, Assert<IsExact<ArrayOrSingle<{ a: number }>, { a: number } | { a: number }[]>>, Assert<IsExact<typeof numbers1, number[]>>, Assert<IsExact<typeof numbers2, number[]>>, Assert<IsExact<typeof strings1, string[]>>, Assert<IsExact<typeof strings2, string[]>>, Assert<IsExact<typeof booleans1, boolean[]>>, Assert<IsExact<typeof booleans2, boolean[]>>, Assert<IsExact<typeof nulls1, null[]>>, Assert<IsExact<typeof nulls2, null[]>>, Assert<IsExact<typeof undefined1, undefined[]>>, Assert<IsExact<typeof undefined2, undefined[]>>, ]; } function testIsAny() { type cases = [ Assert<IsExact<IsAny<string>, false>>, Assert<IsExact<IsAny<number>, false>>, Assert<IsExact<IsAny<boolean>, false>>, Assert<IsExact<IsAny<bigint>, false>>, Assert<IsExact<IsAny<symbol>, false>>, Assert<IsExact<IsAny<undefined>, false>>, Assert<IsExact<IsAny<null>, false>>, Assert<IsExact<IsAny<Function>, false>>, Assert<IsExact<IsAny<Date>, false>>, Assert<IsExact<IsAny<Error>, false>>, Assert<IsExact<IsAny<RegExp>, false>>, Assert<IsExact<IsAny<Map<string, unknown>>, false>>, Assert<IsExact<IsAny<ReadonlyMap<string, unknown>>, false>>, Assert<IsExact<IsAny<WeakMap<{ a: 1 }, unknown>>, false>>, Assert<IsExact<IsAny<Set<string>>, false>>, Assert<IsExact<IsAny<ReadonlySet<string>>, false>>, Assert<IsExact<IsAny<WeakSet<{ a: 1 }>>, false>>, Assert<IsExact<IsAny<{ a: 1 }>, false>>, Assert<IsExact<IsAny<[]>, false>>, Assert<IsExact<IsAny<[1]>, false>>, Assert<IsExact<IsAny<readonly [1]>, false>>, Assert<IsExact<IsAny<readonly number[]>, false>>, Assert<IsExact<IsAny<number[]>, false>>, Assert<IsExact<IsAny<Promise<number>>, false>>, Assert<IsExact<IsAny<unknown>, false>>, Assert<IsExact<IsAny<never>, false>>, Assert<IsExact<IsAny<any>, true>>, ]; }
the_stack
import React, { useState, useEffect, useRef, Fragment } from 'react'; import { jsx, keyframes } from '@emotion/core'; import { BotIndexer } from '@bfc/indexers'; import { useRecoilValue } from 'recoil'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { TooltipHost } from 'office-ui-fabric-react/lib/Tooltip'; import { Icon } from 'office-ui-fabric-react/lib/Icon'; import formatMessage from 'format-message'; import get from 'lodash/get'; import { css } from '@emotion/core'; import { FontSizes } from 'office-ui-fabric-react/lib/Styling'; import { NeutralColors, SharedColors } from '@uifabric/fluent-theme'; import { PrimaryButton } from 'office-ui-fabric-react/lib/Button'; import { Link } from 'office-ui-fabric-react/lib/Link'; import { MessageBar, MessageBarType } from 'office-ui-fabric-react/lib/MessageBar'; import { dispatcherState, settingsState, luFilesSelectorFamily, qnaFilesSelectorFamily, botDisplayNameState, dialogsWithLuProviderSelectorFamily, } from '../../recoilModel'; import settingStorage from '../../utils/dialogSettingStorage'; import { rootBotProjectIdSelector } from '../../recoilModel/selectors/project'; import { mergePropertiesManagedByRootBot } from '../../recoilModel/dispatchers/utils/project'; import { LUIS_REGIONS } from '../../constants'; import { ManageLuis } from '../../components/ManageLuis/ManageLuis'; import { ManageQNA } from '../../components/ManageQNA/ManageQNA'; import { inputFieldStyles, subtext, title } from './styles'; // -------------------- Styles -------------------- // const labelContainer = css` display: flex; flex-direction: row; `; const customerLabel = css` font-size: ${FontSizes.small}; margin-right: 5px; `; const unknownIconStyle = (required) => { return { root: { selectors: { '&::before': { content: required ? " '*'" : '', color: SharedColors.red10, paddingRight: 3, }, }, }, }; }; const externalServiceContainerStyle = css` display: flex; flex-direction: column; `; const errorContainer = css` display: flex; width: 100%; height: 48px; line-height: 48px; background: #fed9cc; color: ${NeutralColors.black}; `; const errorIcon = { root: { color: '#A80000', marginRight: 8, paddingLeft: 12, fontSize: FontSizes.mediumPlus, }, }; const errorTextStyle = css` margin-bottom: 5px; `; const fadeIn = keyframes` from { transform: translate3d(0,-10px,0) } to { translate3d(0,0,0) } `; const luisRegionErrorContainerStyle = css` display: flex; width: 100%; height: 48px; background: #fed9cc; color: ${NeutralColors.black}; line-height: 48px; font-size: ${FontSizes.small}; margin-top: 5px; animation-fill-mode: both; animation-duration: 0.367s; animation-timing-function: cubic-bezier(0.1, 0.9, 0.2, 1); animation-name: ${fadeIn}; `; const luisRegionErrorTextStyle = css` margin-bottom: 5px; `; // -------------------- ExternalService -------------------- // type RootBotExternalServiceProps = { projectId: string; scrollToSectionId?: string; }; const onRenderLabel = (props) => { return ( <div css={labelContainer}> <div css={customerLabel}> {props.label} </div> <TooltipHost content={props.label}> <Icon iconName="Unknown" styles={unknownIconStyle(props.required)} /> </TooltipHost> </div> ); }; const errorElement = (errorText: string) => { if (!errorText) return ''; return ( <span css={errorContainer}> <Icon iconName="ErrorBadge" styles={errorIcon} /> <span css={errorTextStyle}>{errorText}</span> </span> ); }; export const RootBotExternalService: React.FC<RootBotExternalServiceProps> = (props) => { const { projectId, scrollToSectionId = '' } = props; const { setSettings, setQnASettings } = useRecoilValue(dispatcherState); const rootBotProjectId = useRecoilValue(rootBotProjectIdSelector) || ''; const settings = useRecoilValue(settingsState(projectId)); const mergedSettings = mergePropertiesManagedByRootBot(projectId, rootBotProjectId, settings); const sensitiveGroupManageProperty = settingStorage.get(rootBotProjectId); const groupLUISAuthoringKey = get(sensitiveGroupManageProperty, 'luis.authoringKey', {}); const rootLuisKey = groupLUISAuthoringKey.root; const groupLUISEndpointKey = get(sensitiveGroupManageProperty, 'luis.endpointKey', {}); const rootLuisEndpointKey = groupLUISEndpointKey.root; const groupLUISRegion = get(sensitiveGroupManageProperty, 'luis.authoringRegion', {}); const rootLuisRegion = groupLUISRegion.root; const groupQnAKey = get(sensitiveGroupManageProperty, 'qna.subscriptionKey', {}); const rootqnaKey = groupQnAKey.root; const dialogs = useRecoilValue(dialogsWithLuProviderSelectorFamily(projectId)); const luFiles = useRecoilValue(luFilesSelectorFamily(projectId)); const qnaFiles = useRecoilValue(qnaFilesSelectorFamily(projectId)); const botName = useRecoilValue(botDisplayNameState(projectId)); const isLUISKeyNeeded = BotIndexer.shouldUseLuis(dialogs, luFiles); const isQnAKeyNeeded = BotIndexer.shouldUseQnA(dialogs, qnaFiles); const rootLuisName = get(settings, 'luis.name', '') || botName; const [luisKeyErrorMsg, setLuisKeyErrorMsg] = useState<string>(''); const [luisRegionErrorMsg, setLuisRegionErrorMsg] = useState<string>(''); const [qnaKeyErrorMsg, setQnAKeyErrorMsg] = useState<string>(''); const [localRootLuisKey, setLocalRootLuisKey] = useState<string>(rootLuisKey ?? ''); const [localRootQnAKey, setLocalRootQnAKey] = useState<string>(rootqnaKey ?? ''); const [localRootLuisRegion, setLocalRootLuisRegion] = useState<string>(rootLuisRegion ?? ''); const [localRootLuisName, setLocalRootLuisName] = useState<string>(rootLuisName ?? ''); const [displayManageLuis, setDisplayManageLuis] = useState<boolean>(false); const [displayManageQNA, setDisplayManageQNA] = useState<boolean>(false); const luisKeyFieldRef = useRef<HTMLDivElement>(null); const luisRegionFieldRef = useRef<HTMLDivElement>(null); const qnaKeyFieldRef = useRef<HTMLDivElement>(null); const linkToPublishProfile = `/bot/${rootBotProjectId}/publish/all#addNewPublishProfile`; const handleRootLUISKeyOnChange = (e, value) => { if (value) { setLuisKeyErrorMsg(''); setLocalRootLuisKey(value); } else { setLuisKeyErrorMsg( formatMessage('LUIS key is required with the current recognizer setting to start your bot locally, and publish') ); setLocalRootLuisKey(''); } }; const handleRootQnAKeyOnChange = (e, value) => { if (value) { setQnAKeyErrorMsg(''); setLocalRootQnAKey(value); } else { setQnAKeyErrorMsg(formatMessage('QnA Maker Subscription key is required to start your bot locally, and publish')); setLocalRootQnAKey(''); } }; const handleRootLuisRegionOnChange = (e, value: IDropdownOption | undefined) => { if (value != null) { setLuisRegionErrorMsg(''); setLocalRootLuisRegion(value.key as string); } else { setLuisRegionErrorMsg(formatMessage('LUIS region is required')); setLocalRootLuisRegion(''); } }; useEffect(() => { if (!localRootLuisKey) { setLuisKeyErrorMsg( formatMessage( 'LUIS authoring key is required with the current recognizer setting to start your bot locally, and publish' ) ); } else { setLuisKeyErrorMsg(''); } if (!localRootQnAKey) { setQnAKeyErrorMsg(formatMessage('QnA Maker Subscription key is required to start your bot locally, and publish')); } else { setQnAKeyErrorMsg(''); } if (isLUISKeyNeeded && !localRootLuisRegion) { setLuisRegionErrorMsg(formatMessage('LUIS region is required')); } else { setLuisRegionErrorMsg(''); } }, [projectId]); useEffect(() => { handleRootLUISKeyOnChange(null, rootLuisKey); }, [rootLuisKey]); useEffect(() => { handleRootQnAKeyOnChange(null, rootqnaKey); }, [rootqnaKey]); useEffect(() => { handleRootLuisRegionOnChange(null, { key: rootLuisRegion, text: '' }); }, [rootLuisRegion]); useEffect(() => { if (luisKeyFieldRef.current && scrollToSectionId === '#luisKey') { luisKeyFieldRef.current.scrollIntoView({ behavior: 'smooth' }); } if (luisRegionFieldRef.current && scrollToSectionId === '#luisRegion') { luisRegionFieldRef.current.scrollIntoView({ behavior: 'smooth' }); } if (qnaKeyFieldRef.current && scrollToSectionId === '#qnaKey') { qnaKeyFieldRef.current.scrollIntoView({ behavior: 'smooth' }); } }, [scrollToSectionId]); const handleRootLUISNameOnChange = (e, value) => { setLocalRootLuisName(value); }; const handleRootLUISNameOnBlur = () => { setSettings(projectId, { ...mergedSettings, luis: { ...mergedSettings.luis, name: localRootLuisName }, }); }; const handleRootLuisRegionOnBlur = () => { if (isLUISKeyNeeded && !localRootLuisRegion) { setLuisRegionErrorMsg(formatMessage('LUIS region is required')); } setSettings(projectId, { ...mergedSettings, luis: { ...mergedSettings.luis, authoringRegion: localRootLuisRegion }, }); }; const handleRootLuisAuthoringKeyOnBlur = () => { if (!localRootLuisKey) { setLuisKeyErrorMsg( formatMessage('LUIS key is required with the current recognizer setting to start your bot locally, and publish') ); } setSettings(projectId, { ...mergedSettings, luis: { ...mergedSettings.luis, authoringKey: localRootLuisKey }, }); }; const handleRootQnAKeyOnBlur = () => { if (!localRootQnAKey) { setQnAKeyErrorMsg(formatMessage('QnA Maker Subscription key is required to start your bot locally, and publish')); } submitQnASubscripionKey(localRootQnAKey); }; const submitQnASubscripionKey = (key: string) => { if (key) { setSettings(projectId, { ...mergedSettings, qna: { ...mergedSettings.qna, subscriptionKey: key }, }); setQnASettings(projectId, key); } else { setSettings(projectId, { ...mergedSettings, qna: { ...mergedSettings.qna, subscriptionKey: '', endpointKey: '' }, }); } }; const updateLuisSettings = (newLuisSettings) => { setSettings(projectId, { ...mergedSettings, luis: { ...mergedSettings.luis, authoringKey: newLuisSettings.key, authoringRegion: newLuisSettings.region }, }); }; const updateQNASettings = (newQNASettings) => { setSettings(projectId, { ...mergedSettings, qna: { ...mergedSettings.qna, subscriptionKey: newQNASettings.key }, }); setQnASettings(projectId, newQNASettings.key); }; return ( <Fragment> <div css={title}>{formatMessage('Azure Language Understanding')}</div> <div css={subtext}> {formatMessage.rich( 'Language Understanding (LUIS) is an Azure Cognitive Service that uses machine learning to understand natural language input and direct the conversation flow. <a>Learn more.</a> Use an existing Language Understanding (LUIS) key from Azure or create a new key. <a2>Learn more</a2>', { a: ({ children }) => ( <Link key="luis-root-bot-settings-page" href={'https://www.luis.ai/'} target="_blank"> {children} </Link> ), a2: ({ children }) => ( <Link key="luis-root-bot-settings-page-learn-more" href={'https://aka.ms/composer-luis-learnmore'} target="_blank" > {children} </Link> ), } )} </div> <div css={externalServiceContainerStyle}> <TextField ariaLabel={formatMessage('Application name')} data-testid={'rootLUISApplicationName'} id={'luisName'} label={formatMessage('Application name')} placeholder={formatMessage('Type application name')} styles={inputFieldStyles} value={localRootLuisName} onBlur={handleRootLUISNameOnBlur} onChange={handleRootLUISNameOnChange} onRenderLabel={onRenderLabel} /> <div ref={luisKeyFieldRef}> <TextField ariaLabel={formatMessage('Language Understanding authoring key')} data-testid={'rootLUISAuthoringKey'} errorMessage={isLUISKeyNeeded ? errorElement(luisKeyErrorMsg) : ''} id={'luisAuthoringKey'} label={formatMessage('Language Understanding authoring key')} placeholder={formatMessage('Type Language Understanding authoring key')} required={isLUISKeyNeeded} styles={inputFieldStyles} value={localRootLuisKey} onBlur={handleRootLuisAuthoringKeyOnBlur} onChange={handleRootLUISKeyOnChange} onRenderLabel={onRenderLabel} /> </div> <div ref={luisRegionFieldRef}> <Dropdown ariaLabel={formatMessage('Language Understanding region')} data-testid={'rootLUISRegion'} id={'luisRegion'} label={formatMessage('Language Understanding region')} options={LUIS_REGIONS} placeholder={formatMessage('Select region')} required={isLUISKeyNeeded} selectedKey={localRootLuisRegion} styles={inputFieldStyles} onBlur={handleRootLuisRegionOnBlur} onChange={handleRootLuisRegionOnChange} onRenderLabel={onRenderLabel} /> {luisRegionErrorMsg && ( <div css={luisRegionErrorContainerStyle}> <Icon iconName="ErrorBadge" styles={errorIcon} /> <div css={luisRegionErrorTextStyle}>{luisRegionErrorMsg}</div> </div> )} </div> <PrimaryButton disabled={displayManageLuis || displayManageQNA} styles={{ root: { width: '250px', marginTop: '15px' } }} text={formatMessage('Set up Language Understanding')} onClick={() => { setDisplayManageLuis(true); }} /> {localRootLuisKey && !rootLuisEndpointKey && ( <MessageBar messageBarType={MessageBarType.info} styles={{ root: { width: '75%', marginTop: 20 } }}> {formatMessage.rich( 'Your bot is configured with only a LUIS authoring key, which has a limit of 1,000 calls per month. If your bot hits this limit, publish it to Azure using a <a>publishing profile</a> to continue testing.<a2>Learn more</a2>', { a: ({ children }) => ( <Link key="luis-endpoint-key-info" href={linkToPublishProfile}> {children} </Link> ), a2: ({ children }) => ( <Link key="luis-endpoint-key-limits-info" href={'https://aka.ms/composer-settings-luislimits'} target="_blank" > {children} </Link> ), } )} </MessageBar> )} <div css={title}>{formatMessage('Azure QnA Maker')}</div> <div css={subtext}> {formatMessage.rich( 'QnA Maker is an Azure Cognitive services that can extract question-and-answer pairs from a website FAQ. <a>Learn more.</a> Use an existing key from Azure or create a new key. <a2>Learn more.</a2>', { a: ({ children }) => ( <Link key="qna-root-bot-settings-page" href={'https://www.qnamaker.ai/'} target="_blank"> {children} </Link> ), a2: ({ children }) => ( <Link key="qna-root-bot-settings-page-learn-more" href={'https://aka.ms/composer-addqnamaker-learnmore'} target="_blank" > {children} </Link> ), } )} </div> <div ref={qnaKeyFieldRef}> <TextField ariaLabel={formatMessage('QnA Maker Subscription key')} data-testid={'QnASubscriptionKey'} errorMessage={isQnAKeyNeeded ? errorElement(qnaKeyErrorMsg) : ''} id={'qnaKey'} label={formatMessage('QnA Maker Subscription key')} placeholder={formatMessage('Type subscription key')} required={isQnAKeyNeeded} styles={inputFieldStyles} value={localRootQnAKey} onBlur={handleRootQnAKeyOnBlur} onChange={handleRootQnAKeyOnChange} onRenderLabel={onRenderLabel} /> </div> <PrimaryButton disabled={displayManageLuis || displayManageQNA} styles={{ root: { width: '250px', marginTop: '15px' } }} text={formatMessage('Set up QnA Maker')} onClick={() => { setDisplayManageQNA(true); }} /> <ManageLuis hidden={!displayManageLuis} onDismiss={() => { setDisplayManageLuis(false); }} onGetKey={updateLuisSettings} onNext={() => { setDisplayManageLuis(false); }} onToggleVisibility={setDisplayManageLuis} /> <ManageQNA hidden={!displayManageQNA} onDismiss={() => { setDisplayManageQNA(false); }} onGetKey={updateQNASettings} onNext={() => { setDisplayManageQNA(false); }} onToggleVisibility={setDisplayManageQNA} /> </div> </Fragment> ); };
the_stack
import * as _ from 'lodash'; import { Kubectl } from "../kubectl"; import { KUBERNETES_SCHEMA_ENUM_FILE, FALLBACK_SCHEMA_FILE, KUBERNETES_GROUP_VERSION_KIND } from "./yaml-constant"; import { formatComplex, formatOne, formatType } from '../schema-formatting'; import * as swagger from '../components/swagger/swagger'; import { succeeded } from '../errorable'; import * as util from "./yaml-util"; interface KubernetesSchema { readonly name: string; readonly description?: string; readonly id?: string; readonly apiVersion?: string; readonly kind?: string; readonly 'x-kubernetes-group-version-kind'?: any[]; properties?: { [key: string]: any }; } export class KubernetesClusterSchemaHolder { private definitions: { [key: string]: KubernetesSchema } = {}; private schemaEnums: { [key: string]: { [key: string]: [string[]] } }; private crdSchemas: { [key: string]: object | undefined}; public static async fromActiveCluster(kubectl: Kubectl): Promise<KubernetesClusterSchemaHolder> { const holder = new KubernetesClusterSchemaHolder(); await holder.loadSchemaFromActiveCluster(kubectl, KUBERNETES_SCHEMA_ENUM_FILE()); return holder; } public static fallback(): KubernetesClusterSchemaHolder { const holder = new KubernetesClusterSchemaHolder(); const fallbackSchema = util.loadJson(FALLBACK_SCHEMA_FILE()); holder.loadSchemaFromRaw(fallbackSchema, KUBERNETES_SCHEMA_ENUM_FILE(), undefined); return holder; } private async loadSchemaFromActiveCluster(kubectl: Kubectl, schemaEnumFile?: string): Promise<void> { const clusterSwagger = await swagger.getClusterSwagger(kubectl); const crdSchemas = await swagger.getCrdSchemas(kubectl); if (crdSchemas) { this.crdSchemas = crdSchemas; } const schemaRaw = succeeded(clusterSwagger) ? this.definitionsObject(clusterSwagger.result) : util.loadJson(FALLBACK_SCHEMA_FILE()); this.loadSchemaFromRaw(schemaRaw, schemaEnumFile, kubectl); } private definitionsObject(swagger: any): any { return { definitions: swagger.definitions }; } private loadSchemaFromRaw(schemaRaw: any, schemaEnumFile?: string, kubectl?: Kubectl): void { this.schemaEnums = schemaEnumFile ? util.loadJson(schemaEnumFile) : {}; const definitions = schemaRaw.definitions; makeSafeIntOrString(definitions); for (const name of Object.keys(definitions)) { this.saveSchemaWithManifestStyleKeys(name, definitions[name]); } for (const schema of _.values(this.definitions) ) { if (kubectl && this.crdSchemas && schema.id && schema.id.toLowerCase() in this.crdSchemas) { const crdProperties = this.crdSchemas[schema.id.toLowerCase()]; if (crdProperties) { schema.properties = crdProperties; } } if (schema.properties) { // the swagger schema has very short description on properties, we need to get the actual type of // the property and provide more description/properties details, just like `kubernetes explain` do. _.each(schema.properties, (propVal, propKey) => { if (schema.kind && propKey === 'kind') { propVal.markdownDescription = this.getMarkdownDescription(schema.kind, undefined, schema, true); return; } const currentPropertyTypeRef = propVal.$ref || (propVal.items ? propVal.items.$ref : undefined); if (_.isString(currentPropertyTypeRef)) { const id = getNameInDefinitions(currentPropertyTypeRef); const propSchema = this.lookup(id); if (propSchema) { propVal.markdownDescription = this.getMarkdownDescription(propKey, propVal, propSchema); } } else { propVal.markdownDescription = this.getMarkdownDescription(propKey, propVal, undefined); } }); // fix on each node in properties for $ref since it will directly reference '#/definitions/...' // we need to convert it into schema like 'kubernetes://schema/...' // we need also an array to collect them since we need to get schema from _definitions, at this point, we have // not finished the process of add schemas to _definitions, call patchOnRef will fail for some cases. this.replaceDefinitionRefsWithYamlSchemaUris(schema.properties); this.loadEnumsForKubernetesSchema(schema); } } } // get kubernetes schema by the key public lookup(key: string): KubernetesSchema | undefined { return key ? this.definitions[key.toLowerCase()] : undefined; } /** * Save the schema object in swagger json to schema map. * * @param {string} name the property name in definition node of swagger json * @param originalSchema the origin schema object in swagger json */ private saveSchemaWithManifestStyleKeys(name: string, originalSchema: any): void { if (isGroupVersionKindStyle(originalSchema)) { // if the schema contains 'x-kubernetes-group-version-kind'. then it is a direct kubernetes manifest, getManifestStyleSchemas(originalSchema).forEach((schema: KubernetesSchema) => { this.saveSchema({ ...schema, name }); }); } else { // if x-kubernetes-group-version-kind cannot be found, then it is an in-direct schema refereed by // direct kubernetes manifest, eg: io.k8s.kubernetes.pkg.api.v1.PodSpec this.saveSchema({ name, ...originalSchema }); } } // replace schema $ref with values like 'kubernetes://schema/...' private replaceDefinitionRefsWithYamlSchemaUris(node: any): void { if (!node) { return; } if (_.isArray(node)) { for (const subItem of <any[]>node) { this.replaceDefinitionRefsWithYamlSchemaUris(subItem); } } if (!_.isObject(node)) { return; } for (const key of Object.keys(node)) { this.replaceDefinitionRefsWithYamlSchemaUris(node[key]); } if (_.isString(node.$ref)) { const name = getNameInDefinitions(node.$ref); const schema = this.lookup(name); if (schema) { // replacing $ref node.$ref = util.makeKubernetesUri(schema.name); } } } // add enum field for pre-defined enums in schema-enums json file private loadEnumsForKubernetesSchema(node: KubernetesSchema) { if (node.properties && this.schemaEnums[node.name]) { _.each(node.properties, (propSchema, propKey) => { if (this.schemaEnums[node.name][propKey]) { if (propSchema.type === "array" && propSchema.items) { propSchema.items.enum = this.schemaEnums[node.name][propKey]; } else { propSchema.enum = this.schemaEnums[node.name][propKey]; } } }); } } // save the schema to the _definitions private saveSchema(schema: KubernetesSchema): void { if (schema.name) { this.definitions[schema.name.toLowerCase()] = schema; } if (schema.id) { this.definitions[schema.id.toLowerCase()] = schema; } } // get the markdown format of document for the current property and the type of current property private getMarkdownDescription(currentPropertyName: string, currentProperty: any, targetSchema: any, isKind = false): string { if (isKind) { return formatComplex(currentPropertyName, targetSchema.description, undefined, targetSchema.properties); } if (!targetSchema) { return formatOne(currentPropertyName, formatType(currentProperty), currentProperty.description); } const properties = targetSchema.properties; if (properties) { return formatComplex(currentPropertyName, currentProperty ? currentProperty.description : "", targetSchema.description, properties); } return currentProperty ? currentProperty.description : (targetSchema ? targetSchema.description : ""); } } /** * Tell whether or not the swagger schema is a kubernetes manifest schema, a kubernetes manifest schema like Service * should have `x-kubernetes-group-version-kind` node. * * @param originalSchema the origin schema object in swagger json * @return whether or not the swagger schema is */ function isGroupVersionKindStyle(originalSchema: any): boolean { return originalSchema[KUBERNETES_GROUP_VERSION_KIND] && originalSchema[KUBERNETES_GROUP_VERSION_KIND].length; } /** * Process on kubernetes manifest schemas, for each selector in x-kubernetes-group-version-kind, * extract apiVersion and kind and make a id composed by apiVersion and kind. * * @param originalSchema the origin schema object in swagger json * @returns {KubernetesSchema[]} an array of schemas for the same manifest differentiated by id/apiVersion/kind; */ function getManifestStyleSchemas(originalSchema: any): KubernetesSchema[] { const schemas = Array.of<KubernetesSchema>(); // eg: service, pod, deployment const groupKindNode = originalSchema[KUBERNETES_GROUP_VERSION_KIND]; // delete 'x-kubernetes-group-version-kind' since it is not a schema standard, it is only a selector delete originalSchema[KUBERNETES_GROUP_VERSION_KIND]; groupKindNode.forEach((groupKindNode: any) => { const gvk = util.parseKubernetesGroupVersionKind(groupKindNode); if (!gvk) { return; } const { id, apiVersion, kind } = gvk; // a direct kubernetes manifest has two reference keys: id && name // id: apiVersion + kind // name: the name in 'definitions' of schema schemas.push({ id, apiVersion, kind, ...originalSchema }); }); return schemas; } // convert '#/definitions/com.github.openshift.origin.pkg.build.apis.build.v1.ImageLabel' to // 'com.github.openshift.origin.pkg.build.apis.build.v1.ImageLabel' function getNameInDefinitions ($ref: string): string { const prefix = '#/definitions/'; if ($ref.startsWith(prefix)) { return $ref.slice(prefix.length); } else { return prefix; } } function makeSafeIntOrString(definitions: any): void { // We need to tweak the IntOrString schema because the live schema has // it as type 'string' with format 'int-or-string', and this doesn't // play nicely with Red Hat YAML on Mac or Linux - it presents a validation // warning on unquoted integers saying they should be strings. This schema // is more semantically correct and appears to restore the correct behaviour // from RH YAML. const intOrStringDefinition = definitions['io.k8s.apimachinery.pkg.util.intstr.IntOrString']; if (intOrStringDefinition) { if (intOrStringDefinition.type === 'string') { intOrStringDefinition.oneOf = [ { type: 'string' }, { type: 'integer' } ]; delete intOrStringDefinition.type; } } }
the_stack
import { expect } from "chai"; import * as React from "react"; import * as sinon from "sinon"; import { BadgeType, CommonToolbarItem, ConditionalBooleanValue, CustomButtonDefinition, StageUsage, ToolbarItemUtilities, ToolbarOrientation, ToolbarUsage, UiItemsManager, UiItemsProvider, } from "@itwin/appui-abstract"; import { render, waitFor } from "@testing-library/react"; import { CommandItemDef, CustomItemDef, FrameworkVersion, FrontstageActivatedEventArgs, FrontstageDef, FrontstageManager, FrontstageProps, GroupItemDef, SyncUiEventDispatcher, ToolbarComposer, ToolbarHelper, ToolItemDef, } from "../../appui-react"; import { CoreTools } from "../../appui-react/tools/CoreToolDefinitions"; import TestUtils from "../TestUtils"; import { UiFramework } from "../../appui-react/UiFramework"; class TestUiProvider implements UiItemsProvider { public readonly id = "ToolbarComposer-TestUiProvider"; public readonly syncEventId = "syncvisibility"; public hidden = false; private _isHiddenCondition = new ConditionalBooleanValue(() => this.hidden, [this.syncEventId]); public provideToolbarButtonItems(_stageId: string, stageUsage: string, toolbarUsage: ToolbarUsage, toolbarOrientation: ToolbarOrientation): CommonToolbarItem[] { if (stageUsage === StageUsage.General && toolbarUsage === ToolbarUsage.ContentManipulation && toolbarOrientation === ToolbarOrientation.Horizontal) { const groupChildSpec = ToolbarItemUtilities.createActionButton("simple-test-action-tool-in-group", 200, "icon-developer", "addon-tool-added-to-test-group", (): void => { }, { parentToolGroupId: "test.group" }); const nestedGroupChildSpec = ToolbarItemUtilities.createActionButton("simple-test-action-tool-nested", 200, "icon-developer", "addon-tool-added-to-test-group-nested", (): void => { }, { parentToolGroupId: "test.group.nested" }); const simpleActionSpec = ToolbarItemUtilities.createActionButton("simple-test-action-tool", 200, "icon-developer", "addon-tool-1", (): void => { }); const childActionSpec = ToolbarItemUtilities.createActionButton("child-test-action-tool", 210, "icon-developer", "addon-group-child-tool-2", (): void => { }); const addonActionSpec = ToolbarItemUtilities.createActionButton("addon-action-tool-2", 220, "icon-developer", "addon-tool-2", (): void => { }); const groupSpec = ToolbarItemUtilities.createGroupButton("test-tool-group", 230, "icon-developer", "addon-group-1", [childActionSpec, simpleActionSpec], { badgeType: BadgeType.TechnicalPreview, parentToolGroupId: "tool-formatting-setting" }); const visibilityTestActionSpec = ToolbarItemUtilities.createActionButton("visibility-test-action-tool", 240, "icon-developer", "visibility-test-tool", (): void => { }, { isHidden: this._isHiddenCondition }); return [simpleActionSpec, addonActionSpec, groupSpec, groupChildSpec, nestedGroupChildSpec, visibilityTestActionSpec]; } return []; } } describe("<ToolbarComposer />", async () => { const testItemEventId = "test-event"; let visibleState = false; const testIsHiddenFunc = () => !visibleState; const tool1 = new CommandItemDef({ commandId: "test.tool1", label: "Tool_1", iconSpec: "icon-placeholder", isHidden: true, }); const tool2 = new CommandItemDef({ commandId: "test.tool2", label: "Tool_2", iconSpec: "icon-placeholder", isHidden: false, }); const tool1a = new CommandItemDef({ commandId: "test.tool1_a", label: "Tool_1", iconSpec: "icon-placeholder", isDisabled: true, }); const tool2a = new CommandItemDef({ commandId: "test.tool2_a", label: "Tool_2", iconSpec: "icon-placeholder", isDisabled: false, }); const tool1b = new ToolItemDef({ toolId: "test.tool1_b", label: "Tool_1", iconSpec: "icon-placeholder", isHidden: true, }); const tool2b = new ToolItemDef({ toolId: "test.tool2_b", label: "Tool_2", iconSpec: "icon-placeholder", }); const isHiddenCondition = new ConditionalBooleanValue(testIsHiddenFunc, [testItemEventId]); const tool1c = new CommandItemDef({ commandId: "test.tool1_c", label: "Tool_1C", iconSpec: "icon-placeholder", isHidden: isHiddenCondition, }); const tool1d = new CommandItemDef({ commandId: "test.tool1_d", label: "Tool_1D", iconSpec: "icon-placeholder", isHidden: isHiddenCondition, }); const groupNested = new GroupItemDef({ groupId: "test.group.nested", label: "Tool_Group_Nested", iconSpec: "icon-placeholder", items: [tool1c], itemsInColumn: 4, }); const group1 = new GroupItemDef({ groupId: "test.group", label: "Tool_Group", iconSpec: "icon-placeholder", items: [tool1a, tool2a, groupNested], itemsInColumn: 4, }); const custom1 = new CustomItemDef({ customId: "test.custom", iconSpec: "icon-arrow-down", label: "Popup Test", popupPanelNode: <div style={{ width: "200px", height: "100px" }}> <span>hello world!</span> </div>, }); const group2 = new GroupItemDef({ groupId: "test.group2", label: "Tool_Group_2", iconSpec: "icon-placeholder", items: [tool1d], isHidden: isHiddenCondition, }); before(async () => { await TestUtils.initializeUiFramework(); }); after(() => { TestUtils.terminateUiFramework(); }); it("should render", async () => { const renderedComponent = render( <ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={ToolbarHelper.createToolbarItemsFromItemDefs([tool1, tool2])} />); expect(renderedComponent).not.to.be.undefined; }); it("should not be able to create node for bad CustomButtonDefinition", () => { const badItem: CustomButtonDefinition = { id: "bad-no-itemdef", itemPriority: 10, isCustom: true, }; expect(ToolbarHelper.createNodeForToolbarItem(badItem)).to.be.null; }); it("should render with specified items", async () => { const renderedComponent = render( <FrameworkVersion version="2"> <ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={ToolbarHelper.createToolbarItemsFromItemDefs([tool1, tool2, group1, custom1])} /> </FrameworkVersion>); expect(renderedComponent).not.to.be.undefined; expect(renderedComponent.container.querySelector("div.components-toolbar-overflow-sizer.components-horizontal")).to.not.be.null; expect(UiFramework.uiVersion).to.eql("2"); }); it("should render with specified items", async () => { const renderedComponent = render( <FrameworkVersion version="1"> <ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={ToolbarHelper.createToolbarItemsFromItemDefs([tool1, tool2, group1, custom1])} /> </FrameworkVersion>); expect(renderedComponent).not.to.be.undefined; expect(renderedComponent.container.querySelector("div.nz-toolbar-toolbar.nz-direction-bottom.nz-horizontal.nz-panel-alignment-start")).to.not.be.null; expect(UiFramework.uiVersion).to.eql("1"); }); it("should render with specified items", async () => { const renderedComponent = render( <ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={ToolbarHelper.createToolbarItemsFromItemDefs([tool1, tool2, group1, custom1])} />); expect(renderedComponent).not.to.be.undefined; }); it("should render with updated items", async () => { const renderedComponent = render( <ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={ToolbarHelper.createToolbarItemsFromItemDefs([tool1, tool2, group1, custom1])} />); expect(renderedComponent).not.to.be.undefined; expect(renderedComponent.queryByTitle("Tool_2")).not.to.be.null; expect(renderedComponent.queryByTitle("Tool_Group")).not.to.be.null; renderedComponent.rerender(<ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={ToolbarHelper.createToolbarItemsFromItemDefs([tool1, group1])} />); expect(renderedComponent.queryByTitle("Tool_2")).to.be.null; expect(renderedComponent.queryByTitle("Tool_Group")).not.to.be.null; }); it("sync event should not refresh if no items updated", () => { const renderedComponent = render( <ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={ToolbarHelper.createToolbarItemsFromItemDefs([tool1, tool2])} />); expect(renderedComponent).not.to.be.undefined; expect(renderedComponent.queryByTitle("Tool_1")).to.be.null; expect(renderedComponent.queryByTitle("Tool_2")).not.to.be.null; SyncUiEventDispatcher.dispatchImmediateSyncUiEvent(testItemEventId); expect(renderedComponent.queryByTitle("Tool_1")).to.be.null; expect(renderedComponent.queryByTitle("Tool_2")).not.to.be.null; }); it("sync event should refresh updated items", () => { visibleState = false; const items = ToolbarHelper.createToolbarItemsFromItemDefs([tool1b, tool2b, group2, tool1c, tool1d]); const renderedComponent = render( <ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={items} />); expect(renderedComponent).not.to.be.undefined; expect(renderedComponent.queryByTitle("Tool_2")).not.to.be.null; expect(renderedComponent.queryByTitle("Tool_Group_2")).to.be.null; visibleState = true; SyncUiEventDispatcher.dispatchImmediateSyncUiEvent(testItemEventId); expect(renderedComponent.queryByTitle("Tool_2")).not.to.be.null; expect(renderedComponent.queryByTitle("Tool_Group_2")).not.to.be.null; expect(renderedComponent.queryByTitle("Tool_1C")).not.to.be.null; expect(renderedComponent.queryByTitle("Tool_1D")).not.to.be.null; }); it("should add tools from UiItemsManager", async () => { const fakeTimers = sinon.useFakeTimers(); const renderedComponent = render( <ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={ToolbarHelper.createToolbarItemsFromItemDefs([tool1, tool2, group1])} />); expect(renderedComponent).not.to.be.undefined; const testUiProvider = new TestUiProvider(); UiItemsManager.register(testUiProvider); fakeTimers.tick(500); fakeTimers.restore(); expect(await waitFor(() => renderedComponent.queryByTitle("addon-tool-1"))).to.exist; expect(await waitFor(() => renderedComponent.queryByTitle("addon-tool-2"))).to.exist; expect(await waitFor(() => renderedComponent.queryByTitle("addon-group-1"))).to.exist; // new frontstage should trigger refresh /** Id for the Frontstage */ const oldProps: FrontstageProps = { id: "old", defaultTool: CoreTools.selectElementCommand, contentGroup: TestUtils.TestContentGroup2 }; const oldStageDef = new FrontstageDef(); await oldStageDef.initializeFromProps(oldProps); const newProps: FrontstageProps = { id: "new", defaultTool: CoreTools.selectElementCommand, contentGroup: TestUtils.TestContentGroup2 }; const newStageDef = new FrontstageDef(); await newStageDef.initializeFromProps(newProps); FrontstageManager.onFrontstageActivatedEvent.emit({ deactivatedFrontstageDef: oldStageDef, activatedFrontstageDef: newStageDef } as FrontstageActivatedEventArgs); expect(await waitFor(() => renderedComponent.queryByTitle("addon-tool-1"))).to.exist; UiItemsManager.unregister(testUiProvider.id); }); it("should update active item to toolid is set", async () => { visibleState = false; const items = ToolbarHelper.createToolbarItemsFromItemDefs([tool1b, tool2b, group2, tool1c, tool1d]); const groupChildSpec = ToolbarItemUtilities.createActionButton("tool-in-group", 200, "icon-developer", "tool-added-to-group", (): void => { }, { parentToolGroupId: "test.group2" }); items.push(groupChildSpec); const renderedComponent = render( <ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={items} />); expect(renderedComponent).not.to.be.undefined; let buttonElement = await waitFor(() => renderedComponent.queryByTitle("Tool_2")); expect(buttonElement).to.exist; expect(buttonElement?.classList.contains("nz-active")).to.be.false; FrontstageManager.onToolActivatedEvent.emit({ toolId: "test.tool2_b" }); buttonElement = await waitFor(() => renderedComponent.queryByTitle("Tool_2")); expect(buttonElement).to.exist; expect(buttonElement?.classList.contains("nz-active")).to.be.true; FrontstageManager.onToolActivatedEvent.emit({ toolId: "tool-added-to-group" }); // expect(renderedComponent.queryByTitle("tool-added-to-group")).not.to.be.null; }); it("should update items from an external provider's visibility properly", () => { const fakeTimers = sinon.useFakeTimers(); const testUiProvider = new TestUiProvider(); UiItemsManager.register(testUiProvider); const renderedComponent = render( <ToolbarComposer usage={ToolbarUsage.ContentManipulation} orientation={ToolbarOrientation.Horizontal} items={[]} />); expect(renderedComponent.queryByTitle("visibility-test-tool")).not.to.be.null; testUiProvider.hidden = true; SyncUiEventDispatcher.dispatchImmediateSyncUiEvent(testUiProvider.syncEventId); fakeTimers.tick(500); fakeTimers.restore(); expect(renderedComponent.queryByTitle("visibility-test-tool")).to.be.null; UiItemsManager.unregister(testUiProvider.id); }); });
the_stack
import { defineConfig, notEqual } from '@agile-ts/utils'; import { logCodeManager } from '../logCodeManager'; import { Agile } from '../agile'; import { SubscriptionContainer, CallbackSubscriptionContainer, ComponentSubscriptionContainer, } from './subscription'; import { RuntimeJob } from './runtime.job'; export class Runtime { // Agile Instance the Runtime belongs to public agileInstance: () => Agile; // Job that is currently being performed public currentJob: RuntimeJob | null = null; // Jobs to be performed public jobQueue: Array<RuntimeJob> = []; // Jobs that were performed and are ready to re-render public jobsToRerender: Array<RuntimeJob> = []; // Jobs that were performed and couldn't be re-rendered yet. // That is the case when at least one Subscription Container (UI-Component) in the Job // wasn't ready to update (re-render). public notReadyJobsToRerender: Set<RuntimeJob> = new Set(); // Whether the `jobQueue` is currently being actively processed public isPerformingJobs = false; // Current 'bucket' timeout 'scheduled' for updating the Subscribers (UI-Components) public bucketTimeout: NodeJS.Timeout | null = null; /** * The Runtime queues and executes incoming Observer-based Jobs * to prevent [race conditions](https://en.wikipedia.org/wiki/Race_condition#:~:text=A%20race%20condition%20or%20race,the%20possible%20behaviors%20is%20undesirable.) * and optimized the re-rendering of the Observer's subscribed UI-Components. * * Each queued Job is executed when it is its turn * by calling the Job Observer's `perform()` method. * * After successful execution, the Job is added to a re-render queue, * which is first put into the browser's 'Bucket' and started to work off * when resources are left. * * The re-render queue is designed for optimizing the render count * by batching multiple re-render Jobs of the same UI-Component * and ignoring re-render requests for unmounted UI-Components. * * @internal * @param agileInstance - Instance of Agile the Runtime belongs to. */ constructor(agileInstance: Agile) { this.agileInstance = () => agileInstance; } /** * Adds the specified Observer-based Job to the internal Job queue, * where it is executed when it is its turn. * * After successful execution, the Job is assigned to the re-render queue, * where all the Observer's subscribed Subscription Containers (UI-Components) * are updated (re-rendered). * * @public * @param job - Job to be added to the Job queue. * @param config - Configuration object */ public ingest(job: RuntimeJob, config: IngestConfigInterface = {}): void { config = defineConfig(config, { perform: !this.isPerformingJobs, }); // Add specified Job to the queue this.jobQueue.push(job); if (process.env.NODE_ENV !== 'production') { logCodeManager.log( '16:01:00', { tags: ['runtime'], replacers: [job.key] }, job ); } // Run first Job from the queue if (config.perform) { const performJob = this.jobQueue.shift(); if (performJob) this.perform(performJob); } } /** * Performs the specified Job * and assigns it to the re-render queue if necessary. * * After the execution of the provided Job, it is checked whether * there are still Jobs left in the Job queue. * - If so, the next Job in the `jobQueue` is performed. * - If not, the `jobsToRerender` queue is started to work off. * * @internal * @param job - Job to be performed. */ public perform(job: RuntimeJob): void { this.isPerformingJobs = true; this.currentJob = job; // Perform Job job.observer.perform(job); job.performed = true; // Ingest dependents of the Observer into runtime, // since they depend on the Observer and therefore have properly changed too job.observer.dependents.forEach((observer) => observer.ingest()); // Add Job to rerender queue and reset current Job property if (job.rerender) this.jobsToRerender.push(job); this.currentJob = null; if (process.env.NODE_ENV !== 'production') { logCodeManager.log( '16:01:01', { tags: ['runtime'], replacers: [job.key] }, job ); } // Perform Jobs as long as Jobs are left in the queue. // If no Job is left start updating (re-rendering) Subscription Container (UI-Components) // of the Job based on the 'jobsToRerender' queue. if (this.jobQueue.length > 0) { const performJob = this.jobQueue.shift(); if (performJob) this.perform(performJob); } else { this.isPerformingJobs = false; if (this.jobsToRerender.length > 0) { if (this.agileInstance().config.bucket) { // Check if an bucket timeout is active, if so don't call a new one, // since if the active timeout is called it will also proceed Jobs // that were not added before the call if (this.bucketTimeout == null) { // https://stackoverflow.com/questions/9083594/call-settimeout-without-delay this.bucketTimeout = setTimeout(() => { this.bucketTimeout = null; this.updateSubscribers(); }); } } else this.updateSubscribers(); } } } /** * Processes the `jobsToRerender` queue by updating (causing a re-render on) * the subscribed Subscription Containers (UI-Components) of each Job Observer. * * It returns a boolean indicating whether * any Subscription Container (UI-Component) was updated (re-rendered) or not. * * @internal */ public updateSubscribers(): boolean { // Build final 'jobsToRerender' array // based on the new 'jobsToRerender' array and the 'notReadyJobsToRerender' array const jobsToRerender = this.jobsToRerender.concat( Array.from(this.notReadyJobsToRerender) ); this.notReadyJobsToRerender = new Set(); this.jobsToRerender = []; if (!this.agileInstance().hasIntegration() || jobsToRerender.length <= 0) return false; // Extract the Subscription Container to be re-rendered from the Jobs const subscriptionContainerToUpdate = this.extractToUpdateSubscriptionContainer(jobsToRerender); if (subscriptionContainerToUpdate.length <= 0) return false; // Update Subscription Container (trigger re-render on the UI-Component they represent) this.updateSubscriptionContainer(subscriptionContainerToUpdate); return true; } /** * Extracts the Subscription Containers (UI-Components) * to be updated (re-rendered) from the specified Runtime Jobs. * * @internal * @param jobs - Jobs from which to extract the Subscription Containers to be updated. */ public extractToUpdateSubscriptionContainer( jobs: Array<RuntimeJob> ): Array<SubscriptionContainer> { // https://medium.com/@bretcameron/how-to-make-your-code-faster-using-javascript-sets-b432457a4a77 const subscriptionsToUpdate = new Set<SubscriptionContainer>(); // Using for loop for performance optimization // https://stackoverflow.com/questions/43821759/why-array-foreach-is-slower-than-for-loop-in-javascript for (let i = 0; i < jobs.length; i++) { const job = jobs[i]; job.subscriptionContainersToUpdate.forEach((subscriptionContainer) => { let updateSubscriptionContainer = true; // Handle not ready Subscription Container if (!subscriptionContainer.ready) { if ( !job.config.maxTriesToUpdate || job.timesTriedToUpdateCount < job.config.maxTriesToUpdate ) { job.timesTriedToUpdateCount++; this.notReadyJobsToRerender.add(job); if (process.env.NODE_ENV !== 'production') { logCodeManager.log( '16:02:00', { replacers: [subscriptionContainer.key] }, subscriptionContainer ); } } else { if (process.env.NODE_ENV !== 'production') { logCodeManager.log( '16:02:01', { replacers: [job.config.maxTriesToUpdate] }, subscriptionContainer ); } } return; } // TODO has to be overthought because when it is a Component based Subscription // the rerender is triggered via merging the changed properties into the Component. // Although the 'componentId' might be equal, it doesn't mean // that the changed properties are equal! (-> changed properties might get missing) // Check if Subscription Container with same 'componentId' // is already in the 'subscriptionToUpdate' queue (rerender optimisation) // updateSubscriptionContainer = // updateSubscriptionContainer && // Array.from(subscriptionsToUpdate).findIndex( // (sc) => sc.componentId === subscriptionContainer.componentId // ) === -1; // Check whether a selected part of the Observer value has changed updateSubscriptionContainer = updateSubscriptionContainer && this.handleSelectors(subscriptionContainer, job); // Add Subscription Container to the 'subscriptionsToUpdate' queue if (updateSubscriptionContainer) { subscriptionContainer.updatedSubscribers.add(job.observer); subscriptionsToUpdate.add(subscriptionContainer); } job.subscriptionContainersToUpdate.delete(subscriptionContainer); }); } return Array.from(subscriptionsToUpdate); } /** * Updates the specified Subscription Containers. * * Updating a Subscription Container triggers a re-render * on the Component it represents, based on the type of the Subscription Containers. * * @internal * @param subscriptionsToUpdate - Subscription Containers to be updated. */ public updateSubscriptionContainer( subscriptionsToUpdate: Array<SubscriptionContainer> ): void { // Using for loop for performance optimization // https://stackoverflow.com/questions/43821759/why-array-foreach-is-slower-than-for-loop-in-javascript for (let i = 0; i < subscriptionsToUpdate.length; i++) { const subscriptionContainer = subscriptionsToUpdate[i]; // Call 'callback function' if Callback based Subscription if (subscriptionContainer instanceof CallbackSubscriptionContainer) subscriptionContainer.callback(); // Call 'update method' in Integrations if Component based Subscription if (subscriptionContainer instanceof ComponentSubscriptionContainer) this.agileInstance().integrations.update( subscriptionContainer.component, this.getUpdatedObserverValues(subscriptionContainer) ); subscriptionContainer.updatedSubscribers.clear(); } if (process.env.NODE_ENV !== 'production') { logCodeManager.log( '16:01:02', { tags: ['runtime'] }, subscriptionsToUpdate ); } } /** * Maps the values of the updated Observers (`updatedSubscribers`) * of the specified Subscription Container into a key map object. * * The key containing the Observer value is extracted from the Observer itself * or from the Subscription Container's `subscriberKeysWeakMap`. * * @internal * @param subscriptionContainer - Subscription Container from which the `updatedSubscribers` are to be mapped into a key map. */ public getUpdatedObserverValues( subscriptionContainer: SubscriptionContainer ): { [key: string]: any } { const props: { [key: string]: any } = {}; for (const observer of subscriptionContainer.updatedSubscribers) { const key = subscriptionContainer.subscriberKeysWeakMap.get(observer) ?? observer.key; if (key != null) props[key] = observer.value; } return props; } /** * Returns a boolean indicating whether the specified Subscription Container can be updated or not, * based on its selector functions (`selectorsWeakMap`). * * This is done by checking the '.value' and the '.previousValue' property of the Observer represented by the Job. * If a selected property differs, the Subscription Container (UI-Component) is allowed to update (re-render) * and `true` is returned. * * If the Subscription Container has no selector function at all, `true` is returned. * * @internal * @param subscriptionContainer - Subscription Container to be checked if it can be updated. * @param job - Job containing the Observer that is subscribed to the Subscription Container. */ public handleSelectors( subscriptionContainer: SubscriptionContainer, job: RuntimeJob ): boolean { const selectorMethods = subscriptionContainer.selectorsWeakMap.get( job.observer )?.methods; // If no selector functions found, return true. // Because no specific part of the Observer was selected. // -> The Subscription Container should be updated // no matter what has updated in the Observer. if (selectorMethods == null) return true; // Check if a selected part of the Observer value has changed const previousValue = job.observer.previousValue; const newValue = job.observer.value; if (!previousValue && !newValue) return false; // Because not all Observers contain a value/previousValue for (const selectorMethod of selectorMethods) { if ( notEqual(selectorMethod(newValue), selectorMethod(previousValue)) // || newValueDeepness !== previousValueDeepness // Not possible to check the object deepness ) return true; } return false; } } export interface IngestConfigInterface { /** * Whether the ingested Job should be performed immediately * or added to the queue first and then executed when it is his turn. */ perform?: boolean; }
the_stack
import { assertEq } from '../test-helpers'; import { moment } from '../chain'; import { kaLocale } from '../../i18n/ka'; // localeModule('en'); describe('locale: ka', () => { beforeAll(() => { moment.locale('ka', kaLocale); }); afterAll(() => { moment.locale('en'); }); // localeModule('ka'); it('parse', function () { var _tests = 'იანვარი იან_თებერვალი თებ_მარტი მარ_აპრილი აპრ_მაისი მაი_ივნისი ივნ_ივლისი ივლ_აგვისტო აგვ_სექტემბერი სექ_ოქტომბერი ოქტ_ნოემბერი ნოე_დეკემბერი დეკ'.split('_'), i; function equalTest(input, mmm, i) { assertEq(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } let tests: string[][] = []; for (i = 0; i < 12; i++) { tests[i] = _tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); // the last two are broken until https://github.com/nodejs/node/issues/22518 is fixed // equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); // equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } }); it('format', function () { var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'კვირა, თებერვალი მე-14 2010, 3:25:50 pm'], ['ddd, hA', 'კვი, 3PM'], ['M Mo MM MMMM MMM', '2 მე-2 02 თებერვალი თებ'], ['YYYY YY', '2010 10'], ['D Do DD', '14 მე-14 14'], ['d do dddd ddd dd', '0 0 კვირა კვი კვ'], ['DDD DDDo DDDD', '45 45-ე 045'], ['w wo ww', '6 მე-6 06'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['წლის DDDo დღე', 'წლის 45-ე დღე'], ['LTS', '3:25:50 PM'], ['L', '14/02/2010'], ['LL', '14 თებერვალს 2010'], ['LLL', '14 თებერვალს 2010 3:25 PM'], ['LLLL', 'კვირა, 14 თებერვალს 2010 3:25 PM'], ['l', '14/2/2010'], ['ll', '14 თებ 2010'], ['lll', '14 თებ 2010 3:25 PM'], ['llll', 'კვი, 14 თებ 2010 3:25 PM'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { assertEq(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } }); it('format ordinal', function () { assertEq(moment([2011, 0, 1]).format('DDDo'), '1-ლი', '1-ლი'); assertEq(moment([2011, 0, 2]).format('DDDo'), 'მე-2', 'მე-2'); assertEq(moment([2011, 0, 3]).format('DDDo'), 'მე-3', 'მე-3'); assertEq(moment([2011, 0, 4]).format('DDDo'), 'მე-4', 'მე-4'); assertEq(moment([2011, 0, 5]).format('DDDo'), 'მე-5', 'მე-5'); assertEq(moment([2011, 0, 6]).format('DDDo'), 'მე-6', 'მე-6'); assertEq(moment([2011, 0, 7]).format('DDDo'), 'მე-7', 'მე-7'); assertEq(moment([2011, 0, 8]).format('DDDo'), 'მე-8', 'მე-8'); assertEq(moment([2011, 0, 9]).format('DDDo'), 'მე-9', 'მე-9'); assertEq(moment([2011, 0, 10]).format('DDDo'), 'მე-10', 'მე-10'); assertEq(moment([2011, 0, 11]).format('DDDo'), 'მე-11', 'მე-11'); assertEq(moment([2011, 0, 12]).format('DDDo'), 'მე-12', 'მე-12'); assertEq(moment([2011, 0, 13]).format('DDDo'), 'მე-13', 'მე-13'); assertEq(moment([2011, 0, 14]).format('DDDo'), 'მე-14', 'მე-14'); assertEq(moment([2011, 0, 15]).format('DDDo'), 'მე-15', 'მე-15'); assertEq(moment([2011, 0, 16]).format('DDDo'), 'მე-16', 'მე-16'); assertEq(moment([2011, 0, 17]).format('DDDo'), 'მე-17', 'მე-17'); assertEq(moment([2011, 0, 18]).format('DDDo'), 'მე-18', 'მე-18'); assertEq(moment([2011, 0, 19]).format('DDDo'), 'მე-19', 'მე-19'); assertEq(moment([2011, 0, 20]).format('DDDo'), 'მე-20', 'მე-20'); assertEq(moment([2011, 0, 21]).format('DDDo'), '21-ე', '21-ე'); assertEq(moment([2011, 0, 22]).format('DDDo'), '22-ე', '22-ე'); assertEq(moment([2011, 0, 23]).format('DDDo'), '23-ე', '23-ე'); assertEq(moment([2011, 0, 24]).format('DDDo'), '24-ე', '24-ე'); assertEq(moment([2011, 0, 25]).format('DDDo'), '25-ე', '25-ე'); assertEq(moment([2011, 0, 26]).format('DDDo'), '26-ე', '26-ე'); assertEq(moment([2011, 0, 27]).format('DDDo'), '27-ე', '27-ე'); assertEq(moment([2011, 0, 28]).format('DDDo'), '28-ე', '28-ე'); assertEq(moment([2011, 0, 29]).format('DDDo'), '29-ე', '29-ე'); assertEq(moment([2011, 0, 30]).format('DDDo'), '30-ე', '30-ე'); assertEq(moment('2011 40', 'YYYY DDD').format('DDDo'), 'მე-40', 'მე-40'); assertEq(moment('2011 50', 'YYYY DDD').format('DDDo'), '50-ე', '50-ე'); assertEq(moment('2011 60', 'YYYY DDD').format('DDDo'), 'მე-60', 'მე-60'); assertEq(moment('2011 100', 'YYYY DDD').format('DDDo'), 'მე-100', 'მე-100'); assertEq(moment('2011 101', 'YYYY DDD').format('DDDo'), '101-ე', '101-ე'); }); it('format month', function () { var expected = 'იანვარი იან_თებერვალი თებ_მარტი მარ_აპრილი აპრ_მაისი მაი_ივნისი ივნ_ივლისი ივლ_აგვისტო აგვ_სექტემბერი სექ_ოქტომბერი ოქტ_ნოემბერი ნოე_დეკემბერი დეკ'.split('_'), i; for (i = 0; i < expected.length; i++) { assertEq(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } }); it('format week', function () { var expected = 'კვირა კვი კვ_ორშაბათი ორშ ორ_სამშაბათი სამ სა_ოთხშაბათი ოთხ ოთ_ხუთშაბათი ხუთ ხუ_პარასკევი პარ პა_შაბათი შაბ შა'.split('_'), i; for (i = 0; i < expected.length; i++) { assertEq(moment([2011, 0, 2 + i]).format('dddd ddd dd'), expected[i], expected[i]); } }); it('from', function () { var start = moment([2007, 1, 28]); assertEq(start.from(moment([2007, 1, 28]).add({s: 44}), true), 'რამდენიმე წამი', '44 წამი = რამდენიმე წამი'); assertEq(start.from(moment([2007, 1, 28]).add({s: 45}), true), 'წუთი', '45 წამი = წუთი'); assertEq(start.from(moment([2007, 1, 28]).add({s: 89}), true), 'წუთი', '89 წამი = წუთი'); assertEq(start.from(moment([2007, 1, 28]).add({s: 90}), true), '2 წუთი', '90 წამი = 2 წუთი'); assertEq(start.from(moment([2007, 1, 28]).add({m: 44}), true), '44 წუთი', '44 წამი = 44 წუთი'); assertEq(start.from(moment([2007, 1, 28]).add({m: 45}), true), 'საათი', '45 წამი = საათი'); assertEq(start.from(moment([2007, 1, 28]).add({m: 89}), true), 'საათი', '89 წამი = საათი'); assertEq(start.from(moment([2007, 1, 28]).add({m: 90}), true), '2 საათი', '90 წამი = 2 საათი'); assertEq(start.from(moment([2007, 1, 28]).add({h: 5}), true), '5 საათი', '5 საათი = 5 საათი'); assertEq(start.from(moment([2007, 1, 28]).add({h: 21}), true), '21 საათი', '21 საათი = 21 საათი'); assertEq(start.from(moment([2007, 1, 28]).add({h: 22}), true), 'დღე', '22 საათი = დღე'); assertEq(start.from(moment([2007, 1, 28]).add({h: 35}), true), 'დღე', '35 საათი = დღე'); assertEq(start.from(moment([2007, 1, 28]).add({h: 36}), true), '2 დღე', '36 საათი = 2 დღე'); assertEq(start.from(moment([2007, 1, 28]).add({d: 1}), true), 'დღე', '1 დღე = დღე'); assertEq(start.from(moment([2007, 1, 28]).add({d: 5}), true), '5 დღე', '5 დღე = 5 დღე'); assertEq(start.from(moment([2007, 1, 28]).add({d: 25}), true), '25 დღე', '25 დღე = 25 დღე'); assertEq(start.from(moment([2007, 1, 28]).add({d: 26}), true), 'თვე', '26 დღე = თვე'); assertEq(start.from(moment([2007, 1, 28]).add({d: 30}), true), 'თვე', '30 დღე = თვე'); assertEq(start.from(moment([2007, 1, 28]).add({d: 43}), true), 'თვე', '45 დღე = თვე'); assertEq(start.from(moment([2007, 1, 28]).add({d: 46}), true), '2 თვე', '46 დღე = 2 თვე'); assertEq(start.from(moment([2007, 1, 28]).add({d: 74}), true), '2 თვე', '75 დღე = 2 თვე'); assertEq(start.from(moment([2007, 1, 28]).add({d: 76}), true), '3 თვე', '76 დღე = 3 თვე'); assertEq(start.from(moment([2007, 1, 28]).add({M: 1}), true), 'თვე', '1 თვე = თვე'); assertEq(start.from(moment([2007, 1, 28]).add({M: 5}), true), '5 თვე', '5 თვე = 5 თვე'); assertEq(start.from(moment([2007, 1, 28]).add({d: 345}), true), 'წელი', '345 დღე = წელი'); assertEq(start.from(moment([2007, 1, 28]).add({d: 548}), true), '2 წელი', '548 დღე = 2 წელი'); assertEq(start.from(moment([2007, 1, 28]).add({y: 1}), true), 'წელი', '1 წელი = წელი'); assertEq(start.from(moment([2007, 1, 28]).add({y: 5}), true), '5 წელი', '5 წელი = 5 წელი'); }); it('suffix', function () { assertEq(moment(30000).from(0), 'რამდენიმე წამში', 'ში სუფიქსი'); assertEq(moment(0).from(30000), 'რამდენიმე წამის წინ', 'წინ სუფიქსი'); }); it('now from now', function () { assertEq(moment().fromNow(), 'რამდენიმე წამის წინ', 'უნდა აჩვენოს როგორც წარსული'); }); it('fromNow', function () { assertEq(moment().add({s: 30}).fromNow(), 'რამდენიმე წამში', 'რამდენიმე წამში'); assertEq(moment().add({d: 5}).fromNow(), '5 დღეში', '5 დღეში'); }); it('calendar day', function () { var a = moment().hours(12).minutes(0).seconds(0); assertEq(moment(a).calendar(), 'დღეს 12:00 PM-ზე', 'დღეს ამავე დროს'); assertEq(moment(a).add({m: 25}).calendar(), 'დღეს 12:25 PM-ზე', 'ახლანდელ დროს დამატებული 25 წუთი'); assertEq(moment(a).add({h: 1}).calendar(), 'დღეს 1:00 PM-ზე', 'ახლანდელ დროს დამატებული 1 საათი'); assertEq(moment(a).add({d: 1}).calendar(), 'ხვალ 12:00 PM-ზე', 'ხვალ ამავე დროს'); assertEq(moment(a).subtract({h: 1}).calendar(), 'დღეს 11:00 AM-ზე', 'ახლანდელ დროს გამოკლებული 1 საათი'); assertEq(moment(a).subtract({d: 1}).calendar(), 'გუშინ 12:00 PM-ზე', 'გუშინ ამავე დროს'); }); it('calendar next week', function () { var i, m; for (i = 2; i < 7; i++) { m = moment().add({d: i}); assertEq(m.calendar(), m.format('[შემდეგ] dddd LT[-ზე]'), 'დღეს + ' + i + ' დღე ახლანდელ დროს'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assertEq(m.calendar(), m.format('[შემდეგ] dddd LT[-ზე]'), 'დღეს + ' + i + ' დღე დღის დასაწყისში'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assertEq(m.calendar(), m.format('[შემდეგ] dddd LT[-ზე]'), 'დღეს + ' + i + ' დღე დღის დასასრულს'); } }); it('calendar last week', function () { var i, m; for (i = 2; i < 7; i++) { m = moment().subtract({d: i}); assertEq(m.calendar(), m.format('[წინა] dddd LT[-ზე]'), 'დღეს - ' + i + ' დღე ახლანდელ დროს'); m.hours(0).minutes(0).seconds(0).milliseconds(0); assertEq(m.calendar(), m.format('[წინა] dddd LT[-ზე]'), 'დღეს - ' + i + ' დღე დღის დასაწყისში'); m.hours(23).minutes(59).seconds(59).milliseconds(999); assertEq(m.calendar(), m.format('[წინა] dddd LT[-ზე]'), 'დღეს - ' + i + ' დღე დღის დასასრულს'); } }); it('calendar all else', function () { var weeksAgo = moment().subtract({w: 1}), weeksFromNow = moment().add({w: 1}); assertEq(weeksAgo.calendar(), weeksAgo.format('L'), '1 კვირის წინ'); assertEq(weeksFromNow.calendar(), weeksFromNow.format('L'), '1 კვირაში'); weeksAgo = moment().subtract({w: 2}); weeksFromNow = moment().add({w: 2}); assertEq(weeksAgo.calendar(), weeksAgo.format('L'), '2 კვირის წინ'); assertEq(weeksFromNow.calendar(), weeksFromNow.format('L'), '2 კვირაში'); }); it('weeks year starting sunday format', function () { assertEq(moment([2011, 11, 26]).format('w ww wo'), '52 52 52-ე', 'დეკ 26 2011 უნდა იყოს კვირა 52'); assertEq(moment([2012, 0, 1]).format('w ww wo'), '52 52 52-ე', 'იან 1 2012 უნდა იყოს კვირა 52'); assertEq(moment([2012, 0, 2]).format('w ww wo'), '1 01 1-ლი', 'იან 2 2012 უნდა იყოს კვირა 1'); assertEq(moment([2012, 0, 8]).format('w ww wo'), '1 01 1-ლი', 'იან 8 2012 უნდა იყოს კვირა 1'); assertEq(moment([2012, 0, 9]).format('w ww wo'), '2 02 მე-2', 'იან 9 2012 უნდა იყოს კვირა 2'); }); });
the_stack
import * as React from "react"; import { createIntervalTree } from "./interval-tree"; /** * This hook creates the grid cell positioner and cache required by `useMasonry()`. This is * the meat of the grid's layout algorithm, determining which cells to render at a given scroll * position, as well as where to place new items in the grid. * * @param options - Properties that determine the number of columns in the grid, as well * as their widths. * @param options.columnWidth * @param options.width * @param deps - This hook will create a new positioner, clearing all existing cached positions, * whenever the dependencies in this list change. * @param options.columnGutter * @param options.rowGutter * @param options.columnCount */ export function usePositioner( { width, columnWidth = 200, columnGutter = 0, rowGutter, columnCount, }: UsePositionerOptions, deps: React.DependencyList = emptyArr ): Positioner { const initPositioner = (): Positioner => { const [computedColumnWidth, computedColumnCount] = getColumns( width, columnWidth, columnGutter, columnCount ); return createPositioner( computedColumnCount, computedColumnWidth, columnGutter, rowGutter ?? columnGutter ); }; const positionerRef = React.useRef<Positioner>(); if (positionerRef.current === undefined) positionerRef.current = initPositioner(); const prevDeps = React.useRef(deps); const opts = [width, columnWidth, columnGutter, rowGutter, columnCount]; const prevOpts = React.useRef(opts); const optsChanged = !opts.every((item, i) => prevOpts.current[i] === item); if (typeof process !== "undefined" && process.env.NODE_ENV !== "production") { if (deps.length !== prevDeps.current.length) { throw new Error( "usePositioner(): The length of your dependencies array changed." ); } } // Create a new positioner when the dependencies or sizes change // Thanks to https://github.com/khmm12 for pointing this out // https://github.com/jaredLunde/masonic/pull/41 if (optsChanged || !deps.every((item, i) => prevDeps.current[i] === item)) { const prevPositioner = positionerRef.current; const positioner = initPositioner(); prevDeps.current = deps; prevOpts.current = opts; if (optsChanged) { const cacheSize = prevPositioner.size(); for (let index = 0; index < cacheSize; index++) { const pos = prevPositioner.get(index); positioner.set(index, pos !== void 0 ? pos.height : 0); } } positionerRef.current = positioner; } return positionerRef.current; } export interface UsePositionerOptions { /** * The width of the container you're rendering the grid within, i.e. the container * element's `element.offsetWidth` */ width: number; /** * The minimum column width. The `usePositioner()` hook will automatically size the * columns to fill their container based upon the `columnWidth` and `columnGutter` values. * It will never render anything smaller than this width unless its container itself is * smaller than its value. This property is optional if you're using a static `columnCount`. * * @default 200 */ columnWidth?: number; /** * This sets the horizontal space between grid columns in pixels. If `rowGutter` is not set, this * also sets the vertical space between cells within a column in pixels. * * @default 0 */ columnGutter?: number; /** * This sets the vertical space between cells within a column in pixels. If not set, the value of * `columnGutter` is used instead. */ rowGutter?: number; /** * By default, `usePositioner()` derives the column count from the `columnWidth`, `columnGutter`, * and `width` props. However, in some situations it is nice to be able to override that behavior * (e.g. creating a `List` component). */ columnCount?: number; } /** * Creates a cell positioner for the `useMasonry()` hook. The `usePositioner()` hook uses * this utility under the hood. * * @param columnCount - The number of columns in the grid * @param columnWidth - The width of each column in the grid * @param columnGutter - The amount of horizontal space between columns in pixels. * @param rowGutter - The amount of vertical space between cells within a column in pixels (falls back * to `columnGutter`). */ export const createPositioner = ( columnCount: number, columnWidth: number, columnGutter = 0, rowGutter = columnGutter ): Positioner => { // O(log(n)) lookup of cells to render for a given viewport size // Store tops and bottoms of each cell for fast intersection lookup. const intervalTree = createIntervalTree(); // Track the height of each column. // Layout algorithm below always inserts into the shortest column. const columnHeights: number[] = new Array(columnCount); // Used for O(1) item access const items: PositionerItem[] = []; // Tracks the item indexes within an individual column const columnItems: number[][] = new Array(columnCount); for (let i = 0; i < columnCount; i++) { columnHeights[i] = 0; columnItems[i] = []; } return { columnCount, columnWidth, set: (index, height = 0) => { let column = 0; // finds the shortest column and uses it for (let i = 1; i < columnHeights.length; i++) { if (columnHeights[i] < columnHeights[column]) column = i; } const top = columnHeights[column] || 0; columnHeights[column] = top + height + rowGutter; columnItems[column].push(index); items[index] = { left: column * (columnWidth + columnGutter), top, height, column, }; intervalTree.insert(top, top + height, index); }, get: (index) => items[index], // This only updates items in the specific columns that have changed, on and after the // specific items that have changed update: (updates) => { const columns: number[] = new Array(columnCount); let i = 0, j = 0; // determines which columns have items that changed, as well as the minimum index // changed in that column, as all items after that index will have their positions // affected by the change for (; i < updates.length - 1; i++) { const index = updates[i]; const item = items[index]; item.height = updates[++i]; intervalTree.remove(index); intervalTree.insert(item.top, item.top + item.height, index); columns[item.column] = columns[item.column] === void 0 ? index : Math.min(index, columns[item.column]); } for (i = 0; i < columns.length; i++) { // bails out if the column didn't change if (columns[i] === void 0) continue; const itemsInColumn = columnItems[i]; // the index order is sorted with certainty so binary search is a great solution // here as opposed to Array.indexOf() const startIndex = binarySearch(itemsInColumn, columns[i]); const index = columnItems[i][startIndex]; const startItem = items[index]; columnHeights[i] = startItem.top + startItem.height + rowGutter; for (j = startIndex + 1; j < itemsInColumn.length; j++) { const index = itemsInColumn[j]; const item = items[index]; item.top = columnHeights[i]; columnHeights[i] = item.top + item.height + rowGutter; intervalTree.remove(index); intervalTree.insert(item.top, item.top + item.height, index); } } }, // Render all cells visible within the viewport range defined. range: (lo, hi, renderCallback) => intervalTree.search(lo, hi, (index, top) => renderCallback(index, items[index].left, top) ), estimateHeight: (itemCount, defaultItemHeight): number => { const tallestColumn = Math.max(0, Math.max.apply(null, columnHeights)); return itemCount === intervalTree.size ? tallestColumn : tallestColumn + Math.ceil((itemCount - intervalTree.size) / columnCount) * defaultItemHeight; }, shortestColumn: () => { if (columnHeights.length > 1) return Math.min.apply(null, columnHeights); return columnHeights[0] || 0; }, size(): number { return intervalTree.size; }, all(): PositionerItem[] { return items; }, }; }; export interface Positioner { /** * The number of columns in the grid */ columnCount: number; /** * The width of each column in the grid */ columnWidth: number; /** * Sets the position for the cell at `index` based upon the cell's height */ set: (index: number, height: number) => void; /** * Gets the `PositionerItem` for the cell at `index` */ get: (index: number) => PositionerItem | undefined; /** * Updates cells based on their indexes and heights * positioner.update([index, height, index, height, index, height...]) */ update: (updates: number[]) => void; /** * Searches the interval tree for grid cells with a `top` value in * betwen `lo` and `hi` and invokes the callback for each item that * is discovered */ range: ( lo: number, hi: number, renderCallback: (index: number, left: number, top: number) => void ) => void; /** * Returns the number of grid cells in the cache */ size: () => number; /** * Estimates the total height of the grid */ estimateHeight: (itemCount: number, defaultItemHeight: number) => number; /** * Returns the height of the shortest column in the grid */ shortestColumn: () => number; /** * Returns all `PositionerItem` items */ all: () => PositionerItem[]; } export interface PositionerItem { /** * This is how far from the top edge of the grid container in pixels the * item is placed */ top: number; /** * This is how far from the left edge of the grid container in pixels the * item is placed */ left: number; /** * This is the height of the grid cell */ height: number; /** * This is the column number containing the grid cell */ column: number; } /* istanbul ignore next */ const binarySearch = (a: number[], y: number): number => { let l = 0; let h = a.length - 1; while (l <= h) { const m = (l + h) >>> 1; const x = a[m]; if (x === y) return m; else if (x <= y) l = m + 1; else h = m - 1; } return -1; }; const getColumns = ( width = 0, minimumWidth = 0, gutter = 8, columnCount?: number ): [number, number] => { columnCount = columnCount || Math.floor(width / (minimumWidth + gutter)) || 1; const columnWidth = Math.floor( (width - gutter * (columnCount - 1)) / columnCount ); return [columnWidth, columnCount]; }; const emptyArr: [] = [];
the_stack
import Dictionary from '../../../util/Dictionary'; import GraphHierarchyNode from '../datatypes/GraphHierarchyNode'; import GraphHierarchyEdge from '../datatypes/GraphHierarchyEdge'; import Cell from '../../cell/Cell'; import CellArray from '../../cell/CellArray'; import HierarchicalLayout from '../HierarchicalLayout'; import GraphAbstractHierarchyCell from '../datatypes/GraphAbstractHierarchyCell'; /** * Internal model of a hierarchical graph. This model stores nodes and edges * equivalent to the real graph nodes and edges, but also stores the rank of the * cells, the order within the ranks and the new candidate locations of cells. * The internal model also reverses edge direction were appropriate , ignores * self-loop and groups parallels together under one edge object. * * Constructor: mxGraphHierarchyModel * * Creates an internal ordered graph model using the vertices passed in. If * there are any, leftward edge need to be inverted in the internal model * * Arguments: * * graph - the facade describing the graph to be operated on * vertices - the vertices for this hierarchy * ordered - whether or not the vertices are already ordered * deterministic - whether or not this layout should be deterministic on each * tightenToSource - whether or not to tighten vertices towards the sources * scanRanksFromSinks - Whether rank assignment is from the sinks or sources. * usage */ class GraphHierarchyModel { constructor( layout: HierarchicalLayout, vertices: CellArray, roots: CellArray, parent: Cell, tightenToSource: boolean ) { const graph = layout.getGraph(); this.tightenToSource = tightenToSource; this.roots = roots; this.parent = parent; // map of cells to internal cell needed for second run through // to setup the sink of edges correctly this.vertexMapper = new Dictionary(); this.edgeMapper = new Dictionary(); this.maxRank = 0; const internalVertices: { [key: number]: GraphHierarchyNode } = {}; if (vertices == null) { vertices = graph.getChildVertices(parent); } this.maxRank = this.SOURCESCANSTARTRANK; // map of cells to internal cell needed for second run through // to setup the sink of edges correctly. Guess size by number // of edges is roughly same as number of vertices. this.createInternalCells(layout, vertices, internalVertices); // Go through edges set their sink values. Also check the // ordering if and invert edges if necessary for (let i = 0; i < vertices.length; i += 1) { const edges = internalVertices[i].connectsAsSource; for (let j = 0; j < edges.length; j++) { const internalEdge = edges[j]; const realEdges = internalEdge.edges; // Only need to process the first real edge, since // all the edges connect to the same other vertex if (realEdges != null && realEdges.length > 0) { const realEdge = realEdges[0]; let targetCell = layout.getVisibleTerminal(realEdge, false); let internalTargetCell = this.vertexMapper.get(<Cell>targetCell); if (internalVertices[i] === internalTargetCell) { // If there are parallel edges going between two vertices and not all are in the same direction // you can have navigated across one direction when doing the cycle reversal that isn't the same // direction as the first real edge in the array above. When that happens the if above catches // that and we correct the target cell before continuing. // This branch only detects this single case targetCell = layout.getVisibleTerminal(realEdge, true); internalTargetCell = this.vertexMapper.get(<Cell>targetCell); } if (internalTargetCell != null && internalVertices[i] !== internalTargetCell) { internalEdge.target = internalTargetCell; if (internalTargetCell.connectsAsTarget.length === 0) { internalTargetCell.connectsAsTarget = []; } if (internalTargetCell.connectsAsTarget.indexOf(internalEdge) < 0) { internalTargetCell.connectsAsTarget.push(internalEdge); } } } } // Use the temp variable in the internal nodes to mark this // internal vertex as having been visited. internalVertices[i].temp[0] = 1; } } /** * Stores the largest rank number allocated */ maxRank: number; /** * Map from graph vertices to internal model nodes. */ vertexMapper: Dictionary<Cell, GraphHierarchyNode>; /** * Map from graph edges to internal model edges */ edgeMapper: Dictionary<Cell, GraphHierarchyEdge>; /** * Mapping from rank number to actual rank */ ranks: GraphAbstractHierarchyCell[][] | null = null; /** * Store of roots of this hierarchy model, these are real graph cells, not * internal cells */ roots: CellArray | null = null; /** * The parent cell whose children are being laid out */ parent: Cell | null = null; /** * Count of the number of times the ancestor dfs has been used. */ dfsCount: number = 0; /** * High value to start source layering scan rank value from. */ SOURCESCANSTARTRANK: number = 100000000; /** * Whether or not to tighten the assigned ranks of vertices up towards * the source cells. */ tightenToSource: boolean = false; /** * Creates all edges in the internal model * * @param layout Reference to the <HierarchicalLayout> algorithm. * @param vertices Array of {@link Cells} that represent the vertices whom are to * have an internal representation created. * @param internalVertices The array of {@link GraphHierarchyNodes} to have their * information filled in using the real vertices. */ createInternalCells( layout: HierarchicalLayout, vertices: CellArray, internalVertices: { [key: number]: GraphHierarchyNode } ) { const graph = layout.getGraph(); // Create internal edges for (let i = 0; i < vertices.length; i += 1) { internalVertices[i] = new GraphHierarchyNode(vertices[i]); this.vertexMapper.put(vertices[i], internalVertices[i]); // If the layout is deterministic, order the cells // List outgoingCells = graph.getNeighbours(vertices[i], deterministic); const conns = layout.getEdges(vertices[i]); internalVertices[i].connectsAsSource = []; // Create internal edges, but don't do any rank assignment yet // First use the information from the greedy cycle remover to // invert the leftward edges internally for (let j = 0; j < conns.length; j++) { const cell = <Cell>layout.getVisibleTerminal(conns[j], false); // Looking for outgoing edges only if (cell !== vertices[i] && cell.isVertex() && !layout.isVertexIgnored(cell)) { // We process all edge between this source and its targets // If there are edges going both ways, we need to collect // them all into one internal edges to avoid looping problems // later. We assume this direction (source -> target) is the // natural direction if at least half the edges are going in // that direction. // The check below for edges[0] being in the vertex mapper is // in case we've processed this the other way around // (target -> source) and the number of edges in each direction // are the same. All the graph edges will have been assigned to // an internal edge going the other way, so we don't want to // process them again const undirectedEdges = layout.getEdgesBetween(vertices[i], cell, false); const directedEdges = layout.getEdgesBetween(vertices[i], cell, true); if ( undirectedEdges != null && undirectedEdges.length > 0 && this.edgeMapper.get(undirectedEdges[0]) == null && directedEdges.length * 2 >= undirectedEdges.length ) { const internalEdge = new GraphHierarchyEdge(undirectedEdges); for (let k = 0; k < undirectedEdges.length; k++) { const edge = undirectedEdges[k]; this.edgeMapper.put(edge, internalEdge); // Resets all point on the edge and disables the edge style // without deleting it from the cell style graph.resetEdge(edge); if (layout.disableEdgeStyle) { layout.setEdgeStyleEnabled(edge, false); layout.setOrthogonalEdge(edge, true); } } internalEdge.source = internalVertices[i]; if (internalVertices[i].connectsAsSource.indexOf(internalEdge) < 0) { internalVertices[i].connectsAsSource.push(internalEdge); } } } } // Ensure temp variable is cleared from any previous use internalVertices[i].temp[0] = 0; } } /** * Basic determination of minimum layer ranking by working from from sources * or sinks and working through each node in the relevant edge direction. * Starting at the sinks is basically a longest path layering algorithm. */ initialRank(): void { const startNodes: GraphHierarchyNode[] = []; if (this.roots != null) { for (let i = 0; i < this.roots.length; i += 1) { const internalNode = this.vertexMapper.get(this.roots[i]); if (internalNode != null) { startNodes.push(internalNode); } } } const internalNodes = this.vertexMapper.getValues(); for (let i = 0; i < internalNodes.length; i += 1) { // Mark the node as not having had a layer assigned internalNodes[i].temp[0] = -1; } const startNodesCopy = startNodes.slice(); while (startNodes.length > 0) { const internalNode = startNodes[0]; var layerDeterminingEdges; var edgesToBeMarked: GraphHierarchyEdge[] | null; layerDeterminingEdges = internalNode.connectsAsTarget; edgesToBeMarked = internalNode.connectsAsSource; // flag to keep track of whether or not all layer determining // edges have been scanned let allEdgesScanned = true; // Work out the layer of this node from the layer determining // edges. The minimum layer number of any node connected by one of // the layer determining edges variable let minimumLayer = this.SOURCESCANSTARTRANK; for (let i = 0; i < layerDeterminingEdges.length; i += 1) { const internalEdge = layerDeterminingEdges[i]; if (internalEdge.temp[0] === 5270620) { // This edge has been scanned, get the layer of the // node on the other end const otherNode = <GraphHierarchyNode>internalEdge.source; minimumLayer = Math.min(minimumLayer, otherNode.temp[0] - 1); } else { allEdgesScanned = false; break; } } // If all edge have been scanned, assign the layer, mark all // edges in the other direction and remove from the nodes list if (allEdgesScanned) { internalNode.temp[0] = minimumLayer; this.maxRank = Math.min(this.maxRank, minimumLayer); if (edgesToBeMarked != null) { for (let i = 0; i < edgesToBeMarked.length; i += 1) { const internalEdge = <GraphHierarchyEdge>edgesToBeMarked[i]; // Assign unique stamp ( y/m/d/h ) internalEdge.temp[0] = 5270620; // Add node on other end of edge to LinkedList of // nodes to be analysed const otherNode = <GraphHierarchyNode>internalEdge.target; // Only add node if it hasn't been assigned a layer if (otherNode.temp[0] === -1) { startNodes.push(otherNode); // Mark this other node as neither being // unassigned nor assigned so it isn't // added to this list again, but it's // layer isn't used in any calculation. otherNode.temp[0] = -2; } } } startNodes.shift(); } else { // Not all the edges have been scanned, get to the back of // the class and put the dunces cap on const removedCell = startNodes.shift(); startNodes.push(internalNode); if (removedCell === internalNode && startNodes.length === 1) { // This is an error condition, we can't get out of // this loop. It could happen for more than one node // but that's a lot harder to detect. Log the error // TODO make log comment break; } } } // Normalize the ranks down from their large starting value to place // at least 1 sink on layer 0 for (let i = 0; i < internalNodes.length; i += 1) { // Mark the node as not having had a layer assigned internalNodes[i].temp[0] -= this.maxRank; } // Tighten the rank 0 nodes as far as possible for (let i = 0; i < startNodesCopy.length; i += 1) { const internalNode = startNodesCopy[i]; let currentMaxLayer = 0; const layerDeterminingEdges = internalNode.connectsAsSource; for (let j = 0; j < layerDeterminingEdges.length; j++) { const internalEdge = layerDeterminingEdges[j]; const otherNode = <GraphHierarchyNode>internalEdge.target; internalNode.temp[0] = Math.max(currentMaxLayer, otherNode.temp[0] + 1); currentMaxLayer = internalNode.temp[0]; } } // Reset the maxRank to that which would be expected for a from-sink // scan this.maxRank = this.SOURCESCANSTARTRANK - this.maxRank; } /** * Fixes the layer assignments to the values stored in the nodes. Also needs * to create dummy nodes for edges that cross layers. */ fixRanks(): void { // TODO: Should this be a CellArray? const rankList: { [key: number]: GraphAbstractHierarchyCell[] } = {}; this.ranks = []; for (let i = 0; i < this.maxRank + 1; i += 1) { rankList[i] = []; this.ranks.push(rankList[i]); } // Perform a DFS to obtain an initial ordering for each rank. // Without doing this you would end up having to process // crossings for a standard tree. let rootsArray: GraphHierarchyNode[] | null = null; if (this.roots != null) { const oldRootsArray = this.roots; rootsArray = []; for (let i = 0; i < oldRootsArray.length; i += 1) { const cell = oldRootsArray[i]; const internalNode = this.vertexMapper.get(cell); rootsArray[i] = <GraphHierarchyNode>internalNode; } } this.visit( (parent: GraphHierarchyNode, node: GraphHierarchyNode, edge: GraphHierarchyNode, layer: number, seen: number) => { if (seen == 0 && node.maxRank < 0 && node.minRank < 0) { rankList[node.temp[0]].push(node); node.maxRank = node.temp[0]; node.minRank = node.temp[0]; // Set temp[0] to the nodes position in the rank node.temp[0] = rankList[node.maxRank].length - 1; } if (parent != null && edge != null) { const parentToCellRankDifference = parent.maxRank - node.maxRank; if (parentToCellRankDifference > 1) { // There are ranks in between the parent and current cell edge.maxRank = parent.maxRank; edge.minRank = node.maxRank; edge.temp = []; edge.x = []; edge.y = []; for (let i = edge.minRank + 1; i < edge.maxRank; i += 1) { // The connecting edge must be added to the // appropriate ranks rankList[i].push(edge); edge.setGeneralPurposeVariable(i, rankList[i].length - 1); } } } }, rootsArray, false, null ); } /** * A depth first search through the internal heirarchy model. * * @param visitor The visitor function pattern to be called for each node. * @param trackAncestors Whether or not the search is to keep track all nodes * directly above this one in the search path. */ visit( visitor: Function, dfsRoots: GraphHierarchyNode[] | null, trackAncestors: boolean, seenNodes: { [key: string]: GraphHierarchyNode } | null = null ): void { // Run dfs through on all roots if (dfsRoots != null) { for (let i = 0; i < dfsRoots.length; i += 1) { const internalNode = dfsRoots[i]; if (internalNode != null) { if (seenNodes == null) { seenNodes = {}; } if (trackAncestors) { // Set up hash code for root internalNode.hashCode = []; internalNode.hashCode[0] = this.dfsCount; internalNode.hashCode[1] = i; this.extendedDfs( null, internalNode, null, visitor, seenNodes, internalNode.hashCode, i, 0 ); } else { this.dfs(null, internalNode, null, visitor, seenNodes, 0); } } } this.dfsCount++; } } /** * Performs a depth first search on the internal hierarchy model * * @param parent the parent internal node of the current internal node * @param root the current internal node * @param connectingEdge the internal edge connecting the internal node and the parent * internal node, if any * @param visitor the visitor pattern to be called for each node * @param seen a set of all nodes seen by this dfs a set of all of the * ancestor node of the current node * @param layer the layer on the dfs tree ( not the same as the model ranks ) */ dfs( parent: GraphHierarchyNode | null, root: GraphHierarchyNode | null, connectingEdge: GraphHierarchyEdge | null, visitor: Function, seen: { [key: string]: GraphHierarchyNode | null }, layer: number ): void { if (root != null) { const rootId = <string>root.id; if (seen[rootId] == null) { seen[rootId] = root; visitor(parent, root, connectingEdge, layer, 0); // Copy the connects as source list so that visitors // can change the original for edge direction inversions const outgoingEdges = root.connectsAsSource.slice(); for (let i = 0; i < outgoingEdges.length; i += 1) { const internalEdge = outgoingEdges[i]; const targetNode = internalEdge.target; // Root check is O(|roots|) this.dfs(root, targetNode, internalEdge, visitor, seen, layer + 1); } } else { // Use the int field to indicate this node has been seen visitor(parent, root, connectingEdge, layer, 1); } } } /** * Performs a depth first search on the internal hierarchy model. This dfs * extends the default version by keeping track of cells ancestors, but it * should be only used when necessary because of it can be computationally * intensive for deep searches. * * @param parent the parent internal node of the current internal node * @param root the current internal node * @param connectingEdge the internal edge connecting the internal node and the parent * internal node, if any * @param visitor the visitor pattern to be called for each node * @param seen a set of all nodes seen by this dfs * @param ancestors the parent hash code * @param childHash the new hash code for this node * @param layer the layer on the dfs tree ( not the same as the model ranks ) */ extendedDfs( parent: GraphHierarchyNode | null, root: GraphHierarchyNode, connectingEdge: GraphHierarchyEdge | null, visitor: Function, seen: { [key: string]: GraphHierarchyNode }, ancestors: any, childHash: string | number, layer: number ) { // Explanation of custom hash set. Previously, the ancestors variable // was passed through the dfs as a HashSet. The ancestors were copied // into a new HashSet and when the new child was processed it was also // added to the set. If the current node was in its ancestor list it // meant there is a cycle in the graph and this information is passed // to the visitor.visit() in the seen parameter. The HashSet clone was // very expensive on CPU so a custom hash was developed using primitive // types. temp[] couldn't be used so hashCode[] was added to each node. // Each new child adds another int to the array, copying the prefix // from its parent. Child of the same parent add different ints (the // limit is therefore 2^32 children per parent...). If a node has a // child with the hashCode already set then the child code is compared // to the same portion of the current nodes array. If they match there // is a loop. // Note that the basic mechanism would only allow for 1 use of this // functionality, so the root nodes have two ints. The second int is // incremented through each node root and the first is incremented // through each run of the dfs algorithm (therefore the dfs is not // thread safe). The hash code of each node is set if not already set, // or if the first int does not match that of the current run. if (root != null) { if (parent != null) { // Form this nodes hash code if necessary, that is, if the // hashCode variable has not been initialized or if the // start of the parent hash code does not equal the start of // this nodes hash code, indicating the code was set on a // previous run of this dfs. if (root.hashCode == null || root.hashCode[0] != parent.hashCode[0]) { const hashCodeLength = parent.hashCode.length + 1; root.hashCode = parent.hashCode.slice(); root.hashCode[hashCodeLength - 1] = childHash; } } const rootId = <string>root.id; if (seen[rootId] == null) { seen[rootId] = root; visitor(parent, root, connectingEdge, layer, 0); // Copy the connects as source list so that visitors // can change the original for edge direction inversions const outgoingEdges = root.connectsAsSource.slice(); for (let i = 0; i < outgoingEdges.length; i += 1) { const internalEdge = outgoingEdges[i]; const targetNode = <GraphHierarchyNode>internalEdge.target; // Root check is O(|roots|) this.extendedDfs( root, targetNode, internalEdge, visitor, seen, root.hashCode, i, layer + 1 ); } } else { // Use the int field to indicate this node has been seen visitor(parent, root, connectingEdge, layer, 1); } } } } export default GraphHierarchyModel;
the_stack
import { Mutable, Class, Proto, Arrays, HashCode, Comparator, Dictionary, MutableDictionary, FromAny, Creatable, InitType, Initable, ObserverType, Observable, ObserverMethods, ObserverParameters, } from "@swim/util"; import {FastenerContext} from "../fastener/FastenerContext"; import type {Fastener} from "../fastener/Fastener"; import type {ComponentObserver} from "./ComponentObserver"; import {ComponentRelation} from "./"; // forward import /** @public */ export type ComponentFlags = number; /** @public */ export type AnyComponent<C extends Component = Component> = C | ComponentFactory<C> | InitType<C>; /** @public */ export interface ComponentInit { /** @internal */ uid?: never, // force type ambiguity between Component and ComponentInit type?: Creatable<Component>; key?: string; children?: AnyComponent[]; } /** @public */ export interface ComponentFactory<C extends Component = Component, U = AnyComponent<C>> extends Creatable<C>, FromAny<C, U> { fromInit(init: InitType<C>): C; } /** @public */ export interface ComponentClass<C extends Component = Component, U = AnyComponent<C>> extends Function, ComponentFactory<C, U> { readonly prototype: C; } /** @public */ export interface ComponentConstructor<C extends Component = Component, U = AnyComponent<C>> extends ComponentClass<C, U> { new(): C; } /** @public */ export type ComponentCreator<F extends Class<C> & Creatable<InstanceType<F>>, C extends Component = Component> = Class<InstanceType<F>> & Creatable<InstanceType<F>>; /** @public */ export class Component<C extends Component<C> = Component<any>> implements HashCode, FastenerContext, Initable<ComponentInit>, Observable { constructor() { this.uid = (this.constructor as typeof Component).uid(); this.key = void 0; this.flags = 0; this.parent = null; this.nextSibling = null; this.previousSibling = null; this.firstChild = null; this.lastChild = null; this.childMap = null; this.fasteners = null; this.decoherent = null; this.observers = Arrays.empty; FastenerContext.init(this); } get componentType(): Class<Component> { return Component; } /** @override */ readonly observerType?: Class<ComponentObserver>; /** @internal */ readonly uid: number; readonly key: string | undefined; /** @internal */ setKey(key: string | undefined): void { (this as Mutable<this>).key = key; } /** @internal */ readonly flags: ComponentFlags; /** @internal */ setFlags(flags: ComponentFlags): void { (this as Mutable<this>).flags = flags; } readonly parent: C | null; /** @internal */ attachParent(parent: C, nextSibling: C | null): void; attachParent(this: C, parent: C, nextSibling: C | null): void { // assert(this.parent === null); this.willAttachParent(parent); (this as Mutable<typeof this>).parent = parent; let previousSibling: C | null; if (nextSibling !== null) { previousSibling = nextSibling.previousSibling; this.setNextSibling(nextSibling); nextSibling.setPreviousSibling(this); } else { previousSibling = parent.lastChild; parent.setLastChild(this); } if (previousSibling !== null) { previousSibling.setNextSibling(this); this.setPreviousSibling(previousSibling); } else { parent.setFirstChild(this); } if (parent.mounted) { this.cascadeMount(); } this.onAttachParent(parent); this.didAttachParent(parent); } protected willAttachParent(parent: C): void { // hook } protected onAttachParent(parent: C): void { // hook } protected didAttachParent(parent: C): void { // hook } /** @internal */ detachParent(parent: C): void { // assert(this.parent === parent); this.willDetachParent(parent); if (this.mounted) { this.cascadeUnmount(); } this.onDetachParent(parent); const nextSibling = this.nextSibling; const previousSibling = this.previousSibling; if (nextSibling !== null) { this.setNextSibling(null); nextSibling.setPreviousSibling(previousSibling); } else { parent.setLastChild(previousSibling); } if (previousSibling !== null) { previousSibling.setNextSibling(nextSibling); this.setPreviousSibling(null); } else { parent.setFirstChild(nextSibling); } (this as Mutable<this>).parent = null; this.didDetachParent(parent); } protected willDetachParent(parent: C): void { // hook } protected onDetachParent(parent: C): void { // hook } protected didDetachParent(parent: C): void { // hook } readonly nextSibling: C | null; /** @internal */ setNextSibling(nextSibling: C | null): void { (this as Mutable<this>).nextSibling = nextSibling; } readonly previousSibling: C | null; /** @internal */ setPreviousSibling(previousSibling: C | null): void { (this as Mutable<this>).previousSibling = previousSibling; } readonly firstChild: C | null; /** @internal */ setFirstChild(firstChild: C | null): void { (this as Mutable<this>).firstChild = firstChild; } readonly lastChild: C | null; /** @internal */ setLastChild(lastChild: C | null): void { (this as Mutable<this>).lastChild = lastChild; } forEachChild<T>(callback: (child: C) => T | void): T | undefined; forEachChild<T, S>(callback: (this: S, child: C) => T | void, thisArg: S): T | undefined; forEachChild<T, S>(this: C, callback: (this: S | undefined, child: C) => T | void, thisArg?: S): T | undefined { let result: T | undefined; let child = this.firstChild; while (child !== null) { const next = child.nextSibling; const result = callback.call(thisArg, child); if (result !== void 0) { break; } child = next !== null && next.parent === this ? next : null; } return result; } /** @internal */ readonly childMap: Dictionary<C> | null; /** @internal */ protected insertChildMap(child: C): void { const key = child.key; if (key !== void 0) { let childMap = this.childMap as MutableDictionary<C>; if (childMap === null) { childMap = {}; (this as Mutable<this>).childMap = childMap; } childMap[key] = child; } } /** @internal */ protected removeChildMap(child: C): void { const key = child.key; if (key !== void 0) { const childMap = this.childMap as MutableDictionary<C>; if (childMap !== null) { delete childMap[key]; } } } getChild<F extends Class<C>>(key: string, childBound: F): InstanceType<F> | null; getChild(key: string, childBound?: Class<C>): C | null; getChild(key: string, childBound?: Class<C>): C | null { const childMap = this.childMap; if (childMap !== null) { const child = childMap[key]; if (child !== void 0 && (childBound === void 0 || child instanceof childBound)) { return child; } } return null; } setChild(key: string, newChild: C | null): C | null; setChild(this: C, key: string, newChild: C | null): C | null { const oldChild = this.getChild(key); let target: C | null; if (oldChild !== null && newChild !== null && oldChild !== newChild) { // replace newChild.remove(); target = oldChild.nextSibling; if ((oldChild.flags & Component.RemovingFlag) === 0) { oldChild.setFlags(oldChild.flags | Component.RemovingFlag); this.willRemoveChild(oldChild); oldChild.detachParent(this); this.removeChildMap(oldChild); this.onRemoveChild(oldChild); this.didRemoveChild(oldChild); oldChild.setKey(void 0); oldChild.setFlags(oldChild.flags & ~Component.RemovingFlag); } newChild.setKey(oldChild.key); this.willInsertChild(newChild, target); this.insertChildMap(newChild); newChild.attachParent(this, target); this.onInsertChild(newChild, target); this.didInsertChild(newChild, target); newChild.cascadeInsert(); } else if (newChild !== oldChild || newChild !== null && newChild.key !== key) { if (oldChild !== null) { // remove target = oldChild.nextSibling; if ((oldChild.flags & Component.RemovingFlag) === 0) { oldChild.setFlags(oldChild.flags | Component.RemovingFlag); this.willRemoveChild(oldChild); oldChild.detachParent(this); this.removeChildMap(oldChild); this.onRemoveChild(oldChild); this.didRemoveChild(oldChild); oldChild.setKey(void 0); oldChild.setFlags(oldChild.flags & ~Component.RemovingFlag); } } else { target = null; } if (newChild !== null) { // insert newChild.remove(); newChild.setKey(key); this.willInsertChild(newChild, target); this.insertChildMap(newChild); newChild.attachParent(this, target); this.onInsertChild(newChild, target); this.didInsertChild(newChild, target); newChild.cascadeInsert(); } } return oldChild; } appendChild<Child extends C>(child: Child, key?: string): Child; appendChild(child: C, key?: string): C; appendChild(this: C, child: C, key?: string): C { child.remove(); if (key !== void 0) { this.removeChild(key); } child.setKey(key); this.willInsertChild(child, null); this.insertChildMap(child); child.attachParent(this, null); this.onInsertChild(child, null); this.didInsertChild(child, null); child.cascadeInsert(); return child; } prependChild<Child extends C>(child: Child, key?: string): Child; prependChild(child: C, key?: string): C; prependChild(this: C, child: C, key?: string): C { child.remove(); if (key !== void 0) { this.removeChild(key); } const target = this.firstChild; child.setKey(key); this.willInsertChild(child, target); this.insertChildMap(child); child.attachParent(this, target); this.onInsertChild(child, target); this.didInsertChild(child, target); child.cascadeInsert(); return child; } insertChild<Child extends C>(child: Child, target: C | null, key?: string): Child; insertChild(child: C, target: C | null, key?: string): C; insertChild(this: C, child: C, target: C | null, key?: string): C { if (target !== null && target.parent !== this) { throw new Error("insert target is not a child"); } child.remove(); if (key !== void 0) { this.removeChild(key); } child.setKey(key); this.willInsertChild(child, target); this.insertChildMap(child); child.attachParent(this, target); this.onInsertChild(child, target); this.didInsertChild(child, target); child.cascadeInsert(); return child; } replaceChild<Child extends C>(newChild: C, oldChild: Child): Child; replaceChild(newChild: C, oldChild: C): C; replaceChild(this: C, newChild: C, oldChild: C): C { if (oldChild.parent !== this) { throw new Error("replacement target is not a child"); } if (newChild !== oldChild) { newChild.remove(); const target = oldChild.nextSibling; if ((oldChild.flags & Component.RemovingFlag) === 0) { oldChild.setFlags(oldChild.flags | Component.RemovingFlag); this.willRemoveChild(oldChild); oldChild.detachParent(this); this.removeChildMap(oldChild); this.onRemoveChild(oldChild); this.didRemoveChild(oldChild); oldChild.setKey(void 0); oldChild.setFlags(oldChild.flags & ~Component.RemovingFlag); } newChild.setKey(oldChild.key); this.willInsertChild(newChild, target); this.insertChildMap(newChild); newChild.attachParent(this, target); this.onInsertChild(newChild, target); this.didInsertChild(newChild, target); newChild.cascadeInsert(); } return oldChild; } get insertChildFlags(): ComponentFlags { return (this.constructor as typeof Component).InsertChildFlags; } protected willInsertChild(child: C, target: C | null): void { // hook } protected onInsertChild(child: C, target: C | null): void { this.requireUpdate(this.insertChildFlags); this.bindChildFasteners(child, target); } protected didInsertChild(child: C, target: C | null): void { // hook } /** @internal */ cascadeInsert(): void { // hook } removeChild<Child extends C>(child: Child): Child; removeChild(child: C): C; removeChild(key: string | C): C | null; removeChild(this: C, key: string | C): C | null { let child: C | null; if (typeof key === "string") { child = this.getChild(key); if (child === null) { return null; } } else { child = key; if (child.parent !== this) { throw new Error("not a child"); } } if ((child.flags & Component.RemovingFlag) === 0) { child.setFlags(child.flags | Component.RemovingFlag); this.willRemoveChild(child); child.detachParent(this); this.removeChildMap(child); this.onRemoveChild(child); this.didRemoveChild(child); child.setKey(void 0); child.setFlags(child.flags & ~Component.RemovingFlag); } return child; } get removeChildFlags(): ComponentFlags { return (this.constructor as typeof Component).RemoveChildFlags; } protected willRemoveChild(child: C): void { // hook } protected onRemoveChild(child: C): void { this.requireUpdate(this.removeChildFlags); this.unbindChildFasteners(child); } protected didRemoveChild(child: C): void { // hook } removeChildren(): void removeChildren(this: C): void { let child: C | null; while (child = this.lastChild, child !== null) { if ((child.flags & Component.RemovingFlag) !== 0) { throw new Error("inconsistent removeChildren"); } this.willRemoveChild(child); child.detachParent(this); this.removeChildMap(child); this.onRemoveChild(child); this.didRemoveChild(child); child.setKey(void 0); child.setFlags(child.flags & ~Component.RemovingFlag); } } remove(): void; remove(this: C): void { const parent = this.parent; if (parent !== null) { parent.removeChild(this); } } sortChildren(comparator: Comparator<C>): void { let child = this.firstChild; if (child !== null) { const children: C[] = []; do { children.push(child); child = child.nextSibling; } while (child !== null); children.sort(comparator); child = children[0]!; this.setFirstChild(child); child.setPreviousSibling(null); for (let i = 1; i < children.length; i += 1) { const next = children[i]!; child.setNextSibling(next); next.setPreviousSibling(child); child = next; } child.setNextSibling(null); this.setLastChild(child); } } getSuper<F extends Class<C>>(superBound: F): InstanceType<F> | null; getSuper(superBound: Class<C>): C | null; getSuper(superBound: Class<C>): C | null { const parent = this.parent; if (parent === null) { return null; } else if (parent instanceof superBound) { return parent; } else { return (parent as C).getSuper(superBound); } } getBase<F extends Class<C>>(baseBound: F): InstanceType<F> | null; getBase(baseBound: Class<C>): C | null; getBase(baseBound: Class<C>): C | null { const parent = this.parent; if (parent === null) { return null; } else { const base = parent.getBase(baseBound); if (base !== null) { return base; } else { return parent instanceof baseBound ? parent : null; } } } get mounted(): boolean { return (this.flags & Component.MountedFlag) !== 0; } get mountFlags(): ComponentFlags { return (this.constructor as typeof Component).MountFlags; } mount(): void { if (!this.mounted && this.parent === null) { this.cascadeMount(); this.cascadeInsert(); } } /** @internal */ cascadeMount(): void { if ((this.flags & Component.MountedFlag) === 0) { this.willMount(); this.setFlags(this.flags | Component.MountedFlag); this.onMount(); this.mountChildren(); this.didMount(); } else { throw new Error("already mounted"); } } protected willMount(): void { // hook } protected onMount(): void { this.requireUpdate(this.mountFlags); this.mountFasteners(); } protected didMount(): void { // hook } /** @internal */ protected mountChildren(): void; protected mountChildren(this: C): void { let child = this.firstChild; while (child !== null) { const next = child.nextSibling; child.cascadeMount(); if (next !== null && next.parent !== this) { throw new Error("inconsistent mount"); } child = next; } } unmount(): void { if (this.mounted && this.parent === null) { this.cascadeUnmount(); } } /** @internal */ cascadeUnmount(): void { if ((this.flags & Component.MountedFlag) !== 0) { this.willUnmount(); this.setFlags(this.flags & ~Component.MountedFlag); this.unmountChildren(); this.onUnmount(); this.didUnmount(); } else { throw new Error("already unmounted"); } } protected willUnmount(): void { // hook } protected onUnmount(): void { this.unmountFasteners(); } protected didUnmount(): void { // hook } /** @internal */ protected unmountChildren(): void; protected unmountChildren(this: C): void { let child = this.lastChild; while (child !== null) { const prev = child.previousSibling; child.cascadeUnmount(); if (prev !== null && prev.parent !== this) { throw new Error("inconsistent unmount"); } child = prev; } } requireUpdate(updateFlags: ComponentFlags, immediate?: boolean): void { // hook } /** @internal */ readonly fasteners: {[fastenerName: string]: Fastener | undefined} | null; /** @override */ hasFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): boolean { const fasteners = this.fasteners; if (fasteners !== null) { const fastener = fasteners[fastenerName]; if (fastener !== void 0 && (fastenerBound === void 0 || fastenerBound === null || fastener instanceof fastenerBound)) { return true; } } return false; } /** @override */ getFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null; /** @override */ getFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null; getFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null { const fasteners = this.fasteners; if (fasteners !== null) { const fastener = fasteners[fastenerName]; if (fastener !== void 0 && (fastenerBound === void 0 || fastenerBound === null || fastener instanceof fastenerBound)) { return fastener; } } return null; } /** @override */ setFastener(fastenerName: string, newFastener: Fastener | null): void { const fasteners = this.fasteners; const oldFastener: Fastener | null | undefined = fasteners !== null ? fasteners[fastenerName] ?? null : null; if (oldFastener !== newFastener) { if (oldFastener !== null) { this.detachFastener(fastenerName, oldFastener); } if (newFastener !== null) { this.attachFastener(fastenerName, newFastener); } } } /** @internal */ protected attachFastener(fastenerName: string, fastener: Fastener): void { let fasteners = this.fasteners; if (fasteners === null) { fasteners = {}; (this as Mutable<this>).fasteners = fasteners; } // assert(fasteners[fastenerName] === void 0); this.willAttachFastener(fastenerName, fastener); fasteners[fastenerName] = fastener; if (this.mounted) { fastener.mount(); } this.onAttachFastener(fastenerName, fastener); this.didAttachFastener(fastenerName, fastener); } protected willAttachFastener(fastenerName: string, fastener: Fastener): void { // hook } protected onAttachFastener(fastenerName: string, fastener: Fastener): void { this.bindFastener(fastener); } protected didAttachFastener(fastenerName: string, fastener: Fastener): void { // hook } /** @internal */ protected detachFastener(fastenerName: string, fastener: Fastener): void { const fasteners = this.fasteners!; // assert(fasteners !== null); // assert(fasteners[fastenerName] === fastener); this.willDetachFastener(fastenerName, fastener); this.onDetachFastener(fastenerName, fastener); if (this.mounted) { fastener.unmount(); } delete fasteners[fastenerName]; this.didDetachFastener(fastenerName, fastener); } protected willDetachFastener(fastenerName: string, fastener: Fastener): void { // hook } protected onDetachFastener(fastenerName: string, fastener: Fastener): void { // hook } protected didDetachFastener(fastenerName: string, fastener: Fastener): void { // hook } /** @override */ getLazyFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null; /** @override */ getLazyFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null; getLazyFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null { return FastenerContext.getLazyFastener(this, fastenerName, fastenerBound); } /** @override */ getSuperFastener<F extends Fastener<any>>(fastenerName: string, fastenerBound: Proto<F>): F | null; /** @override */ getSuperFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null; getSuperFastener(fastenerName: string, fastenerBound?: Proto<Fastener> | null): Fastener | null { const parent = this.parent; if (parent === null) { return null; } else { const parentFastener = parent.getLazyFastener(fastenerName, fastenerBound); if (parentFastener !== null) { return parentFastener; } else { return parent.getSuperFastener(fastenerName, fastenerBound); } } } /** @internal */ protected mountFasteners(): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; fastener.mount(); } } /** @internal */ protected unmountFasteners(): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; fastener.unmount(); } } protected bindFastener(fastener: Fastener): void; protected bindFastener(this: C, fastener: Fastener): void { if (fastener.binds) { let child = this.firstChild; while (child !== null) { const next = child.nextSibling; this.bindChildFastener(fastener, child, next); child = next !== null && next.parent === this ? next : null; } } } /** @internal */ protected bindChildFasteners(child: C, target: C | null): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; this.bindChildFastener(fastener, child, target); } } /** @internal */ protected bindChildFastener(fastener: Fastener, child: C, target: C | null): void { if (fastener instanceof ComponentRelation) { fastener.bindComponent(child, target); } } /** @internal */ protected unbindChildFasteners(child: C): void { const fasteners = this.fasteners; for (const fastenerName in fasteners) { const fastener = fasteners[fastenerName]!; this.unbindChildFastener(fastener, child); } } /** @internal */ protected unbindChildFastener(fastener: Fastener, child: C): void { if (fastener instanceof ComponentRelation) { fastener.unbindComponent(child); } } /** @internal */ readonly decoherent: ReadonlyArray<Fastener> | null; /** @override */ decohereFastener(fastener: Fastener): void { let decoherent = this.decoherent as Fastener[]; if (decoherent === null) { decoherent = []; (this as Mutable<this>).decoherent = decoherent; } decoherent.push(fastener); } recohereFasteners(t?: number): void { const decoherent = this.decoherent; if (decoherent !== null) { const decoherentCount = decoherent.length; if (decoherentCount !== 0) { if (t === void 0) { t = performance.now(); } (this as Mutable<this>).decoherent = null; for (let i = 0; i < decoherentCount; i += 1) { const fastener = decoherent[i]!; fastener.recohere(t); } } } } /** @internal */ readonly observers: ReadonlyArray<ObserverType<this>>; /** @override */ observe(observer: ObserverType<this>): void { const oldObservers = this.observers; const newObservers = Arrays.inserted(observer, oldObservers); if (oldObservers !== newObservers) { this.willObserve(observer); (this as Mutable<this>).observers = newObservers; this.onObserve(observer); this.didObserve(observer); } } protected willObserve(observer: ObserverType<this>): void { // hook } protected onObserve(observer: ObserverType<this>): void { // hook } protected didObserve(observer: ObserverType<this>): void { // hook } /** @override */ unobserve(observer: ObserverType<this>): void { const oldObservers = this.observers; const newObservers = Arrays.removed(observer, oldObservers); if (oldObservers !== newObservers) { this.willUnobserve(observer); (this as Mutable<this>).observers = newObservers; this.onUnobserve(observer); this.didUnobserve(observer); } } protected willUnobserve(observer: ObserverType<this>): void { // hook } protected onUnobserve(observer: ObserverType<this>): void { // hook } protected didUnobserve(observer: ObserverType<this>): void { // hook } forEachObserver<T>(callback: (this: this, observer: ObserverType<this>) => T | void): T | undefined { let result: T | undefined; const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]!; result = callback.call(this, observer as ObserverType<this>) as T | undefined; if (result !== void 0) { return result; } } return result; } callObservers<O, K extends keyof ObserverMethods<O>>(this: this & {readonly observerType?: Class<O>}, key: K, ...args: ObserverParameters<O, K>): void { const observers = this.observers; for (let i = 0, n = observers.length; i < n; i += 1) { const observer = observers[i]! as ObserverMethods<O>; const method = observer[key]; if (typeof method === "function") { method.call(observer, ...args); } } } /** @override */ equals(that: unknown): boolean { return this === that; } /** @override */ hashCode(): number { return this.uid; } /** @override */ init(init: ComponentInit): void { // hook } static create<F extends new () => InstanceType<F>>(this: F): InstanceType<F> { return new this(); } static fromInit<F extends Class<InstanceType<F>>>(this: F, init: InitType<InstanceType<F>>): InstanceType<F> { let type: Creatable<InstanceType<F>>; if ((typeof init === "object" && init !== null || typeof init === "function") && Creatable.is((init as ComponentInit).type)) { type = (init as ComponentInit).type as Creatable<InstanceType<F>>; } else { type = this as unknown as Creatable<InstanceType<F>>; } const component = type.create(); (component as Initable<InitType<F>>).init(init); return component; } static fromAny<F extends Class<InstanceType<F>>>(this: F, value: AnyComponent<InstanceType<F>>): InstanceType<F> { if (value === void 0 || value === null) { return value as InstanceType<F>; } else if (value instanceof Component) { if (value instanceof this) { return value; } else { throw new TypeError(value + " not an instance of " + this); } } else if (Creatable.is(value)) { return (value as Creatable<InstanceType<F>>).create(); } else { return (this as unknown as ComponentFactory<InstanceType<F>>).fromInit(value); } } /** @internal */ static uid: () => number = (function () { let nextId = 1; return function uid(): number { const id = ~~nextId; nextId += 1; return id; } })(); /** @internal */ static readonly MountedFlag: ComponentFlags = 1 << 0; /** @internal */ static readonly RemovingFlag: ComponentFlags = 1 << 1; /** @internal */ static readonly FlagShift: number = 2; /** @internal */ static readonly FlagMask: ComponentFlags = (1 << Component.FlagShift) - 1; static readonly MountFlags: ComponentFlags = 0; static readonly InsertChildFlags: ComponentFlags = 0; static readonly RemoveChildFlags: ComponentFlags = 0; }
the_stack
import { createContext } from 'react' import { deleteDeepProp, setDeepProp, typeCheck, randomString, generateArrayKeyReg, generateReg, } from '@jdfed/utils' import addField from './addField' import deleteField from './deleteField' import { upgradeTips, toArray } from '@jdfed/utils' import type { Action, State, SetErrType } from '@jdfed/utils' export const FormDataContext = createContext('') const formDataReducer = (state: State, action: Action): void => { const type = action.type switch (type) { // 即将废弃,建议使用reset case 'reload': { upgradeTips('reload', 'reset') // eslint-disable-next-line @typescript-eslint/no-unused-vars const { type, ...args } = action Object.assign(state, args) break } case 'reset': { Object.assign(state, action.action.state) break } // 即将废弃,使用setValidate case 'setDataSchema': { upgradeTips('setDataSchema', 'setValidate') // eslint-disable-next-line @typescript-eslint/no-unused-vars const { type, ...args } = action if (args.dataSchema) { state.dataSchema = args.dataSchema } else { for (const i in args) { const mapKeys = i.split('.') if (args?.isDelete) { deleteDeepProp(mapKeys, state.dataSchema) } else { setDeepProp(mapKeys, state.dataSchema, args[i]) } } } break } case 'setValidate': { const { set, dataSchema } = action.action let deleteKeys = action.action.deleteKeys if (set) { for (const i in set) { setDeepProp(i.split('.'), state.dataSchema, set[i]) } } if (deleteKeys) { deleteKeys = toArray(deleteKeys) deleteKeys.map((fieldKey) => { deleteDeepProp(fieldKey.split('.'), state.dataSchema) }) } if (dataSchema) { state.dataSchema = dataSchema } break } // 即将废弃,建议使用setUi case 'setUiSchema': { upgradeTips('setUiSchema', 'setUi') // eslint-disable-next-line @typescript-eslint/no-unused-vars const { type, ...args } = action if (args.uiSchema) { state.uiSchema = args.uiSchema } else { for (const i in args) { const mapKeys = i.split('.') setDeepProp(mapKeys, state.uiSchema, args[i]) } } break } // 即将废弃,建议使用setUi case 'deleteUiSchema': { upgradeTips('deleteUiSchema', 'setUi') const mapKeys = action.key.split('.') deleteDeepProp(mapKeys, state.uiSchema) break } case 'setUi': { const { set, uiSchema } = action.action let deleteKeys = action.action.deleteKeys if (set) { for (const i in set) { setDeepProp(i.split('.'), state.uiSchema, set[i]) } } if (deleteKeys) { deleteKeys = toArray(deleteKeys) deleteKeys.map((fieldKey) => { deleteDeepProp(fieldKey.split('.'), state.uiSchema) }) } if (uiSchema) { state.uiSchema = uiSchema } break } // 即将废弃,建议使用setData case 'setFormData': { upgradeTips('setFormData', 'setData') // eslint-disable-next-line @typescript-eslint/no-unused-vars const { type, ...args } = action if (args.formData) { state.formData = args.formData } else { for (const i in args) { setDeepProp(i.split('.'), state.formData, args[i], state.typePath) // 将当前变化的key记录下来 state.changeKey = i } } break } // 即将废弃,建议使用setData case 'deleteFormData': { upgradeTips('setFormData', 'setData') state.changeKey = action.key const mapKeys = action.key.split('.') deleteDeepProp(mapKeys, state.formData) break } case 'setData': { const { set, formData } = action.action let deleteKeys = action.action.deleteKeys if (set) { for (const i in set) { setDeepProp(i.split('.'), state.formData, set[i], state.typePath) // 将当前变化的key记录下来 state.changeKey = i } } if (deleteKeys) { deleteKeys = toArray(deleteKeys) deleteKeys.map((fieldKey) => { state.changeKey = fieldKey deleteDeepProp(fieldKey.split('.'), state.formData) }) } if (formData) { state.formData = formData } break } case 'deleteField': { deleteField({ action: action.action, state }) break } case 'addField': { addField({ action: action.action, state }) break } case 'setAjvErr': { let deleteKeys = action.action.deleteKeys const { errors, set } = action.action if (set) { for (const i in set) { state.ajvErrors[i] = set[i] } } if (deleteKeys) { deleteKeys = toArray(deleteKeys) deleteKeys.map((fieldKey) => { delete state.ajvErrors[fieldKey] }) } if (errors) { state.ajvErrors = errors } break } // 即将废弃,建议使用setErr case 'setError': { upgradeTips('setError', 'setErr') // eslint-disable-next-line @typescript-eslint/no-unused-vars const { type, ...args } = action if (args.errors && typeCheck(args.errors) === 'Object') { const ignoreErr: Record<string, string> = {} // ignore 用来将type:change的异步校验的结果保存下来。防止被validae给清空 if ( (args.ignore && Array.isArray(args.ignore)) || state.ignoreErrKey.length > 0 ) { Array.from( new Set([...(args.ignore || []), ...state.ignoreErrKey]) ).map((item) => { if (state.errors[item]) { ignoreErr[item] = state.errors[item] } }) } state.errors = { ...(args.errors as Record<string, string>), ...ignoreErr, } } else { for (const i in args) { const params = args as SetErrType if (params?.action?.ignore) { state.ignoreErrKey = Array.from( new Set([...state.ignoreErrKey, ...params.action.ignore]) ) } state.errors[i] = args[i as keyof typeof args] as string } } break } // 即将废弃,建议使用setErr case 'deleteError': { upgradeTips('deleteError', 'setErr') if (Array.isArray(action.key)) { action.key.map((item) => { delete state.errors[item] }) } else { delete state.errors[action.key] } break } case 'setErr': { let deleteKeys = action.action.deleteKeys const { errors, set } = action.action if (set) { for (const i in set) { state.customErrors[i] = set[i] } } if (deleteKeys) { deleteKeys = toArray(deleteKeys) deleteKeys.map((fieldKey) => { const arr: Array<Record<string, string>> = [] Object.keys(state.customErrors).map((key) => { const reg = new RegExp( `^${fieldKey.split('.').join('\\.')}(\\..+)*`, 'g' ) // 判断是否有嵌套,删除嵌套 if (reg.test(key)) { delete state.customErrors[key] } const fieldKeyToTypeMap = Object.keys(state.typePath).find( (item) => { const startArr = fieldKey.split('.') startArr.pop() return generateReg(startArr).test(item) } ) if ( fieldKeyToTypeMap && state.typePath[fieldKeyToTypeMap]?.type === 'array' ) { const fieldKeyArr = fieldKey.split('.') const order = fieldKeyArr.pop() as string const reg = new RegExp( `^${fieldKeyArr.join('\\.')}\\.(\\d)(\\..+)*`, 'g' ) const res = reg.exec(key) // 嵌套情况:需要重新设置被删除的项的后续项的arrayKey if (res !== null) { const [, index, end] = res if (+index >= +order) { arr[+index] = { ...arr[+index], [end || '']: state.customErrors[key], } } } } }) // 父元素是数组,删除需要切换 if (arr.length > 0) { const fieldKeyArr = fieldKey.split('.') fieldKeyArr.pop() const start = fieldKeyArr.join('.') arr.map((item, index) => { if (!item) return for (const i in item) { if (state.customErrors[`${start}.${+index + 1}${i}`]) { state.customErrors[`${start}.${index}${i}`] = state.customErrors[`${start}.${+index + 1}${i}`] } else { delete state.customErrors[`${start}.${index}${i}`] } } }) } }) } if (errors) { state.customErrors = errors } break } case 'setChecking': { if ('action' in action) { state.checking = action.action.checking } else { state.checking = action.checking } break } case 'setVisibleKey': { let { fieldKey, deleteKeys } = action.action if (fieldKey) { fieldKey = toArray(fieldKey) state.visibleFieldKey = Array.from( new Set([...state.visibleFieldKey, ...fieldKey]) ) } if (deleteKeys) { deleteKeys = toArray(deleteKeys) state.visibleFieldKey = state.visibleFieldKey.filter( (item) => !deleteKeys?.includes(item) ) } break } case 'setDefaultSuccess': { state.hasDefault = action.action.hasDefault break } case 'setArrayKey': { const { isDelete, fieldKey, order, move } = action.action // 当前数组的所有react key let fieldKeyComKey = state.arrayKey[fieldKey] || [] const hasOrder = Object.prototype.hasOwnProperty.call( action.action, 'order' ) if (isDelete && hasOrder && typeof order === 'number') { fieldKeyComKey.splice(order, 1) // 需要交换的数据 const arr: Record<string, string[]>[] = [] // 若存在嵌套,批量切换后续嵌套 Object.keys(state.arrayKey).map((item) => { const reg = generateArrayKeyReg( fieldKey.split('.').concat(String(order)) ) const res = reg.exec(item) // 嵌套情况:需要重新设置被删除的项的后续项的arrayKey if (res !== null) { const [, , index, end] = res if (+index >= order) { arr[+index] = { ...arr[+index], [end]: state.arrayKey[item], } } } }) arr.map((item, index) => { if (!item) return for (const i in item) { if (index === arr.length - 1) { delete state.arrayKey[`${fieldKey}.${index}${i}`] } else { state.arrayKey[`${fieldKey}.${index}${i}`] = state.arrayKey[`${fieldKey}.${+index + 1}${i}`] } } }) } else { if (move) { fieldKeyComKey.splice( move[1], 0, fieldKeyComKey.splice(move[0], 1)[0] ) // 若存在嵌套,批量切换后续嵌套 // 需要交换的arrayKey let change: Record<string, string[]> // 需要交换的customErr let changeCustomError: Record<string, string> // 需要交换的arrayKey const arr: Record<string, string[]>[] = [] // 需要交换的customErrors const customErrorsArr: Array<Record<string, string>> = [] // 拖拽方向 let direction = '' Object.keys(state.arrayKey).map((item) => { const reg = generateArrayKeyReg( fieldKey.split('.').concat(String(order)) ) const res = reg.exec(item) // 嵌套情况:需要重新设置被删除的项的后续项的arrayKey if (res !== null) { const [, , index, end] = res // 从上往下拖拽 if (move[0] < move[1]) { direction = 'topToBottom' if (+index >= move[0] && +index <= move[1]) { arr[+index] = { ...arr[+index], [end]: state.arrayKey[item], } } } else { // 从下往上拖拽 direction = 'bottomToTop' if (+index <= move[0] && +index >= move[1]) { arr[+index] = { ...arr[+index], [end]: state.arrayKey[item], } } } } }) Object.keys(state.customErrors).map((item) => { const fieldKeyArr = fieldKey.split('.') const reg = new RegExp( `^${fieldKeyArr.join('\\.')}\\.(\\d)(\\..+)*`, 'g' ) const res = reg.exec(item) // 嵌套情况:需要重新设置被删除的项的后续项的arrayKey if (res !== null) { const [, index, end] = res // 从上往下拖拽 if (move[0] < move[1]) { direction = 'topToBottom' if (+index >= move[0] && +index <= move[1]) { customErrorsArr[+index] = { ...customErrorsArr[+index], [end || '']: state.customErrors[item], } } } else { // 从下往上拖拽 direction = 'bottomToTop' if (+index <= move[0] && +index >= move[1]) { customErrorsArr[+index] = { ...customErrorsArr[+index], [end || '']: state.customErrors[item], } } } } }) switch (direction) { case 'topToBottom': { arr.map((item, index) => { if (!item) return if (+index === move[0]) { change = item for (const i in item) { state.arrayKey[`${fieldKey}.${index}${i}`] = state.arrayKey[`${fieldKey}.${+index + 1}${i}`] } } else if (+index === move[1]) { for (const i in change) { state.arrayKey[`${fieldKey}.${index}${i}`] = change[i] } } else { for (const i in item) { state.arrayKey[`${fieldKey}.${index}${i}`] = state.arrayKey[`${fieldKey}.${+index + 1}${i}`] } } }) customErrorsArr.map((item, index) => { if (!item) return if (+index === move[0]) { changeCustomError = item for (const i in item) { state.customErrors[`${fieldKey}.${index}${i}`] = state.customErrors[`${fieldKey}.${+index + 1}${i}`] } } else if (+index === move[1]) { for (const i in changeCustomError) { state.customErrors[`${fieldKey}.${index}${i}`] = changeCustomError[i] } } else { for (const i in item) { state.customErrors[`${fieldKey}.${index}${i}`] = state.customErrors[`${fieldKey}.${+index + 1}${i}`] } } }) break } case 'bottomToTop': arr .slice() .reverse() .map((item, index, arr) => { if (!item) return const newIndex = arr.length - 1 - +index if (newIndex === move[0]) { change = item for (const i in item) { state.arrayKey[`${fieldKey}.${newIndex}${i}`] = state.arrayKey[`${fieldKey}.${newIndex - 1}${i}`] } } else if (newIndex === move[1]) { for (const i in change) { state.arrayKey[`${fieldKey}.${newIndex}${i}`] = change[i] } } else { for (const i in item) { state.arrayKey[`${fieldKey}.${newIndex}${i}`] = state.arrayKey[`${fieldKey}.${newIndex - 1}${i}`] } } }) customErrorsArr .slice() .reverse() .map((item, index, arr) => { if (!item) return const newIndex = arr.length - 1 - +index if (newIndex === move[0]) { changeCustomError = item for (const i in item) { state.customErrors[`${fieldKey}.${newIndex}${i}`] = state.customErrors[`${fieldKey}.${newIndex - 1}${i}`] } } else if (newIndex === move[1]) { for (const i in changeCustomError) { state.customErrors[`${fieldKey}.${newIndex}${i}`] = changeCustomError[i] } } else { for (const i in item) { state.customErrors[`${fieldKey}.${newIndex}${i}`] = state.customErrors[`${fieldKey}.${newIndex - 1}${i}`] } } }) break default: break } } else if (hasOrder && typeof order === 'number') { fieldKeyComKey[order] = randomString(52) } else { try { const formDataKey = fieldKey.split('.') const fieldData = formDataKey.reduce((prev, cur) => { if (prev[cur]) { return prev[cur] } else { return [] } }, state.formData) fieldKeyComKey = fieldData.map(() => { return randomString(52) }) } catch (error) { // console.log(error) } } state.arrayKey[fieldKey] = fieldKeyComKey } } } } export default formDataReducer
the_stack
import { AfterViewInit, Component, ElementRef, Input, OnDestroy, OnInit, ViewChild, ViewEncapsulation, EventEmitter, Output } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Pagination, UserProcessInstanceFilterRepresentation, ScriptFilesApi } from '@alfresco/js-api'; import { FORM_FIELD_VALIDATORS, FormRenderingService, FormService, DynamicTableRow, ValidateDynamicTableRowEvent, AppConfigService, PaginationComponent, UserPreferenceValues, AlfrescoApiService, UserPreferencesService, LogService, DataCellEvent, NotificationService } from '@alfresco/adf-core'; import { AnalyticsReportListComponent } from '@alfresco/adf-insights'; import { ProcessFiltersComponent, ProcessInstance, ProcessInstanceDetailsComponent, ProcessInstanceListComponent, StartProcessInstanceComponent, AppsListComponent, FilterRepresentationModel, TaskDetailsComponent, TaskDetailsEvent, TaskFiltersComponent, TaskListComponent, ProcessFormRenderingService } from '@alfresco/adf-process-services'; import { Subject } from 'rxjs'; import { /*CustomEditorComponent*/ CustomStencil01 } from './custom-editor/custom-editor.component'; import { DemoFieldValidator } from './demo-field-validator'; import { PreviewService } from '../../services/preview.service'; import { Location } from '@angular/common'; import { takeUntil } from 'rxjs/operators'; const currentProcessIdNew = '__NEW__'; const currentTaskIdNew = '__NEW__'; const TASK_ROUTE = 0; const PROCESS_ROUTE = 1; const REPORT_ROUTE = 2; @Component({ selector: 'app-process-service', templateUrl: './process-service.component.html', styleUrls: ['./process-service.component.scss'], encapsulation: ViewEncapsulation.None, providers: [ { provide: FormRenderingService, useClass: ProcessFormRenderingService } ] }) export class ProcessServiceComponent implements AfterViewInit, OnDestroy, OnInit { @ViewChild('activitiFilter') activitiFilter: TaskFiltersComponent; @ViewChild('processListPagination') processListPagination: PaginationComponent; @ViewChild('taskListPagination') taskListPagination: PaginationComponent; @ViewChild('taskList') taskList: TaskListComponent; @ViewChild('activitiProcessFilter') activitiProcessFilter: ProcessFiltersComponent; @ViewChild('processList') processList: ProcessInstanceListComponent; @ViewChild('activitiProcessDetails') activitiProcessDetails: ProcessInstanceDetailsComponent; @ViewChild('activitiDetails') activitiDetails: TaskDetailsComponent; @ViewChild('activitiStartProcess') activitiStartProcess: StartProcessInstanceComponent; @ViewChild('analyticsReportList', { static: true }) analyticsReportList: AnalyticsReportListComponent; @Input() appId: number = null; filterSelected: any = null; @Output() changePageSize = new EventEmitter<Pagination>(); selectFirstReport = false; multiSelectTask = false; multiSelectProcess = false; selectionMode = 'single'; taskContextMenu = false; processContextMenu = false; private tabs = { tasks: 0, processes: 1, reports: 2 }; layoutType: string; currentTaskId: string; currentProcessInstanceId: string; taskSchemaColumns: any[] = []; taskPage = 0; processPage = 0; paginationPageSize = 0; processSchemaColumns: any[] = []; showHeaderContent = true; defaultProcessDefinitionName: string; defaultProcessName: string; defaultTaskName: string; activeTab: number = this.tabs.tasks; // tasks|processes|reports taskFilter: FilterRepresentationModel; report: any; processFilter: UserProcessInstanceFilterRepresentation; blobFile: any; flag = true; presetColumn = 'default'; showTaskTab: boolean; showProcessTab: boolean; showProcessFilterIcon: boolean; showTaskFilterIcon: boolean; showApplications: boolean; applicationId: number; processDefinitionName: string; fieldValidators = [ ...FORM_FIELD_VALIDATORS, new DemoFieldValidator() ]; private onDestroy$ = new Subject<boolean>(); private scriptFileApi: ScriptFilesApi; constructor(private elementRef: ElementRef, private route: ActivatedRoute, private router: Router, private apiService: AlfrescoApiService, private logService: LogService, private appConfig: AppConfigService, private preview: PreviewService, formRenderingService: FormRenderingService, formService: FormService, private location: Location, private notificationService: NotificationService, private preferenceService: UserPreferencesService) { this.scriptFileApi = new ScriptFilesApi(this.apiService.getInstance()); this.defaultProcessName = this.appConfig.get<string>('adf-start-process.name'); this.defaultProcessDefinitionName = this.appConfig.get<string>('adf-start-process.processDefinitionName'); this.defaultTaskName = this.appConfig.get<string>('adf-start-task.name'); this.processDefinitionName = this.defaultProcessDefinitionName; // Uncomment this line to replace all 'text' field editors with custom component // formRenderingService.setComponentTypeResolver('text', () => CustomEditorComponent, true); // Uncomment this line to map 'custom_stencil_01' to local editor component formRenderingService.setComponentTypeResolver('custom_stencil_01', () => CustomStencil01, true); formService.formLoaded .pipe(takeUntil(this.onDestroy$)) .subscribe(formEvent => { this.logService.log(`Form loaded: ${formEvent.form.id}`); }); formService.formFieldValueChanged .pipe(takeUntil(this.onDestroy$)) .subscribe(formFieldEvent => { this.logService.log(`Field value changed. Form: ${formFieldEvent.form.id}, Field: ${formFieldEvent.field.id}, Value: ${formFieldEvent.field.value}`); }); this.preferenceService .select(UserPreferenceValues.PaginationSize) .pipe(takeUntil(this.onDestroy$)) .subscribe((pageSize) => { this.paginationPageSize = pageSize; }); formService.validateDynamicTableRow .pipe(takeUntil(this.onDestroy$)) .subscribe( (validateDynamicTableRowEvent: ValidateDynamicTableRowEvent) => { const row: DynamicTableRow = validateDynamicTableRowEvent.row; if (row && row.value && row.value.name === 'admin') { validateDynamicTableRowEvent.summary.isValid = false; validateDynamicTableRowEvent.summary.message = 'Sorry, wrong value. You cannot use "admin".'; validateDynamicTableRowEvent.preventDefault(); } } ); formService.formContentClicked .pipe(takeUntil(this.onDestroy$)) .subscribe((content) => { this.showContentPreview(content); }); formService.validateForm .pipe(takeUntil(this.onDestroy$)) .subscribe(validateFormEvent => { this.logService.log('Error form:' + validateFormEvent.errorsField); }); // Uncomment this block to see form event handling in action /* formService.formEvents .pipe(takeUntil(this.onDestroy$)) .subscribe((event: Event) => { this.logService.log('Event fired:' + event.type); this.logService.log('Event Target:' + event.target); }); */ } ngOnInit() { if (this.router.url.includes('processes')) { this.activeTab = this.tabs.processes; } this.showProcessTab = this.activeTab === this.tabs.processes; this.showTaskTab = this.activeTab === this.tabs.tasks; this.route.params.subscribe((params) => { const applicationId = params['appId']; this.filterSelected = params['filterId'] ? { id: +params['filterId'] } : { index: 0 }; if (applicationId && applicationId !== '0') { this.appId = params['appId']; this.applicationId = this.appId; } this.taskFilter = null; this.currentTaskId = null; this.processFilter = null; this.currentProcessInstanceId = null; }); this.layoutType = AppsListComponent.LAYOUT_GRID; } ngOnDestroy() { this.onDestroy$.next(true); this.onDestroy$.complete(); } onTaskFilterClick(filter: FilterRepresentationModel): void { this.applyTaskFilter(filter); this.resetTaskPaginationPage(); } resetTaskPaginationPage() { this.taskPage = 0; } toggleHeaderContent(): void { this.showHeaderContent = !this.showHeaderContent; } onTabChange(event: any): void { const index = event.index; if (index === TASK_ROUTE) { this.showTaskTab = event.index === this.tabs.tasks; this.relocateLocationToTask(); } else if (index === PROCESS_ROUTE) { this.showProcessTab = event.index === this.tabs.processes; this.relocateLocationToProcess(); if (this.processList) { this.processList.reload(); } } else if (index === REPORT_ROUTE) { this.relocateLocationToReport(); } } onChangePageSize(event: Pagination): void { this.preferenceService.paginationSize = event.maxItems; this.changePageSize.emit(event); } onReportClick(event: any): void { this.report = event; } onSuccessTaskFilterList(): void { this.applyTaskFilter(this.activitiFilter.getCurrentFilter()); } applyTaskFilter(filter: FilterRepresentationModel) { this.taskFilter = Object.assign({}, filter); if (filter && this.taskList) { this.taskList.hasCustomDataSource = false; } this.relocateLocationToTask(); } onStartTaskSuccess(event: any): void { this.activitiFilter.selectFilterWithTask(event.id); this.currentTaskId = event.id; } onCancelStartTask() { this.currentTaskId = null; this.reloadTaskFilters(); } onSuccessTaskList() { this.currentTaskId = this.taskList.getCurrentId(); } onProcessFilterChange(event: UserProcessInstanceFilterRepresentation): void { this.processFilter = event; this.resetProcessPaginationPage(); this.relocateLocationToProcess(); } resetProcessPaginationPage() { this.processPage = 0; } onSuccessProcessFilterList(): void { this.processFilter = this.activitiProcessFilter.getCurrentFilter(); } onSuccessProcessList(): void { this.currentProcessInstanceId = this.processList.getCurrentId(); } onTaskRowClick(taskId: string): void { this.currentTaskId = taskId; } onTaskRowDblClick(event: CustomEvent) { const taskId = event.detail.value.obj.id; this.currentTaskId = taskId; } onProcessRowDblClick(event: CustomEvent) { const processInstanceId = event.detail.value.obj.id; this.currentProcessInstanceId = processInstanceId; } onProcessRowClick(processInstanceId: string): void { this.currentProcessInstanceId = processInstanceId; } onEditReport(): void { this.analyticsReportList.reload(); } onReportSaved(reportId: number): void { this.analyticsReportList.reload(reportId); } onReportDeleted(): void { this.analyticsReportList.reload(); this.analyticsReportList.selectReport(null); } navigateStartProcess(): void { this.currentProcessInstanceId = currentProcessIdNew; } navigateStartTask(): void { this.currentTaskId = currentTaskIdNew; } onStartProcessInstance(instance: ProcessInstance): void { this.currentProcessInstanceId = instance.id; this.activitiStartProcess.reset(); this.activitiProcessFilter.selectRunningFilter(); } onCancelProcessInstance() { this.currentProcessInstanceId = null; this.reloadProcessFilters(); } onStartProcessError(event: any) { this.notificationService.showError(event.message); } isStartProcessMode(): boolean { return this.currentProcessInstanceId === currentProcessIdNew; } isStartTaskMode(): boolean { return this.currentTaskId === currentTaskIdNew; } processCancelled(): void { this.currentProcessInstanceId = null; this.processList.reload(); } onFormCompleted(): void { this.currentTaskId = null; if (this.taskListPagination) { this.taskPage = this.taskListPagination.current - 1; } if (!this.taskList) { this.navigateToProcess(); } else { this.taskList.hasCustomDataSource = false; this.taskList.reload(); } } navigateToProcess(): void { this.router.navigate([`/activiti/apps/${this.appId}/processes/`]); } relocateLocationToProcess(): void { this.location.go(`/activiti/apps/${this.appId || 0}/processes/${this.processFilter ? this.processFilter.id : 0}`); } relocateLocationToTask(): void { this.location.go(`/activiti/apps/${this.appId || 0}/tasks/${this.taskFilter ? this.taskFilter.id : 0}`); } relocateLocationToReport(): void { this.location.go(`/activiti/apps/${this.appId || 0}/report/`); } onContentClick(content: any): void { this.showContentPreview(content); } private showContentPreview(content: any) { if (content.contentBlob) { this.preview.showBlob(content.name, content.contentBlob); } else { this.preview.showResource(content.sourceId.split(';')[0]); } } onAuditClick(event: any) { this.logService.log(event); } onAuditError(event: any): void { this.logService.error('My custom error message' + event); } onTaskCreated(data: any): void { this.currentTaskId = data.parentTaskId; this.taskList.reload(); } onTaskDeleted(): void { this.taskList.reload(); } ngAfterViewInit() { this.loadStencilScriptsInPageFromProcessService(); } loadStencilScriptsInPageFromProcessService() { this.scriptFileApi.getControllers().then((response) => { if (response) { const stencilScript = document.createElement('script'); stencilScript.type = 'text/javascript'; stencilScript.text = response; this.elementRef.nativeElement.appendChild(stencilScript); } }); } onShowProcessDiagram(event: any): void { this.router.navigate(['/activiti/apps/' + this.appId + '/diagram/' + event.value]); } onProcessDetailsTaskClick(event: TaskDetailsEvent): void { event.preventDefault(); this.activeTab = this.tabs.tasks; const taskId = event.value.id; const processTaskDataRow: any = { id: taskId, name: event.value.name || 'No name', created: event.value.created }; if (this.taskList) { this.taskList.setCustomDataSource([processTaskDataRow]); this.taskList.selectTask(taskId); } this.currentTaskId = taskId; } private reloadProcessFilters(): void { this.activitiProcessFilter.selectFilter(this.activitiProcessFilter.getCurrentFilter()); } private reloadTaskFilters(): void { this.activitiFilter.selectFilter(this.activitiFilter.getCurrentFilter()); } onRowClick(event): void { this.logService.log(event); } onRowDblClick(event): void { this.logService.log(event); } onAssignTask() { this.taskList.reload(); this.currentTaskId = null; } onShowTaskRowContextMenu(event: DataCellEvent) { event.value.actions = [ { data: event.value.row['obj'], model: { key: 'taskDetails', icon: 'open', title: 'TASK_LIST_DEMO.TASK_CONTEXT_MENU', visible: true }, subject: new Subject() } ]; } onShowProcessRowContextMenu(event: DataCellEvent) { event.value.actions = [ { data: event.value.row['obj'], model: { key: 'processDetails', icon: 'open', title: 'PROCESS_LIST_DEMO.PROCESS_CONTEXT_MENU', visible: true }, subject: new Subject() } ]; } }
the_stack
import * as Objects from "./objects"; export interface AccountChangePasswordResponse { /** * New token */ token: string; /** * New secret */ secret?: string; [key: string]: any; } export interface AccountGetActiveOffersResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.AccountOffer[]; } export type AccountGetAppPermissionsResponse = number; export interface AccountGetBannedResponse { /** * Total number */ count: number; [key: string]: any; items: number[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroup[]; } export type AccountGetCountersResponse = Objects.AccountAccountCounters; export type AccountGetInfoResponse = Objects.AccountInfo; export type AccountGetProfileInfoResponse = Objects.AccountUserSettings; export type AccountGetPushSettingsResponse = Objects.AccountPushSettings; export interface AccountSaveProfileInfoResponse { [key: string]: any; } export type AdsAddOfficeUsersResponse = boolean | number; export type AdsCheckLinkResponse = Objects.AdsLinkStatus; export type AdsCreateAdsResponse = number[]; export type AdsCreateCampaignsResponse = number[]; export type AdsCreateClientsResponse = number[]; export interface AdsCreateTargetGroupResponse { /** * Group ID */ id?: number; /** * Pixel code */ pixel?: string; [key: string]: any; } export type AdsDeleteAdsResponse = number[]; export type AdsDeleteCampaignsResponse = number; export type AdsDeleteClientsResponse = number; export type AdsGetAccountsResponse = Objects.AdsAccount[]; export type AdsGetAdsLayoutResponse = Objects.AdsAdLayout[]; export type AdsGetAdsTargetingResponse = Objects.AdsTargSettings[]; export type AdsGetAdsResponse = Objects.AdsAd[]; export type AdsGetBudgetResponse = number; export type AdsGetCampaignsResponse = Objects.AdsCampaign[]; export interface AdsGetCategoriesResponse { [key: string]: any; v1?: Objects.AdsCategory[]; v2?: Objects.AdsCategory[]; } export type AdsGetClientsResponse = Objects.AdsClient[]; export type AdsGetDemographicsResponse = Objects.AdsDemoStats[]; export type AdsGetFloodStatsResponse = Objects.AdsFloodStats; export interface AdsGetLookalikeRequestsResponse { /** * Total count of found lookalike requests */ count: number; [key: string]: any; items: Objects.AdsLookalikeRequest[]; } export interface AdsGetMusiciansResponse { [key: string]: any; items: Objects.AdsMusician[]; } export type AdsGetOfficeUsersResponse = Objects.AdsUsers[]; export type AdsGetPostsReachResponse = Objects.AdsPromotedPostReach[]; export type AdsGetRejectionReasonResponse = Objects.AdsRejectReason; export type AdsGetStatisticsResponse = Objects.AdsStats[]; export type AdsGetSuggestionsCitiesResponse = Objects.AdsTargSuggestionsCities[]; export type AdsGetSuggestionsRegionsResponse = Objects.AdsTargSuggestionsRegions[]; export type AdsGetSuggestionsResponse = Objects.AdsTargSuggestions[]; export type AdsGetSuggestionsSchoolsResponse = Objects.AdsTargSuggestionsSchools[]; export type AdsGetTargetGroupsResponse = Objects.AdsTargetGroup[]; export type AdsGetTargetingStatsResponse = Objects.AdsTargStats; export type AdsGetUploadURLResponse = string; export type AdsGetVideoUploadURLResponse = string; export type AdsImportTargetContactsResponse = number; export type AdsRemoveOfficeUsersResponse = boolean | number; export type AdsUpdateAdsResponse = number[]; export type AdsUpdateCampaignsResponse = number; export type AdsUpdateClientsResponse = number; export type AdsUpdateOfficeUsersResponse = Objects.AdsUpdateOfficeUsersResult[]; export interface AdswebGetAdCategoriesResponse { [key: string]: any; categories: Objects.AdswebGetAdCategoriesResponseCategoriesCategory[]; } export interface AdswebGetAdUnitCodeResponse { [key: string]: any; html: string; } export interface AdswebGetAdUnitsResponse { [key: string]: any; count: number; ad_units?: Objects.AdswebGetAdUnitsResponseAdUnitsAdUnit[]; } export interface AdswebGetFraudHistoryResponse { [key: string]: any; count: number; entries?: Objects.AdswebGetFraudHistoryResponseEntriesEntry[]; } export interface AdswebGetSitesResponse { [key: string]: any; count: number; sites?: Objects.AdswebGetSitesResponseSitesSite[]; } export interface AdswebGetStatisticsResponse { [key: string]: any; next_page_id?: string; items: Objects.AdswebGetStatisticsResponseItemsItem[]; } export interface AppWidgetsGetAppImageUploadServerResponse { /** * To upload an image, generate POST-request to upload_url with a file in photo field. Then call appWidgets.saveAppImage method */ upload_url?: string; [key: string]: any; } export type AppWidgetsGetAppImagesResponse = Objects.AppWidgetsPhotos; export interface AppWidgetsGetGroupImageUploadServerResponse { /** * To upload an image, generate POST-request to upload_url with a file in photo field. Then call appWidgets.saveAppImage method */ upload_url?: string; [key: string]: any; } export type AppWidgetsGetGroupImagesResponse = Objects.AppWidgetsPhotos; export type AppWidgetsGetImagesByIdResponse = Objects.AppWidgetsPhoto[]; export type AppWidgetsSaveAppImageResponse = Objects.AppWidgetsPhoto; export type AppWidgetsSaveGroupImageResponse = Objects.AppWidgetsPhoto; export type AppsGetCatalogResponse = Objects.AppsCatalogList; export interface AppsGetFriendsListResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.UsersUserFull[]; } export interface AppsGetLeaderboardExtendedResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.AppsLeaderboard[]; profiles?: Objects.UsersUserMin[]; } export interface AppsGetLeaderboardResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.AppsLeaderboard[]; } export interface AppsGetMiniAppPoliciesResponse { /** * URL of the app's privacy policy */ privacy_policy?: string; /** * URL of the app's terms */ terms?: string; [key: string]: any; } export interface AppsGetScopesResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.AppsScope[]; } export type AppsGetScoreResponse = number; export interface AppsGetResponse { /** * Total number of applications */ count?: number; [key: string]: any; items?: Objects.AppsApp[]; } export interface AppsImageUploadResponse { /** * Uploading hash */ hash?: string; /** * Uploaded photo data */ image?: string; [key: string]: any; } export type AppsSendRequestResponse = number; export interface AuthRestoreResponse { /** * 1 if success */ success?: 1; /** * Parameter needed to grant access by code */ sid?: string; [key: string]: any; } export type BaseBoolResponse = Objects.BaseBoolInt; export type BaseGetUploadServerResponse = Objects.BaseUploadServer; export type BaseOkResponse = 1; export type BoardAddTopicResponse = number; export type BoardCreateCommentResponse = number; export interface BoardGetCommentsExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.BoardTopicComment[]; profiles: Objects.UsersUser[]; groups: Objects.GroupsGroup[]; } export interface BoardGetCommentsResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.BoardTopicComment[]; } export interface BoardGetTopicsExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.BoardTopic[]; profiles: Objects.UsersUserMin[]; } export interface BoardGetTopicsResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.BoardTopic[]; } export interface DatabaseGetChairsResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.BaseObject[]; } export type DatabaseGetCitiesByIdResponse = Objects.BaseObject[]; export interface DatabaseGetCitiesResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.DatabaseCity[]; } export type DatabaseGetCountriesByIdResponse = Objects.BaseCountry[]; export interface DatabaseGetCountriesResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.BaseCountry[]; } export interface DatabaseGetFacultiesResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.DatabaseFaculty[]; } export type DatabaseGetMetroStationsByIdResponse = Objects.DatabaseStation[]; export interface DatabaseGetMetroStationsResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.DatabaseStation[]; } export interface DatabaseGetRegionsResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.DatabaseRegion[]; } export type DatabaseGetSchoolClassesResponse = any[][]; export interface DatabaseGetSchoolsResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.DatabaseSchool[]; } export interface DatabaseGetUniversitiesResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.DatabaseUniversity[]; } export type DocsAddResponse = number; export interface DocsDocUploadResponse { /** * Uploaded file data */ file?: string; [key: string]: any; } export type DocsGetByIdResponse = Objects.DocsDoc[]; export interface DocsGetTypesResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.DocsDocTypes[]; } export type DocsGetUploadServerResponse = Objects.BaseUploadServer; export interface DocsGetResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.DocsDoc[]; } export interface DocsSaveResponse { [key: string]: any; } export interface DocsSearchResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.DocsDoc[]; } export type DonutGetSubscriptionResponse = Objects.DonutDonatorSubscriptionInfo; export interface DonutGetSubscriptionsResponse { [key: string]: any; subscriptions: Objects.DonutDonatorSubscriptionInfo[]; count?: number; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; } export interface DownloadedGamesPaidStatusResponse { /** * Game has been paid */ is_paid: boolean | number; [key: string]: any; } export type FaveAddTagResponse = Objects.FaveTag; export interface FaveGetPagesResponse { [key: string]: any; count?: number; items?: Objects.FavePage[]; } export interface FaveGetTagsResponse { [key: string]: any; count?: number; items?: Objects.FaveTag[]; } export interface FaveGetExtendedResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.FaveBookmark[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroup[]; } export interface FaveGetResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.FaveBookmark[]; } export interface FriendsAddListResponse { /** * List ID */ list_id: number; [key: string]: any; } export type FriendsAddResponse = 1 | 2 | 4; export type FriendsAreFriendsExtendedResponse = Objects.FriendsFriendExtendedStatus[]; export type FriendsAreFriendsResponse = Objects.FriendsFriendStatus[]; export interface FriendsDeleteResponse { /** * Returns 1 if friend has been deleted */ friend_deleted?: 1; /** * Returns 1 if out request has been canceled */ out_request_deleted?: 1; /** * Returns 1 if incoming request has been declined */ in_request_deleted?: 1; /** * Returns 1 if suggestion has been declined */ suggestion_deleted?: 1; [key: string]: any; success: number; } export type FriendsGetAppUsersResponse = number[]; export type FriendsGetByPhonesResponse = Objects.FriendsUserXtrPhone[]; export interface FriendsGetListsResponse { /** * Total number of friends lists */ count: number; [key: string]: any; items: Objects.FriendsFriendsList[]; } export type FriendsGetMutualResponse = number[]; export type FriendsGetMutualTargetUidsResponse = Objects.FriendsMutualFriend[]; export interface FriendsGetOnlineOnlineMobileResponse { /** * User ID */ online?: number[]; /** * User ID */ online_mobile?: number[]; [key: string]: any; } export type FriendsGetOnlineResponse = number[]; export type FriendsGetRecentResponse = number[]; export interface FriendsGetRequestsExtendedResponse { /** * Total requests number */ count?: number; [key: string]: any; items?: Objects.FriendsRequestsXtrMessage[]; } export interface FriendsGetRequestsNeedMutualResponse { /** * Total requests number */ count?: number; [key: string]: any; items?: Objects.FriendsRequests[]; } export interface FriendsGetRequestsResponse { /** * Total requests number */ count?: number; /** * User ID */ items?: number[]; /** * Total unread requests number */ count_unread?: number; [key: string]: any; } export interface FriendsGetSuggestionsResponse { /** * Total results number */ count: number; [key: string]: any; items: Objects.UsersUserFull[]; } export interface FriendsGetFieldsResponse { /** * Total friends number */ count: number; [key: string]: any; items: Objects.UsersUserFull[]; } export interface FriendsGetResponse { /** * Total friends number */ count: number; /** * User ID */ items: number[]; [key: string]: any; } export interface FriendsSearchResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.UsersUserFull[]; } export interface GiftsGetResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.GiftsGift[]; } export type GroupsAddAddressResponse = Objects.GroupsAddress; export interface GroupsAddCallbackServerResponse { [key: string]: any; server_id: number; } export type GroupsAddLinkResponse = Objects.GroupsLinksItem; export type GroupsCreateResponse = Objects.GroupsGroup; export type GroupsEditAddressResponse = Objects.GroupsAddress; export interface GroupsGetAddressesResponse { /** * Total count of addresses */ count: number; [key: string]: any; items: Objects.GroupsAddress[]; } export interface GroupsGetBannedResponse { /** * Total users number */ count: number; [key: string]: any; items: Objects.GroupsBannedItem[]; } export type GroupsGetByIdObjectLegacyResponse = Objects.GroupsGroupFull[]; export interface GroupsGetCallbackConfirmationCodeResponse { /** * Confirmation code */ code: string; [key: string]: any; } export interface GroupsGetCallbackServersResponse { [key: string]: any; count: number; items: Objects.GroupsCallbackServer[]; } export type GroupsGetCallbackSettingsResponse = Objects.GroupsCallbackSettings; export interface GroupsGetCatalogInfoExtendedResponse { [key: string]: any; categories?: Objects.GroupsGroupCategoryFull[]; } export interface GroupsGetCatalogInfoResponse { [key: string]: any; categories?: Objects.GroupsGroupCategory[]; } export interface GroupsGetCatalogResponse { /** * Total communities number */ count: number; [key: string]: any; items: Objects.GroupsGroup[]; } export interface GroupsGetInvitedUsersResponse { /** * Total communities number */ count: number; [key: string]: any; items: Objects.UsersUserFull[]; } export interface GroupsGetInvitesExtendedResponse { /** * Total communities number */ count: number; [key: string]: any; items: Objects.GroupsGroupFull[]; profiles: Objects.UsersUserMin[]; groups: Objects.GroupsGroupFull[]; } export interface GroupsGetInvitesResponse { /** * Total communities number */ count: number; [key: string]: any; items: Objects.GroupsGroupFull[]; } export type GroupsGetLongPollServerResponse = Objects.GroupsLongPollServer; export type GroupsGetLongPollSettingsResponse = Objects.GroupsLongPollSettings; export interface GroupsGetMembersFieldsResponse { /** * Total members number */ count: number; [key: string]: any; items: Objects.GroupsUserXtrRole[]; } export interface GroupsGetMembersFilterResponse { /** * Total members number */ count: number; [key: string]: any; items: Objects.GroupsMemberRole[]; } export interface GroupsGetMembersResponse { /** * Total members number */ count: number; /** * User ID */ items: number[]; [key: string]: any; } export interface GroupsGetRequestsFieldsResponse { /** * Total communities number */ count: number; [key: string]: any; items: Objects.UsersUserFull[]; } export interface GroupsGetRequestsResponse { /** * Total communities number */ count: number; /** * User ID */ items: number[]; [key: string]: any; } export interface GroupsGetSettingsResponse { /** * Community's page domain */ address?: string; /** * Articles settings */ articles: number; /** * Photo suggests setting */ recognize_photo?: number; /** * City id of group */ city_id: number; /** * Country id of group */ country_id: number; /** * Community description */ description: string; /** * Information about the group category */ public_category?: number; /** * Information about the group subcategory */ public_subcategory?: number; /** * URL of the RSS feed */ rss?: string; /** * Start date */ start_date?: number; /** * Finish date in Unix-time format */ finish_date?: number; /** * Community subject ID */ subject?: number; /** * Community title */ title: string; /** * Community website */ website?: string; /** * Community phone */ phone?: string; /** * Community email */ email?: string; [key: string]: any; sections_list?: Objects.GroupsSectionsListItem[]; obscene_words: string[]; event_group_id?: number; public_category_list?: Objects.GroupsGroupPublicCategoryList[]; public_date?: string; public_date_label?: string; subject_list?: Objects.GroupsSubjectItem[]; } export type GroupsGetTagListResponse = Objects.GroupsGroupTag[]; export interface GroupsGetTokenPermissionsResponse { [key: string]: any; mask: number; permissions: Objects.GroupsTokenPermissionSetting[]; } export interface GroupsGetObjectExtendedResponse { /** * Total communities number */ count: number; [key: string]: any; items: Objects.GroupsGroupFull[]; } export interface GroupsGetResponse { /** * Total communities number */ count: number; /** * Community ID */ items: number[]; [key: string]: any; } export interface GroupsIsMemberExtendedResponse { [key: string]: any; } export type GroupsIsMemberResponse = Objects.BaseBoolInt; export type GroupsIsMemberUserIdsExtendedResponse = Objects.GroupsMemberStatusFull[]; export type GroupsIsMemberUserIdsResponse = Objects.GroupsMemberStatus[]; export interface GroupsSearchResponse { /** * Total communities number */ count: number; [key: string]: any; items: Objects.GroupsGroup[]; } export interface LikesAddResponse { /** * Total likes number */ likes: number; [key: string]: any; } export interface LikesDeleteResponse { /** * Total likes number */ likes: number; [key: string]: any; } export interface LikesGetListExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.UsersUserMin[]; } export interface LikesGetListResponse { /** * Total number */ count: number; /** * User ID */ items: number[]; [key: string]: any; } export interface LikesIsLikedResponse { [key: string]: any; } export interface MarketAddAlbumResponse { /** * Album ID */ market_album_id?: number; [key: string]: any; } export interface MarketAddResponse { /** * Item ID */ market_item_id: number; [key: string]: any; } export type MarketCreateCommentResponse = number; export type MarketDeleteCommentResponse = Objects.BaseBoolInt; export interface MarketGetAlbumByIdResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.MarketMarketAlbum[]; } export interface MarketGetAlbumsResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.MarketMarketAlbum[]; } export interface MarketGetByIdExtendedResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.MarketMarketItemFull[]; } export interface MarketGetByIdResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.MarketMarketItem[]; } export interface MarketGetCategoriesNewResponse { [key: string]: any; items: Objects.MarketMarketCategoryTree[]; } export interface MarketGetCategoriesResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.MarketMarketCategory[]; } export interface MarketGetCommentsResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.WallWallComment[]; } export interface MarketGetGroupOrdersResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MarketOrder[]; } export interface MarketGetOrderByIdResponse { [key: string]: any; } export interface MarketGetOrderItemsResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MarketOrderItem[]; } export interface MarketGetOrdersExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MarketOrder[]; groups?: Objects.GroupsGroupFull[]; } export interface MarketGetOrdersResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MarketOrder[]; } export interface MarketGetExtendedResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.MarketMarketItemFull[]; variants?: Objects.MarketMarketItemFull[]; } export interface MarketGetResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.MarketMarketItem[]; variants?: Objects.MarketMarketItem[]; } export type MarketRestoreCommentResponse = Objects.BaseBoolInt; export interface MarketSearchExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MarketMarketItemFull[]; variants?: Objects.MarketMarketItemFull[]; } export interface MarketSearchResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MarketMarketItem[]; variants?: Objects.MarketMarketItem[]; } export type MessagesCreateChatResponse = number; export interface MessagesDeleteChatPhotoResponse { /** * Service message ID */ message_id?: number; [key: string]: any; } export interface MessagesDeleteConversationResponse { /** * Id of the last message, that was deleted */ last_deleted_id: number; [key: string]: any; } export type MessagesDeleteResponse = any; export type MessagesEditResponse = Objects.BaseBoolInt; export interface MessagesGetByConversationMessageIdResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MessagesMessage[]; } export interface MessagesGetByIdExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MessagesMessage[]; profiles: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; } export interface MessagesGetByIdResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MessagesMessage[]; } export interface MessagesGetChatPreviewResponse { [key: string]: any; profiles?: Objects.UsersUserFull[]; } export type MessagesGetChatChatIdsFieldsResponse = Objects.MessagesChatFull[]; export type MessagesGetChatChatIdsResponse = Objects.MessagesChat[]; export type MessagesGetChatFieldsResponse = Objects.MessagesChatFull; export type MessagesGetChatResponse = Objects.MessagesChat; export interface MessagesGetConversationMembersResponse { /** * Chat members count */ count: number; [key: string]: any; items: Objects.MessagesConversationMember[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; } export type MessagesGetConversationsByIdExtendedResponse = Objects.MessagesGetConversationById; export type MessagesGetConversationsByIdResponse = Objects.MessagesGetConversationById; export interface MessagesGetConversationsResponse { /** * Total number */ count: number; /** * Unread dialogs number */ unread_count?: number; [key: string]: any; items: Objects.MessagesConversationWithMessage[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; } export interface MessagesGetHistoryAttachmentsResponse { /** * Value for pagination */ next_from?: string; [key: string]: any; items?: Objects.MessagesHistoryAttachment[]; } export interface MessagesGetHistoryExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MessagesMessage[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; conversations?: Objects.MessagesConversation[]; } export interface MessagesGetHistoryResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MessagesMessage[]; } export interface MessagesGetImportantMessagesExtendedResponse { [key: string]: any; profiles?: Objects.UsersUser[]; groups?: Objects.GroupsGroup[]; conversations?: Objects.MessagesConversation[]; } export interface MessagesGetImportantMessagesResponse { [key: string]: any; profiles?: Objects.UsersUser[]; groups?: Objects.GroupsGroup[]; conversations?: Objects.MessagesConversation[]; } export interface MessagesGetIntentUsersResponse { [key: string]: any; count: number; items: number[]; profiles?: Objects.UsersUserFull[]; } export interface MessagesGetInviteLinkResponse { [key: string]: any; link?: string; } export type MessagesGetLastActivityResponse = Objects.MessagesLastActivity; export interface MessagesGetLongPollHistoryResponse { /** * Longpoll event value */ history?: number[][]; /** * Persistence timestamp */ new_pts?: number; /** * Has more */ more?: boolean | number; [key: string]: any; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroup[]; chats?: Objects.MessagesChat[]; from_pts?: number; conversations?: Objects.MessagesConversation[]; } export type MessagesGetLongPollServerResponse = Objects.MessagesLongpollParams; export interface MessagesIsMessagesFromGroupAllowedResponse { [key: string]: any; } export interface MessagesJoinChatByInviteLinkResponse { [key: string]: any; chat_id?: number; } export type MessagesMarkAsImportantResponse = number[]; export type MessagesPinResponse = Objects.MessagesPinnedMessage; export interface MessagesSearchConversationsExtendedResponse { /** * Total results number */ count: number; [key: string]: any; items: Objects.MessagesConversation[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; } export interface MessagesSearchConversationsResponse { /** * Total results number */ count: number; [key: string]: any; items: Objects.MessagesConversation[]; } export interface MessagesSearchExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MessagesMessage[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; conversations?: Objects.MessagesConversation[]; } export interface MessagesSearchResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.MessagesMessage[]; } export type MessagesSendResponse = number; export type MessagesSendUserIdsResponse = Objects.MessagesSendUserIdsResponseItem[]; export interface MessagesSetChatPhotoResponse { /** * Service message ID */ message_id?: number; [key: string]: any; } export interface NewsfeedGetBannedExtendedResponse { [key: string]: any; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; } export interface NewsfeedGetBannedResponse { /** * Community ID */ groups?: number[]; /** * User ID */ members?: number[]; [key: string]: any; } export interface NewsfeedGetCommentsResponse { /** * Next from value */ next_from?: string; [key: string]: any; items: Objects.NewsfeedNewsfeedItem[]; profiles: Objects.UsersUserFull[]; groups: Objects.GroupsGroupFull[]; } export interface NewsfeedGetListsExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.NewsfeedListFull[]; } export interface NewsfeedGetListsResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.NewsfeedList[]; } export interface NewsfeedGetMentionsResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.WallWallpostToId[]; } export interface NewsfeedGetRecommendedResponse { /** * Next from value */ next_from?: string; [key: string]: any; items?: Objects.NewsfeedNewsfeedItem[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; } export interface NewsfeedGetSuggestedSourcesResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.UsersSubscriptionsItem[]; } export interface NewsfeedGetResponse { /** * New from value */ next_from?: string; [key: string]: any; items?: Objects.NewsfeedNewsfeedItem[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; } export interface NewsfeedIgnoreItemResponse { [key: string]: any; status: boolean | number; } export type NewsfeedSaveListResponse = number; export interface NewsfeedSearchExtendedResponse { /** * Filtered number */ count?: number; /** * Total number */ total_count?: number; [key: string]: any; items?: Objects.WallWallpostFull[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroupFull[]; suggested_queries?: string[]; next_from?: string; } export interface NewsfeedSearchResponse { /** * Filtered number */ count?: number; /** * Total number */ total_count?: number; [key: string]: any; items?: Objects.WallWallpostFull[]; suggested_queries?: string[]; next_from?: string; } export type NotesAddResponse = number; export type NotesCreateCommentResponse = number; export type NotesGetByIdResponse = Objects.NotesNote; export interface NotesGetCommentsResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.NotesNoteComment[]; } export interface NotesGetResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.NotesNote[]; } export interface NotificationsGetResponse { /** * Total number */ count?: number; /** * Time when user has been checked notifications last time */ last_viewed?: number; [key: string]: any; items?: Objects.NotificationsNotificationItem[]; profiles?: Objects.UsersUser[]; groups?: Objects.GroupsGroup[]; photos?: Objects.PhotosPhoto[]; videos?: Objects.VideoVideo[]; apps?: Objects.AppsApp[]; next_from?: string; ttl?: number; } export type NotificationsMarkAsViewedResponse = Objects.BaseBoolInt; export type NotificationsSendMessageResponse = Objects.NotificationsSendMessageItem[]; export type OrdersCancelSubscriptionResponse = Objects.BaseBoolInt; export type OrdersChangeStateResponse = string; export type OrdersGetAmountResponse = Objects.OrdersAmount[]; export type OrdersGetByIdResponse = Objects.OrdersOrder[]; export type OrdersGetUserSubscriptionByIdResponse = Objects.OrdersSubscription; export interface OrdersGetUserSubscriptionsResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.OrdersSubscription[]; } export type OrdersGetResponse = Objects.OrdersOrder[]; export type OrdersUpdateSubscriptionResponse = Objects.BaseBoolInt; export type PagesGetHistoryResponse = Objects.PagesWikipageHistory[]; export type PagesGetTitlesResponse = Objects.PagesWikipage[]; export type PagesGetVersionResponse = Objects.PagesWikipageFull; export type PagesGetResponse = Objects.PagesWikipageFull; export type PagesParseWikiResponse = string; export type PagesSaveAccessResponse = number; export type PagesSaveResponse = number; export type PhotosCopyResponse = number; export type PhotosCreateAlbumResponse = Objects.PhotosPhotoAlbumFull; export type PhotosCreateCommentResponse = number; export type PhotosDeleteCommentResponse = Objects.BaseBoolInt; export type PhotosGetAlbumsCountResponse = number; export interface PhotosGetAlbumsResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.PhotosPhotoAlbumFull[]; } export interface PhotosGetAllCommentsResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.PhotosCommentXtrPid[]; } export interface PhotosGetAllExtendedResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.PhotosPhotoFullXtrRealOffset[]; } export interface PhotosGetAllResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.PhotosPhotoXtrRealOffset[]; } export interface PhotosGetByIdExtendedResponse { [key: string]: any; items: Objects.PhotosPhotoFull[]; } export type PhotosGetByIdLegacyExtendedResponse = Objects.PhotosPhotoFull[]; export type PhotosGetByIdLegacyResponse = Objects.PhotosPhoto[]; export interface PhotosGetByIdResponse { [key: string]: any; items?: Objects.PhotosPhoto[]; } export interface PhotosGetCommentsExtendedResponse { /** * Total number */ count: number; /** * Real offset of the comments */ real_offset?: number; [key: string]: any; items: Objects.WallWallComment[]; profiles: Objects.UsersUserFull[]; groups: Objects.GroupsGroupFull[]; } export interface PhotosGetCommentsResponse { /** * Total number */ count?: number; /** * Real offset of the comments */ real_offset?: number; [key: string]: any; items?: Objects.WallWallComment[]; } export type PhotosGetMarketUploadServerResponse = Objects.BaseUploadServer; export type PhotosGetMessagesUploadServerResponse = Objects.PhotosPhotoUpload; export interface PhotosGetNewTagsResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.PhotosPhotoXtrTagInfo[]; } export type PhotosGetTagsResponse = Objects.PhotosPhotoTag[]; export type PhotosGetUploadServerResponse = Objects.PhotosPhotoUpload; export interface PhotosGetUserPhotosExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.PhotosPhotoFull[]; } export interface PhotosGetUserPhotosResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.PhotosPhoto[]; } export type PhotosGetWallUploadServerResponse = Objects.PhotosPhotoUpload; export interface PhotosGetExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.PhotosPhotoFull[]; } export interface PhotosGetResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.PhotosPhoto[]; } export interface PhotosMarketAlbumUploadResponse { /** * Community ID */ gid?: number; /** * Uploading hash */ hash?: string; /** * Uploaded photo data */ photo?: string; /** * Upload server number */ server?: number; [key: string]: any; } export interface PhotosMarketUploadResponse { /** * Crop data */ crop_data?: string; /** * Crop hash */ crop_hash?: string; /** * Community ID */ group_id?: number; /** * Uploading hash */ hash?: string; /** * Uploaded photo data */ photo?: string; /** * Upload server number */ server?: number; [key: string]: any; } export interface PhotosMessageUploadResponse { /** * Uploading hash */ hash?: string; /** * Uploaded photo data */ photo?: string; /** * Upload server number */ server?: number; [key: string]: any; } export interface PhotosOwnerCoverUploadResponse { /** * Uploading hash */ hash?: string; /** * Uploaded photo data */ photo?: string; [key: string]: any; } export interface PhotosOwnerUploadResponse { /** * Uploading hash */ hash?: string; /** * Uploaded photo data */ photo?: string; /** * Upload server number */ server?: number; [key: string]: any; } export interface PhotosPhotoUploadResponse { /** * Album ID */ aid?: number; /** * Uploading hash */ hash?: string; /** * Uploaded photo data */ photo?: string; /** * Uploaded photos data */ photos_list?: string; /** * Upload server number */ server?: number; [key: string]: any; } export type PhotosPutTagResponse = number; export type PhotosRestoreCommentResponse = Objects.BaseBoolInt; export type PhotosSaveMarketAlbumPhotoResponse = Objects.PhotosPhoto[]; export type PhotosSaveMarketPhotoResponse = Objects.PhotosPhoto[]; export type PhotosSaveMessagesPhotoResponse = Objects.PhotosPhoto[]; export type PhotosSaveOwnerCoverPhotoResponse = Objects.BaseImage[]; export interface PhotosSaveOwnerPhotoResponse { /** * Photo hash */ photo_hash: string; /** * Uploaded image url */ photo_src: string; /** * Uploaded image url */ photo_src_big?: string; /** * Uploaded image url */ photo_src_small?: string; /** * Returns 1 if profile photo is saved */ saved?: number; /** * Created post ID */ post_id?: number; [key: string]: any; } export type PhotosSaveWallPhotoResponse = Objects.PhotosPhoto[]; export type PhotosSaveResponse = Objects.PhotosPhoto[]; export interface PhotosSearchResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.PhotosPhoto[]; } export interface PhotosWallUploadResponse { /** * Uploading hash */ hash?: string; /** * Uploaded photo data */ photo?: string; /** * Upload server number */ server?: number; [key: string]: any; } export interface PodcastsSearchPodcastResponse { /** * Total amount of found results */ results_total: number; [key: string]: any; podcasts: Objects.PodcastExternalData[]; } export type PollsAddVoteResponse = Objects.BaseBoolInt; export type PollsCreateResponse = Objects.PollsPoll; export type PollsDeleteVoteResponse = Objects.BaseBoolInt; export type PollsGetBackgroundsResponse = Objects.PollsBackground[]; export type PollsGetByIdResponse = Objects.PollsPoll; export type PollsGetVotersResponse = Objects.PollsVoters[]; export type PollsSavePhotoResponse = Objects.PollsBackground; export interface PrettyCardsCreateResponse { /** * Owner ID of created pretty card */ owner_id: number; /** * Card ID of created pretty card */ card_id: string; [key: string]: any; } export interface PrettyCardsDeleteResponse { /** * Owner ID of deleted pretty card */ owner_id: number; /** * Card ID of deleted pretty card */ card_id: string; /** * Error reason if error happened */ error?: string; [key: string]: any; } export interface PrettyCardsEditResponse { /** * Owner ID of edited pretty card */ owner_id: number; /** * Card ID of edited pretty card */ card_id: string; [key: string]: any; } export type PrettyCardsGetByIdResponse = Objects.PrettyCardsPrettyCard[]; export type PrettyCardsGetUploadURLResponse = string; export interface PrettyCardsGetResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.PrettyCardsPrettyCard[]; } export interface SearchGetHintsResponse { [key: string]: any; count: number; items: Objects.SearchHint[]; suggested_queries?: string[]; } export type SecureCheckTokenResponse = Objects.SecureTokenChecked; export type SecureGetAppBalanceResponse = number; export type SecureGetSmsHistoryResponse = Objects.SecureSmsNotification[]; export type SecureGetTransactionsHistoryResponse = Objects.SecureTransaction[]; export type SecureGetUserLevelResponse = Objects.SecureLevel[]; export type SecureGiveEventStickerResponse = Objects.SecureGiveEventStickerItem[]; export type SecureSendNotificationResponse = number[]; export type StatsGetPostReachResponse = Objects.StatsWallpostStat[]; export type StatsGetResponse = Objects.StatsPeriod[]; export type StatusGetResponse = Objects.StatusStatus; export type StorageGetKeysResponse = string[]; export type StorageGetResponse = Objects.StorageValue[]; export type StoreGetFavoriteStickersResponse = Objects.BaseSticker[]; export type StoreGetProductsResponse = Objects.StoreProduct[]; export interface StoreGetStickersKeywordsResponse { /** * Total count of chunks to load */ chunks_count?: number; /** * Chunks version hash */ chunks_hash?: string; [key: string]: any; count: number; dictionary: Objects.StoreStickersKeyword[]; } export interface StoriesGetBannedExtendedResponse { /** * Stories count */ count: number; /** * Owner ID */ items: number[]; [key: string]: any; profiles: Objects.UsersUserFull[]; groups: Objects.GroupsGroupFull[]; } export interface StoriesGetBannedResponse { /** * Stories count */ count: number; /** * Owner ID */ items: number[]; [key: string]: any; } export interface StoriesGetByIdExtendedResponse { /** * Stories count */ count: number; [key: string]: any; items: Objects.StoriesStory[]; profiles: Objects.UsersUserFull[]; groups: Objects.GroupsGroupFull[]; } export interface StoriesGetByIdResponse { /** * Stories count */ count: number; [key: string]: any; items: Objects.StoriesStory[]; } export interface StoriesGetPhotoUploadServerResponse { /** * Upload URL */ upload_url: string; [key: string]: any; user_ids: number[]; } export type StoriesGetStatsResponse = Objects.StoriesStoryStats; export interface StoriesGetVideoUploadServerResponse { /** * Upload URL */ upload_url: string; [key: string]: any; user_ids: number[]; } export interface StoriesGetViewersExtendedV5115Response { /** * Viewers count */ count: number; [key: string]: any; items: Objects.StoriesViewersItem[]; hidden_reason?: string; } export interface StoriesGetViewersExtendedResponse { /** * Viewers count */ count: number; [key: string]: any; items: Objects.UsersUserFull[]; } export interface StoriesGetV5113Response { [key: string]: any; count: number; items: Objects.StoriesFeedItem[]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroup[]; need_upload_screen?: boolean | number; } export interface StoriesGetResponse { /** * Stories count */ count: number; [key: string]: any; items: Objects.StoriesStory[][]; profiles?: Objects.UsersUserFull[]; groups?: Objects.GroupsGroup[]; need_upload_screen?: boolean | number; } export interface StoriesSaveResponse { [key: string]: any; count: number; items: Objects.StoriesStory[]; profiles?: Objects.UsersUser[]; groups?: Objects.GroupsGroup[]; } export interface StoriesUploadResponse { /** * A string hash that is used in the stories.save method */ upload_result?: string; [key: string]: any; } export interface StreamingGetServerUrlResponse { /** * Server host */ endpoint?: string; /** * Access key */ key?: string; [key: string]: any; } export interface UsersGetFollowersFieldsResponse { /** * Total number of available results */ count: number; [key: string]: any; items: Objects.UsersUserFull[]; } export interface UsersGetFollowersResponse { /** * Total friends number */ count: number; /** * User ID */ items: number[]; [key: string]: any; } export interface UsersGetSubscriptionsExtendedResponse { /** * Total number of available results */ count: number; [key: string]: any; items: Objects.UsersSubscriptionsItem[]; } export interface UsersGetSubscriptionsResponse { [key: string]: any; } export type UsersGetResponse = Objects.UsersUserXtrCounters[]; export interface UsersSearchResponse { /** * Total number of available results */ count?: number; [key: string]: any; items?: Objects.UsersUserFull[]; } export type UtilsCheckLinkResponse = Objects.UtilsLinkChecked; export interface UtilsGetLastShortenedLinksResponse { /** * Total number of available results */ count?: number; [key: string]: any; items?: Objects.UtilsLastShortenedLink[]; } export type UtilsGetLinkStatsExtendedResponse = Objects.UtilsLinkStatsExtended; export type UtilsGetLinkStatsResponse = Objects.UtilsLinkStats; export type UtilsGetServerTimeResponse = number; export type UtilsGetShortLinkResponse = Objects.UtilsShortLink; export type UtilsResolveScreenNameResponse = Objects.UtilsDomainResolved; export interface VideoAddAlbumResponse { /** * Created album ID */ album_id: number; [key: string]: any; } export type VideoCreateCommentResponse = number; export type VideoGetAlbumByIdResponse = Objects.VideoVideoAlbumFull; export interface VideoGetAlbumsByVideoExtendedResponse { /** * Total number */ count?: number; [key: string]: any; items?: Objects.VideoVideoAlbumFull[]; } export type VideoGetAlbumsByVideoResponse = number[]; export interface VideoGetAlbumsExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.VideoVideoAlbumFull[]; } export interface VideoGetAlbumsResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.VideoVideoAlbumFull[]; } export interface VideoGetCommentsExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.WallWallComment[]; profiles: Objects.UsersUserMin[]; groups: Objects.GroupsGroupFull[]; } export interface VideoGetCommentsResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.WallWallComment[]; } export interface VideoGetResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.VideoVideoFull[]; profiles?: Objects.UsersUserMin[]; groups?: Objects.GroupsGroupFull[]; } export type VideoRestoreCommentResponse = Objects.BaseBoolInt; export type VideoSaveResponse = Objects.VideoSaveResult; export interface VideoSearchExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.VideoVideoFull[]; profiles: Objects.UsersUser[]; groups: Objects.GroupsGroupFull[]; } export interface VideoSearchResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.VideoVideo[]; } export interface VideoUploadResponse { /** * Video size */ size?: number; /** * Video ID */ video_id?: number; [key: string]: any; } export interface WallCreateCommentResponse { /** * Created comment ID */ comment_id: number; [key: string]: any; } export interface WallEditResponse { /** * Edited post ID */ post_id: number; [key: string]: any; } export interface WallGetByIdExtendedResponse { [key: string]: any; items: Objects.WallWallpostFull[]; profiles: Objects.UsersUserFull[]; groups: Objects.GroupsGroupFull[]; } export type WallGetByIdLegacyResponse = Objects.WallWallpostFull[]; export interface WallGetByIdResponse { [key: string]: any; items?: Objects.WallWallpostFull[]; } export interface WallGetCommentExtendedResponse { [key: string]: any; items: Objects.WallWallComment[]; profiles: Objects.UsersUser[]; groups: Objects.GroupsGroup[]; } export interface WallGetCommentResponse { [key: string]: any; items: Objects.WallWallComment[]; } export interface WallGetCommentsExtendedResponse { /** * Total number */ count: number; /** * Information whether current user can comment the post */ can_post?: boolean | number; /** * Information whether groups can comment the post */ groups_can_post?: boolean | number; /** * Count of replies of current level */ current_level_count?: number; [key: string]: any; items: Objects.WallWallComment[]; show_reply_button?: boolean | number; profiles: Objects.UsersUser[]; groups: Objects.GroupsGroup[]; } export interface WallGetCommentsResponse { /** * Total number */ count: number; /** * Information whether current user can comment the post */ can_post?: boolean | number; /** * Information whether groups can comment the post */ groups_can_post?: boolean | number; /** * Count of replies of current level */ current_level_count?: number; [key: string]: any; items: Objects.WallWallComment[]; } export interface WallGetRepostsResponse { [key: string]: any; items: Objects.WallWallpostFull[]; profiles: Objects.UsersUser[]; groups: Objects.GroupsGroup[]; } export interface WallGetExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.WallWallpostFull[]; profiles: Objects.UsersUserFull[]; groups: Objects.GroupsGroupFull[]; } export interface WallGetResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.WallWallpostFull[]; } export interface WallPostAdsStealthResponse { /** * Created post ID */ post_id: number; [key: string]: any; } export interface WallPostResponse { /** * Created post ID */ post_id: number; [key: string]: any; } export interface WallRepostResponse { /** * Created post ID */ post_id: number; /** * Reposts number */ reposts_count: number; /** * Reposts to wall number */ wall_repost_count?: number; /** * Reposts to mail number */ mail_repost_count?: number; /** * Reposts number */ likes_count: number; [key: string]: any; success: number; } export interface WallSearchExtendedResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.WallWallpostFull[]; profiles: Objects.UsersUserFull[]; groups: Objects.GroupsGroupFull[]; } export interface WallSearchResponse { /** * Total number */ count: number; [key: string]: any; items: Objects.WallWallpostFull[]; } export interface WidgetsGetCommentsResponse { /** * Total number */ count: number; [key: string]: any; posts: Objects.WidgetsWidgetComment[]; } export interface WidgetsGetPagesResponse { /** * Total number */ count: number; [key: string]: any; pages: Objects.WidgetsWidgetPage[]; }
the_stack
jest.mock('dgram') import { Socket } from '../__mocks__/dgram' import { AtemSocketChild, ConnectionState, PacketFlag } from '../atemSocketChild' import { Util } from '../..' import * as fakeTimers from '@sinonjs/fake-timers' import { DEFAULT_PORT } from '../../atem' const ADDRESS = '127.0.0.1' function getSocket(child: AtemSocketChild): Socket { const socket = (child as any)._socket as Socket expect(socket).toBeTruthy() expect(socket.isOpen).toBeTruthy() socket.expectedAddress = ADDRESS socket.expectedPort = DEFAULT_PORT return socket } function getState(child: AtemSocketChild): ConnectionState { return (child as any)._connectionState as ConnectionState } function getInflightIds(child: AtemSocketChild): number[] { return (child as any)._inFlight.map((p: any) => p.packetId) } function fakeConnect(child: AtemSocketChild): void { const child2 = child as any child2._connectionState = ConnectionState.Established child2._address = '127.0.0.1' child2.startTimers() } function createSocketChild( onCommandsReceived?: (payload: Buffer, packetId: number) => Promise<void>, onCommandsAcknowledged?: (ids: Array<{ packetId: number; trackingId: number }>) => Promise<void>, onDisconnect?: () => Promise<void> ): AtemSocketChild { return new AtemSocketChild( { address: ADDRESS, port: DEFAULT_PORT, debugBuffers: false, }, onDisconnect || ((): Promise<void> => Promise.resolve()), // async msg => { console.log(msg) }, (): Promise<void> => Promise.resolve(), onCommandsReceived || ((): Promise<void> => Promise.resolve()), onCommandsAcknowledged || ((): Promise<void> => Promise.resolve()) ) } describe('SocketChild', () => { let clock: fakeTimers.Clock beforeEach(() => { clock = fakeTimers.install() }) afterEach(() => { clock.uninstall() }) test('Establish connection', async () => { const child = createSocketChild() try { const socket = getSocket(child) let receivedPacket = false socket.sendImpl = (msg: Buffer): void => { // Shouldnt only get one send expect(receivedPacket).toBeFalsy() receivedPacket = true expect(msg).toEqual(Util.COMMAND_CONNECT_HELLO) } expect(getState(child)).toEqual(ConnectionState.Closed) await child.connect(ADDRESS, DEFAULT_PORT) // Ensure everything has ticked through clock.tick(20) // Confirm something was sent expect(receivedPacket).toBeTruthy() expect(getState(child)).toEqual(ConnectionState.SynSent) receivedPacket = false socket.sendImpl = (msg: Buffer): void => { // Shouldnt only get one send expect(receivedPacket).toBeFalsy() receivedPacket = true expect(msg).toEqual( Buffer.from([0x80, 0x0c, 0x53, 0x1b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) ) } // Now get the connection established await socket.emitMessage( clock, Buffer.from([ 0x10, 0x14, // Length & Type 0x53, 0x1b, // Session Id 0x00, 0x00, // Not acking 0x00, 0x00, // Not asking for retransmit 0x00, 0xd1, // 'Client pkt id' Not sure why this 0x00, 0x00, // Packet Id 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Unknown Payload ]) ) // Ensure everything has ticked through await clock.tickAsync(20) // Confirm something was sent expect(receivedPacket).toBeTruthy() expect(getState(child)).toEqual(ConnectionState.Established) } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) function genAckRequestMessage(pktId: number, extraLength?: number): Buffer { const buffer = Buffer.from([ 0x08, 0x0c + (extraLength || 0), // Length & Type 0x53, 0x1b, // Session Id 0x00, 0x00, // Not acking 0x00, 0x00, // Not asking for retransmit 0x00, 0x00, // 'Client pkt id' Not needed 0x00, 0x00, // Packet Id ]) buffer.writeUInt16BE(pktId, 10) // Packet Id return buffer } test('Ack - delayed', async () => { const child = createSocketChild() try { fakeConnect(child) const socket = getSocket(child) const acked: number[] = [] let gotUnknown = false socket.sendImpl = (msg: Buffer): void => { const opcode = msg.readUInt8(0) >> 3 if (opcode & PacketFlag.AckReply) { acked.push(msg.readUInt16BE(4)) } else { gotUnknown = true // Shouldnt get any other sends // expect(false).toBeTruthy() } } await socket.emitMessage(clock, genAckRequestMessage(1)) // Nothing should have been sent immediately expect(acked).toEqual([]) expect(gotUnknown).toBeFalse() // Still nothing sent clock.tick(4) expect(acked).toEqual([]) expect(gotUnknown).toBeFalse() // Should be an ack a little later clock.tick(10) expect(acked).toEqual([1]) expect(gotUnknown).toBeFalse() } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) test('Ack - bulk', async () => { const child = createSocketChild() try { fakeConnect(child) const socket = getSocket(child) let acked: number[] = [] let gotUnknown = false socket.sendImpl = (msg: Buffer): void => { const opcode = msg.readUInt8(0) >> 3 if (opcode & PacketFlag.AckReply) { acked.push(msg.readUInt16BE(4)) } else { gotUnknown = true // Shouldnt get any other sends // expect(false).toBeTruthy() } } for (let i = 1; i <= 15; i++) { await socket.emitMessage(clock, genAckRequestMessage(i)) } // Nothing should have been sent yet await clock.tickAsync(4) expect(acked).toEqual([]) expect(gotUnknown).toBeFalse() // One more will trigger an ack await socket.emitMessage(clock, genAckRequestMessage(16)) expect(acked).toEqual([16]) expect(gotUnknown).toBeFalse() acked = [] // Nothing more should be acked clock.tick(10) expect(acked).toEqual([]) expect(gotUnknown).toBeFalse() } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) test('Inbound commands', async () => { let gotCmds: number[] = [] const child = createSocketChild((buf) => { gotCmds.push(buf.length) return Promise.resolve() }) try { fakeConnect(child) const socket = getSocket(child) let gotUnknown = false socket.sendImpl = (_msg: Buffer): void => { gotUnknown = true // Shouldnt get any other sends expect(false).toBeTruthy() } gotCmds = [] // Nothing await socket.emitMessage(clock, genAckRequestMessage(1)) expect(gotCmds).toEqual([]) expect(gotUnknown).toBeFalse() // Some payload const buffer = Buffer.concat([genAckRequestMessage(2, 1), Buffer.from([0])]) await socket.emitMessage(clock, buffer) expect(gotCmds).toEqual([1]) expect(gotUnknown).toBeFalse() gotCmds = [] // Repeated should not re-emit await socket.emitMessage(clock, buffer) expect(gotCmds).toEqual([]) expect(gotUnknown).toBeFalse() // Previous should not re-emit await socket.emitMessage(clock, Buffer.concat([genAckRequestMessage(1, 1), Buffer.from([0])])) expect(gotCmds).toEqual([]) expect(gotUnknown).toBeFalse() // Another payload await socket.emitMessage(clock, Buffer.concat([genAckRequestMessage(3, 1), Buffer.from([0])])) expect(gotCmds).toEqual([1]) expect(gotUnknown).toBeFalse() gotCmds = [] } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) test('Inbound commands - around wrap', async () => { let gotCmds: number[] = [] const child = createSocketChild((buf) => { gotCmds.push(buf.length) return Promise.resolve() }) try { fakeConnect(child) const socket = getSocket(child) ;(child as any)._lastReceivedPacketId = 32766 // 32767 is max let gotUnknown = false socket.sendImpl = (_msg: Buffer): void => { gotUnknown = true // Shouldnt get any other sends expect(false).toBeTruthy() } gotCmds = [] // Nothing await socket.emitMessage(clock, Buffer.concat([genAckRequestMessage(32766, 1), Buffer.from([0])])) expect(gotCmds).toEqual([]) expect(gotUnknown).toBeFalse() // Some payload const lastBuffer = Buffer.concat([genAckRequestMessage(32767, 1), Buffer.from([0])]) await socket.emitMessage(clock, lastBuffer) expect(gotCmds).toEqual([1]) expect(gotUnknown).toBeFalse() gotCmds = [] // Should not re-emit await socket.emitMessage(clock, lastBuffer) expect(gotCmds).toEqual([]) expect(gotUnknown).toBeFalse() gotCmds = [] // Now it has wrapped const firstBuffer = Buffer.concat([genAckRequestMessage(0, 1), Buffer.from([0])]) await socket.emitMessage(clock, firstBuffer) expect(gotCmds).toEqual([1]) expect(gotUnknown).toBeFalse() gotCmds = [] // Next buffer await socket.emitMessage(clock, Buffer.concat([genAckRequestMessage(1, 1), Buffer.from([0])])) expect(gotCmds).toEqual([1]) expect(gotUnknown).toBeFalse() gotCmds = [] // Should not re-emit await socket.emitMessage(clock, firstBuffer) expect(gotCmds).toEqual([]) expect(gotUnknown).toBeFalse() gotCmds = [] // Retransmit of lastBuffer is not uncommon, it should not re-emit await socket.emitMessage(clock, lastBuffer) expect(gotCmds).toEqual([]) expect(gotUnknown).toBeFalse() gotCmds = [] // Ensure that the first buffer still does not re-emit await socket.emitMessage(clock, firstBuffer) expect(gotCmds).toEqual([]) expect(gotUnknown).toBeFalse() gotCmds = [] } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) test('SendCommands', async () => { const child = createSocketChild() try { fakeConnect(child) const socket = getSocket(child) ;(child as any)._nextSendPacketId = 123 let received: Array<{ id: number; payload: Buffer }> = [] socket.sendImpl = (msg: Buffer): void => { const opcode = msg.readUInt8(0) >> 3 expect(opcode).toEqual(PacketFlag.AckRequest) received.push({ id: msg.readUInt16BE(10), payload: msg.slice(12), }) } // Send something const buf1 = [0, 1, 2] const cmdName = 'test' const buf1Expected = Buffer.alloc(11) buf1Expected.writeUInt16BE(buf1Expected.length, 0) buf1Expected.write(cmdName, 4, 4) Buffer.from(buf1).copy(buf1Expected, 8) child.sendCommands([{ payload: buf1, rawName: cmdName, trackingId: 1 }]) expect(received).toEqual([ { id: 123, payload: buf1Expected, }, ]) received = [] expect(getInflightIds(child)).toEqual([123]) // Send another child.sendCommands([{ payload: buf1, rawName: cmdName, trackingId: 1 }]) expect(received).toEqual([ { id: 124, payload: buf1Expected, }, ]) received = [] expect(getInflightIds(child)).toEqual([123, 124]) } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) function genAckCommandMessage(pktId: number): Buffer { const buffer = Buffer.from([ 0x80, 0x0c, // Length & Type 0x53, 0x1b, // Session Id 0x00, 0x00, // Acking - set after 0x00, 0x00, // Not asking for retransmit 0x00, 0x00, // 'Client pkt id' Not needed 0x00, 0x00, // No Packet Id ]) buffer.writeUInt16BE(pktId, 4) // Acked Id return buffer } test('SendCommand - acks', async () => { let acked: Array<{ packetId: number; trackingId: number }> = [] const child = createSocketChild(undefined, async (ids) => { acked.push(...ids) }) try { fakeConnect(child) const socket = getSocket(child) ;(child as any)._nextSendPacketId = 123 let received: number[] = [] socket.sendImpl = (msg: Buffer): void => { const opcode = msg.readUInt8(0) >> 3 expect(opcode).toEqual(PacketFlag.AckRequest) received.push(msg.readUInt16BE(10)) } acked = [] // Send some stuff const buf1 = [0, 1, 2] child.sendCommands([ { payload: buf1, rawName: '', trackingId: 5 }, { payload: buf1, rawName: '', trackingId: 6 }, { payload: buf1, rawName: '', trackingId: 7 }, ]) child.sendCommands([{ payload: buf1, rawName: '', trackingId: 8 }]) child.sendCommands([ { payload: buf1, rawName: '', trackingId: 9 }, { payload: buf1, rawName: '', trackingId: 10 }, ]) expect(received).toEqual([123, 124, 125, 126, 127, 128]) received = [] expect(getInflightIds(child)).toEqual([123, 124, 125, 126, 127, 128]) expect(acked).toEqual([]) // Ack a couple await socket.emitMessage(clock, genAckCommandMessage(125)) expect(getInflightIds(child)).toEqual([126, 127, 128]) expect(acked).toEqual([ { packetId: 123, trackingId: 5 }, { packetId: 124, trackingId: 6 }, { packetId: 125, trackingId: 7 }, ]) acked = [] // Another ack await socket.emitMessage(clock, genAckCommandMessage(126)) expect(getInflightIds(child)).toEqual([127, 128]) expect(acked).toEqual([{ packetId: 126, trackingId: 8 }]) } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) test('SendCommand - acks wrap', async () => { let acked: Array<{ packetId: number; trackingId: number }> = [] const child = createSocketChild(undefined, async (ids) => { acked.push(...ids) }) try { fakeConnect(child) const socket = getSocket(child) ;(child as any)._nextSendPacketId = 32764 // 32767 is max let received: number[] = [] socket.sendImpl = (msg: Buffer): void => { const opcode = msg.readUInt8(0) >> 3 expect(opcode).toEqual(PacketFlag.AckRequest) received.push(msg.readUInt16BE(10)) } acked = [] // Send some stuff const buf1 = [0, 1, 2] child.sendCommands([ { payload: buf1, rawName: '', trackingId: 5 }, // 32764 { payload: buf1, rawName: '', trackingId: 6 }, // 32765 { payload: buf1, rawName: '', trackingId: 7 }, // 32766 ]) child.sendCommands([ { payload: buf1, rawName: '', trackingId: 8 }, // 32767 ]) child.sendCommands([ { payload: buf1, rawName: '', trackingId: 9 }, // 0 { payload: buf1, rawName: '', trackingId: 10 }, // 1 ]) expect(received).toEqual([32764, 32765, 32766, 32767, 0, 1]) received = [] expect(getInflightIds(child)).toEqual([32764, 32765, 32766, 32767, 0, 1]) expect(acked).toEqual([]) // Ack a couple await socket.emitMessage(clock, genAckCommandMessage(32766)) expect(getInflightIds(child)).toEqual([32767, 0, 1]) expect(acked).toEqual([ { packetId: 32764, trackingId: 5 }, { packetId: 32765, trackingId: 6 }, { packetId: 32766, trackingId: 7 }, ]) acked = [] // Another ack await socket.emitMessage(clock, genAckCommandMessage(0)) expect(getInflightIds(child)).toEqual([1]) expect(acked).toEqual([ { packetId: 32767, trackingId: 8 }, { packetId: 0, trackingId: 9 }, ]) } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) test('SendCommand - retransmit timeouts', async () => { let acked: Array<{ packetId: number; trackingId: number }> = [] const child = createSocketChild(undefined, async (ids) => { acked.push(...ids) }) try { fakeConnect(child) const socket = getSocket(child) ;(child as any)._nextSendPacketId = 32764 // 32767 is max let received: number[] = [] socket.sendImpl = (msg: Buffer): void => { const opcode = msg.readUInt8(0) >> 3 expect(opcode).toEqual(PacketFlag.AckRequest) received.push(msg.readUInt16BE(10)) } acked = [] // Send some stuff const buf1 = [0, 1, 2] child.sendCommands([ { payload: buf1, rawName: '', trackingId: 5 }, // 32764 { payload: buf1, rawName: '', trackingId: 6 }, // 32765 { payload: buf1, rawName: '', trackingId: 7 }, // 32766 { payload: buf1, rawName: '', trackingId: 8 }, // 32767 { payload: buf1, rawName: '', trackingId: 9 }, // 0 { payload: buf1, rawName: '', trackingId: 10 }, // 1 ]) expect(received).toEqual([32764, 32765, 32766, 32767, 0, 1]) received = [] expect(getInflightIds(child)).toEqual([32764, 32765, 32766, 32767, 0, 1]) expect(acked).toEqual([]) // Ack a couple to ensure socket is running properly await socket.emitMessage(clock, genAckCommandMessage(32765)) expect(getInflightIds(child)).toEqual([32766, 32767, 0, 1]) expect(acked).toEqual([ { packetId: 32764, trackingId: 5 }, { packetId: 32765, trackingId: 6 }, ]) acked = [] expect(received).toEqual([]) received = [] // Let the commands be resent await clock.tickAsync(80) expect(received).toEqual([32766, 32767, 0, 1]) received = [] // Should keep happening await clock.tickAsync(80) expect(received).toEqual([32766, 32767, 0, 1]) received = [] // Add another to the queue child.sendCommands([ { payload: buf1, rawName: '', trackingId: 11 }, // 2 ]) expect(received).toEqual([2]) received = [] expect(getInflightIds(child)).toEqual([32766, 32767, 0, 1, 2]) expect(acked).toEqual([]) // And again, this time with the new thing await clock.tickAsync(80) expect(received).toEqual([32766, 32767, 0, 1, 2]) received = [] } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) function genRetransmitRequestCommandMessage(pktId: number): Buffer { const buffer = Buffer.from([ 0x40, 0x0c, // Length & Type 0x53, 0x1b, // Session Id 0x00, 0x00, // Not acking 0x00, 0x00, // retransmit - set after 0x00, 0x00, // 'Client pkt id' Not needed 0x00, 0x00, // No Packet Id ]) buffer.writeUInt16BE(pktId, 6) // retransmit Id return buffer } test('SendCommand - retransmit request', async () => { let acked: Array<{ packetId: number; trackingId: number }> = [] const child = createSocketChild(undefined, async (ids) => { acked.push(...ids) }) try { fakeConnect(child) const socket = getSocket(child) ;(child as any)._nextSendPacketId = 32764 // 32767 is max let received: number[] = [] socket.sendImpl = (msg: Buffer): void => { const opcode = msg.readUInt8(0) >> 3 expect(opcode).toEqual(PacketFlag.AckRequest) received.push(msg.readUInt16BE(10)) } acked = [] // Send some stuff const buf1 = [0, 1, 2] child.sendCommands([ { payload: buf1, rawName: '', trackingId: 5 }, // 32764 { payload: buf1, rawName: '', trackingId: 6 }, // 32765 { payload: buf1, rawName: '', trackingId: 7 }, // 32766 { payload: buf1, rawName: '', trackingId: 8 }, // 32767 { payload: buf1, rawName: '', trackingId: 9 }, // 0 { payload: buf1, rawName: '', trackingId: 10 }, // 1 ]) expect(received).toEqual([32764, 32765, 32766, 32767, 0, 1]) received = [] expect(getInflightIds(child)).toEqual([32764, 32765, 32766, 32767, 0, 1]) expect(acked).toEqual([]) // Ack a couple to ensure socket is running properly await socket.emitMessage(clock, genAckCommandMessage(32765)) expect(getInflightIds(child)).toEqual([32766, 32767, 0, 1]) expect(acked).toEqual([ { packetId: 32764, trackingId: 5 }, { packetId: 32765, trackingId: 6 }, ]) acked = [] expect(received).toEqual([]) received = [] // The device asks for a retransmit await socket.emitMessage(clock, genRetransmitRequestCommandMessage(32766)) expect(received).toEqual([32766, 32767, 0, 1]) received = [] // And again await socket.emitMessage(clock, genRetransmitRequestCommandMessage(32767)) expect(received).toEqual([32767, 0, 1]) received = [] } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) test('SendCommand - retransmit request future', async () => { const acked: Array<{ packetId: number; trackingId: number }> = [] let connected = true const child = createSocketChild( undefined, async (ids) => { acked.push(...ids) }, async () => { connected = false } ) try { fakeConnect(child) const socket = getSocket(child) ;(child as any)._nextSendPacketId = 32767 // 32767 is max connected = true // Send some stuff const buf1 = [0, 1, 2] child.sendCommands([ { payload: buf1, rawName: '', trackingId: 5 }, // 32767 { payload: buf1, rawName: '', trackingId: 6 }, // 0 ]) expect(getInflightIds(child)).toEqual([32767, 0]) expect(acked).toEqual([]) expect(connected).toBeTrue() // The device asks for a retransmit of a future packet await socket.emitMessage(clock, genRetransmitRequestCommandMessage(1)) expect(getInflightIds(child)).toEqual([]) expect(connected).toBeFalse() } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) test('SendCommand - retransmit request previous', async () => { const acked: Array<{ packetId: number; trackingId: number }> = [] let connected = true const child = createSocketChild( undefined, async (ids) => { acked.push(...ids) }, async () => { connected = false } ) try { fakeConnect(child) const socket = getSocket(child) ;(child as any)._nextSendPacketId = 32767 // 32767 is max connected = true // Send some stuff const buf1 = [0, 1, 2] child.sendCommands([ { payload: buf1, rawName: '', trackingId: 5 }, // 32767 { payload: buf1, rawName: '', trackingId: 6 }, // 0 ]) expect(getInflightIds(child)).toEqual([32767, 0]) expect(acked).toEqual([]) expect(connected).toBeTrue() // The device asks for a retransmit of a past packet await socket.emitMessage(clock, genRetransmitRequestCommandMessage(32766)) expect(getInflightIds(child)).toEqual([]) expect(connected).toBeFalse() } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) test('Reconnect timer', async () => { let acked: Array<{ packetId: number; trackingId: number }> = [] let connected = true const child = createSocketChild( undefined, async (ids) => { acked.push(...ids) }, async () => { connected = false } ) try { fakeConnect(child) const socket = getSocket(child) ;(child as any)._nextSendPacketId = 32767 // 32767 is max connected = true acked = [] // Send some stuff const buf1 = [0, 1, 2] child.sendCommands([ { payload: buf1, rawName: '', trackingId: 5 }, // 32767 { payload: buf1, rawName: '', trackingId: 6 }, // 0 ]) expect(getInflightIds(child)).toEqual([32767, 0]) expect(acked).toEqual([]) expect(connected).toBeTrue() // Ack a couple to ensure socket is running properly await socket.emitMessage(clock, genAckCommandMessage(0)) expect(getInflightIds(child)).toEqual([]) expect(acked).toEqual([ { packetId: 32767, trackingId: 5 }, { packetId: 0, trackingId: 6 }, ]) acked = [] // Tick to let the timer execute await clock.tickAsync(1500) expect(connected).toBeTrue() expect(getInflightIds(child)).toEqual([]) expect(acked).toEqual([]) // Still nothing await clock.tickAsync(1500) expect(connected).toBeTrue() expect(getInflightIds(child)).toEqual([]) expect(acked).toEqual([]) // Not quite await clock.tickAsync(1990) expect(connected).toBeTrue() child.sendCommands([ { payload: buf1, rawName: '', trackingId: 7 }, // 1 ]) expect(getInflightIds(child)).toEqual([1]) expect(acked).toEqual([]) // Timeout await clock.tickAsync(20) expect(connected).toBeFalse() expect(getInflightIds(child)).toEqual([]) expect(acked).toEqual([]) } finally { if (child) { // Try and cleanup any timers await child.disconnect() } } }) })
the_stack
import { Injectable } from '@angular/core'; import { select, Store } from '@ngrx/store'; import { combineLatest, iif, Observable } from 'rxjs'; import { filter, map, switchMap, tap, withLatestFrom } from 'rxjs/operators'; import { AuthService } from '../../auth/user-auth/facade/auth.service'; import { AnonymousConsent, ANONYMOUS_CONSENT_STATUS, ConsentTemplate, } from '../../model/index'; import { AnonymousConsentsActions } from '../store/actions/index'; import { StateWithAnonymousConsents } from '../store/anonymous-consents-state'; import { AnonymousConsentsSelectors } from '../store/selectors/index'; @Injectable({ providedIn: 'root' }) export class AnonymousConsentsService { constructor( protected store: Store<StateWithAnonymousConsents>, protected authService: AuthService ) {} /** * Retrieves the anonymous consent templates. */ loadTemplates(): void { this.store.dispatch( new AnonymousConsentsActions.LoadAnonymousConsentTemplates() ); } /** * Conditionally triggers the load of the anonymous consent templates if: * - `loadIfMissing` parameter is set to `true` * - the `templates` in the store are `undefined` * * Otherwise it just returns the value from the store. * * @param loadIfMissing setting to `true` will trigger the load of the templates if the currently stored templates are `undefined` */ getTemplates(loadIfMissing = false): Observable<ConsentTemplate[]> { return iif( () => loadIfMissing, this.store.pipe( select(AnonymousConsentsSelectors.getAnonymousConsentTemplatesValue), withLatestFrom(this.getLoadTemplatesLoading()), filter(([_templates, loading]) => !loading), tap(([templates, _loading]) => { if (!Boolean(templates)) { this.loadTemplates(); } }), filter(([templates, _loading]) => Boolean(templates)), map(([templates, _loading]) => templates) ), this.store.pipe( select(AnonymousConsentsSelectors.getAnonymousConsentTemplatesValue) ) ); } /** * Returns the anonymous consent templates with the given template code. * @param templateCode a template code by which to filter anonymous consent templates. */ getTemplate(templateCode: string): Observable<ConsentTemplate | undefined> { return this.store.pipe( select( AnonymousConsentsSelectors.getAnonymousConsentTemplate(templateCode) ) ); } /** * Returns an indicator for the loading status for the anonymous consent templates. */ getLoadTemplatesLoading(): Observable<boolean> { return this.store.pipe( select(AnonymousConsentsSelectors.getAnonymousConsentTemplatesLoading) ); } /** * Returns an indicator for the success status for the anonymous consent templates. */ getLoadTemplatesSuccess(): Observable<boolean> { return this.store.pipe( select(AnonymousConsentsSelectors.getAnonymousConsentTemplatesSuccess) ); } /** * Returns an indicator for the error status for the anonymous consent templates. */ getLoadTemplatesError(): Observable<boolean> { return this.store.pipe( select(AnonymousConsentsSelectors.getAnonymousConsentTemplatesError) ); } /** * Resets the loading, success and error indicators for the anonymous consent templates. */ resetLoadTemplatesState(): void { this.store.dispatch( new AnonymousConsentsActions.ResetLoadAnonymousConsentTemplates() ); } /** * Returns all the anonymous consents. */ getConsents(): Observable<AnonymousConsent[]> { return this.store.pipe( select(AnonymousConsentsSelectors.getAnonymousConsents) ); } /** * Puts the provided anonymous consents into the store. */ setConsents(consents: AnonymousConsent[]): void { return this.store.dispatch( new AnonymousConsentsActions.SetAnonymousConsents(consents) ); } /** * Returns the anonymous consent for the given template ID. * * As a side-effect, the method will call `getTemplates(true)` to load the templates if those are not present. * * @param templateId a template ID by which to filter anonymous consent templates. */ getConsent(templateId: string): Observable<AnonymousConsent | undefined> { return this.authService.isUserLoggedIn().pipe( filter((authenticated) => !authenticated), tap(() => this.getTemplates(true)), switchMap(() => this.store.pipe( select( AnonymousConsentsSelectors.getAnonymousConsentByTemplateCode( templateId ) ) ) ) ); } /** * Give a consent for the given `templateCode` * @param templateCode for which to give the consent */ giveConsent(templateCode: string): void { this.store.dispatch( new AnonymousConsentsActions.GiveAnonymousConsent(templateCode) ); } /** * Sets all the anonymous consents' state to given. */ giveAllConsents(): Observable<ConsentTemplate[]> { return this.getTemplates(true).pipe( tap((templates) => templates.forEach((template) => { if (template.id) { this.giveConsent(template.id); } }) ) ); } /** * Returns `true` if the provided `consent` is given. * @param consent a consent to test */ isConsentGiven(consent: AnonymousConsent | undefined): boolean { return ( (consent && consent.consentState === ANONYMOUS_CONSENT_STATUS.GIVEN) ?? false ); } /** * Withdraw a consent for the given `templateCode` * @param templateCode for which to withdraw the consent */ withdrawConsent(templateCode: string): void { this.store.dispatch( new AnonymousConsentsActions.WithdrawAnonymousConsent(templateCode) ); } /** * Sets all the anonymous consents' state to withdrawn. */ withdrawAllConsents(): Observable<ConsentTemplate[]> { return this.getTemplates(true).pipe( tap((templates) => templates.forEach((template) => { if (template.id) { this.withdrawConsent(template.id); } }) ) ); } /** * Returns `true` if the provided `consent` is withdrawn. * @param consent a consent to test */ isConsentWithdrawn(consent: AnonymousConsent): boolean { return ( consent && consent.consentState === ANONYMOUS_CONSENT_STATUS.WITHDRAWN ); } /** * Toggles the dismissed state of the anonymous consents banner. * @param dismissed the banner will be dismissed if `true` is passed, otherwise it will be visible. */ toggleBannerDismissed(dismissed: boolean): void { this.store.dispatch( new AnonymousConsentsActions.ToggleAnonymousConsentsBannerDissmissed( dismissed ) ); if (dismissed) { this.toggleTemplatesUpdated(false); } } /** * Returns `true` if the banner was dismissed, `false` otherwise. */ isBannerDismissed(): Observable<boolean> { return this.store.pipe( select(AnonymousConsentsSelectors.getAnonymousConsentsBannerDismissed) ); } /** * Returns `true` if the consent templates were updated on the back-end. * If the templates are not present in the store, it triggers the load. */ getTemplatesUpdated(): Observable<boolean> { return this.getTemplates(true).pipe( switchMap(() => this.store.pipe( select(AnonymousConsentsSelectors.getAnonymousConsentTemplatesUpdate) ) ) ); } /** * Toggles the `updated` slice of the state * @param updated */ toggleTemplatesUpdated(updated: boolean): void { this.store.dispatch( new AnonymousConsentsActions.ToggleAnonymousConsentTemplatesUpdated( updated ) ); } /** * Returns `true` if either the banner is not dismissed or if the templates were updated on the back-end. * Otherwise, it returns `false`. */ isBannerVisible(): Observable<boolean> { return combineLatest([ this.isBannerDismissed(), this.getTemplatesUpdated(), ]).pipe( tap(() => this.checkConsentVersions()), map(([dismissed, updated]) => !dismissed || updated) ); } /** * Dispatches an action to trigger the check * whether the anonymous consent version have been updated */ private checkConsentVersions(): void { this.store.dispatch( new AnonymousConsentsActions.AnonymousConsentCheckUpdatedVersions() ); } /** * Returns `true` if there's a mismatch in template versions between the provided `currentTemplates` and `newTemplates` * @param currentTemplates current templates to check * @param newTemplates new templates to check */ detectUpdatedTemplates( currentTemplates: ConsentTemplate[], newTemplates: ConsentTemplate[] ): boolean { if (newTemplates.length !== currentTemplates.length) { return true; } for (let i = 0; i < newTemplates.length; i++) { const newTemplate = newTemplates[i]; const currentTemplate = currentTemplates[i]; if (newTemplate.version !== currentTemplate.version) { return true; } } return false; } /** * Serializes using `JSON.stringify()` and encodes using `encodeURIComponent()` methods * @param consents to serialize and encode */ serializeAndEncode(consents: AnonymousConsent[]): string { if (!consents) { return ''; } const serialized = JSON.stringify(consents); const encoded = encodeURIComponent(serialized); return encoded; } /** * Decodes using `decodeURIComponent()` and deserializes using `JSON.parse()` * @param rawConsents to decode an deserialize */ decodeAndDeserialize(rawConsents: string): AnonymousConsent[] { const decoded = decodeURIComponent(rawConsents); if (decoded.length > 0) { const unserialized = JSON.parse(decoded) as AnonymousConsent[]; return unserialized; } return []; } /** * * Compares the given `newConsents` and `previousConsents` and returns `true` if there are differences (the `newConsents` are updates). * Otherwise it returns `false`. * * @param newConsents new consents to compare * @param previousConsents old consents to compare */ consentsUpdated( newConsents: AnonymousConsent[], previousConsents: AnonymousConsent[] ): boolean { const newRawConsents = this.serializeAndEncode(newConsents); const previousRawConsents = this.serializeAndEncode(previousConsents); return newRawConsents !== previousRawConsents; } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormContract_Detail { interface tab_general_Sections { administration: DevKit.Controls.Section; allotment_details: DevKit.Controls.Section; contract_detail_information: DevKit.Controls.Section; notes: DevKit.Controls.Section; pricing: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { general: tab_general; } interface Body { Tab: Tabs; /** Enter the date when the contract line becomes active. */ ActiveOn: DevKit.Controls.Date; /** Shows the number of cases or minutes remaining, based on the resolved cases logged to the contract line. */ AllotmentsRemaining: DevKit.Controls.Integer; /** Shows the number of cases or minutes used in the resolved cases on the contract line. */ AllotmentsUsed: DevKit.Controls.Integer; /** Select the customer account or contact to provide a quick link to additional customer details, such as address, phone number, activities, and orders. */ CustomerId: DevKit.Controls.Lookup; /** Type the discount amount for the contract line to deduct any negotiated or other savings from the net amount due. */ Discount: DevKit.Controls.Money; /** Type the discount rate that should be applied to the Total Price, for use in calculating the net amount due for the contract line. */ DiscountPercentage: DevKit.Controls.Decimal; /** Enter the date when the contract line expires. The date is automatically filled with the contract date, but you can change it if required. */ ExpiresOn: DevKit.Controls.Date; /** Type the number of units of the specified product or service that are eligible for support on the contract line. */ InitialQuantity: DevKit.Controls.Integer; /** Shows the total charge to the customer for the contract line, calculated as the Total Price minus any discounts. */ Net: DevKit.Controls.Money; notescontrol: DevKit.Controls.Note; /** Type the total service charge for the contract line before any discounts are credited. */ Price: DevKit.Controls.Money; /** Choose the product that is eligible for services on the contract line. */ ProductId: DevKit.Controls.Lookup; /** Type the serial number for the product that is eligible for services on the contract line. */ ProductSerialNumber: DevKit.Controls.String; /** Shows the cost per case or minute, calculated by dividing the Total Price value by the total number of cases or minutes allocated to the contract line. */ Rate: DevKit.Controls.Money; /** Choose the address for the customer account or contact where the services are provided. */ ServiceAddress: DevKit.Controls.Lookup; /** Type a title or name that describes the contract line. */ Title: DevKit.Controls.String; /** Type the total number of minutes or cases allowed for the contract line. */ TotalAllotments: DevKit.Controls.Integer; /** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */ UoMId: DevKit.Controls.Lookup; } } class FormContract_Detail extends DevKit.IForm { /** * DynamicsCrm.DevKit form Contract_Detail * @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 Contract_Detail */ Body: DevKit.FormContract_Detail.Body; } namespace FormContractDetail_Information { interface tab_administration_Sections { customer_information: DevKit.Controls.Section; serial_number: DevKit.Controls.Section; } interface tab_general_Sections { allotment_details: DevKit.Controls.Section; contract_detail_information: DevKit.Controls.Section; pricing: DevKit.Controls.Section; } interface tab_notes_Sections { notes: DevKit.Controls.Section; } interface tab_administration extends DevKit.Controls.ITab { Section: tab_administration_Sections; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface tab_notes extends DevKit.Controls.ITab { Section: tab_notes_Sections; } interface Tabs { administration: tab_administration; general: tab_general; notes: tab_notes; } interface Body { Tab: Tabs; /** Enter the date when the contract line becomes active. */ ActiveOn: DevKit.Controls.Date; /** Shows the number of cases or minutes remaining, based on the resolved cases logged to the contract line. */ AllotmentsRemaining: DevKit.Controls.Integer; /** Shows the number of cases or minutes used in the resolved cases on the contract line. */ AllotmentsUsed: DevKit.Controls.Integer; /** Select the customer account or contact to provide a quick link to additional customer details, such as address, phone number, activities, and orders. */ CustomerId: DevKit.Controls.Lookup; /** Type the discount amount for the contract line to deduct any negotiated or other savings from the net amount due. */ Discount: DevKit.Controls.Money; /** Type the discount rate that should be applied to the Total Price, for use in calculating the net amount due for the contract line. */ DiscountPercentage: DevKit.Controls.Decimal; /** Enter the date when the contract line expires. The date is automatically filled with the contract date, but you can change it if required. */ ExpiresOn: DevKit.Controls.Date; /** Type the number of units of the specified product or service that are eligible for support on the contract line. */ InitialQuantity: DevKit.Controls.Integer; /** Shows the total charge to the customer for the contract line, calculated as the Total Price minus any discounts. */ Net: DevKit.Controls.Money; notescontrol: DevKit.Controls.Note; /** Type the total service charge for the contract line before any discounts are credited. */ Price: DevKit.Controls.Money; /** Choose the product that is eligible for services on the contract line. */ ProductId: DevKit.Controls.Lookup; /** Type the serial number for the product that is eligible for services on the contract line. */ ProductSerialNumber: DevKit.Controls.String; /** Shows the cost per case or minute, calculated by dividing the Total Price value by the total number of cases or minutes allocated to the contract line. */ Rate: DevKit.Controls.Money; /** Choose the address for the customer account or contact where the services are provided. */ ServiceAddress: DevKit.Controls.Lookup; /** Type a title or name that describes the contract line. */ Title: DevKit.Controls.String; /** Type the total number of minutes or cases allowed for the contract line. */ TotalAllotments: DevKit.Controls.Integer; /** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */ UoMId: DevKit.Controls.Lookup; } } class FormContractDetail_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form ContractDetail_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 ContractDetail_Information */ Body: DevKit.FormContractDetail_Information.Body; } class ContractDetailApi { /** * DynamicsCrm.DevKit ContractDetailApi * @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 account with which the contract is associated. */ AccountId: DevKit.WebApi.LookupValueReadonly; /** Enter the date when the contract line becomes active. */ ActiveOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Shows the number of minutes over the Total Allotments field that have been spent on resolved cases related to the contract line. */ AllotmentsOverage: DevKit.WebApi.IntegerValueReadonly; /** Shows the number of cases or minutes remaining, based on the resolved cases logged to the contract line. */ AllotmentsRemaining: DevKit.WebApi.IntegerValueReadonly; /** Shows the number of cases or minutes used in the resolved cases on the contract line. */ AllotmentsUsed: DevKit.WebApi.IntegerValueReadonly; /** Unique identifier for the contact associated with the contract line. */ ContactId: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the contract line. */ ContractDetailId: DevKit.WebApi.GuidValue; /** Unique identifier of the contract associated with the contract line. */ ContractId: DevKit.WebApi.LookupValue; /** Status of the contract. */ ContractStateCode: DevKit.WebApi.OptionSetValueReadonly; /** Shows who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; customerid_account: DevKit.WebApi.LookupValue; customerid_contact: DevKit.WebApi.LookupValue; /** Type the discount amount for the contract line to deduct any negotiated or other savings from the net amount due. */ Discount: DevKit.WebApi.MoneyValue; /** Value of the Discount in base currency. */ Discount_Base: DevKit.WebApi.MoneyValueReadonly; /** Type the discount rate that should be applied to the Total Price, for use in calculating the net amount due for the contract line. */ DiscountPercentage: DevKit.WebApi.DecimalValue; /** Days of the week and times for which the contract line item is effective. */ EffectivityCalendar: DevKit.WebApi.StringValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Enter the date when the contract line expires. The date is automatically filled with the contract date, but you can change it if required. */ ExpiresOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Type the number of units of the specified product or service that are eligible for support on the contract line. */ InitialQuantity: DevKit.WebApi.IntegerValue; /** Type the line item number for the contract line to easily identify the contract line and make sure it's listed in the correct order in the parent contract. */ LineItemOrder: DevKit.WebApi.IntegerValue; /** Shows who last updated the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows the total charge to the customer for the contract line, calculated as the Total Price minus any discounts. */ Net: DevKit.WebApi.MoneyValueReadonly; /** Value of the Net in base currency. */ Net_Base: DevKit.WebApi.MoneyValueReadonly; /** 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.LookupValueReadonly; /** 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.LookupValueReadonly; /** 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; /** Type the total service charge for the contract line before any discounts are credited. */ Price: DevKit.WebApi.MoneyValue; /** Value of the Total Price in base currency. */ Price_Base: DevKit.WebApi.MoneyValueReadonly; /** Choose the product that is eligible for services on the contract line. */ ProductId: DevKit.WebApi.LookupValue; /** Type the serial number for the product that is eligible for services on the contract line. */ ProductSerialNumber: DevKit.WebApi.StringValue; /** Shows the cost per case or minute, calculated by dividing the Total Price value by the total number of cases or minutes allocated to the contract line. */ Rate: DevKit.WebApi.MoneyValueReadonly; /** Value of the Rate in base currency. */ Rate_Base: DevKit.WebApi.MoneyValueReadonly; /** Choose the address for the customer account or contact where the services are provided. */ ServiceAddress: DevKit.WebApi.LookupValue; /** Select the unit type allotted in the contract line, such as cases or minutes, to determine the level of support. */ ServiceContractUnitsCode: DevKit.WebApi.OptionSetValue; /** Shows whether the contract line is existing, renewed, canceled, or expired. You can't edit a contract line after it is saved, regardless of the status. */ StateCode: DevKit.WebApi.OptionSetValue; /** Select the contract line's status. */ StatusCode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Type a title or name that describes the contract line. */ Title: DevKit.WebApi.StringValue; /** Type the total number of minutes or cases allowed for the contract line. */ TotalAllotments: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValueReadonly; /** Choose the unit of measurement for the base unit quantity for this purchase, such as each or dozen. */ UoMId: DevKit.WebApi.LookupValue; /** Unique identifier of the unit group associated with the contract line. */ UoMScheduleId: DevKit.WebApi.LookupValue; /** 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 ContractDetail { enum ContractStateCode { } enum ServiceContractUnitsCode { /** 1 */ Default_Value } enum StateCode { /** 2 */ Canceled, /** 0 */ Existing, /** 3 */ Expired, /** 1 */ Renewed } enum StatusCode { /** 3 */ Canceled, /** 4 */ Expired, /** 1 */ New, /** 2 */ Renewed } 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':['Contract Detail','Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { describe, it, run, expect } from 'https://deno.land/x/tincan@0.2.2/mod.ts' import { InitAppAndTest, runServer } from '../util.ts' import { setHeader, getResponseHeader, setVaryHeader, setContentType, setLocationHeader } from '../../extensions/res/headers.ts' import { redirect } from '../../extensions/res/redirect.ts' import { formatResponse } from '../../extensions/res/format.ts' import { attachment } from '../../extensions/res/download.ts' import { setCookie, clearCookie } from '../../extensions/res/cookie.ts' import * as path from 'https://deno.land/std@0.106.0/path/mod.ts' import type { Request } from '../../request.ts' const __dirname = new URL('.', import.meta.url).pathname describe('res.set(field, val)', () => { it('should set a string header with a string value', async () => { const { fetch } = InitAppAndTest((_, res) => { setHeader(res)('hello', 'World') res.end() }) await fetch.get('/').expect('hello', 'World') }) it('should set an array of header values', async () => { const { fetch } = InitAppAndTest((_, res) => { setHeader(res)('foo', ['bar', 'baz']) res.end() }) await fetch.get('/').expect('foo', 'bar,baz') }) it('should throw if `Content-Type` header is passed as an array', async () => { const { fetch } = InitAppAndTest((_, res) => { try { setHeader(res)('content-type', ['foo', 'bar']) } catch (e) { res.status = 500 res.end((e as TypeError).message) } }) await fetch.get('/').expect(500, 'Content-Type cannot be set to an Array') }) it('if the first argument is object, then map keys to values', async () => { const { fetch } = InitAppAndTest((_, res) => { setHeader(res)({ foo: 'bar' }) res.end() }) await fetch.get('/').expect('foo', 'bar') }) it('should not set a charset of one is already set', async () => { const { fetch } = InitAppAndTest((_, res) => { setHeader(res)('content-type', 'text/plain; charset=UTF-8') res.end() }) await fetch.get('/').expect('content-type', 'text/plain; charset=UTF-8') }) }) describe('res.get(field)', () => { it('should get a header with a specified field', async () => { const { fetch } = InitAppAndTest((_, res) => { setHeader(res)('hello', 'World') res.end(getResponseHeader(res)('hello')) }) await fetch.get('/').expect('World') }) }) describe('res.vary(field)', () => { it('should set a "Vary" header properly', async () => { const { fetch } = InitAppAndTest((_, res) => { setVaryHeader(res)('User-Agent').end() }) await fetch.get('/').expect('Vary', 'User-Agent') }) }) describe('res.redirect(url, status)', () => { it('should set 302 status and message about redirecting', async () => { const { fetch } = InitAppAndTest((req, res) => { redirect(req, res, () => {})('/abc') }) await fetch.get('/').expect('Location', '/abc').expect(302 /* 'Redirecting to' */) }) it('should send an HTML link to redirect to', async () => { const { fetch } = InitAppAndTest((req, res) => { if (req.url === '/abc') { req.respond({ status: 200, body: 'Hello World' }) } else { redirect(req, res, () => {})('/abc') } }) await fetch .get('/') .set('Accept', 'text/html') .expect(302 /* '<p>Found. Redirecting to <a href="/abc">/abc</a></p>' */) }) }) describe('res.format(obj)', () => { /* it('should send text by default', async () => { const request = runServer((req, res) => { formatResponse(req, res, () => {})({ text: (req: Request) => req.respond({ body: `Hello World` }) }).end() }) await request.get('/').expect(200).expect('Hello World') }) */ /* it('should send HTML if specified in "Accepts" header', async () => { const request = runServer((req, res) => { // eslint-disable-next-line @typescript-eslint/no-empty-function formatResponse(req, res, () => {})({ text: (req: Request) => req.respond({ body: `Hello World` }), html: (req: Request) => req.respond({ body: '<h1>Hello World</h1>' }) }).end() }) await request .get('/') .set('Accept', 'text/html') .expect(200, '<h1>Hello World</h1>') .expect('Content-Type', 'text/html') }) */ it('should throw 406 status when invalid MIME is specified', async () => { const request = runServer((req, res) => { formatResponse(req, res, (err) => { res.status = err.status res.send(err.message) })({ text: (req: Request) => req.respond({ body: `Hello World` }) }).end() }) await request.get('/').set('Accept', 'foo/bar').expect(406) }) it('should call `default` as a function if specified', async () => { const request = runServer((req, res) => { formatResponse(req, res, () => {})({ default: () => res.end('Hello World') }).end() }) await request.get('/').expect(200) }) }) describe('res.type(type)', () => { it('should detect MIME type', async () => { const { fetch } = InitAppAndTest((_, res) => { setContentType(res)('html').end() }) await fetch.get('/').expect('Content-Type', 'text/html; charset=utf-8') }) it('should detect MIME type by extension', async () => { const { fetch } = InitAppAndTest((_, res) => { setContentType(res)('.html').end() }) await fetch.get('/').expect('Content-Type', 'text/html; charset=utf-8') }) }) describe('res.attachment(filename)', () => { it('should set Content-Disposition without a filename specified', async () => { const { fetch } = InitAppAndTest((_, res) => { attachment(res)().end() }) await fetch.get('/').expect('Content-Disposition', 'attachment') }) it('should set Content-Disposition with a filename specified', async () => { const { fetch } = InitAppAndTest((_, res) => { attachment(res)(path.join(__dirname, '../fixtures', 'favicon.ico')).end() }) await fetch.get('/').expect('Content-Disposition', 'attachment; filename="favicon.ico"') }) }) /* describe('res.download(filename)', () => { it('should set Content-Disposition based on path', async () => { const { fetch } = InitAppAndTest((req, res) => { download(req, res)(path.join(__dirname, '../fixtures', 'favicon.ico')) }) await fetch .get('/') .expect('Content-Disposition', 'attachment; filename="favicon.ico"') .expect('Content-Encoding', 'utf-8') }) it('should set Content-Disposition based on filename', async () => { const { fetch } = InitAppAndTest((req, res) => { download(req, res)(path.join(__dirname, '../fixtures', 'favicon.ico'), 'favicon.icon') }) await fetch.get('/').expect('Content-Disposition', 'attachment; filename="favicon.icon"') }) it('should set "root" from options', async () => { const { fetch } = InitAppAndTest((req, res) => { download(req, res)('favicon.ico', undefined, { root: path.join(__dirname, '../fixtures') }) }) await fetch.get('/').expect('Content-Disposition', 'attachment; filename="favicon.ico"') }) it(`should pass options to sendFile`, async () => { const { fetch } = InitAppAndTest((req, res) => { download(req, res)(path.join(__dirname, '../fixtures', 'favicon.ico'), undefined, { encoding: 'ascii' }) }) await fetch.get('/').expect('Content-Disposition', 'attachment; filename="favicon.ico"') }) it('should set headers from options', async () => { const { fetch } = InitAppAndTest((req, res) => { download(req, res)(path.join(__dirname, '../fixtures', 'favicon.ico'), undefined, { headers: { 'X-Custom-Header': 'Value' } }) }) await fetch .get('/') .expect('Content-Disposition', 'attachment; filename="favicon.ico"') .expect('X-Custom-Header', 'Value') }) }) */ describe('res.location(url)', () => { it('sets the "Location" header', async () => { const { fetch } = InitAppAndTest((req, res) => { setLocationHeader(req, res)('https://example.com').end() }) await fetch.get('/').expect('Location', 'https://example.com').expect(200) }) it('should encode URL', async () => { const { fetch } = InitAppAndTest((req, res) => { setLocationHeader(req, res)('https://google.com?q=\u2603 §10').end() }) await fetch.get('/').expect('Location', 'https://google.com?q=%E2%98%83%20%C2%A710').expect(200) }) it('should not touch encoded sequences', async () => { const { fetch } = InitAppAndTest((req, res) => { setLocationHeader(req, res)('https://google.com?q=%A710').end() }) await fetch.get('/').expect('Location', 'https://google.com?q=%A710').expect(200) }) }) describe('res.cookie(name, value, options)', () => { it('serializes the cookie and puts it in a Set-Cookie header', async () => { const request = runServer((req, res) => { setCookie(req, res)('hello', 'world').end() expect(res.headers.get('Set-Cookie')).toBe('hello=world; Path=/') }) await request.get('/').expect(200) }) it('sets default path to "/" if not specified in options', async () => { const request = runServer((req, res) => { setCookie(req, res)('hello', 'world').end() expect(res.headers.get('Set-Cookie')).toContain('Path=/') }) await request.get('/').expect(200) }) it('should set "maxAge" and "expires" from options', async () => { const maxAge = 3600 * 24 * 365 const request = runServer((req, res) => { setCookie(req, res)('hello', 'world', { maxAge }).end() expect(res.headers.get('Set-Cookie')).toContain(`Max-Age=${maxAge / 1000}; Path=/; Expires=`) }) await request.get('/').expect(200) }) it('should append to Set-Cookie if called multiple times', async () => { const request = runServer((req, res) => { setCookie(req, res)('hello', 'world') setCookie(req, res)('foo', 'bar').end() }) await request.get('/').expect(200).expect('Set-Cookie', 'hello=world, foo=bar') }) }) describe('res.clearCookie(name, options)', () => { it('sets path to "/" if not specified in options', async () => { const request = runServer((_, res) => { clearCookie(res)('cookie').end() expect(res.headers.get('Set-Cookie')).toContain('Path=/;') }) await request.get('/').expect(200) }) }) run()
the_stack
import { Badge, Spacer, useTheme, useToasts } from "@geist-ui/react"; import PrimaryButton from "../common/PrimaryButton"; import React, { useCallback, useEffect, useMemo, useState } from "react"; import { ClientGameLibrary, Player, MenuButton, ClientParty, ChatMessage, } from "../../types/types"; import GameMenu from "../in-game/GameMenu"; import GameSelector from "../library/GameSelector"; import PlayerList from "../party/PlayerList"; import GameFrame from "../in-game/GameFrame"; import Connecting from "./Connecting"; import { ChatBox } from "../chat/ChatBox"; import Swal from "sweetalert2"; import { ToastAction } from "@geist-ui/react/dist/use-toasts/use-toast"; import ButtonGroup from "../common/ButtonGroup"; import { logEvent } from "../../utils/analytics"; import { filterClean, MODE_MAP } from "../../utils/utils"; import { differenceInMilliseconds } from "date-fns"; import GameDetail from "../detail/GameDetail"; import { RocketcrabMode } from "../../types/enums"; import { useRouter } from "next/router"; const GameLayout = ({ partyState, onExitGame, onStartGame, onHostGameLoaded, onSendChat, gameLibrary, thisPlayer, reconnecting, onKick, unreadMsgCount, clearUnreadMsgCount, newestMsg, mode, }: GameLayoutProps): JSX.Element => { const router = useRouter(); const isKidsMode = router.locale === RocketcrabMode.KIDS; const host = MODE_MAP[mode]; const { code, gameState, selectedGameId, playerList, chat } = partyState; const { isHost } = thisPlayer; const thisGame = gameLibrary.gameList.find( ({ id }) => id == selectedGameId ); const [statusCollapsed, setStatusCollapsed] = useState(false); const [showMenu, setShowMenu] = useState(false); const [showGameLibrary, setShowGameLibrary] = useState(false); const [showPlayerList, setShowPlayerList] = useState(false); const [showChat, setShowChat] = useState(false); const [showGameInfo, setShowGameInfo] = useState(false); // https://stackoverflow.com/a/48830513 const [frameRefresh, setFrameRefresh] = useState(0); const [enableToasts, setEnableToasts] = useState(!isKidsMode); const [, setToast] = useToasts(); const [lastShownToastDate, setLastShownToastDate] = useState(0); const igLogEvent = useCallback( (event) => logEvent("inGame-" + event, isHost ? "isHost" : "notHost"), [isHost] ); const { palette: { accents_1, accents_2 }, } = useTheme(); const actions = useMemo( (): ToastAction[] => [ { name: "Mute", passive: true, handler: (event, cancel) => { cancel(); promptMute(); }, }, { name: "Reply", passive: true, handler: (event, cancel) => { cancel(); setShowMenu(false); setShowChat(true); igLogEvent("toastChatReply"); }, }, { name: "Dismiss", passive: true, handler: (event, cancel) => cancel(), }, ], [] ); useEffect(() => { if (!newestMsg) return; const { playerId, playerName, message, date } = newestMsg; const lastMessageCameInOverOneSecondAgo = differenceInMilliseconds(Date.now(), date) > 1000; // don't show a toast for an old message that happens to be the latest // when we are initializing if (!lastShownToastDate && lastMessageCameInOverOneSecondAgo) { setLastShownToastDate(date); return; } // don't show toasts if they were muted by the user if (!enableToasts) return; // don't show toasts if the chat is open if (showChat) return; // don't show toasts for your own messages if (playerId === thisPlayer.id) return; setToast({ text: "🚀🦀 " + playerName + ": " + filterClean(message), actions, }); igLogEvent("toastMsg"); }, [newestMsg]); const hostName = playerList.find(({ isHost }) => isHost).name; const menuButtons: Array<MenuButton> = [ { label: "Chat", hostOnly: false, onClick: useCallback(() => { setShowMenu(false); setShowChat(true); igLogEvent("showChat"); }, []), badgeCount: unreadMsgCount, hide: isKidsMode, }, { label: "Players", hostOnly: false, onClick: useCallback(() => { setShowMenu(false); setShowPlayerList(true); igLogEvent("showPlayers"); }, []), }, { label: "About this game", hostOnly: false, onClick: useCallback(() => { setShowMenu(false); setShowGameInfo(true); igLogEvent("gameInfo"); }, []), }, { label: "Browse games", hostOnly: false, onClick: useCallback(() => { setShowMenu(false); setShowGameLibrary(true); igLogEvent("browseGames"); }, []), }, { label: "Reload my game", hostOnly: false, onClick: useCallback(() => { Swal.fire({ title: "Are your sure?", text: "If reloading doesn't fix your issue, tell your party host, " + hostName + ", to try the Reload All button.", showCancelButton: true, confirmButtonText: `Reload my game`, icon: "warning", heightAuto: false, }).then(({ isConfirmed }) => { if (isConfirmed) { setShowMenu(false); setFrameRefresh(frameRefresh + 1); igLogEvent("reloadMe"); } }); }, [frameRefresh]), }, { label: "Reload all", hostOnly: true, onClick: useCallback(() => { Swal.fire({ title: "Are your sure?", text: "Your current session in " + thisGame.name + " will be lost!", showCancelButton: true, confirmButtonText: `Reload All`, icon: "warning", heightAuto: false, }).then(({ isConfirmed }) => { if (isConfirmed) { setShowMenu(false); onStartGame(); igLogEvent("reloadAll"); } }); }, [onStartGame]), }, { label: "Exit to party", hostOnly: true, onClick: useCallback(() => { Swal.fire({ title: "Are your sure?", text: "Your current session in " + thisGame.name + " will be lost!", showCancelButton: true, confirmButtonText: "Exit to party", icon: "warning", heightAuto: false, }).then(({ isConfirmed }) => { if (isConfirmed) { setShowMenu(false); onExitGame(); igLogEvent("exitToParty"); } }); }, [onExitGame]), }, ]; const combinedMenuBadgeCount = menuButtons.reduce( (prev, curr) => prev + (curr.badgeCount ?? 0), 0 ); const promptMute = () => { Swal.fire({ title: "Are your sure?", text: "New chat messages won't appear over your game, but you can still see them in the menu!", showCancelButton: true, confirmButtonText: "Mute chat", icon: "question", heightAuto: false, }).then(({ isConfirmed }) => { if (isConfirmed) { setEnableToasts(false); igLogEvent("muteChat"); } }); }; const hideAllWindows = useCallback(() => { setShowGameLibrary(false); setShowPlayerList(false); setShowChat(false); setShowGameInfo(false); }, [setShowGameLibrary, setShowPlayerList, setShowChat]); const statusClass = "status " + (statusCollapsed ? "status-collapsed" : ""); return ( <div className="layout"> <div className={statusClass}> <div className="logo" onClick={() => { setStatusCollapsed(!statusCollapsed); setShowMenu(false); hideAllWindows(); igLogEvent("clickLogo"); }} > <img src="/rocket.svg" className="rocket" /> <img src="/crab.svg" className="crab" /> </div> {!statusCollapsed && ( <> <div className="url"> {host}/{code} </div> <div> <Badge.Anchor placement="bottomLeft"> {!showMenu && combinedMenuBadgeCount > 0 && ( <Badge type="error" size="mini"> {combinedMenuBadgeCount} </Badge> )} <PrimaryButton onClick={() => { setShowMenu(!showMenu); hideAllWindows(); igLogEvent("clickMenu"); }} size="small" > {showMenu ? "▲" : "▼"} Menu </PrimaryButton> </Badge.Anchor> </div> {showMenu && ( <GameMenu isHost={isHost} menuButtons={menuButtons} /> )} </> )} </div> <GameFrame gameState={gameState} selectedGameId={selectedGameId} onHostGameLoaded={onHostGameLoaded} thisPlayer={thisPlayer} thisGame={thisGame} frameRefreshCount={frameRefresh} /> {showGameLibrary && ( <div className="component-frame"> <GameSelector gameLibrary={gameLibrary} onDone={hideAllWindows} onSelectGame={(gameId: string, gameName: string) => { if (!isHost) return; Swal.fire({ title: "Switch to " + gameName + "?", text: "Your current session in " + thisGame.name + " will be lost!", showCancelButton: true, confirmButtonText: "Switch!", icon: "warning", heightAuto: false, }).then(({ isConfirmed }) => { if (isConfirmed) { setShowMenu(false); onStartGame(gameId); igLogEvent("switchGame"); } }); }} backToLabel="game" isHost={isHost} /> </div> )} {showPlayerList && ( <div className="component-frame"> <PlayerList playerList={playerList} disableHideShow={true} startHidden={false} onKick={onKick} disableEditName={true} meId={thisPlayer.id} /> <Spacer y={0.5} /> <PrimaryButton onClick={hideAllWindows}> Close </PrimaryButton> </div> )} {showChat && ( <div className="component-frame"> <ChatBox chat={chat} thisPlayer={thisPlayer} onSendChat={onSendChat} disableHideShow={true} unreadMsgCount={unreadMsgCount} clearUnreadMsgCount={clearUnreadMsgCount} /> <Spacer y={0.5} /> <ButtonGroup> <PrimaryButton onClick={hideAllWindows}> Close </PrimaryButton> <PrimaryButton onClick={ enableToasts ? promptMute : () => setEnableToasts(true) } > {enableToasts ? "Mute" : "Unmute"} </PrimaryButton> </ButtonGroup> </div> )} {showGameInfo && ( <div className="component-frame"> <GameDetail game={thisGame} allCategories={gameLibrary.categories} /> <Spacer y={0.5} /> <PrimaryButton onClick={hideAllWindows}> Close </PrimaryButton> </div> )} <style jsx>{` .layout { display: flex; flex-flow: column; height: 100%; } .status { border-bottom: 1px solid ${accents_2}; display: flex; justify-content: space-between; align-content: center; padding: 0.5em; height: 2em; z-index: 1; background-color: ${accents_1}; } @media only screen and (max-width: 385px) { .status { font-size: 0.9em; margin-bottom: 0em; } .logo { line-height: 2em; font-size: 1em; } } .status-collapsed { position: fixed; width: fit-content; border: none; border-radius: 8px; top: 0.5em; left: 0.5em; backdrop-filter: blur(5px); background-color: rgba(255, 255, 255, 0.2); } .logo { margin: 0; user-select: none; cursor: pointer; line-height: 2.8em; } .rocket { height: 1.5em; margin-left: 0.1em; filter: drop-shadow(0 0 6px cyan); } .crab { height: 1.5em; margin-left: 0.25em; filter: drop-shadow(0 0 6px #ff0000d9); } .url { font-size: 1.2em; line-height: 1em; height: 1em; margin: auto 0; font-weight: bold; font-family: "Inconsolata", monospace; } .component-frame { padding: 1em; text-align: center; position: absolute; top: 3em; right: 0; background: ${accents_1}; border: 1px solid ${accents_2}; width: min(24em, 100vw - 3em); margin: 0.5em; box-shadow: 0 1px 6px rgba(32, 33, 36, 0.28); } `}</style> {reconnecting && <Connecting />} </div> ); }; type GameLayoutProps = { partyState: ClientParty; onExitGame: () => void; onStartGame: (gameId?: string) => void; onHostGameLoaded: () => void; onSendChat: (message: string) => void; gameLibrary: ClientGameLibrary; thisPlayer: Player; reconnecting: boolean; onKick: (id: number, name: string) => void; unreadMsgCount: number; newestMsg: ChatMessage; clearUnreadMsgCount: () => void; mode: RocketcrabMode; }; export default GameLayout;
the_stack
import { DelimiterMark } from 'src/compilation/delimiterMark'; import { TagDisposition } from 'src/compilation/tag'; import { TagParser } from 'src/compilation/tagParser'; import { Delimiters } from 'src/delimiters'; import { DocxParser } from 'src/office'; import { XmlParser, XmlTextNode } from 'src/xml'; import { parseXml } from '../../testUtils'; describe(nameof(TagParser), () => { it('trims tag names', () => { const paragraph = parseXml(` <w:p><w:r><w:t>{# my loop }{ my tag }{/ my loop }</w:t></w:r></w:p> `, false); const textNode = paragraph.childNodes[0].childNodes[0].childNodes[0] as XmlTextNode; expect(textNode.textContent).toEqual('{# my loop }{ my tag }{/ my loop }'); const delimiters: DelimiterMark[] = [ { isOpen: true, index: 0, xmlTextNode: textNode }, { isOpen: false, index: 12, xmlTextNode: textNode }, { isOpen: true, index: 13, xmlTextNode: textNode }, { isOpen: false, index: 23, xmlTextNode: textNode }, { isOpen: true, index: 24, xmlTextNode: textNode }, { isOpen: false, index: 36, xmlTextNode: textNode } ]; const parser = createTagParser(); const tags = parser.parse(delimiters); expect(tags.length).toEqual(3); // open tag expect(tags[0].disposition).toEqual(TagDisposition.Open); expect(tags[0].name).toEqual('my loop'); expect(tags[0].rawText).toEqual('{# my loop }'); // middle tag expect(tags[1].disposition).toEqual(TagDisposition.SelfClosed); expect(tags[1].name).toEqual('my tag'); expect(tags[1].rawText).toEqual('{ my tag }'); // close tag expect(tags[2].disposition).toEqual(TagDisposition.Close); expect(tags[2].name).toEqual('my loop'); expect(tags[2].rawText).toEqual('{/ my loop }'); }); it('parses correctly multiple tags on the same text node', () => { const paragraph = parseXml(` <w:p> <w:r> <w:t>{#loop}{/loop}</w:t> </w:r> </w:p> `); const textNode = paragraph.childNodes[0].childNodes[0].childNodes[0] as XmlTextNode; const delimiters: DelimiterMark[] = [ { isOpen: true, index: 0, xmlTextNode: textNode }, { isOpen: false, index: 6, xmlTextNode: textNode }, { isOpen: true, index: 7, xmlTextNode: textNode }, { isOpen: false, index: 13, xmlTextNode: textNode } ]; const parser = createTagParser(); const tags = parser.parse(delimiters); expect(tags.length).toEqual(2); // open tag expect(tags[0].disposition).toEqual(TagDisposition.Open); expect(tags[0].name).toEqual('loop'); expect(tags[0].rawText).toEqual('{#loop}'); // close tag expect(tags[1].disposition).toEqual(TagDisposition.Close); expect(tags[1].name).toEqual('loop'); expect(tags[1].rawText).toEqual('{/loop}'); }); it('parses correctly multiple tags on the same text node, with leading text', () => { const paragraph = parseXml(` <w:p> <w:r> <w:t>text1{#loop}text2{/loop}</w:t> </w:r> </w:p> `); const textNode = paragraph.childNodes[0].childNodes[0].childNodes[0] as XmlTextNode; const delimiters: DelimiterMark[] = [ { isOpen: true, index: 5, xmlTextNode: textNode }, { isOpen: false, index: 11, xmlTextNode: textNode }, { isOpen: true, index: 17, xmlTextNode: textNode }, { isOpen: false, index: 23, xmlTextNode: textNode } ]; const parser = createTagParser(); const tags = parser.parse(delimiters); expect(tags.length).toEqual(2); // open tag expect(tags[0].disposition).toEqual(TagDisposition.Open); expect(tags[0].name).toEqual('loop'); expect(tags[0].rawText).toEqual('{#loop}'); // close tag expect(tags[1].disposition).toEqual(TagDisposition.Close); expect(tags[1].name).toEqual('loop'); expect(tags[1].rawText).toEqual('{/loop}'); }); it('parses correctly a butterfly }{', () => { const paragraphNode = parseXml(` <w:p> <w:r> <w:t>{#loop</w:t> <w:t>}{</w:t> <w:t>/loop}</w:t> </w:r> </w:p> `); const runNode = paragraphNode.childNodes[0]; const firstTextNode = runNode.childNodes[0].childNodes[0] as XmlTextNode; const secondTextNode = runNode.childNodes[1].childNodes[0] as XmlTextNode; const thirdTextNode = runNode.childNodes[2].childNodes[0] as XmlTextNode; const delimiters: DelimiterMark[] = [ { isOpen: true, index: 0, xmlTextNode: firstTextNode }, { isOpen: false, index: 0, xmlTextNode: secondTextNode }, { isOpen: true, index: 1, xmlTextNode: secondTextNode }, { isOpen: false, index: 5, xmlTextNode: thirdTextNode } ]; const parser = createTagParser(); const tags = parser.parse(delimiters); expect(tags.length).toEqual(2); // open tag expect(tags[0].disposition).toEqual(TagDisposition.Open); expect(tags[0].name).toEqual('loop'); expect(tags[0].rawText).toEqual('{#loop}'); // close tag expect(tags[1].disposition).toEqual(TagDisposition.Close); expect(tags[1].name).toEqual('loop'); expect(tags[1].rawText).toEqual('{/loop}'); }); it('parses correctly a splitted simple tag', () => { const paragraphNode = parseXml(` <w:p> <w:r> <w:t>{#loo</w:t> <w:t>p}</w:t> </w:r> </w:p> `); const runNode = paragraphNode.childNodes[0]; const firstTextNode = runNode.childNodes[0].childNodes[0] as XmlTextNode; const secondTextNode = runNode.childNodes[1].childNodes[0] as XmlTextNode; const delimiters: DelimiterMark[] = [ { isOpen: true, index: 0, xmlTextNode: firstTextNode }, { isOpen: false, index: 1, xmlTextNode: secondTextNode } ]; const parser = createTagParser(); const tags = parser.parse(delimiters); expect(tags.length).toEqual(1); // tag expect(tags[0].disposition).toEqual(TagDisposition.Open); expect(tags[0].name).toEqual('loop'); expect(tags[0].rawText).toEqual('{#loop}'); }); it('parses correctly a splitted closing tag', () => { const paragraphNode = parseXml(` <w:p> <w:r> <w:t>{#loop}{text}{/</w:t> </w:r> <w:r> <w:t>loop</w:t> </w:r> <w:r> <w:t>}</w:t> </w:r> </w:p> `); const firstTextNode = paragraphNode.childNodes[0].childNodes[0].childNodes[0] as XmlTextNode; expect(firstTextNode.textContent).toEqual('{#loop}{text}{/'); const thirdTextNode = paragraphNode.childNodes[2].childNodes[0].childNodes[0] as XmlTextNode; expect(thirdTextNode.textContent).toEqual('}'); const delimiters: DelimiterMark[] = [ { isOpen: true, index: 0, xmlTextNode: firstTextNode }, { isOpen: false, index: 6, xmlTextNode: firstTextNode }, { isOpen: true, index: 7, xmlTextNode: firstTextNode }, { isOpen: false, index: 12, xmlTextNode: firstTextNode }, { isOpen: true, index: 13, xmlTextNode: firstTextNode }, { isOpen: false, index: 0, xmlTextNode: thirdTextNode } ]; const parser = createTagParser(); const tags = parser.parse(delimiters); expect(tags).toHaveLength(3); expect(tags[0].disposition).toEqual(TagDisposition.Open); expect(tags[0].name).toEqual('loop'); expect(tags[0].rawText).toEqual('{#loop}'); expect(tags[1].disposition).toEqual(TagDisposition.SelfClosed); expect(tags[1].name).toEqual('text'); expect(tags[1].rawText).toEqual('{text}'); expect(tags[2].disposition).toEqual(TagDisposition.Close); expect(tags[2].name).toEqual('loop'); expect(tags[2].rawText).toEqual('{/loop}'); }); }); function createTagParser(): TagParser { const xmlParser = new XmlParser(); const docxParser = new DocxParser(xmlParser); const delimiters = new Delimiters(); return new TagParser(docxParser, delimiters); }
the_stack
import { ActionsUnion, IComponentState, IGatsbyState, IQueryState, } from "../types" type QueryId = string // page query path or static query id type ComponentPath = string type NodeId = string type ConnectionName = string export const FLAG_DIRTY_NEW_PAGE = 0b0001 export const FLAG_DIRTY_TEXT = 0b0010 export const FLAG_DIRTY_DATA = 0b0100 export const FLAG_DIRTY_PAGE_CONTEXT = 0b1000 export const FLAG_ERROR_EXTRACTION = 0b0001 export const FLAG_RUNNING_INFLIGHT = 0b0001 const initialState = (): IGatsbyState["queries"] => { return { byNode: new Map<NodeId, Set<QueryId>>(), byConnection: new Map<ConnectionName, Set<QueryId>>(), queryNodes: new Map<QueryId, Set<NodeId>>(), trackedQueries: new Map<QueryId, IQueryState>(), trackedComponents: new Map<ComponentPath, IComponentState>(), deletedQueries: new Set<QueryId>(), dirtyQueriesListToEmitViaWebsocket: [], } } const initialQueryState = (): IQueryState => { return { dirty: -1, // unknown, must be set right after init running: 0, } } const initialComponentState = (): IComponentState => { return { componentPath: ``, query: ``, pages: new Set<QueryId>(), errors: 0, // TODO: staticQueries: new Set<QueryId>() } } /** * Tracks query dirtiness. Dirty queries are queries that: * * - depend on nodes or node collections (via `actions.createPageDependency`) that have changed. * - have been recently extracted (or their query text has changed) * - belong to newly created pages (or pages with modified context) * * Dirty queries must be re-ran. */ export function queriesReducer( state: IGatsbyState["queries"] = initialState(), action: ActionsUnion ): IGatsbyState["queries"] { switch (action.type) { case `DELETE_CACHE`: return initialState() case `CREATE_PAGE`: { const { path, componentPath } = action.payload let query = state.trackedQueries.get(path) if (!query || action.contextModified) { query = registerQuery(state, path) query.dirty = setFlag( query.dirty, action.contextModified ? FLAG_DIRTY_PAGE_CONTEXT : FLAG_DIRTY_NEW_PAGE ) state = trackDirtyQuery(state, path) } registerComponent(state, componentPath).pages.add(path) state.deletedQueries.delete(path) return state } case `DELETE_PAGE`: { // Don't actually remove the page query from trackedQueries, just mark it as "deleted". Why? // We promote a technique of a consecutive deletePage/createPage calls in onCreatePage hook, // see https://www.gatsbyjs.com/docs/creating-and-modifying-pages/#pass-context-to-pages // If we remove a query and then re-add, it will be marked as dirty. // This is OK for cold cache but with warm cache we will re-run all of those queries (unnecessarily). // We will reconcile the state after createPages API call and actually delete those queries. state.deletedQueries.add(action.payload.path) return state } case `API_FINISHED`: { if (action.payload.apiName !== `createPages`) { return state } for (const queryId of state.deletedQueries) { for (const component of state.trackedComponents.values()) { component.pages.delete(queryId) } state = clearNodeDependencies(state, queryId) state = clearConnectionDependencies(state, queryId) state.trackedQueries.delete(queryId) } state.deletedQueries.clear() return state } case `QUERY_EXTRACTED`: { // Note: this action is called even in case of // extraction error or missing query (with query === ``) // TODO: use hash instead of a query text const { componentPath, query } = action.payload const component = registerComponent(state, componentPath) if (hasFlag(component.errors, FLAG_ERROR_EXTRACTION)) { return state } if (component.query !== query) { // Invalidate all pages associated with a component when query text changes for (const queryId of component.pages) { const query = state.trackedQueries.get(queryId) if (query) { query.dirty = setFlag(query.dirty, FLAG_DIRTY_TEXT) state = trackDirtyQuery(state, queryId) } } component.query = query } return state } case `QUERY_EXTRACTION_GRAPHQL_ERROR`: case `QUERY_EXTRACTION_BABEL_ERROR`: case `QUERY_EXTRACTION_BABEL_SUCCESS`: { const { componentPath } = action.payload const component = registerComponent(state, componentPath) const set = action.type !== `QUERY_EXTRACTION_BABEL_SUCCESS` component.errors = setFlag(component.errors, FLAG_ERROR_EXTRACTION, set) return state } case `REPLACE_STATIC_QUERY`: { // Only called when static query text has changed, so no need to compare // TODO: unify the behavior? const query = registerQuery(state, action.payload.id) query.dirty = setFlag(query.dirty, FLAG_DIRTY_TEXT) // static queries are not on demand, so skipping tracking which // queries were marked dirty recently // state = trackDirtyQuery(state, action.payload.id) state.deletedQueries.delete(action.payload.id) return state } case `REMOVE_STATIC_QUERY`: { state.deletedQueries.add(action.payload) return state } case `CREATE_COMPONENT_DEPENDENCY`: { const { path: queryId, nodeId, connection } = action.payload if (nodeId) { state = addNodeDependency(state, queryId, nodeId) } if (connection) { state = addConnectionDependency(state, queryId, connection) } return state } case `QUERY_START`: { // Reset data dependencies as they will be updated when running the query const { path } = action.payload state = clearNodeDependencies(state, path) state = clearConnectionDependencies(state, path) const query = state.trackedQueries.get(path) if (query) { query.running = setFlag(query.running, FLAG_RUNNING_INFLIGHT) } return state } case `CREATE_NODE`: case `DELETE_NODE`: { const node = action.payload if (!node) { return state } const queriesByNode = state.byNode.get(node.id) ?? [] const queriesByConnection = state.byConnection.get(node.internal.type) ?? [] for (const queryId of queriesByNode) { const query = state.trackedQueries.get(queryId) if (query) { query.dirty = setFlag(query.dirty, FLAG_DIRTY_DATA) state = trackDirtyQuery(state, queryId) } } for (const queryId of queriesByConnection) { const query = state.trackedQueries.get(queryId) if (query) { query.dirty = setFlag(query.dirty, FLAG_DIRTY_DATA) state = trackDirtyQuery(state, queryId) } } return state } case `PAGE_QUERY_RUN`: { const { path } = action.payload const query = registerQuery(state, path) query.dirty = 0 query.running = 0 // TODO: also return state } case `SET_PROGRAM_STATUS`: { if (action.payload === `BOOTSTRAP_FINISHED`) { // Reset the running state (as it could've been persisted) for (const [, query] of state.trackedQueries) { query.running = 0 } // Reset list of dirty queries (this is used only to notify runtime and it could've been persisted) state.dirtyQueriesListToEmitViaWebsocket = [] } return state } case `QUERY_CLEAR_DIRTY_QUERIES_LIST_TO_EMIT_VIA_WEBSOCKET`: { state.dirtyQueriesListToEmitViaWebsocket = [] return state } case `MERGE_WORKER_QUERY_STATE`: { assertCorrectWorkerState(action.payload) state = mergeWorkerDataDependencies(state, action.payload) return state } default: return state } } function setFlag(allFlags: number, flag: number, set = true): number { if (allFlags < 0) { allFlags = 0 } return set ? allFlags | flag : allFlags & ~flag } export function hasFlag(allFlags: number, flag: number): boolean { return allFlags >= 0 && (allFlags & flag) > 0 } function addNodeDependency( state: IGatsbyState["queries"], queryId: QueryId, nodeId: NodeId ): IGatsbyState["queries"] { // Perf: using two-side maps. // Without additional `queryNodes` map we would have to loop through // all existing nodes in `clearNodeDependencies` to delete node <-> query dependency let nodeQueries = state.byNode.get(nodeId) if (!nodeQueries) { nodeQueries = new Set<QueryId>() state.byNode.set(nodeId, nodeQueries) } let queryNodes = state.queryNodes.get(queryId) if (!queryNodes) { queryNodes = new Set<NodeId>() state.queryNodes.set(queryId, queryNodes) } nodeQueries.add(queryId) queryNodes.add(nodeId) return state } function addConnectionDependency( state: IGatsbyState["queries"], queryId: QueryId, connection: ConnectionName ): IGatsbyState["queries"] { // Note: not using two-side maps for connections as associated overhead // for small number of elements is greater then benefits, so no perf. gains let queryIds = state.byConnection.get(connection) if (!queryIds) { queryIds = new Set() state.byConnection.set(connection, queryIds) } queryIds.add(queryId) return state } function clearNodeDependencies( state: IGatsbyState["queries"], queryId: QueryId ): IGatsbyState["queries"] { const queryNodeIds = state.queryNodes.get(queryId) ?? new Set() for (const nodeId of queryNodeIds) { const nodeQueries = state.byNode.get(nodeId) if (nodeQueries) { nodeQueries.delete(queryId) } } return state } function clearConnectionDependencies( state: IGatsbyState["queries"], queryId: QueryId ): IGatsbyState["queries"] { for (const [, queryIds] of state.byConnection) { queryIds.delete(queryId) } return state } function registerQuery( state: IGatsbyState["queries"], queryId: QueryId ): IQueryState { let query = state.trackedQueries.get(queryId) if (!query) { query = initialQueryState() state.trackedQueries.set(queryId, query) } return query } function registerComponent( state: IGatsbyState["queries"], componentPath: string ): IComponentState { let component = state.trackedComponents.get(componentPath) if (!component) { component = initialComponentState() component.componentPath = componentPath state.trackedComponents.set(componentPath, component) } return component } function trackDirtyQuery( state: IGatsbyState["queries"], queryId: QueryId ): IGatsbyState["queries"] { if (process.env.GATSBY_EXPERIMENTAL_QUERY_ON_DEMAND) { state.dirtyQueriesListToEmitViaWebsocket.push(queryId) } return state } interface IWorkerStateChunk { workerId: number queryStateChunk: IGatsbyState["queries"] } function mergeWorkerDataDependencies( state: IGatsbyState["queries"], workerStateChunk: IWorkerStateChunk ): IGatsbyState["queries"] { const queryState = workerStateChunk.queryStateChunk // First clear data dependencies for all queries tracked by worker for (const queryId of queryState.trackedQueries.keys()) { state = clearNodeDependencies(state, queryId) state = clearConnectionDependencies(state, queryId) } // Now re-add all data deps from worker for (const [nodeId, queries] of queryState.byNode) { for (const queryId of queries) { state = addNodeDependency(state, queryId, nodeId) } } for (const [connectionName, queries] of queryState.byConnection) { for (const queryId of queries) { state = addConnectionDependency(state, queryId, connectionName) } } return state } function assertCorrectWorkerState({ queryStateChunk, workerId, }: IWorkerStateChunk): void { if (queryStateChunk.deletedQueries.size !== 0) { throw new Error( `Assertion failed: workerState.deletedQueries.size === 0 (worker #${workerId})` ) } if (queryStateChunk.trackedComponents.size !== 0) { throw new Error( `Assertion failed: queryStateChunk.trackedComponents.size === 0 (worker #${workerId})` ) } for (const query of queryStateChunk.trackedQueries.values()) { if (query.dirty) { throw new Error( `Assertion failed: all worker queries are not dirty (worker #${workerId})` ) } if (query.running) { throw new Error( `Assertion failed: all worker queries are not running (worker #${workerId})` ) } } }
the_stack
module es { export class SpatialHash { public gridBounds: Rectangle = new Rectangle(); public _raycastParser: RaycastResultParser; /** * 散列中每个单元格的大小 */ public _cellSize: number; /** * 1除以单元格大小。缓存结果,因为它被大量使用。 */ public _inverseCellSize: number; /** * 重叠检查缓存框 */ public _overlapTestBox: Box = new Box(0, 0); /** * 重叠检查缓存圈 */ public _overlapTestCircle: Circle = new Circle(0); /** * 保存所有数据的字典 */ public _cellDict: NumberDictionary<Collider> = new NumberDictionary<Collider>(); /** * 用于返回冲突信息的共享HashSet */ public _tempHashSet: Set<Collider> = new Set<Collider>(); constructor(cellSize: number = 100) { this._cellSize = cellSize; this._inverseCellSize = 1 / this._cellSize; this._raycastParser = new RaycastResultParser(); } /** * 将对象添加到SpatialHash * @param collider */ public register(collider: Collider) { let bounds = collider.bounds.clone(); collider.registeredPhysicsBounds = bounds; let p1 = this.cellCoords(bounds.x, bounds.y); let p2 = this.cellCoords(bounds.right, bounds.bottom); // 更新边界以跟踪网格大小 if (!this.gridBounds.contains(p1.x, p1.y)) { this.gridBounds = RectangleExt.union(this.gridBounds, p1); } if (!this.gridBounds.contains(p2.x, p2.y)) { this.gridBounds = RectangleExt.union(this.gridBounds, p2); } for (let x = p1.x; x <= p2.x; x++) { for (let y = p1.y; y <= p2.y; y++) { // 如果没有单元格,我们需要创建它 let c: Collider[] = this.cellAtPosition(x, y, true); c.push(collider); } } } /** * 从SpatialHash中删除对象 * @param collider */ public remove(collider: Collider) { let bounds = collider.registeredPhysicsBounds.clone(); let p1 = this.cellCoords(bounds.x, bounds.y); let p2 = this.cellCoords(bounds.right, bounds.bottom); for (let x = p1.x; x <= p2.x; x++) { for (let y = p1.y; y <= p2.y; y++) { // 单元格应该始终存在,因为这个碰撞器应该在所有查询的单元格中 let cell = this.cellAtPosition(x, y); Insist.isNotNull(cell, `从不存在碰撞器的单元格中移除碰撞器: [${collider}]`); if (cell != null) new es.List(cell).remove(collider); } } } /** * 使用蛮力方法从SpatialHash中删除对象 * @param obj */ public removeWithBruteForce(obj: Collider) { this._cellDict.remove(obj); } public clear() { this._cellDict.clear(); } public debugDraw(secondsToDisplay: number) { for (let x = this.gridBounds.x; x <= this.gridBounds.right; x++) { for (let y = this.gridBounds.y; y <= this.gridBounds.bottom; y++) { let cell = this.cellAtPosition(x, y); if (cell != null && cell.length > 0) this.debugDrawCellDetails(x, y, secondsToDisplay); } } } private debugDrawCellDetails(x: number, y: number, secondsToDisplay: number = 0.5) { Graphics.instance.batcher.drawHollowRect(x * this._cellSize, y * this._cellSize, this._cellSize, this._cellSize, new Color(255, 0, 0), secondsToDisplay); Graphics.instance.batcher.end(); } /** * 返回边框与单元格相交的所有对象 * @param bounds * @param excludeCollider * @param layerMask */ public aabbBroadphase(bounds: Rectangle, excludeCollider: Collider, layerMask: number): Collider[] { this._tempHashSet.clear(); const p1 = this.cellCoords(bounds.x, bounds.y); const p2 = this.cellCoords(bounds.right, bounds.bottom); for (let x = p1.x; x <= p2.x; x++) { for (let y = p1.y; y <= p2.y; y++) { const cell = this.cellAtPosition(x, y); if (!cell) continue; // 当cell不为空。循环并取回所有碰撞器 for (let i = 0; i < cell.length; i++) { const collider = cell[i]; // 如果它是自身或者如果它不匹配我们的层掩码 跳过这个碰撞器 if (collider == excludeCollider || !Flags.isFlagSet(layerMask, collider.physicsLayer.value)) continue; if (bounds.intersects(collider.bounds)) { this._tempHashSet.add(collider); } } } } return Array.from(this._tempHashSet); } /** * 通过空间散列投掷一条线,并将该线碰到的任何碰撞器填入碰撞数组 * https://github.com/francisengelmann/fast_voxel_traversal/blob/master/main.cpp * http://www.cse.yorku.ca/~amana/research/grid.pdf * @param start * @param end * @param hits * @param layerMask */ public linecast(start: Vector2, end: Vector2, hits: RaycastHit[], layerMask: number, ignoredColliders: Set<Collider>) { let ray = new Ray2D(start, end); this._raycastParser.start(ray, hits, layerMask, ignoredColliders); // 获取我们的起始/结束位置,与我们的网格在同一空间内 let currentCell = this.cellCoords(start.x, start.y); let lastCell = this.cellCoords(end.x, end.y); // 我们向什么方向递增单元格检查? let stepX = Math.sign(ray.direction.x); let stepY = Math.sign(ray.direction.y); // 我们要确保,如果我们在同一条线上或同一排上,就不会踩到不必要的方向上 if (currentCell.x == lastCell.x) stepX = 0; if (currentCell.y == lastCell.y) stepY = 0; // 计算单元格的边界。 // 当步长为正数时,下一个单元格在这个单元格之后,意味着我们要加1。 let xStep = stepX < 0 ? 0 : stepX; let yStep = stepY < 0 ? 0 : stepY; let nextBoundaryX = (currentCell.x + xStep) * this._cellSize; let nextBoundaryY = (currentCell.y + yStep) * this._cellSize; // 确定射线穿过第一个垂直体素边界时的t值,y/水平也是如此。 // 这两个值的最小值将表明我们可以沿着射线移动多少,并且仍然保持在当前的体素中,对于接近垂直/水平的射线可能是无限的。 let tMaxX = ray.direction.x != 0 ? (nextBoundaryX - ray.start.x) / ray.direction.x : Number.MAX_VALUE; let tMaxY = ray.direction.y != 0 ? (nextBoundaryY - ray.start.y) / ray.direction.y : Number.MAX_VALUE; // 我们要走多远才能从一个单元格的边界穿过一个单元格 let tDeltaX = ray.direction.x != 0 ? this._cellSize / (ray.direction.x * stepX) : Number.MAX_VALUE; let tDeltaY = ray.direction.y != 0 ? this._cellSize / (ray.direction.y * stepY) : Number.MAX_VALUE; // 开始遍历并返回交叉单元格。 let cell = this.cellAtPosition(currentCell.x, currentCell.y); if (cell != null && this._raycastParser.checkRayIntersection(currentCell.x, currentCell.y, cell)) { this._raycastParser.reset(); return this._raycastParser.hitCounter; } while (currentCell.x != lastCell.x || currentCell.y != lastCell.y) { if (tMaxX < tMaxY) { currentCell.x = MathHelper.approach(currentCell.x, lastCell.x, Math.abs(stepX)); tMaxX += tDeltaX; } else { currentCell.y = MathHelper.approach(currentCell.y, lastCell.y, Math.abs(stepY)); tMaxY += tDeltaY; } cell = this.cellAtPosition(currentCell.x, currentCell.y); if (cell && this._raycastParser.checkRayIntersection(currentCell.x, currentCell.y, cell)) { this._raycastParser.reset(); return this._raycastParser.hitCounter; } } // 复位 this._raycastParser.reset(); return this._raycastParser.hitCounter; } /** * 获取所有在指定矩形范围内的碰撞器 * @param rect * @param results * @param layerMask */ public overlapRectangle(rect: Rectangle, results: Collider[], layerMask: number) { this._overlapTestBox.updateBox(rect.width, rect.height); this._overlapTestBox.position = rect.location.clone(); let resultCounter = 0; let potentials = this.aabbBroadphase(rect, null, layerMask); for (let collider of potentials) { if (collider instanceof BoxCollider) { results[resultCounter] = collider; resultCounter++; } else if (collider instanceof CircleCollider) { if (Collisions.rectToCircle(rect, collider.bounds.center, collider.bounds.width * 0.5)) { results[resultCounter] = collider; resultCounter++; } } else if (collider instanceof PolygonCollider) { if (collider.shape.overlaps(this._overlapTestBox)) { results[resultCounter] = collider; resultCounter++; } } else { throw new Error("overlapRectangle对这个类型没有实现!"); } if (resultCounter == results.length) return resultCounter; } return resultCounter; } /** * 获取所有落在指定圆圈内的碰撞器 * @param circleCenter * @param radius * @param results * @param layerMask */ public overlapCircle(circleCenter: Vector2, radius: number, results: Collider[], layerMask): number { const bounds = new Rectangle(circleCenter.x - radius, circleCenter.y - radius, radius * 2, radius * 2); this._overlapTestCircle.radius = radius; this._overlapTestCircle.position = circleCenter; let resultCounter = 0; const potentials = this.aabbBroadphase(bounds, null, layerMask); for (let collider of potentials) { if (collider instanceof BoxCollider) { if (collider.shape.overlaps(this._overlapTestCircle)) { results[resultCounter] = collider; resultCounter++; } } else if (collider instanceof CircleCollider) { if (collider.shape.overlaps(this._overlapTestCircle)) { results[resultCounter] = collider; resultCounter++; } } else if (collider instanceof PolygonCollider) { if (collider.shape.overlaps(this._overlapTestCircle)) { results[resultCounter] = collider; resultCounter++; } } else { throw new Error("对这个对撞机类型的overlapCircle没有实现!"); } // 如果我们所有的结果数据有了则返回 if (resultCounter === results.length) return resultCounter; } return resultCounter; } /** * 获取单元格的x,y值作为世界空间的x,y值 * @param x * @param y */ public cellCoords(x: number, y: number): Vector2 { return new Vector2(Math.floor(x * this._inverseCellSize), Math.floor(y * this._inverseCellSize)); } /** * 获取世界空间x,y值的单元格。 * 如果单元格为空且createCellIfEmpty为true,则会创建一个新的单元格 * @param x * @param y * @param createCellIfEmpty */ public cellAtPosition(x: number, y: number, createCellIfEmpty: boolean = false): Collider[] { let cell: Collider[] = this._cellDict.tryGetValue(x, y); if (!cell) { if (createCellIfEmpty) { cell = []; this._cellDict.add(x, y, cell); } } return cell; } } export class NumberDictionary<T> { public _store: Map<string, T[]> = new Map<string, T[]>(); public add(x: number, y: number, list: T[]) { this._store.set(this.getKey(x, y), list); } /** * 使用蛮力方法从字典存储列表中移除碰撞器 * @param obj */ public remove(obj: T) { this._store.forEach(list => { let linqList = new es.List(list); if (linqList.contains(obj)) linqList.remove(obj); }) } public tryGetValue(x: number, y: number): T[] { return this._store.get(this.getKey(x, y)); } public getKey(x: number, y: number) { return `${x}_${y}`; } /** * 清除字典数据 */ public clear() { this._store.clear(); } } export class RaycastResultParser { public hitCounter: number; public static compareRaycastHits = (a: RaycastHit, b: RaycastHit) => { if (a.distance !== b.distance) { return a.distance - b.distance; } else { return a.collider.castSortOrder - b.collider.castSortOrder; } }; public _hits: RaycastHit[]; public _tempHit: RaycastHit = new RaycastHit(); public _checkedColliders: Collider[] = []; public _cellHits: RaycastHit[] = []; public _ray: Ray2D; public _layerMask: number; private _ignoredColliders: Set<Collider>; public start(ray: Ray2D, hits: RaycastHit[], layerMask: number, ignoredColliders: Set<Collider>) { this._ray = ray; this._hits = hits; this._layerMask = layerMask; this._ignoredColliders = ignoredColliders; this.hitCounter = 0; } /** * 如果hits数组被填充,返回true。单元格不能为空! * @param cellX * @param cellY * @param cell */ public checkRayIntersection(cellX: number, cellY: number, cell: Collider[]): boolean { for (let i = 0; i < cell.length; i++) { const potential = cell[i]; // 管理我们已经处理过的碰撞器 if (new es.List(this._checkedColliders).contains(potential)) continue; this._checkedColliders.push(potential); // 只有当我们被设置为这样做时才会点击触发器 if (potential.isTrigger && !Physics.raycastsHitTriggers) continue; // 确保碰撞器在图层蒙版上 if (!Flags.isFlagSet(this._layerMask, potential.physicsLayer.value)) continue; if (this._ignoredColliders && this._ignoredColliders.has(potential)) { continue; } // TODO: rayIntersects的性能够吗?需要测试它。Collisions.rectToLine可能更快 // TODO: 如果边界检查返回更多数据,我们就不需要为BoxCollider检查做任何事情 // 在做形状测试之前先做一个边界检查 const colliderBounds = potential.bounds; const res = colliderBounds.rayIntersects(this._ray); if (res.intersected && res.distance <= 1) { if (potential.shape.collidesWithLine(this._ray.start, this._ray.end, this._tempHit)) { // 检查一下,我们应该排除这些射线,射线cast是否在碰撞器中开始 if (!Physics.raycastsStartInColliders && potential.shape.containsPoint(this._ray.start)) continue; // TODO: 确保碰撞点在当前单元格中,如果它没有保存它以供以后计算 this._tempHit.collider = potential; this._cellHits.push(this._tempHit); } } } if (this._cellHits.length === 0) return false; // 所有处理单元完成。对结果进行排序并将命中结果打包到结果数组中 this._cellHits.sort(RaycastResultParser.compareRaycastHits); for (let i = 0; i < this._cellHits.length; i++) { this._hits[this.hitCounter] = this._cellHits[i]; // 增加命中计数器,如果它已经达到数组大小的限制,我们就完成了 this.hitCounter++; if (this.hitCounter === this._hits.length) return true; } return false; } public reset() { this._hits = null; this._checkedColliders.length = 0; this._cellHits.length = 0; this._ignoredColliders = null; } } }
the_stack
import { expect } from 'chai'; import { GeoPoint } from '../../../src/api/geo_point'; import { Timestamp } from '../../../src/api/timestamp'; import { serverTimestamp } from '../../../src/model/server_timestamps'; import { canonicalId, valueCompare, valueEquals, estimateByteSize, refValue, deepClone } from '../../../src/model/values'; import * as api from '../../../src/protos/firestore_proto_api'; import { primitiveComparator } from '../../../src/util/misc'; import { blob, dbId, expectCorrectComparisonGroups, expectEqualitySets, key, ref, wrap } from '../../util/helpers'; describe('Values', () => { const date1 = new Date(2016, 4, 2, 1, 5); const date2 = new Date(2016, 5, 20, 10, 20, 30); it('compares values for equality', () => { // Each subarray compares equal to each other and false to every other value const values: api.Value[][] = [ [wrap(true), wrap(true)], [wrap(false), wrap(false)], [wrap(null), wrap(null)], [wrap(0 / 0), wrap(Number.NaN), wrap(NaN)], // -0.0 and 0.0 order the same but are not considered equal. [wrap(-0.0)], [wrap(0.0)], [wrap(1), { integerValue: 1 }], // Doubles and Integers order the same but are not considered equal. [{ doubleValue: 1.0 }], [wrap(1.1), wrap(1.1)], [wrap(blob(0, 1, 2)), wrap(blob(0, 1, 2))], [wrap(blob(0, 1))], [wrap('string'), wrap('string')], [wrap('strin')], // latin small letter e + combining acute accent [wrap('e\u0301b')], // latin small letter e with acute accent [wrap('\u00e9a')], [wrap(date1), wrap(Timestamp.fromDate(date1))], [wrap(date2)], [ // NOTE: ServerTimestampValues can't be parsed via wrap(). serverTimestamp(Timestamp.fromDate(date1), null), serverTimestamp(Timestamp.fromDate(date1), null) ], [serverTimestamp(Timestamp.fromDate(date2), null)], [wrap(new GeoPoint(0, 1)), wrap(new GeoPoint(0, 1))], [wrap(new GeoPoint(1, 0))], [wrap(ref('coll/doc1')), wrap(ref('coll/doc1'))], [wrap(ref('coll/doc2'))], [wrap(['foo', 'bar']), wrap(['foo', 'bar'])], [wrap(['foo', 'bar', 'baz'])], [wrap(['foo'])], [wrap({ bar: 1, foo: 2 }), wrap({ foo: 2, bar: 1 })], [wrap({ bar: 2, foo: 1 })], [wrap({ bar: 1, foo: 1 })], [wrap({ foo: 1 })] ]; expectEqualitySets(values, (v1, v2) => valueEquals(v1, v2)); }); it('normalizes values for equality', () => { // Each subarray compares equal to each other and false to every other value const values: api.Value[][] = [ [{ integerValue: '1' }, { integerValue: 1 }], [{ doubleValue: '1.0' }, { doubleValue: 1.0 }], [ { timestampValue: '2007-04-05T14:30:01Z' }, { timestampValue: '2007-04-05T14:30:01.000Z' }, { timestampValue: '2007-04-05T14:30:01.000000Z' }, { timestampValue: '2007-04-05T14:30:01.000000000Z' }, { timestampValue: { seconds: 1175783401 } }, { timestampValue: { seconds: '1175783401' } }, { timestampValue: { seconds: 1175783401, nanos: 0 } } ], [ { timestampValue: '2007-04-05T14:30:01.100Z' }, { timestampValue: { seconds: 1175783401, nanos: 100000000 } } ], [{ bytesValue: new Uint8Array([0, 1, 2]) }, { bytesValue: 'AAEC' }] ]; expectEqualitySets(values, (v1, v2) => valueEquals(v1, v2)); }); it('orders types correctly', () => { const groups = [ // null first [wrap(null)], // booleans [wrap(false)], [wrap(true)], // numbers [wrap(NaN)], [wrap(-Infinity)], [wrap(-Number.MAX_VALUE)], [wrap(Number.MIN_SAFE_INTEGER - 1)], [wrap(Number.MIN_SAFE_INTEGER)], [wrap(-1.1)], // Integers and Doubles order the same. [{ integerValue: -1 }, { doubleValue: -1 }], [wrap(-Number.MIN_VALUE)], // zeros all compare the same. [{ integerValue: 0 }, { doubleValue: 0 }, { doubleValue: -0 }], [wrap(Number.MIN_VALUE)], [{ integerValue: 1 }, { doubleValue: 1 }], [wrap(1.1)], [wrap(Number.MAX_SAFE_INTEGER)], [wrap(Number.MAX_SAFE_INTEGER + 1)], [wrap(Infinity)], // timestamps [wrap(date1)], [wrap(date2)], [ { timestampValue: '2020-04-05T14:30:01Z' }, { timestampValue: '2020-04-05T14:30:01.000Z' }, { timestampValue: '2020-04-05T14:30:01.000000Z' }, { timestampValue: '2020-04-05T14:30:01.000000000Z' } ], // server timestamps come after all concrete timestamps. [serverTimestamp(Timestamp.fromDate(date1), null)], [serverTimestamp(Timestamp.fromDate(date2), null)], // strings [wrap('')], [wrap('\u0000\ud7ff\ue000\uffff')], [wrap('(╯°□°)╯︵ ┻━┻')], [wrap('a')], [wrap('abc def')], // latin small letter e + combining acute accent + latin small letter b [wrap('e\u0301b')], [wrap('æ')], // latin small letter e with acute accent + latin small letter a [wrap('\u00e9a')], // blobs [wrap(blob())], [wrap(blob(0))], [wrap(blob(0, 1, 2, 3, 4))], [wrap(blob(0, 1, 2, 4, 3))], [wrap(blob(255))], // reference values [refValue(dbId('p1', 'd1'), key('c1/doc1'))], [refValue(dbId('p1', 'd1'), key('c1/doc2'))], [refValue(dbId('p1', 'd1'), key('c10/doc1'))], [refValue(dbId('p1', 'd1'), key('c2/doc1'))], [refValue(dbId('p1', 'd2'), key('c1/doc1'))], [refValue(dbId('p2', 'd1'), key('c1/doc1'))], // geo points [wrap(new GeoPoint(-90, -180))], [wrap(new GeoPoint(-90, 0))], [wrap(new GeoPoint(-90, 180))], [wrap(new GeoPoint(0, -180))], [wrap(new GeoPoint(0, 0))], [wrap(new GeoPoint(0, 180))], [wrap(new GeoPoint(1, -180))], [wrap(new GeoPoint(1, 0))], [wrap(new GeoPoint(1, 180))], [wrap(new GeoPoint(90, -180))], [wrap(new GeoPoint(90, 0))], [wrap(new GeoPoint(90, 180))], // arrays [wrap([])], [wrap(['bar'])], [wrap(['foo'])], [wrap(['foo', 1])], [wrap(['foo', 2])], [wrap(['foo', '0'])], // objects [wrap({ bar: 0 })], [wrap({ bar: 0, foo: 1 })], [wrap({ foo: 1 })], [wrap({ foo: 2 })], [wrap({ foo: '0' })] ]; expectCorrectComparisonGroups( groups, (left: api.Value, right: api.Value) => { return valueCompare(left, right); } ); }); it('normalizes values for comparison', () => { const groups = [ [{ integerValue: '1' }, { integerValue: 1 }], [{ doubleValue: '2' }, { doubleValue: 2 }], [ { timestampValue: '2007-04-05T14:30:01Z' }, { timestampValue: { seconds: 1175783401 } } ], [ { timestampValue: '2007-04-05T14:30:01.999Z' }, { timestampValue: { seconds: 1175783401, nanos: 999000000 } } ], [ { timestampValue: '2007-04-05T14:30:02Z' }, { timestampValue: { seconds: 1175783402 } } ], [ { timestampValue: '2007-04-05T14:30:02.100Z' }, { timestampValue: { seconds: 1175783402, nanos: 100000000 } } ], [ { timestampValue: '2007-04-05T14:30:02.100001Z' }, { timestampValue: { seconds: 1175783402, nanos: 100001000 } } ], [{ bytesValue: new Uint8Array([0, 1, 2]) }, { bytesValue: 'AAEC' }], [{ bytesValue: new Uint8Array([0, 1, 3]) }, { bytesValue: 'AAED' }] ]; expectCorrectComparisonGroups( groups, (left: api.Value, right: api.Value) => { return valueCompare(left, right); } ); }); it('estimates size correctly for fixed sized values', () => { // This test verifies that each member of a group takes up the same amount // of space in memory (based on its estimated in-memory size). const equalityGroups = [ { expectedByteSize: 4, elements: [wrap(null), wrap(false), wrap(true)] }, { expectedByteSize: 4, elements: [wrap(blob(0, 1)), wrap(blob(128, 129))] }, { expectedByteSize: 8, elements: [wrap(NaN), wrap(Infinity), wrap(1), wrap(1.1)] }, { expectedByteSize: 16, elements: [wrap(new GeoPoint(0, 0)), wrap(new GeoPoint(0, 0))] }, { expectedByteSize: 16, elements: [wrap(Timestamp.fromMillis(100)), wrap(Timestamp.now())] }, { expectedByteSize: 16, elements: [ serverTimestamp(Timestamp.fromMillis(100), null), serverTimestamp(Timestamp.now(), null) ] }, { expectedByteSize: 20, elements: [ serverTimestamp(Timestamp.fromMillis(100), wrap(true)), serverTimestamp(Timestamp.now(), wrap(false)) ] }, { expectedByteSize: 42, elements: [ refValue(dbId('p1', 'd1'), key('c1/doc1')), refValue(dbId('p2', 'd2'), key('c2/doc2')) ] }, { expectedByteSize: 6, elements: [wrap('foo'), wrap('bar')] }, { expectedByteSize: 4, elements: [wrap(['a', 'b']), wrap(['c', 'd'])] }, { expectedByteSize: 6, elements: [wrap({ a: 'a', b: 'b' }), wrap({ c: 'c', d: 'd' })] } ]; for (const group of equalityGroups) { for (const element of group.elements) { expect(estimateByteSize(element)).to.equal(group.expectedByteSize); } } }); it('estimates size correctly for relatively sized values', () => { // This test verifies for each group that the estimated size increases // as the size of the underlying data grows. const relativeGroups: api.Value[][] = [ [wrap(blob(0)), wrap(blob(0, 1))], [ serverTimestamp(Timestamp.fromMillis(100), null), serverTimestamp(Timestamp.now(), wrap(null)) ], [ refValue(dbId('p1', 'd1'), key('c1/doc1')), refValue(dbId('p1', 'd1'), key('c1/doc1/c2/doc2')) ], [wrap('foo'), wrap('foobar')], [wrap(['a', 'b']), wrap(['a', 'bc'])], [wrap(['a', 'b']), wrap(['a', 'b', 'c'])], [wrap({ a: 'a', b: 'b' }), wrap({ a: 'a', b: 'bc' })], [wrap({ a: 'a', b: 'b' }), wrap({ a: 'a', bc: 'b' })], [wrap({ a: 'a', b: 'b' }), wrap({ a: 'a', b: 'b', c: 'c' })] ]; for (const group of relativeGroups) { const expectedOrder = group; const actualOrder = group .slice() .sort((l, r) => primitiveComparator(estimateByteSize(l), estimateByteSize(r)) ); expect(expectedOrder).to.deep.equal(actualOrder); } }); it('canonicalizes values', () => { expect(canonicalId(wrap(null))).to.equal('null'); expect(canonicalId(wrap(true))).to.equal('true'); expect(canonicalId(wrap(false))).to.equal('false'); expect(canonicalId(wrap(1))).to.equal('1'); expect(canonicalId(wrap(1.1))).to.equal('1.1'); expect(canonicalId(wrap(new Timestamp(30, 1000)))).to.equal( 'time(30,1000)' ); expect(canonicalId(wrap('a'))).to.equal('a'); expect(canonicalId(wrap(blob(1, 2, 3)))).to.equal('AQID'); expect(canonicalId(refValue(dbId('p1', 'd1'), key('c1/doc1')))).to.equal( 'c1/doc1' ); expect(canonicalId(wrap(new GeoPoint(30, 60)))).to.equal('geo(30,60)'); expect(canonicalId(wrap([1, 2, 3]))).to.equal('[1,2,3]'); expect( canonicalId( wrap({ 'a': 1, 'b': 2, 'c': '3' }) ) ).to.equal('{a:1,b:2,c:3}'); expect( canonicalId(wrap({ 'a': ['b', { 'c': new GeoPoint(30, 60) }] })) ).to.equal('{a:[b,{c:geo(30,60)}]}'); }); it('canonical IDs ignore sort order', () => { expect( canonicalId( wrap({ 'a': 1, 'b': 2, 'c': '3' }) ) ).to.equal('{a:1,b:2,c:3}'); expect( canonicalId( wrap({ 'c': 3, 'b': 2, 'a': '1' }) ) ).to.equal('{a:1,b:2,c:3}'); }); it('clones properties without normalization', () => { const values = [ { integerValue: '1' }, { integerValue: 1 }, { doubleValue: '2' }, { doubleValue: 2 }, { timestampValue: '2007-04-05T14:30:01Z' }, { timestampValue: { seconds: 1175783401 } }, { timestampValue: '2007-04-05T14:30:01.999Z' }, { timestampValue: { seconds: 1175783401, nanos: 999000000 } }, { timestampValue: '2007-04-05T14:30:02Z' }, { timestampValue: { seconds: 1175783402 } }, { timestampValue: '2007-04-05T14:30:02.100Z' }, { timestampValue: { seconds: 1175783402, nanos: 100000000 } }, { timestampValue: '2007-04-05T14:30:02.100001Z' }, { timestampValue: { seconds: 1175783402, nanos: 100001000 } }, { bytesValue: new Uint8Array([0, 1, 2]) }, { bytesValue: 'AAEC' }, { bytesValue: new Uint8Array([0, 1, 3]) }, { bytesValue: 'AAED' } ]; for (const value of values) { expect(deepClone(value)).to.deep.equal(value); const mapValue = { mapValue: { fields: { foo: value } } }; expect(deepClone(mapValue)).to.deep.equal(mapValue); const arrayValue = { arrayValue: { values: [value] } }; expect(deepClone(arrayValue)).to.deep.equal(arrayValue); } }); });
the_stack
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { AbstractClient } from "../../../common/abstract_client" import { ClientConfig } from "../../../common/interface" import { ModifyDiskExtraPerformanceRequest, RenewDiskRequest, AttachDisksResponse, DescribeSnapshotOperationLogsRequest, ModifyAutoSnapshotPolicyAttributeResponse, InquiryPriceCreateDisksResponse, BindAutoSnapshotPolicyRequest, CreateSnapshotResponse, DescribeAutoSnapshotPoliciesRequest, ModifySnapshotsSharePermissionResponse, DescribeDiskStoragePoolRequest, SnapshotOperationLog, ModifyDiskAttributesResponse, InquirePriceModifyDiskExtraPerformanceResponse, CreateDisksRequest, AttachDisksRequest, DescribeDiskAssociatedAutoSnapshotPolicyRequest, DescribeSnapshotsRequest, TerminateDisksResponse, DescribeDiskConfigQuotaResponse, InquiryPriceResizeDiskResponse, Tag, ResizeDiskResponse, Disk, ModifyAutoSnapshotPolicyAttributeRequest, DetachDisksRequest, ModifyDisksChargeTypeResponse, CreateSnapshotRequest, DescribeInstancesDiskNumRequest, DescribeSnapshotSharePermissionResponse, InquiryPriceRenewDisksRequest, DescribeSnapshotSharePermissionRequest, DescribeSnapshotOperationLogsResponse, DeleteSnapshotsRequest, ModifyDisksRenewFlagResponse, DeleteAutoSnapshotPoliciesResponse, DescribeDisksResponse, Placement, DeleteSnapshotsResponse, ModifyDisksRenewFlagRequest, ModifyDiskAttributesRequest, GetSnapOverviewRequest, Image, TerminateDisksRequest, CdcSize, DescribeInstancesDiskNumResponse, DescribeDiskOperationLogsResponse, ResizeDiskRequest, ModifyDisksChargeTypeRequest, CreateAutoSnapshotPolicyResponse, ModifySnapshotAttributeRequest, UnbindAutoSnapshotPolicyRequest, DiskConfig, DeleteAutoSnapshotPoliciesRequest, DiskChargePrepaid, Filter, InquiryPriceCreateDisksRequest, DescribeSnapshotsResponse, Snapshot, CreateDisksResponse, AutoSnapshotPolicy, ModifySnapshotsSharePermissionRequest, DiskOperationLog, BindAutoSnapshotPolicyResponse, DescribeDiskOperationLogsRequest, DescribeDisksRequest, DetachDisksResponse, InquiryPriceRenewDisksResponse, SharePermission, DescribeDiskStoragePoolResponse, Policy, Price, InquirePriceModifyDiskExtraPerformanceRequest, InquiryPriceResizeDiskRequest, DescribeDiskConfigQuotaRequest, DescribeDiskAssociatedAutoSnapshotPolicyResponse, GetSnapOverviewResponse, ApplySnapshotResponse, ModifySnapshotAttributeResponse, PrepayPrice, RenewDiskResponse, DescribeAutoSnapshotPoliciesResponse, Cdc, UnbindAutoSnapshotPolicyResponse, AttachDetail, CreateAutoSnapshotPolicyRequest, ModifyDiskExtraPerformanceResponse, ApplySnapshotRequest, } from "./cbs_models" /** * cbs client * @class */ export class Client extends AbstractClient { constructor(clientConfig: ClientConfig) { super("cbs.tencentcloudapi.com", "2017-03-12", clientConfig) } /** * 本接口(ModifyDiskExtraPerformance)用于调整云硬盘额外的性能。 * 目前仅支持极速型SSD云硬盘(CLOUD_TSSD)和高性能SSD云硬盘(CLOUD_HSSD)。 */ async ModifyDiskExtraPerformance( req: ModifyDiskExtraPerformanceRequest, cb?: (error: string, rep: ModifyDiskExtraPerformanceResponse) => void ): Promise<ModifyDiskExtraPerformanceResponse> { return this.request("ModifyDiskExtraPerformance", req, cb) } /** * 本接口(RenewDisk)用于续费云硬盘。 * 只支持预付费的云硬盘。云硬盘类型可以通过[DescribeDisks](/document/product/362/16315)接口查询,见输出参数中DiskChargeType字段解释。 * 支持与挂载实例一起续费的场景,需要在[DiskChargePrepaid](/document/product/362/15669#DiskChargePrepaid)参数中指定CurInstanceDeadline,此时会按对齐到子机续费后的到期时间来续费。 */ async RenewDisk( req: RenewDiskRequest, cb?: (error: string, rep: RenewDiskResponse) => void ): Promise<RenewDiskResponse> { return this.request("RenewDisk", req, cb) } /** * 本接口(DescribeInstancesDiskNum)用于查询实例已挂载云硬盘数量。 * 支持批量操作,当传入多个云服务器实例ID,返回结果会分别列出每个云服务器挂载的云硬盘数量。 */ async DescribeInstancesDiskNum( req: DescribeInstancesDiskNumRequest, cb?: (error: string, rep: DescribeInstancesDiskNumResponse) => void ): Promise<DescribeInstancesDiskNumResponse> { return this.request("DescribeInstancesDiskNum", req, cb) } /** * 本接口(InquiryPriceResizeDisk)用于扩容云硬盘询价。 * 只支持预付费模式的云硬盘扩容询价。 */ async InquiryPriceResizeDisk( req: InquiryPriceResizeDiskRequest, cb?: (error: string, rep: InquiryPriceResizeDiskResponse) => void ): Promise<InquiryPriceResizeDiskResponse> { return this.request("InquiryPriceResizeDisk", req, cb) } /** * 本接口(InquirePriceModifyDiskExtraPerformance)用于调整云硬盘额外性能询价。 */ async InquirePriceModifyDiskExtraPerformance( req: InquirePriceModifyDiskExtraPerformanceRequest, cb?: (error: string, rep: InquirePriceModifyDiskExtraPerformanceResponse) => void ): Promise<InquirePriceModifyDiskExtraPerformanceResponse> { return this.request("InquirePriceModifyDiskExtraPerformance", req, cb) } /** * 本接口(DescribeAutoSnapshotPolicies)用于查询定期快照策略。 * 可以根据定期快照策略ID、名称或者状态等信息来查询定期快照策略的详细信息,不同条件之间为与(AND)的关系,过滤信息详细请见过滤器`Filter`。 * 如果参数为空,返回当前用户一定数量(`Limit`所指定的数量,默认为20)的定期快照策略表。 */ async DescribeAutoSnapshotPolicies( req: DescribeAutoSnapshotPoliciesRequest, cb?: (error: string, rep: DescribeAutoSnapshotPoliciesResponse) => void ): Promise<DescribeAutoSnapshotPoliciesResponse> { return this.request("DescribeAutoSnapshotPolicies", req, cb) } /** * 本接口(AttachDisks)用于挂载云硬盘。 * 支持批量操作,将多块云盘挂载到同一云主机。如果多个云盘中存在不允许挂载的云盘,则操作不执行,返回特定的错误码。 * 本接口为异步接口,当挂载云盘的请求成功返回时,表示后台已发起挂载云盘的操作,可通过接口[DescribeDisks](/document/product/362/16315)来查询对应云盘的状态,如果云盘的状态由“ATTACHING”变为“ATTACHED”,则为挂载成功。 */ async AttachDisks( req: AttachDisksRequest, cb?: (error: string, rep: AttachDisksResponse) => void ): Promise<AttachDisksResponse> { return this.request("AttachDisks", req, cb) } /** * 本接口(ModifyDisksRenewFlag)用于修改云硬盘续费标识,支持批量修改。 */ async ModifyDisksRenewFlag( req: ModifyDisksRenewFlagRequest, cb?: (error: string, rep: ModifyDisksRenewFlagResponse) => void ): Promise<ModifyDisksRenewFlagResponse> { return this.request("ModifyDisksRenewFlag", req, cb) } /** * 本接口(ModifyAutoSnapshotPolicyAttribute)用于修改定期快照策略属性。 * 可通过该接口修改定期快照策略的执行策略、名称、是否激活等属性。 * 修改保留天数时必须保证不与是否永久保留属性冲突,否则整个操作失败,以特定的错误码返回。 */ async ModifyAutoSnapshotPolicyAttribute( req: ModifyAutoSnapshotPolicyAttributeRequest, cb?: (error: string, rep: ModifyAutoSnapshotPolicyAttributeResponse) => void ): Promise<ModifyAutoSnapshotPolicyAttributeResponse> { return this.request("ModifyAutoSnapshotPolicyAttribute", req, cb) } /** * 本接口(InquiryPriceCreateDisks)用于创建云硬盘询价。 * 支持查询创建多块云硬盘的价格,此时返回结果为总价格。 */ async InquiryPriceCreateDisks( req: InquiryPriceCreateDisksRequest, cb?: (error: string, rep: InquiryPriceCreateDisksResponse) => void ): Promise<InquiryPriceCreateDisksResponse> { return this.request("InquiryPriceCreateDisks", req, cb) } /** * 查询云盘操作日志功能已迁移至LookUpEvents接口(https://cloud.tencent.com/document/product/629/12359),本接口(DescribeDiskOperationLogs)即将下线,后续不再提供调用,请知悉。 */ async DescribeDiskOperationLogs( req: DescribeDiskOperationLogsRequest, cb?: (error: string, rep: DescribeDiskOperationLogsResponse) => void ): Promise<DescribeDiskOperationLogsResponse> { return this.request("DescribeDiskOperationLogs", req, cb) } /** * 本接口(DeleteAutoSnapshotPolicies)用于删除定期快照策略。 * 支持批量操作。如果多个定期快照策略存在无法删除的,则操作不执行,以特定错误码返回。 */ async DeleteAutoSnapshotPolicies( req: DeleteAutoSnapshotPoliciesRequest, cb?: (error: string, rep: DeleteAutoSnapshotPoliciesResponse) => void ): Promise<DeleteAutoSnapshotPoliciesResponse> { return this.request("DeleteAutoSnapshotPolicies", req, cb) } /** * 本接口(DescribeDisks)用于查询云硬盘列表。 * 可以根据云硬盘ID、云硬盘类型或者云硬盘状态等信息来查询云硬盘的详细信息,不同条件之间为与(AND)的关系,过滤信息详细请见过滤器`Filter`。 * 如果参数为空,返回当前用户一定数量(`Limit`所指定的数量,默认为20)的云硬盘列表。 */ async DescribeDisks( req: DescribeDisksRequest, cb?: (error: string, rep: DescribeDisksResponse) => void ): Promise<DescribeDisksResponse> { return this.request("DescribeDisks", req, cb) } /** * 本接口(CreateDisks)用于创建云硬盘。 * 预付费云盘的购买会预先扣除本次云盘购买所需金额,在调用本接口前请确保账户余额充足。 * 本接口支持传入数据盘快照来创建云盘,实现将快照数据复制到新购云盘上。 * 本接口为异步接口,当创建请求下发成功后会返回一个新建的云盘ID列表,此时云盘的创建并未立即完成。可以通过调用[DescribeDisks](/document/product/362/16315)接口根据DiskId查询对应云盘,如果能查到云盘,且状态为'UNATTACHED'或'ATTACHED',则表示创建成功。 */ async CreateDisks( req: CreateDisksRequest, cb?: (error: string, rep: CreateDisksResponse) => void ): Promise<CreateDisksResponse> { return this.request("CreateDisks", req, cb) } /** * * 只支持修改弹性云盘的项目ID。随云主机创建的云硬盘项目ID与云主机联动。可以通过[DescribeDisks](/document/product/362/16315)接口查询,见输出参数中Portable字段解释。 * “云硬盘名称”仅为方便用户自己管理之用,腾讯云并不以此名称作为提交工单或是进行云盘管理操作的依据。 * 支持批量操作,如果传入多个云盘ID,则所有云盘修改为同一属性。如果存在不允许操作的云盘,则操作不执行,以特定错误码返回。 */ async ModifyDiskAttributes( req: ModifyDiskAttributesRequest, cb?: (error: string, rep: ModifyDiskAttributesResponse) => void ): Promise<ModifyDiskAttributesResponse> { return this.request("ModifyDiskAttributes", req, cb) } /** * 本接口(DeleteSnapshots)用于删除快照。 * 快照必须处于NORMAL状态,快照状态可以通过[DescribeSnapshots](/document/product/362/15647)接口查询,见输出参数中SnapshotState字段解释。 * 支持批量操作。如果多个快照存在无法删除的快照,则操作不执行,以特定的错误码返回。 */ async DeleteSnapshots( req: DeleteSnapshotsRequest, cb?: (error: string, rep: DeleteSnapshotsResponse) => void ): Promise<DeleteSnapshotsResponse> { return this.request("DeleteSnapshots", req, cb) } /** * 本接口(ModifySnapshotAttribute)用于修改指定快照的属性。 * 当前仅支持修改快照名称及将非永久快照修改为永久快照。 * “快照名称”仅为方便用户自己管理之用,腾讯云并不以此名称作为提交工单或是进行快照管理操作的依据。 */ async ModifySnapshotAttribute( req: ModifySnapshotAttributeRequest, cb?: (error: string, rep: ModifySnapshotAttributeResponse) => void ): Promise<ModifySnapshotAttributeResponse> { return this.request("ModifySnapshotAttribute", req, cb) } /** * 本接口(DescribeDiskAssociatedAutoSnapshotPolicy)用于查询云盘绑定的定期快照策略。 */ async DescribeDiskAssociatedAutoSnapshotPolicy( req: DescribeDiskAssociatedAutoSnapshotPolicyRequest, cb?: (error: string, rep: DescribeDiskAssociatedAutoSnapshotPolicyResponse) => void ): Promise<DescribeDiskAssociatedAutoSnapshotPolicyResponse> { return this.request("DescribeDiskAssociatedAutoSnapshotPolicy", req, cb) } /** * 本接口(BindAutoSnapshotPolicy)用于绑定云硬盘到指定的定期快照策略。 * 每个地域下的定期快照策略配额限制请参考文档[定期快照](/document/product/362/8191)。 * 当已绑定定期快照策略的云硬盘处于未使用状态(即弹性云盘未挂载或非弹性云盘的主机处于关机状态)将不会创建定期快照。 */ async BindAutoSnapshotPolicy( req: BindAutoSnapshotPolicyRequest, cb?: (error: string, rep: BindAutoSnapshotPolicyResponse) => void ): Promise<BindAutoSnapshotPolicyResponse> { return this.request("BindAutoSnapshotPolicy", req, cb) } /** * 本接口(DescribeSnapshots)用于查询快照的详细信息。 * 根据快照ID、创建快照的云硬盘ID、创建快照的云硬盘类型等对结果进行过滤,不同条件之间为与(AND)的关系,过滤信息详细请见过滤器`Filter`。 * 如果参数为空,返回当前用户一定数量(`Limit`所指定的数量,默认为20)的快照列表。 */ async DescribeSnapshots( req: DescribeSnapshotsRequest, cb?: (error: string, rep: DescribeSnapshotsResponse) => void ): Promise<DescribeSnapshotsResponse> { return this.request("DescribeSnapshots", req, cb) } /** * 本接口(DescribeSnapshotSharePermission)用于查询快照的分享信息。 */ async DescribeSnapshotSharePermission( req: DescribeSnapshotSharePermissionRequest, cb?: (error: string, rep: DescribeSnapshotSharePermissionResponse) => void ): Promise<DescribeSnapshotSharePermissionResponse> { return this.request("DescribeSnapshotSharePermission", req, cb) } /** * 本接口(CreateAutoSnapshotPolicy)用于创建定期快照策略。 * 每个地域可创建的定期快照策略数量限制请参考文档[定期快照](/document/product/362/8191)。 * 每个地域可创建的快照有数量和容量的限制,具体请见腾讯云控制台快照页面提示,如果快照超配额,定期快照创建会失败。 */ async CreateAutoSnapshotPolicy( req: CreateAutoSnapshotPolicyRequest, cb?: (error: string, rep: CreateAutoSnapshotPolicyResponse) => void ): Promise<CreateAutoSnapshotPolicyResponse> { return this.request("CreateAutoSnapshotPolicy", req, cb) } /** * 接口请求域名: cbs.tencentcloudapi.com 。 本接口 (ModifyDisksChargeType) 用于切换云盘的计费模式。 只支持从 POSTPAID_BY_HOUR 计费模式切换为PREPAID计费模式。 非弹性云盘不支持此接口,请通过修改实例计费模式接口将实例连同非弹性云盘一起转换。 默认接口请求频率限制:10次/秒。 */ async ModifyDisksChargeType( req: ModifyDisksChargeTypeRequest, cb?: (error: string, rep: ModifyDisksChargeTypeResponse) => void ): Promise<ModifyDisksChargeTypeResponse> { return this.request("ModifyDisksChargeType", req, cb) } /** * 本接口(TerminateDisks)用于退还云硬盘。 * 不再使用的云盘,可通过本接口主动退还。 * 本接口支持退还预付费云盘和按小时后付费云盘。按小时后付费云盘可直接退还,预付费云盘需符合退还规则。 * 支持批量操作,每次请求批量云硬盘的上限为50。如果批量云盘存在不允许操作的,请求会以特定错误码返回。 */ async TerminateDisks( req: TerminateDisksRequest, cb?: (error: string, rep: TerminateDisksResponse) => void ): Promise<TerminateDisksResponse> { return this.request("TerminateDisks", req, cb) } /** * 本接口(DescribeDiskConfigQuota)用于查询云硬盘配额。 */ async DescribeDiskConfigQuota( req: DescribeDiskConfigQuotaRequest, cb?: (error: string, rep: DescribeDiskConfigQuotaResponse) => void ): Promise<DescribeDiskConfigQuotaResponse> { return this.request("DescribeDiskConfigQuota", req, cb) } /** * 本接口(UnbindAutoSnapshotPolicy)用于解除云硬盘绑定的定期快照策略。 * 支持批量操作,可一次解除多个云盘与同一定期快照策略的绑定。 * 如果传入的云盘未绑定到当前定期快照策略,接口将自动跳过,仅解绑与当前定期快照策略绑定的云盘。 */ async UnbindAutoSnapshotPolicy( req: UnbindAutoSnapshotPolicyRequest, cb?: (error: string, rep: UnbindAutoSnapshotPolicyResponse) => void ): Promise<UnbindAutoSnapshotPolicyResponse> { return this.request("UnbindAutoSnapshotPolicy", req, cb) } /** * 本接口(DescribeDiskStoragePool)查询用户的云硬盘独享集群列表。 * 可以根据独享集群ID(CdcId)、集群区域名(zone)类型等信息来查询和过滤云硬盘独享集群详细信息,不同条件之间为与(AND)的关系,过滤信息详细请见过滤器`Filter`。 * 如果参数为空,返回当前用户一定数量(`Limit`所指定的数量,默认为20)的云硬盘独享集群列表。 */ async DescribeDiskStoragePool( req: DescribeDiskStoragePoolRequest, cb?: (error: string, rep: DescribeDiskStoragePoolResponse) => void ): Promise<DescribeDiskStoragePoolResponse> { return this.request("DescribeDiskStoragePool", req, cb) } /** * 本接口(ApplySnapshot)用于回滚快照到原云硬盘。 * 仅支持回滚到原云硬盘上。对于数据盘快照,如果您需要复制快照数据到其它云硬盘上,请使用[CreateDisks](/document/product/362/16312)接口创建新的弹性云盘,将快照数据复制到新购云盘上。 * 用于回滚的快照必须处于NORMAL状态。快照状态可以通过[DescribeSnapshots](/document/product/362/15647)接口查询,见输出参数中SnapshotState字段解释。 * 如果是弹性云盘,则云盘必须处于未挂载状态,云硬盘挂载状态可以通过[DescribeDisks](/document/product/362/16315)接口查询,见Attached字段解释;如果是随实例一起购买的非弹性云盘,则实例必须处于关机状态,实例状态可以通过[DescribeInstancesStatus](/document/product/213/15738)接口查询。 */ async ApplySnapshot( req: ApplySnapshotRequest, cb?: (error: string, rep: ApplySnapshotResponse) => void ): Promise<ApplySnapshotResponse> { return this.request("ApplySnapshot", req, cb) } /** * 本接口(DescribeSnapshotOperationLogs)用于查询快照操作日志列表。 可根据快照ID过滤。快照ID形如:snap-a1kmcp13。 */ async DescribeSnapshotOperationLogs( req: DescribeSnapshotOperationLogsRequest, cb?: (error: string, rep: DescribeSnapshotOperationLogsResponse) => void ): Promise<DescribeSnapshotOperationLogsResponse> { return this.request("DescribeSnapshotOperationLogs", req, cb) } /** * 本接口(ModifySnapshotsSharePermission)用于修改快照分享信息。 分享快照后,被分享账户可以通过该快照创建云硬盘。 * 每个快照最多可分享给50个账户。 * 分享快照无法更改名称,描述,仅可用于创建云硬盘。 * 只支持分享到对方账户相同地域。 * 仅支持分享数据盘快照。 */ async ModifySnapshotsSharePermission( req: ModifySnapshotsSharePermissionRequest, cb?: (error: string, rep: ModifySnapshotsSharePermissionResponse) => void ): Promise<ModifySnapshotsSharePermissionResponse> { return this.request("ModifySnapshotsSharePermission", req, cb) } /** * 本接口(CreateSnapshot)用于对指定云盘创建快照。 * 只有具有快照能力的云硬盘才能创建快照。云硬盘是否具有快照能力可由[DescribeDisks](/document/product/362/16315)接口查询,见SnapshotAbility字段。 * 可创建快照数量限制见[产品使用限制](https://cloud.tencent.com/doc/product/362/5145)。 */ async CreateSnapshot( req: CreateSnapshotRequest, cb?: (error: string, rep: CreateSnapshotResponse) => void ): Promise<CreateSnapshotResponse> { return this.request("CreateSnapshot", req, cb) } /** * 获取快照概览信息 */ async GetSnapOverview( req?: GetSnapOverviewRequest, cb?: (error: string, rep: GetSnapOverviewResponse) => void ): Promise<GetSnapOverviewResponse> { return this.request("GetSnapOverview", req, cb) } /** * 本接口(ResizeDisk)用于扩容云硬盘。 * 只支持扩容弹性云盘。云硬盘类型可以通过[DescribeDisks](/document/product/362/16315)接口查询,见输出参数中Portable字段解释。非弹性云硬盘需通过[ResizeInstanceDisks](/document/product/213/15731)接口扩容。 * 本接口为异步接口,接口成功返回时,云盘并未立即扩容到指定大小,可通过接口[DescribeDisks](/document/product/362/16315)来查询对应云盘的状态,如果云盘的状态为“EXPANDING”,表示正在扩容中。 */ async ResizeDisk( req: ResizeDiskRequest, cb?: (error: string, rep: ResizeDiskResponse) => void ): Promise<ResizeDiskResponse> { return this.request("ResizeDisk", req, cb) } /** * 本接口(DetachDisks)用于卸载云硬盘。 * 支持批量操作,卸载挂载在同一主机上的多块云盘。如果多块云盘中存在不允许卸载的云盘,则操作不执行,返回特定的错误码。 * 本接口为异步接口,当请求成功返回时,云盘并未立即从主机卸载,可通过接口[DescribeDisks](/document/product/362/16315)来查询对应云盘的状态,如果云盘的状态由“ATTACHED”变为“UNATTACHED”,则为卸载成功。 */ async DetachDisks( req: DetachDisksRequest, cb?: (error: string, rep: DetachDisksResponse) => void ): Promise<DetachDisksResponse> { return this.request("DetachDisks", req, cb) } /** * 本接口(InquiryPriceRenewDisks)用于续费云硬盘询价。 * 只支持查询预付费模式的弹性云盘续费价格。 * 支持与挂载实例一起续费的场景,需要在[DiskChargePrepaid](/document/product/362/15669#DiskChargePrepaid)参数中指定CurInstanceDeadline,此时会按对齐到实例续费后的到期时间来续费询价。 * 支持为多块云盘指定不同的续费时长,此时返回的价格为多块云盘续费的总价格。 */ async InquiryPriceRenewDisks( req: InquiryPriceRenewDisksRequest, cb?: (error: string, rep: InquiryPriceRenewDisksResponse) => void ): Promise<InquiryPriceRenewDisksResponse> { return this.request("InquiryPriceRenewDisks", req, cb) } }
the_stack
import sdk, { MediaObject, Camera, ScryptedInterface } from "@scrypted/sdk"; import { EventEmitter } from "stream"; import { HikVisionCameraAPI } from "./hikvision-camera-api"; import { Destroyable, UrlMediaStreamOptions, RtspProvider, RtspSmartCamera } from "../../rtsp/src/rtsp"; import { HikVisionCameraEvent } from "./hikvision-camera-api"; const { mediaManager } = sdk; class HikVisionCamera extends RtspSmartCamera implements Camera { hasCheckedCodec = false; channelIds: Promise<string[]>; client: HikVisionCameraAPI; listenEvents() { let motionTimeout: NodeJS.Timeout; const ret = new EventEmitter() as (EventEmitter & Destroyable); ret.destroy = () => { }; (async () => { const api = (this.provider as HikVisionProvider).createSharedClient(this.getHttpAddress(), this.getUsername(), this.getPassword()); try { const events = await api.listenEvents(); ret.destroy = () => { events.removeAllListeners(); }; let ignoreCameraNumber: boolean; events.on('close', () => ret.emit('error', new Error('close'))); events.on('error', e => ret.emit('error', e)); events.on('event', async (event: HikVisionCameraEvent, cameraNumber: string) => { if (event === HikVisionCameraEvent.MotionDetected || event === HikVisionCameraEvent.LineDetection || event === HikVisionCameraEvent.FieldDetection) { // check if the camera+channel field is in use, and filter events. if (this.getRtspChannel()) { // it is possible to set it up to use a camera number // on an nvr IP (which gives RTSP urls through the NVR), but then use a http port // that gives a filtered event stream from only that camera. // this this case, the camera numbers will not // match as they will be always be "1". // to detect that a camera specific endpoint is being used // can look at the channel ids, and see if that camera number is found. // this is different from the use case where the NVR or camera // is using a port other than 80 (the default). // could add a setting to have the user explicitly denote nvr usage // but that is error prone. const userCameraNumber = this.getCameraNumber(); if (ignoreCameraNumber === undefined && this.channelIds) { const channelIds = await this.channelIds; ignoreCameraNumber = true; for (const id of channelIds) { if (id.startsWith(userCameraNumber)) { ignoreCameraNumber = false; break; } } } if (!ignoreCameraNumber && cameraNumber !== userCameraNumber) { // this.console.error(`### Skipping motion event ${cameraNumber} != ${this.getCameraNumber()}`); return; } } // this.console.error('### Detected motion, camera: ', cameraNumber); this.motionDetected = true; clearTimeout(motionTimeout); motionTimeout = setTimeout(() => this.motionDetected = false, 30000); } }) } catch (e) { ret.emit('error', e); } })(); return ret; } createClient() { return new HikVisionCameraAPI(this.getHttpAddress(), this.getUsername(), this.getPassword(), this.console); } getClient() { if (!this.client) this.client = this.createClient(); (async () => { if (this.hasCheckedCodec) return; const streamSetup = await this.client.checkStreamSetup(this.getRtspChannel()); this.hasCheckedCodec = true; if (streamSetup.videoCodecType !== 'H.264') { this.log.a(`This camera is configured for ${streamSetup.videoCodecType} on the main channel. Configuring it it for H.264 is recommended for optimal performance.`); } if (!this.isAudioDisabled() && streamSetup.audioCodecType && streamSetup.audioCodecType !== 'AAC') { this.log.a(`This camera is configured for ${streamSetup.audioCodecType} on the main channel. Configuring it for AAC is recommended for optimal performance.`); } })(); return this.client; } async takeSmartCameraPicture(): Promise<MediaObject> { const api = this.getClient(); return mediaManager.createMediaObject(await api.jpegSnapshot(this.getRtspChannel()), 'image/jpeg'); } async getUrlSettings() { return [ { key: 'rtspChannel', title: 'Channel Number', description: "Optional: The channel number to use for snapshots. E.g., 101, 201, etc. The camera portion, e.g., 1, 2, etc, will be used to construct the RTSP stream.", placeholder: '101', value: this.storage.getItem('rtspChannel'), }, ...await super.getUrlSettings(), { key: 'rtspUrlParams', title: 'RTSP URL Parameters Override', description: "Optional: Override the RTSP URL parameters. E.g.: ?transportmode=unicast", placeholder: this.getRtspUrlParams(), value: this.storage.getItem('rtspUrlParams'), }, ] } getRtspChannel() { return this.storage.getItem('rtspChannel'); } getCameraNumber() { const channel = this.getRtspChannel(); // have users with more than 10 cameras. unsure if it is possible // to have more than 10 substreams... if (channel?.length > 3) return channel.substring(0, channel.length - 2); return channel?.substring(0, 1) || '1'; } getRtspUrlParams() { return this.storage.getItem('rtspUrlParams') || '?transportmode=unicast'; } async getConstructedVideoStreamOptions(): Promise<UrlMediaStreamOptions[]> { if (!this.channelIds) { const client = this.getClient(); this.channelIds = new Promise(async (resolve, reject) => { const isOld = await client.checkIsOldModel(); if (isOld) { this.console.error('Old NVR. Defaulting to two camera configuration'); const camNumber = this.getCameraNumber() || '1'; resolve([camNumber + '01', camNumber + '02']); } else try { const response = await client.digestAuth.request({ url: `http://${this.getHttpAddress()}/ISAPI/Streaming/channels`, responseType: 'text', }); const xml: string = response.data; const matches = xml.matchAll(/<id>(.*?)<\/id>/g); const ids = []; for (const m of matches) { ids.push(m[1]); } resolve(ids); } catch (e) { const cameraNumber = this.getCameraNumber() || '1'; this.console.error('error retrieving channel ids', e); resolve([cameraNumber + '01', cameraNumber + '02']); this.channelIds = undefined; } }) } const channelIds = await this.channelIds; const params = this.getRtspUrlParams() || '?transportmode=unicast'; // due to being able to override the channel number, and NVR providing per channel port access, // do not actually use these channel ids, and just use it to determine the number of channels // available for a camera. const ret = []; const cameraNumber = this.getCameraNumber() || '1'; for (let index = 0; index < channelIds.length; index++) { const channel = (index + 1).toString().padStart(2, '0'); const mso = this.createRtspMediaStreamOptions(`rtsp://${this.getRtspAddress()}/ISAPI/Streaming/channels/${cameraNumber}${channel}/${params}`, index); ret.push(mso); } return ret; } showRtspUrlOverride() { return false; } async putSetting(key: string, value: string) { this.client = undefined; this.channelIds = undefined; super.putSetting(key, value); } } class HikVisionProvider extends RtspProvider { clients: Map<string, HikVisionCameraAPI>; constructor() { super(); } getAdditionalInterfaces() { return [ ScryptedInterface.Camera, ScryptedInterface.MotionSensor, ]; } createSharedClient(address: string, username: string, password: string) { if (!this.clients) this.clients = new Map(); const key = `${address}#${username}#${password}`; const check = this.clients.get(key); if (check) return check; const client = new HikVisionCameraAPI(address, username, password, this.console); this.clients.set(key, client); return client; } createCamera(nativeId: string) { return new HikVisionCamera(nativeId, this); } } export default new HikVisionProvider();
the_stack
* @packageDocumentation * @module core/math */ import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { Mat3 } from './mat3'; import { Quat } from './quat'; import { IMat4Like, IVec3Like } from './type-define'; import { EPSILON } from './utils'; import { Vec3 } from './vec3'; import { legacyCC } from '../global-exports'; export const preTransforms = Object.freeze([ Object.freeze([1, 0, 0, 1]), // SurfaceTransform.IDENTITY Object.freeze([0, 1, -1, 0]), // SurfaceTransform.ROTATE_90 Object.freeze([-1, 0, 0, -1]), // SurfaceTransform.ROTATE_180 Object.freeze([0, -1, 1, 0]), // SurfaceTransform.ROTATE_270 ]); /** * @en Mathematical 4x4 matrix. * @zh 表示四维(4x4)矩阵。 */ export class Mat4 extends ValueType { public static IDENTITY = Object.freeze(new Mat4()); /** * @en Clone a matrix and save the results to out matrix * @zh 获得指定矩阵的拷贝 */ public static clone <Out extends IMat4Like> (a: Out) { return new Mat4( a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, a.m08, a.m09, a.m10, a.m11, a.m12, a.m13, a.m14, a.m15, ); } /** * @en Copy a matrix into the out matrix * @zh 复制目标矩阵 */ public static copy <Out extends IMat4Like> (out: Out, a: Out) { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; out.m03 = a.m03; out.m04 = a.m04; out.m05 = a.m05; out.m06 = a.m06; out.m07 = a.m07; out.m08 = a.m08; out.m09 = a.m09; out.m10 = a.m10; out.m11 = a.m11; out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; return out; } /** * @en Sets a matrix with the given values and save the results to out matrix * @zh 设置矩阵值 */ public static set <Out extends IMat4Like> ( out: Out, m00: number, m01: number, m02: number, m03: number, m10: number, m11: number, m12: number, m13: number, m20: number, m21: number, m22: number, m23: number, m30: number, m31: number, m32: number, m33: number, ) { out.m00 = m00; out.m01 = m01; out.m02 = m02; out.m03 = m03; out.m04 = m10; out.m05 = m11; out.m06 = m12; out.m07 = m13; out.m08 = m20; out.m09 = m21; out.m10 = m22; out.m11 = m23; out.m12 = m30; out.m13 = m31; out.m14 = m32; out.m15 = m33; return out; } /** * @en return an identity matrix. * @zh 将目标赋值为单位矩阵 */ public static identity <Out extends IMat4Like> (out: Out) { out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = 1; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = 1; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; } /** * @en Transposes a matrix and save the results to out matrix * @zh 转置矩阵 */ public static transpose <Out extends IMat4Like> (out: Out, a: Out) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a12 = a.m06; const a13 = a.m07; const a23 = a.m11; out.m01 = a.m04; out.m02 = a.m08; out.m03 = a.m12; out.m04 = a01; out.m06 = a.m09; out.m07 = a.m13; out.m08 = a02; out.m09 = a12; out.m11 = a.m14; out.m12 = a03; out.m13 = a13; out.m14 = a23; } else { out.m00 = a.m00; out.m01 = a.m04; out.m02 = a.m08; out.m03 = a.m12; out.m04 = a.m01; out.m05 = a.m05; out.m06 = a.m09; out.m07 = a.m13; out.m08 = a.m02; out.m09 = a.m06; out.m10 = a.m10; out.m11 = a.m14; out.m12 = a.m03; out.m13 = a.m07; out.m14 = a.m11; out.m15 = a.m15; } return out; } /** * @en Inverts a matrix. When matrix is not invertible the matrix will be set to zeros. * @zh 矩阵求逆,注意,在矩阵不可逆时,会返回一个全为 0 的矩阵。 */ public static invert <Out extends IMat4Like> (out: Out, a: Out) { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; const a30 = a.m12; const a31 = a.m13; const a32 = a.m14; const a33 = a.m15; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; const b02 = a00 * a13 - a03 * a10; const b03 = a01 * a12 - a02 * a11; const b04 = a01 * a13 - a03 * a11; const b05 = a02 * a13 - a03 * a12; const b06 = a20 * a31 - a21 * a30; const b07 = a20 * a32 - a22 * a30; const b08 = a20 * a33 - a23 * a30; const b09 = a21 * a32 - a22 * a31; const b10 = a21 * a33 - a23 * a31; const b11 = a22 * a33 - a23 * a32; // Calculate the determinant let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (det === 0) { out.m00 = 0; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = 0; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = 0; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 0; return out; } det = 1.0 / det; out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; out.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det; out.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det; out.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det; out.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det; out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; out.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det; out.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det; out.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det; out.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det; out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; out.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det; out.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det; out.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det; out.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det; out.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det; return out; } /** * @en Calculates the determinant of a matrix * @zh 矩阵行列式 */ public static determinant <Out extends IMat4Like> (a: Out): number { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; const a30 = a.m12; const a31 = a.m13; const a32 = a.m14; const a33 = a.m15; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; const b02 = a00 * a13 - a03 * a10; const b03 = a01 * a12 - a02 * a11; const b04 = a01 * a13 - a03 * a11; const b05 = a02 * a13 - a03 * a12; const b06 = a20 * a31 - a21 * a30; const b07 = a20 * a32 - a22 * a30; const b08 = a20 * a33 - a23 * a30; const b09 = a21 * a32 - a22 * a31; const b10 = a21 * a33 - a23 * a31; const b11 = a22 * a33 - a23 * a32; // Calculate the determinant return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; } /** * @en Multiply two matrices and save the results to out matrix * @zh 矩阵乘法 */ public static multiply <Out extends IMat4Like> (out: Out, a: Out, b: Out) { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; const a30 = a.m12; const a31 = a.m13; const a32 = a.m14; const a33 = a.m15; // Cache only the current line of the second matrix let b0 = b.m00; let b1 = b.m01; let b2 = b.m02; let b3 = b.m03; out.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b.m04; b1 = b.m05; b2 = b.m06; b3 = b.m07; out.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b.m08; b1 = b.m09; b2 = b.m10; b3 = b.m11; out.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = b.m12; b1 = b.m13; b2 = b.m14; b3 = b.m15; out.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; out.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; out.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; out.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; return out; } /** * @en Transform a matrix with the given vector and save results to the out matrix * @zh 在给定矩阵变换基础上加入变换 */ public static transform <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, a: Out, v: VecLike) { const x = v.x; const y = v.y; const z = v.z; if (a === out) { out.m12 = a.m00 * x + a.m04 * y + a.m08 * z + a.m12; out.m13 = a.m01 * x + a.m05 * y + a.m09 * z + a.m13; out.m14 = a.m02 * x + a.m06 * y + a.m10 * z + a.m14; out.m15 = a.m03 * x + a.m07 * y + a.m11 * z + a.m15; } else { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; const a30 = a.m12; const a31 = a.m13; const a32 = a.m14; const a33 = a.m15; out.m00 = a00; out.m01 = a01; out.m02 = a02; out.m03 = a03; out.m04 = a10; out.m05 = a11; out.m06 = a12; out.m07 = a13; out.m08 = a20; out.m09 = a21; out.m10 = a22; out.m11 = a23; out.m12 = a00 * x + a10 * y + a20 * z + a.m12; out.m13 = a01 * x + a11 * y + a21 * z + a.m13; out.m14 = a02 * x + a12 * y + a22 * z + a.m14; out.m15 = a03 * x + a13 * y + a23 * z + a.m15; } return out; } /** * @en Transform a matrix with the given translation vector and save results to the out matrix * @zh 在给定矩阵变换基础上加入新位移变换 */ public static translate <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, a: Out, v: VecLike) { console.warn('function changed'); if (a === out) { out.m12 += v.x; out.m13 += v.y; out.m14 += v.z; } else { out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; out.m03 = a.m03; out.m04 = a.m04; out.m05 = a.m05; out.m06 = a.m06; out.m07 = a.m07; out.m08 = a.m08; out.m09 = a.m09; out.m10 = a.m10; out.m11 = a.m11; out.m12 += v.x; out.m13 += v.y; out.m14 += v.z; out.m15 = a.m15; } return out; } /** * @en Multiply a matrix with a scale matrix given by a scale vector and save the results into the out matrix * @zh 在给定矩阵变换基础上加入新缩放变换 */ public static scale <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, a: Out, v: VecLike) { const x = v.x; const y = v.y; const z = v.z; out.m00 = a.m00 * x; out.m01 = a.m01 * x; out.m02 = a.m02 * x; out.m03 = a.m03 * x; out.m04 = a.m04 * y; out.m05 = a.m05 * y; out.m06 = a.m06 * y; out.m07 = a.m07 * y; out.m08 = a.m08 * z; out.m09 = a.m09 * z; out.m10 = a.m10 * z; out.m11 = a.m11 * z; out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; return out; } /** * @en Rotates the transform by the given angle and save the results into the out matrix * @zh 在给定矩阵变换基础上加入新旋转变换 * @param rad Angle of rotation (in radians) * @param axis axis of rotation */ public static rotate <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, a: Out, rad: number, axis: VecLike) { let x = axis.x; let y = axis.y; let z = axis.z; let len = Math.sqrt(x * x + y * y + z * z); if (Math.abs(len) < EPSILON) { return null; } len = 1 / len; x *= len; y *= len; z *= len; const s = Math.sin(rad); const c = Math.cos(rad); const t = 1 - c; const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; // Construct the elements of the rotation matrix const b00 = x * x * t + c; const b01 = y * x * t + z * s; const b02 = z * x * t - y * s; const b10 = x * y * t - z * s; const b11 = y * y * t + c; const b12 = z * y * t + x * s; const b20 = x * z * t + y * s; const b21 = y * z * t - x * s; const b22 = z * z * t + c; // Perform rotation-specific matrix multiplication out.m00 = a00 * b00 + a10 * b01 + a20 * b02; out.m01 = a01 * b00 + a11 * b01 + a21 * b02; out.m02 = a02 * b00 + a12 * b01 + a22 * b02; out.m03 = a03 * b00 + a13 * b01 + a23 * b02; out.m04 = a00 * b10 + a10 * b11 + a20 * b12; out.m05 = a01 * b10 + a11 * b11 + a21 * b12; out.m06 = a02 * b10 + a12 * b11 + a22 * b12; out.m07 = a03 * b10 + a13 * b11 + a23 * b12; out.m08 = a00 * b20 + a10 * b21 + a20 * b22; out.m09 = a01 * b20 + a11 * b21 + a21 * b22; out.m10 = a02 * b20 + a12 * b21 + a22 * b22; out.m11 = a03 * b20 + a13 * b21 + a23 * b22; // If the source and destination differ, copy the unchanged last row if (a !== out) { out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; } return out; } /** * @en Transform a matrix with a given angle around X axis and save the results to the out matrix * @zh 在给定矩阵变换基础上加入绕 X 轴的旋转变换 * @param rad Angle of rotation (in radians) */ public static rotateX <Out extends IMat4Like> (out: Out, a: Out, rad: number) { const s = Math.sin(rad); const c = Math.cos(rad); const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; if (a !== out) { // If the source and destination differ, copy the unchanged rows out.m00 = a.m00; out.m01 = a.m01; out.m02 = a.m02; out.m03 = a.m03; out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; } // Perform axis-specific matrix multiplication out.m04 = a10 * c + a20 * s; out.m05 = a11 * c + a21 * s; out.m06 = a12 * c + a22 * s; out.m07 = a13 * c + a23 * s; out.m08 = a20 * c - a10 * s; out.m09 = a21 * c - a11 * s; out.m10 = a22 * c - a12 * s; out.m11 = a23 * c - a13 * s; return out; } /** * @en Transform a matrix with a given angle around Y axis and save the results to the out matrix * @zh 在给定矩阵变换基础上加入绕 Y 轴的旋转变换 * @param rad Angle of rotation (in radians) */ public static rotateY <Out extends IMat4Like> (out: Out, a: Out, rad: number) { const s = Math.sin(rad); const c = Math.cos(rad); const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; if (a !== out) { // If the source and destination differ, copy the unchanged rows out.m04 = a.m04; out.m05 = a.m05; out.m06 = a.m06; out.m07 = a.m07; out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; } // Perform axis-specific matrix multiplication out.m00 = a00 * c - a20 * s; out.m01 = a01 * c - a21 * s; out.m02 = a02 * c - a22 * s; out.m03 = a03 * c - a23 * s; out.m08 = a00 * s + a20 * c; out.m09 = a01 * s + a21 * c; out.m10 = a02 * s + a22 * c; out.m11 = a03 * s + a23 * c; return out; } /** * @en Transform a matrix with a given angle around Z axis and save the results to the out matrix * @zh 在给定矩阵变换基础上加入绕 Z 轴的旋转变换 * @param rad Angle of rotation (in radians) */ public static rotateZ <Out extends IMat4Like> (out: Out, a: Out, rad: number) { const s = Math.sin(rad); const c = Math.cos(rad); const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; // If the source and destination differ, copy the unchanged last row if (a !== out) { out.m08 = a.m08; out.m09 = a.m09; out.m10 = a.m10; out.m11 = a.m11; out.m12 = a.m12; out.m13 = a.m13; out.m14 = a.m14; out.m15 = a.m15; } // Perform axis-specific matrix multiplication out.m00 = a00 * c + a10 * s; out.m01 = a01 * c + a11 * s; out.m02 = a02 * c + a12 * s; out.m03 = a03 * c + a13 * s; out.m04 = a10 * c - a00 * s; out.m05 = a11 * c - a01 * s; out.m06 = a12 * c - a02 * s; out.m07 = a13 * c - a03 * s; return out; } /** * @en Sets the out matrix with a translation vector * @zh 计算位移矩阵 */ public static fromTranslation <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, v: VecLike) { out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = 1; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = 1; out.m11 = 0; out.m12 = v.x; out.m13 = v.y; out.m14 = v.z; out.m15 = 1; return out; } /** * @en Sets the out matrix with a scale vector * @zh 计算缩放矩阵 */ public static fromScaling <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, v: VecLike) { out.m00 = v.x; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = v.y; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = v.z; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; } /** * @en Sets the out matrix with rotation angle * @zh 计算旋转矩阵 */ public static fromRotation <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, rad: number, axis: VecLike) { let x = axis.x; let y = axis.y; let z = axis.z; let len = Math.sqrt(x * x + y * y + z * z); if (Math.abs(len) < EPSILON) { return null; } len = 1 / len; x *= len; y *= len; z *= len; const s = Math.sin(rad); const c = Math.cos(rad); const t = 1 - c; // Perform rotation-specific matrix multiplication out.m00 = x * x * t + c; out.m01 = y * x * t + z * s; out.m02 = z * x * t - y * s; out.m03 = 0; out.m04 = x * y * t - z * s; out.m05 = y * y * t + c; out.m06 = z * y * t + x * s; out.m07 = 0; out.m08 = x * z * t + y * s; out.m09 = y * z * t - x * s; out.m10 = z * z * t + c; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; } /** * @en Calculates the matrix representing a rotation around the X axis * @zh 计算绕 X 轴的旋转矩阵 */ public static fromXRotation <Out extends IMat4Like> (out: Out, rad: number) { const s = Math.sin(rad); const c = Math.cos(rad); // Perform axis-specific matrix multiplication out.m00 = 1; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = c; out.m06 = s; out.m07 = 0; out.m08 = 0; out.m09 = -s; out.m10 = c; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; } /** * @en Calculates the matrix representing a rotation around the Y axis * @zh 计算绕 Y 轴的旋转矩阵 */ public static fromYRotation <Out extends IMat4Like> (out: Out, rad: number) { const s = Math.sin(rad); const c = Math.cos(rad); // Perform axis-specific matrix multiplication out.m00 = c; out.m01 = 0; out.m02 = -s; out.m03 = 0; out.m04 = 0; out.m05 = 1; out.m06 = 0; out.m07 = 0; out.m08 = s; out.m09 = 0; out.m10 = c; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; } /** * @en Calculates the matrix representing a rotation around the Z axis * @zh 计算绕 Z 轴的旋转矩阵 */ public static fromZRotation <Out extends IMat4Like> (out: Out, rad: number) { const s = Math.sin(rad); const c = Math.cos(rad); // Perform axis-specific matrix multiplication out.m00 = c; out.m01 = s; out.m02 = 0; out.m03 = 0; out.m04 = -s; out.m05 = c; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = 1; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; } /** * @en Calculates the transform representing the combination of a rotation and a translation * @zh 根据旋转和位移信息计算矩阵 */ public static fromRT <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, q: Quat, v: VecLike) { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; const z2 = z + z; const xx = x * x2; const xy = x * y2; const xz = x * z2; const yy = y * y2; const yz = y * z2; const zz = z * z2; const wx = w * x2; const wy = w * y2; const wz = w * z2; out.m00 = 1 - (yy + zz); out.m01 = xy + wz; out.m02 = xz - wy; out.m03 = 0; out.m04 = xy - wz; out.m05 = 1 - (xx + zz); out.m06 = yz + wx; out.m07 = 0; out.m08 = xz + wy; out.m09 = yz - wx; out.m10 = 1 - (xx + yy); out.m11 = 0; out.m12 = v.x; out.m13 = v.y; out.m14 = v.z; out.m15 = 1; return out; } /** * @en Extracts the translation from the matrix, assuming it's composed in order of scale, rotation, translation * @zh 提取矩阵的位移信息, 默认矩阵中的变换以 S->R->T 的顺序应用 */ public static getTranslation <Out extends IMat4Like, VecLike extends IVec3Like> (out: VecLike, mat: Out) { out.x = mat.m12; out.y = mat.m13; out.z = mat.m14; return out; } /** * @en Extracts the scale vector from the matrix, assuming it's composed in order of scale, rotation, translation * @zh 提取矩阵的缩放信息, 默认矩阵中的变换以 S->R->T 的顺序应用 */ public static getScaling <Out extends IMat4Like, VecLike extends IVec3Like> (out: VecLike, mat: Out) { const m00 = m3_1.m00 = mat.m00; const m01 = m3_1.m01 = mat.m01; const m02 = m3_1.m02 = mat.m02; const m04 = m3_1.m03 = mat.m04; const m05 = m3_1.m04 = mat.m05; const m06 = m3_1.m05 = mat.m06; const m08 = m3_1.m06 = mat.m08; const m09 = m3_1.m07 = mat.m09; const m10 = m3_1.m08 = mat.m10; out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06); out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10); // account for refections if (Mat3.determinant(m3_1) < 0) { out.x *= -1; } return out; } /** * @en Extracts the rotation from the matrix, assuming it's composed in order of scale, rotation, translation * @zh 提取矩阵的旋转信息, 默认输入矩阵不含有缩放信息,如考虑缩放应使用 `toRTS` 函数。 */ public static getRotation <Out extends IMat4Like> (out: Quat, mat: Out) { const trace = mat.m00 + mat.m05 + mat.m10; let S = 0; if (trace > 0) { S = Math.sqrt(trace + 1.0) * 2; out.w = 0.25 * S; out.x = (mat.m06 - mat.m09) / S; out.y = (mat.m08 - mat.m02) / S; out.z = (mat.m01 - mat.m04) / S; } else if ((mat.m00 > mat.m05) && (mat.m00 > mat.m10)) { S = Math.sqrt(1.0 + mat.m00 - mat.m05 - mat.m10) * 2; out.w = (mat.m06 - mat.m09) / S; out.x = 0.25 * S; out.y = (mat.m01 + mat.m04) / S; out.z = (mat.m08 + mat.m02) / S; } else if (mat.m05 > mat.m10) { S = Math.sqrt(1.0 + mat.m05 - mat.m00 - mat.m10) * 2; out.w = (mat.m08 - mat.m02) / S; out.x = (mat.m01 + mat.m04) / S; out.y = 0.25 * S; out.z = (mat.m06 + mat.m09) / S; } else { S = Math.sqrt(1.0 + mat.m10 - mat.m00 - mat.m05) * 2; out.w = (mat.m01 - mat.m04) / S; out.x = (mat.m08 + mat.m02) / S; out.y = (mat.m06 + mat.m09) / S; out.z = 0.25 * S; } return out; } /** * @en Extracts the scale, rotation and translation from the matrix, assuming it's composed in order of scale, rotation, translation * @zh 提取旋转、位移、缩放信息, 默认矩阵中的变换以 S->R->T 的顺序应用 */ public static toRTS <Out extends IMat4Like, VecLike extends IVec3Like> (m: Out, q: Quat, v: VecLike, s: VecLike) { s.x = Vec3.set(v3_1, m.m00, m.m01, m.m02).length(); m3_1.m00 = m.m00 / s.x; m3_1.m01 = m.m01 / s.x; m3_1.m02 = m.m02 / s.x; s.y = Vec3.set(v3_1, m.m04, m.m05, m.m06).length(); m3_1.m03 = m.m04 / s.y; m3_1.m04 = m.m05 / s.y; m3_1.m05 = m.m06 / s.y; s.z = Vec3.set(v3_1, m.m08, m.m09, m.m10).length(); m3_1.m06 = m.m08 / s.z; m3_1.m07 = m.m09 / s.z; m3_1.m08 = m.m10 / s.z; const det = Mat3.determinant(m3_1); if (det < 0) { s.x *= -1; m3_1.m00 *= -1; m3_1.m01 *= -1; m3_1.m02 *= -1; } Quat.fromMat3(q, m3_1); // already normalized Vec3.set(v, m.m12, m.m13, m.m14); } /** * @en Compose a matrix from scale, rotation and translation, applied in order. * @zh 根据旋转、位移、缩放信息计算矩阵,以 S->R->T 的顺序应用 */ public static fromRTS <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, q: Quat, v: VecLike, s: VecLike) { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; const z2 = z + z; const xx = x * x2; const xy = x * y2; const xz = x * z2; const yy = y * y2; const yz = y * z2; const zz = z * z2; const wx = w * x2; const wy = w * y2; const wz = w * z2; const sx = s.x; const sy = s.y; const sz = s.z; out.m00 = (1 - (yy + zz)) * sx; out.m01 = (xy + wz) * sx; out.m02 = (xz - wy) * sx; out.m03 = 0; out.m04 = (xy - wz) * sy; out.m05 = (1 - (xx + zz)) * sy; out.m06 = (yz + wx) * sy; out.m07 = 0; out.m08 = (xz + wy) * sz; out.m09 = (yz - wx) * sz; out.m10 = (1 - (xx + yy)) * sz; out.m11 = 0; out.m12 = v.x; out.m13 = v.y; out.m14 = v.z; out.m15 = 1; return out; } /** * @en Compose a matrix from scale, rotation and translation, applied in order, from a given origin * @zh 根据指定的旋转、位移、缩放及变换中心信息计算矩阵,以 S->R->T 的顺序应用 * @param q Rotation quaternion * @param v Translation vector * @param s Scaling vector * @param o transformation Center */ public static fromRTSOrigin <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, q: Quat, v: VecLike, s: VecLike, o: VecLike) { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; const z2 = z + z; const xx = x * x2; const xy = x * y2; const xz = x * z2; const yy = y * y2; const yz = y * z2; const zz = z * z2; const wx = w * x2; const wy = w * y2; const wz = w * z2; const sx = s.x; const sy = s.y; const sz = s.z; const ox = o.x; const oy = o.y; const oz = o.z; out.m00 = (1 - (yy + zz)) * sx; out.m01 = (xy + wz) * sx; out.m02 = (xz - wy) * sx; out.m03 = 0; out.m04 = (xy - wz) * sy; out.m05 = (1 - (xx + zz)) * sy; out.m06 = (yz + wx) * sy; out.m07 = 0; out.m08 = (xz + wy) * sz; out.m09 = (yz - wx) * sz; out.m10 = (1 - (xx + yy)) * sz; out.m11 = 0; out.m12 = v.x + ox - (out.m00 * ox + out.m04 * oy + out.m08 * oz); out.m13 = v.y + oy - (out.m01 * ox + out.m05 * oy + out.m09 * oz); out.m14 = v.z + oz - (out.m02 * ox + out.m06 * oy + out.m10 * oz); out.m15 = 1; return out; } /** * @en Sets the out matrix with the given quaternion * @zh 根据指定的旋转信息计算矩阵 */ public static fromQuat <Out extends IMat4Like> (out: Out, q: Quat) { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; const z2 = z + z; const xx = x * x2; const yx = y * x2; const yy = y * y2; const zx = z * x2; const zy = z * y2; const zz = z * z2; const wx = w * x2; const wy = w * y2; const wz = w * z2; out.m00 = 1 - yy - zz; out.m01 = yx + wz; out.m02 = zx - wy; out.m03 = 0; out.m04 = yx - wz; out.m05 = 1 - xx - zz; out.m06 = zy + wx; out.m07 = 0; out.m08 = zx + wy; out.m09 = zy - wx; out.m10 = 1 - xx - yy; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; } /** * @en Calculates the matrix representing the given frustum * @zh 根据指定的视锥体信息计算矩阵 * @param left The X coordinate of the left side of the near projection plane in view space. * @param right The X coordinate of the right side of the near projection plane in view space. * @param bottom The Y coordinate of the bottom side of the near projection plane in view space. * @param top The Y coordinate of the top side of the near projection plane in view space. * @param near Z distance to the near plane from the origin in view space. * @param far Z distance to the far plane from the origin in view space. */ public static frustum <Out extends IMat4Like> (out: Out, left: number, right: number, bottom: number, top: number, near: number, far: number) { const rl = 1 / (right - left); const tb = 1 / (top - bottom); const nf = 1 / (near - far); out.m00 = (near * 2) * rl; out.m01 = 0; out.m02 = 0; out.m03 = 0; out.m04 = 0; out.m05 = (near * 2) * tb; out.m06 = 0; out.m07 = 0; out.m08 = (right + left) * rl; out.m09 = (top + bottom) * tb; out.m10 = (far + near) * nf; out.m11 = -1; out.m12 = 0; out.m13 = 0; out.m14 = (far * near * 2) * nf; out.m15 = 0; return out; } /** * @en Calculates perspective projection matrix * @zh 计算透视投影矩阵 * @param fovy Vertical field-of-view in degrees. * @param aspect Aspect ratio * @param near Near depth clipping plane value. * @param far Far depth clipping plane value. */ public static perspective <Out extends IMat4Like> ( out: Out, fov: number, aspect: number, near: number, far: number, isFOVY = true, minClipZ = -1, projectionSignY = 1, orientation = 0, ) { const f = 1.0 / Math.tan(fov / 2); const nf = 1 / (near - far); const x = isFOVY ? f / aspect : f; const y = (isFOVY ? f : f * aspect) * projectionSignY; const preTransform = preTransforms[orientation]; out.m00 = x * preTransform[0]; out.m01 = x * preTransform[1]; out.m02 = 0; out.m03 = 0; out.m04 = y * preTransform[2]; out.m05 = y * preTransform[3]; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = (far - minClipZ * near) * nf; out.m11 = -1; out.m12 = 0; out.m13 = 0; out.m14 = far * near * nf * (1 - minClipZ); out.m15 = 0; return out; } /** * @en Calculates orthogonal projection matrix * @zh 计算正交投影矩阵 * @param left Left-side x-coordinate. * @param right Right-side x-coordinate. * @param bottom Bottom y-coordinate. * @param top Top y-coordinate. * @param near Near depth clipping plane value. * @param far Far depth clipping plane value. */ public static ortho <Out extends IMat4Like> ( out: Out, left: number, right: number, bottom: number, top: number, near: number, far: number, minClipZ = -1, projectionSignY = 1, orientation = 0, ) { const lr = 1 / (left - right); const bt = 1 / (bottom - top) * projectionSignY; const nf = 1 / (near - far); const x = -2 * lr; const y = -2 * bt; const dx = (left + right) * lr; const dy = (top + bottom) * bt; const preTransform = preTransforms[orientation]; out.m00 = x * preTransform[0]; out.m01 = x * preTransform[1]; out.m02 = 0; out.m03 = 0; out.m04 = y * preTransform[2]; out.m05 = y * preTransform[3]; out.m06 = 0; out.m07 = 0; out.m08 = 0; out.m09 = 0; out.m10 = nf * (1 - minClipZ); out.m11 = 0; out.m12 = dx * preTransform[0] + dy * preTransform[2]; out.m13 = dx * preTransform[1] + dy * preTransform[3]; out.m14 = (near - minClipZ * far) * nf; out.m15 = 1; return out; } /** * @en * Calculates the matrix with the view point information, given by eye position, target center and the up vector. * Note that center to eye vector can't be zero or parallel to the up vector * @zh * 根据视点计算矩阵,注意 `eye - center` 不能为零向量或与 `up` 向量平行 * @param eye The source point. * @param center The target point. * @param up The vector describing the up direction. */ public static lookAt <Out extends IMat4Like, VecLike extends IVec3Like> (out: Out, eye: VecLike, center: VecLike, up: VecLike) { const eyex = eye.x; const eyey = eye.y; const eyez = eye.z; const upx = up.x; const upy = up.y; const upz = up.z; const centerx = center.x; const centery = center.y; const centerz = center.z; let z0 = eyex - centerx; let z1 = eyey - centery; let z2 = eyez - centerz; let len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); z0 *= len; z1 *= len; z2 *= len; let x0 = upy * z2 - upz * z1; let x1 = upz * z0 - upx * z2; let x2 = upx * z1 - upy * z0; len = 1 / Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); x0 *= len; x1 *= len; x2 *= len; const y0 = z1 * x2 - z2 * x1; const y1 = z2 * x0 - z0 * x2; const y2 = z0 * x1 - z1 * x0; out.m00 = x0; out.m01 = y0; out.m02 = z0; out.m03 = 0; out.m04 = x1; out.m05 = y1; out.m06 = z1; out.m07 = 0; out.m08 = x2; out.m09 = y2; out.m10 = z2; out.m11 = 0; out.m12 = -(x0 * eyex + x1 * eyey + x2 * eyez); out.m13 = -(y0 * eyex + y1 * eyey + y2 * eyez); out.m14 = -(z0 * eyex + z1 * eyey + z2 * eyez); out.m15 = 1; return out; } /** * @en Calculates the inverse transpose of a matrix and save the results to out matrix * @zh 计算逆转置矩阵 */ public static inverseTranspose <Out extends IMat4Like> (out: Out, a: Out) { const a00 = a.m00; const a01 = a.m01; const a02 = a.m02; const a03 = a.m03; const a10 = a.m04; const a11 = a.m05; const a12 = a.m06; const a13 = a.m07; const a20 = a.m08; const a21 = a.m09; const a22 = a.m10; const a23 = a.m11; const a30 = a.m12; const a31 = a.m13; const a32 = a.m14; const a33 = a.m15; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; const b02 = a00 * a13 - a03 * a10; const b03 = a01 * a12 - a02 * a11; const b04 = a01 * a13 - a03 * a11; const b05 = a02 * a13 - a03 * a12; const b06 = a20 * a31 - a21 * a30; const b07 = a20 * a32 - a22 * a30; const b08 = a20 * a33 - a23 * a30; const b09 = a21 * a32 - a22 * a31; const b10 = a21 * a33 - a23 * a31; const b11 = a22 * a33 - a23 * a32; // Calculate the determinant let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { return null; } det = 1.0 / det; out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det; out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det; out.m03 = 0; out.m04 = (a02 * b10 - a01 * b11 - a03 * b09) * det; out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; out.m06 = (a01 * b08 - a00 * b10 - a03 * b06) * det; out.m07 = 0; out.m08 = (a31 * b05 - a32 * b04 + a33 * b03) * det; out.m09 = (a32 * b02 - a30 * b05 - a33 * b01) * det; out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; out.m11 = 0; out.m12 = 0; out.m13 = 0; out.m14 = 0; out.m15 = 1; return out; } /** * @en Transform a matrix object to a flat array * @zh 矩阵转数组 * @param ofs Array Start Offset */ public static toArray <Out extends IWritableArrayLike<number>> (out: Out, m: IMat4Like, ofs = 0) { out[ofs + 0] = m.m00; out[ofs + 1] = m.m01; out[ofs + 2] = m.m02; out[ofs + 3] = m.m03; out[ofs + 4] = m.m04; out[ofs + 5] = m.m05; out[ofs + 6] = m.m06; out[ofs + 7] = m.m07; out[ofs + 8] = m.m08; out[ofs + 9] = m.m09; out[ofs + 10] = m.m10; out[ofs + 11] = m.m11; out[ofs + 12] = m.m12; out[ofs + 13] = m.m13; out[ofs + 14] = m.m14; out[ofs + 15] = m.m15; return out; } /** * @en Generates or sets a matrix with a flat array * @zh 数组转矩阵 * @param ofs Array Start Offset */ public static fromArray <Out extends IMat4Like> (out: Out, arr: IWritableArrayLike<number>, ofs = 0) { out.m00 = arr[ofs + 0]; out.m01 = arr[ofs + 1]; out.m02 = arr[ofs + 2]; out.m03 = arr[ofs + 3]; out.m04 = arr[ofs + 4]; out.m05 = arr[ofs + 5]; out.m06 = arr[ofs + 6]; out.m07 = arr[ofs + 7]; out.m08 = arr[ofs + 8]; out.m09 = arr[ofs + 9]; out.m10 = arr[ofs + 10]; out.m11 = arr[ofs + 11]; out.m12 = arr[ofs + 12]; out.m13 = arr[ofs + 13]; out.m14 = arr[ofs + 14]; out.m15 = arr[ofs + 15]; return out; } /** * @en Adds two matrices and save the results to out matrix * @zh 逐元素矩阵加法 */ public static add <Out extends IMat4Like> (out: Out, a: Out, b: Out) { out.m00 = a.m00 + b.m00; out.m01 = a.m01 + b.m01; out.m02 = a.m02 + b.m02; out.m03 = a.m03 + b.m03; out.m04 = a.m04 + b.m04; out.m05 = a.m05 + b.m05; out.m06 = a.m06 + b.m06; out.m07 = a.m07 + b.m07; out.m08 = a.m08 + b.m08; out.m09 = a.m09 + b.m09; out.m10 = a.m10 + b.m10; out.m11 = a.m11 + b.m11; out.m12 = a.m12 + b.m12; out.m13 = a.m13 + b.m13; out.m14 = a.m14 + b.m14; out.m15 = a.m15 + b.m15; return out; } /** * @en Subtracts matrix b from matrix a and save the results to out matrix * @zh 逐元素矩阵减法 */ public static subtract <Out extends IMat4Like> (out: Out, a: Out, b: Out) { out.m00 = a.m00 - b.m00; out.m01 = a.m01 - b.m01; out.m02 = a.m02 - b.m02; out.m03 = a.m03 - b.m03; out.m04 = a.m04 - b.m04; out.m05 = a.m05 - b.m05; out.m06 = a.m06 - b.m06; out.m07 = a.m07 - b.m07; out.m08 = a.m08 - b.m08; out.m09 = a.m09 - b.m09; out.m10 = a.m10 - b.m10; out.m11 = a.m11 - b.m11; out.m12 = a.m12 - b.m12; out.m13 = a.m13 - b.m13; out.m14 = a.m14 - b.m14; out.m15 = a.m15 - b.m15; return out; } /** * @en Multiply each element of a matrix by a scalar number and save the results to out matrix * @zh 矩阵标量乘法 */ public static multiplyScalar <Out extends IMat4Like> (out: Out, a: Out, b: number) { out.m00 = a.m00 * b; out.m01 = a.m01 * b; out.m02 = a.m02 * b; out.m03 = a.m03 * b; out.m04 = a.m04 * b; out.m05 = a.m05 * b; out.m06 = a.m06 * b; out.m07 = a.m07 * b; out.m08 = a.m08 * b; out.m09 = a.m09 * b; out.m10 = a.m10 * b; out.m11 = a.m11 * b; out.m12 = a.m12 * b; out.m13 = a.m13 * b; out.m14 = a.m14 * b; out.m15 = a.m15 * b; return out; } /** * @en Adds two matrices after multiplying each element of the second operand by a scalar number. And save the results to out matrix. * @zh 逐元素矩阵标量乘加: A + B * scale */ public static multiplyScalarAndAdd <Out extends IMat4Like> (out: Out, a: Out, b: Out, scale: number) { out.m00 = a.m00 + (b.m00 * scale); out.m01 = a.m01 + (b.m01 * scale); out.m02 = a.m02 + (b.m02 * scale); out.m03 = a.m03 + (b.m03 * scale); out.m04 = a.m04 + (b.m04 * scale); out.m05 = a.m05 + (b.m05 * scale); out.m06 = a.m06 + (b.m06 * scale); out.m07 = a.m07 + (b.m07 * scale); out.m08 = a.m08 + (b.m08 * scale); out.m09 = a.m09 + (b.m09 * scale); out.m10 = a.m10 + (b.m10 * scale); out.m11 = a.m11 + (b.m11 * scale); out.m12 = a.m12 + (b.m12 * scale); out.m13 = a.m13 + (b.m13 * scale); out.m14 = a.m14 + (b.m14 * scale); out.m15 = a.m15 + (b.m15 * scale); return out; } /** * @en Returns whether the specified matrices are equal. * @zh 矩阵等价判断 */ public static strictEquals <Out extends IMat4Like> (a: Out, b: Out) { return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08 && a.m09 === b.m09 && a.m10 === b.m10 && a.m11 === b.m11 && a.m12 === b.m12 && a.m13 === b.m13 && a.m14 === b.m14 && a.m15 === b.m15; } /** * @en Returns whether the specified matrices are approximately equal. * @zh 排除浮点数误差的矩阵近似等价判断 */ public static equals <Out extends IMat4Like> (a: Out, b: Out, epsilon = EPSILON) { // TAOCP vol.2, 3rd ed., s.4.2.4, p.213-225 // defines a 'close enough' relationship between u and v that scales for magnitude return ( Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) && Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) && Math.abs(a.m02 - b.m02) <= epsilon * Math.max(1.0, Math.abs(a.m02), Math.abs(b.m02)) && Math.abs(a.m03 - b.m03) <= epsilon * Math.max(1.0, Math.abs(a.m03), Math.abs(b.m03)) && Math.abs(a.m04 - b.m04) <= epsilon * Math.max(1.0, Math.abs(a.m04), Math.abs(b.m04)) && Math.abs(a.m05 - b.m05) <= epsilon * Math.max(1.0, Math.abs(a.m05), Math.abs(b.m05)) && Math.abs(a.m06 - b.m06) <= epsilon * Math.max(1.0, Math.abs(a.m06), Math.abs(b.m06)) && Math.abs(a.m07 - b.m07) <= epsilon * Math.max(1.0, Math.abs(a.m07), Math.abs(b.m07)) && Math.abs(a.m08 - b.m08) <= epsilon * Math.max(1.0, Math.abs(a.m08), Math.abs(b.m08)) && Math.abs(a.m09 - b.m09) <= epsilon * Math.max(1.0, Math.abs(a.m09), Math.abs(b.m09)) && Math.abs(a.m10 - b.m10) <= epsilon * Math.max(1.0, Math.abs(a.m10), Math.abs(b.m10)) && Math.abs(a.m11 - b.m11) <= epsilon * Math.max(1.0, Math.abs(a.m11), Math.abs(b.m11)) && Math.abs(a.m12 - b.m12) <= epsilon * Math.max(1.0, Math.abs(a.m12), Math.abs(b.m12)) && Math.abs(a.m13 - b.m13) <= epsilon * Math.max(1.0, Math.abs(a.m13), Math.abs(b.m13)) && Math.abs(a.m14 - b.m14) <= epsilon * Math.max(1.0, Math.abs(a.m14), Math.abs(b.m14)) && Math.abs(a.m15 - b.m15) <= epsilon * Math.max(1.0, Math.abs(a.m15), Math.abs(b.m15)) ); } /** * @en Value at column 0 row 0 of the matrix. * @zh 矩阵第 0 列第 0 行的元素。 */ public m00: number; /** * @en Value at column 0 row 1 of the matrix. * @zh 矩阵第 0 列第 1 行的元素。 */ public m01: number; /** * @en Value at column 0 row 2 of the matrix. * @zh 矩阵第 0 列第 2 行的元素。 */ public m02: number; /** * @en Value at column 0 row 3 of the matrix. * @zh 矩阵第 0 列第 3 行的元素。 */ public m03: number; /** * @en Value at column 1 row 0 of the matrix. * @zh 矩阵第 1 列第 0 行的元素。 */ public m04: number; /** * @en Value at column 1 row 1 of the matrix. * @zh 矩阵第 1 列第 1 行的元素。 */ public m05: number; /** * @en Value at column 1 row 2 of the matrix. * @zh 矩阵第 1 列第 2 行的元素。 */ public m06: number; /** * @en Value at column 1 row 3 of the matrix. * @zh 矩阵第 1 列第 3 行的元素。 */ public m07: number; /** * @en Value at column 2 row 0 of the matrix. * @zh 矩阵第 2 列第 0 行的元素。 */ public m08: number; /** * @en Value at column 2 row 1 of the matrix. * @zh 矩阵第 2 列第 1 行的元素。 */ public m09: number; /** * @en Value at column 2 row 2 of the matrix. * @zh 矩阵第 2 列第 2 行的元素。 */ public m10: number; /** * @en Value at column 2 row 3 of the matrix. * @zh 矩阵第 2 列第 3 行的元素。 */ public m11: number; /** * @en Value at column 3 row 0 of the matrix. * @zh 矩阵第 3 列第 0 行的元素。 */ public m12: number; /** * @en Value at column 3 row 1 of the matrix. * @zh 矩阵第 3 列第 1 行的元素。 */ public m13: number; /** * @en Value at column 3 row 2 of the matrix. * @zh 矩阵第 3 列第 2 行的元素。 */ public m14: number; /** * @en Value at column 3 row 3 of the matrix. * @zh 矩阵第 3 列第 3 行的元素。 */ public m15: number; constructor (other: Mat4); constructor ( m00?: number, m01?: number, m02?: number, m03?: number, m04?: number, m05?: number, m06?: number, m07?: number, m08?: number, m09?: number, m10?: number, m11?: number, m12?: number, m13?: number, m14?: number, m15?: number); constructor ( m00: Mat4 | number = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 0, m05 = 1, m06 = 0, m07 = 0, m08 = 0, m09 = 0, m10 = 1, m11 = 0, m12 = 0, m13 = 0, m14 = 0, m15 = 1, ) { super(); if (typeof m00 === 'object') { this.m00 = m00.m00; this.m01 = m00.m01; this.m02 = m00.m02; this.m03 = m00.m03; this.m04 = m00.m04; this.m05 = m00.m05; this.m06 = m00.m06; this.m07 = m00.m07; this.m08 = m00.m08; this.m09 = m00.m09; this.m10 = m00.m10; this.m11 = m00.m11; this.m12 = m00.m12; this.m13 = m00.m13; this.m14 = m00.m14; this.m15 = m00.m15; } else { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m04 = m04; this.m05 = m05; this.m06 = m06; this.m07 = m07; this.m08 = m08; this.m09 = m09; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m14 = m14; this.m15 = m15; } } /** * @en Clone a new matrix from the current matrix. * @zh 克隆当前矩阵。 */ public clone () { return new Mat4( this.m00, this.m01, this.m02, this.m03, this.m04, this.m05, this.m06, this.m07, this.m08, this.m09, this.m10, this.m11, this.m12, this.m13, this.m14, this.m15, ); } /** * @en Sets the matrix with another one's value. * @zh 设置当前矩阵使其与指定矩阵相等。 * @param other Specified matrix. * @return this */ public set (other: Mat4); /** * @en Set the matrix with values of all elements * @zh 设置当前矩阵指定元素值。 * @return this */ public set ( m00?: number, m01?: number, m02?: number, m03?: number, m04?: number, m05?: number, m06?: number, m07?: number, m08?: number, m09?: number, m10?: number, m11?: number, m12?: number, m13?: number, m14?: number, m15?: number); public set (m00: Mat4 | number = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 0, m05 = 1, m06 = 0, m07 = 0, m08 = 0, m09 = 0, m10 = 1, m11 = 0, m12 = 0, m13 = 0, m14 = 0, m15 = 1) { if (typeof m00 === 'object') { this.m01 = m00.m01; this.m02 = m00.m02; this.m03 = m00.m03; this.m04 = m00.m04; this.m05 = m00.m05; this.m06 = m00.m06; this.m07 = m00.m07; this.m08 = m00.m08; this.m09 = m00.m09; this.m10 = m00.m10; this.m11 = m00.m11; this.m12 = m00.m12; this.m13 = m00.m13; this.m14 = m00.m14; this.m15 = m00.m15; this.m00 = m00.m00; } else { this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m04 = m04; this.m05 = m05; this.m06 = m06; this.m07 = m07; this.m08 = m08; this.m09 = m09; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; this.m14 = m14; this.m15 = m15; this.m00 = m00; } return this; } /** * @en Returns whether the specified matrices are approximately equal. * @zh 判断当前矩阵是否在误差范围内与指定矩阵相等。 * @param other Comparative matrix * @param epsilon The error allowed. It`s should be a non-negative number. * @return Returns `true' when the elements of both matrices are equal; otherwise returns `false'. */ public equals (other: Mat4, epsilon = EPSILON): boolean { return ( Math.abs(this.m00 - other.m00) <= epsilon * Math.max(1.0, Math.abs(this.m00), Math.abs(other.m00)) && Math.abs(this.m01 - other.m01) <= epsilon * Math.max(1.0, Math.abs(this.m01), Math.abs(other.m01)) && Math.abs(this.m02 - other.m02) <= epsilon * Math.max(1.0, Math.abs(this.m02), Math.abs(other.m02)) && Math.abs(this.m03 - other.m03) <= epsilon * Math.max(1.0, Math.abs(this.m03), Math.abs(other.m03)) && Math.abs(this.m04 - other.m04) <= epsilon * Math.max(1.0, Math.abs(this.m04), Math.abs(other.m04)) && Math.abs(this.m05 - other.m05) <= epsilon * Math.max(1.0, Math.abs(this.m05), Math.abs(other.m05)) && Math.abs(this.m06 - other.m06) <= epsilon * Math.max(1.0, Math.abs(this.m06), Math.abs(other.m06)) && Math.abs(this.m07 - other.m07) <= epsilon * Math.max(1.0, Math.abs(this.m07), Math.abs(other.m07)) && Math.abs(this.m08 - other.m08) <= epsilon * Math.max(1.0, Math.abs(this.m08), Math.abs(other.m08)) && Math.abs(this.m09 - other.m09) <= epsilon * Math.max(1.0, Math.abs(this.m09), Math.abs(other.m09)) && Math.abs(this.m10 - other.m10) <= epsilon * Math.max(1.0, Math.abs(this.m10), Math.abs(other.m10)) && Math.abs(this.m11 - other.m11) <= epsilon * Math.max(1.0, Math.abs(this.m11), Math.abs(other.m11)) && Math.abs(this.m12 - other.m12) <= epsilon * Math.max(1.0, Math.abs(this.m12), Math.abs(other.m12)) && Math.abs(this.m13 - other.m13) <= epsilon * Math.max(1.0, Math.abs(this.m13), Math.abs(other.m13)) && Math.abs(this.m14 - other.m14) <= epsilon * Math.max(1.0, Math.abs(this.m14), Math.abs(other.m14)) && Math.abs(this.m15 - other.m15) <= epsilon * Math.max(1.0, Math.abs(this.m15), Math.abs(other.m15)) ); } /** * @en Returns whether the specified matrices are equal. * @zh 判断当前矩阵是否与指定矩阵相等。 * @param other Comparative matrix * @return Returns `true' when the elements of both matrices are equal; otherwise returns `false'. */ public strictEquals (other: Mat4): boolean { return this.m00 === other.m00 && this.m01 === other.m01 && this.m02 === other.m02 && this.m03 === other.m03 && this.m04 === other.m04 && this.m05 === other.m05 && this.m06 === other.m06 && this.m07 === other.m07 && this.m08 === other.m08 && this.m09 === other.m09 && this.m10 === other.m10 && this.m11 === other.m11 && this.m12 === other.m12 && this.m13 === other.m13 && this.m14 === other.m14 && this.m15 === other.m15; } /** * @en Returns a string representation of a matrix. * @zh 返回当前矩阵的字符串表示。 * @return 当前矩阵的字符串表示。 */ public toString () { return `[\n${ this.m00}, ${this.m01}, ${this.m02}, ${this.m03},\n${ this.m04}, ${this.m05}, ${this.m06}, ${this.m07},\n${ this.m08}, ${this.m09}, ${this.m10}, ${this.m11},\n${ this.m12}, ${this.m13}, ${this.m14}, ${this.m15}\n` + ']'; } /** * @en set the current matrix to an identity matrix. * @zh 将当前矩阵设为单位矩阵。 * @return `this` */ public identity () { this.m00 = 1; this.m01 = 0; this.m02 = 0; this.m03 = 0; this.m04 = 0; this.m05 = 1; this.m06 = 0; this.m07 = 0; this.m08 = 0; this.m09 = 0; this.m10 = 1; this.m11 = 0; this.m12 = 0; this.m13 = 0; this.m14 = 0; this.m15 = 1; return this; } /** * @en set the current matrix to an zero matrix. * @zh 将当前矩阵设为 0矩阵。 * @return `this` */ public zero () { this.m00 = 0; this.m01 = 0; this.m02 = 0; this.m03 = 0; this.m04 = 0; this.m05 = 0; this.m06 = 0; this.m07 = 0; this.m08 = 0; this.m09 = 0; this.m10 = 0; this.m11 = 0; this.m12 = 0; this.m13 = 0; this.m14 = 0; this.m15 = 0; return this; } /** * @en Transposes the current matrix. * @zh 计算当前矩阵的转置矩阵。 */ public transpose () { const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; const a12 = this.m06; const a13 = this.m07; const a23 = this.m11; this.m01 = this.m04; this.m02 = this.m08; this.m03 = this.m12; this.m04 = a01; this.m06 = this.m09; this.m07 = this.m13; this.m08 = a02; this.m09 = a12; this.m11 = this.m14; this.m12 = a03; this.m13 = a13; this.m14 = a23; return this; } /** * @en Inverts the current matrix. When matrix is not invertible the matrix will be set to zeros. * @zh 计算当前矩阵的逆矩阵。注意,在矩阵不可逆时,会返回一个全为 0 的矩阵。 */ public invert () { const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; const a30 = this.m12; const a31 = this.m13; const a32 = this.m14; const a33 = this.m15; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; const b02 = a00 * a13 - a03 * a10; const b03 = a01 * a12 - a02 * a11; const b04 = a01 * a13 - a03 * a11; const b05 = a02 * a13 - a03 * a12; const b06 = a20 * a31 - a21 * a30; const b07 = a20 * a32 - a22 * a30; const b08 = a20 * a33 - a23 * a30; const b09 = a21 * a32 - a22 * a31; const b10 = a21 * a33 - a23 * a31; const b11 = a22 * a33 - a23 * a32; // Calculate the determinant let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (det === 0) { this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); return this; } det = 1.0 / det; this.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det; this.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det; this.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det; this.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det; this.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det; this.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det; this.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det; this.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det; this.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det; this.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det; this.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det; this.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det; this.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det; this.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det; this.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det; this.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det; return this; } /** * @en Calculates the determinant of the current matrix. * @zh 计算当前矩阵的行列式。 * @return 当前矩阵的行列式。 */ public determinant (): number { const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; const a30 = this.m12; const a31 = this.m13; const a32 = this.m14; const a33 = this.m15; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; const b02 = a00 * a13 - a03 * a10; const b03 = a01 * a12 - a02 * a11; const b04 = a01 * a13 - a03 * a11; const b05 = a02 * a13 - a03 * a12; const b06 = a20 * a31 - a21 * a30; const b07 = a20 * a32 - a22 * a30; const b08 = a20 * a33 - a23 * a30; const b09 = a21 * a32 - a22 * a31; const b10 = a21 * a33 - a23 * a31; const b11 = a22 * a33 - a23 * a32; // Calculate the determinant return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; } /** * @en Adds the current matrix and another matrix to the current matrix. * @zh 矩阵加法。将当前矩阵与指定矩阵的相加,结果返回给当前矩阵。 * @param mat the second operand */ public add (mat: Mat4) { this.m00 += mat.m00; this.m01 += mat.m01; this.m02 += mat.m02; this.m03 += mat.m03; this.m04 += mat.m04; this.m05 += mat.m05; this.m06 += mat.m06; this.m07 += mat.m07; this.m08 += mat.m08; this.m09 += mat.m09; this.m10 += mat.m10; this.m11 += mat.m11; this.m12 += mat.m12; this.m13 += mat.m13; this.m14 += mat.m14; this.m15 += mat.m15; return this; } /** * @en Subtracts another matrix from the current matrix. * @zh 计算矩阵减法。将当前矩阵减去指定矩阵的结果赋值给当前矩阵。 * @param mat the second operand */ public subtract (mat: Mat4) { this.m00 -= mat.m00; this.m01 -= mat.m01; this.m02 -= mat.m02; this.m03 -= mat.m03; this.m04 -= mat.m04; this.m05 -= mat.m05; this.m06 -= mat.m06; this.m07 -= mat.m07; this.m08 -= mat.m08; this.m09 -= mat.m09; this.m10 -= mat.m10; this.m11 -= mat.m11; this.m12 -= mat.m12; this.m13 -= mat.m13; this.m14 -= mat.m14; this.m15 -= mat.m15; return this; } /** * @en Multiply the current matrix with another matrix. * @zh 矩阵乘法。将当前矩阵左乘指定矩阵的结果赋值给当前矩阵。 * @param mat the second operand */ public multiply (mat: Mat4) { const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; const a30 = this.m12; const a31 = this.m13; const a32 = this.m14; const a33 = this.m15; // Cache only the current line of the second matrix let b0 = mat.m00; let b1 = mat.m01; let b2 = mat.m02; let b3 = mat.m03; this.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; this.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; this.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; this.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = mat.m04; b1 = mat.m05; b2 = mat.m06; b3 = mat.m07; this.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; this.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; this.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; this.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = mat.m08; b1 = mat.m09; b2 = mat.m10; b3 = mat.m11; this.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; this.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; this.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; this.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; b0 = mat.m12; b1 = mat.m13; b2 = mat.m14; b3 = mat.m15; this.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; this.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; this.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; this.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; return this; } /** * @en Multiply each element of the current matrix by a scalar number. * @zh 矩阵数乘。将当前矩阵与指定标量的数乘结果赋值给当前矩阵。 * @param scalar amount to scale the matrix's elements by */ public multiplyScalar (scalar: number) { this.m00 *= scalar; this.m01 *= scalar; this.m02 *= scalar; this.m03 *= scalar; this.m04 *= scalar; this.m05 *= scalar; this.m06 *= scalar; this.m07 *= scalar; this.m08 *= scalar; this.m09 *= scalar; this.m10 *= scalar; this.m11 *= scalar; this.m12 *= scalar; this.m13 *= scalar; this.m14 *= scalar; this.m15 *= scalar; return this; } /** * @en Translate the current matrix by the given vector * @zh 将当前矩阵左乘位移矩阵的结果赋值给当前矩阵,位移矩阵由各个轴的位移给出。 * @param vec vector to translate by */ public translate (vec: Vec3) { console.warn('function changed'); this.m12 += vec.x; this.m13 += vec.y; this.m14 += vec.z; return this; } /** * @en Multiply the current matrix with a scale vector. * @zh 将当前矩阵左乘缩放矩阵的结果赋值给当前矩阵,缩放矩阵由各个轴的缩放给出。 * @param vec vector to scale by */ public scale (vec: Vec3) { const x = vec.x; const y = vec.y; const z = vec.z; this.m00 *= x; this.m01 *= x; this.m02 *= x; this.m03 *= x; this.m04 *= y; this.m05 *= y; this.m06 *= y; this.m07 *= y; this.m08 *= z; this.m09 *= z; this.m10 *= z; this.m11 *= z; return this; } /** * @en Rotates the current matrix by the given angle around the given axis * @zh 将当前矩阵左乘旋转矩阵的结果赋值给当前矩阵,旋转矩阵由旋转轴和旋转角度给出。 * @param rad Angle of rotation (in radians) * @param axis Axis of rotation */ public rotate (rad: number, axis: Vec3) { let x = axis.x; let y = axis.y; let z = axis.z; let len = Math.sqrt(x * x + y * y + z * z); if (Math.abs(len) < EPSILON) { return null; } len = 1 / len; x *= len; y *= len; z *= len; const s = Math.sin(rad); const c = Math.cos(rad); const t = 1 - c; const a00 = this.m00; const a01 = this.m01; const a02 = this.m02; const a03 = this.m03; const a10 = this.m04; const a11 = this.m05; const a12 = this.m06; const a13 = this.m07; const a20 = this.m08; const a21 = this.m09; const a22 = this.m10; const a23 = this.m11; // Construct the elements of the rotation matrix const b00 = x * x * t + c; const b01 = y * x * t + z * s; const b02 = z * x * t - y * s; const b10 = x * y * t - z * s; const b11 = y * y * t + c; const b12 = z * y * t + x * s; const b20 = x * z * t + y * s; const b21 = y * z * t - x * s; const b22 = z * z * t + c; // Perform rotation-specific matrix multiplication this.m00 = a00 * b00 + a10 * b01 + a20 * b02; this.m01 = a01 * b00 + a11 * b01 + a21 * b02; this.m02 = a02 * b00 + a12 * b01 + a22 * b02; this.m03 = a03 * b00 + a13 * b01 + a23 * b02; this.m04 = a00 * b10 + a10 * b11 + a20 * b12; this.m05 = a01 * b10 + a11 * b11 + a21 * b12; this.m06 = a02 * b10 + a12 * b11 + a22 * b12; this.m07 = a03 * b10 + a13 * b11 + a23 * b12; this.m08 = a00 * b20 + a10 * b21 + a20 * b22; this.m09 = a01 * b20 + a11 * b21 + a21 * b22; this.m10 = a02 * b20 + a12 * b21 + a22 * b22; this.m11 = a03 * b20 + a13 * b21 + a23 * b22; return this; } /** * @en Returns the translation vector component of a transformation matrix. * @zh 从当前矩阵中计算出位移变换的部分,并以各个轴上位移的形式赋值给出口向量。 * @param out Vector to receive translation component. */ public getTranslation (out: Vec3) { out.x = this.m12; out.y = this.m13; out.z = this.m14; return out; } /** * @en Returns the scale factor component of a transformation matrix * @zh 从当前矩阵中计算出缩放变换的部分,并以各个轴上缩放的形式赋值给出口向量。 * @param out Vector to receive scale component */ public getScale (out: Vec3) { const m00 = m3_1.m00 = this.m00; const m01 = m3_1.m01 = this.m01; const m02 = m3_1.m02 = this.m02; const m04 = m3_1.m03 = this.m04; const m05 = m3_1.m04 = this.m05; const m06 = m3_1.m05 = this.m06; const m08 = m3_1.m06 = this.m08; const m09 = m3_1.m07 = this.m09; const m10 = m3_1.m08 = this.m10; out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02); out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06); out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10); // account for refections if (Mat3.determinant(m3_1) < 0) { out.x *= -1; } return out; } /** * @en Returns the rotation factor component of a transformation matrix * @zh 从当前矩阵中计算出旋转变换的部分,并以四元数的形式赋值给出口四元数。 * @param out Vector to receive rotation component */ public getRotation (out: Quat) { const trace = this.m00 + this.m05 + this.m10; let S = 0; if (trace > 0) { S = Math.sqrt(trace + 1.0) * 2; out.w = 0.25 * S; out.x = (this.m06 - this.m09) / S; out.y = (this.m08 - this.m02) / S; out.z = (this.m01 - this.m04) / S; } else if ((this.m00 > this.m05) && (this.m00 > this.m10)) { S = Math.sqrt(1.0 + this.m00 - this.m05 - this.m10) * 2; out.w = (this.m06 - this.m09) / S; out.x = 0.25 * S; out.y = (this.m01 + this.m04) / S; out.z = (this.m08 + this.m02) / S; } else if (this.m05 > this.m10) { S = Math.sqrt(1.0 + this.m05 - this.m00 - this.m10) * 2; out.w = (this.m08 - this.m02) / S; out.x = (this.m01 + this.m04) / S; out.y = 0.25 * S; out.z = (this.m06 + this.m09) / S; } else { S = Math.sqrt(1.0 + this.m10 - this.m00 - this.m05) * 2; out.w = (this.m01 - this.m04) / S; out.x = (this.m08 + this.m02) / S; out.y = (this.m06 + this.m09) / S; out.z = 0.25 * S; } return out; } /** * @en Resets the matrix values by the given rotation quaternion, translation vector and scale vector * @zh 重置当前矩阵的值,使其表示指定的旋转、缩放、位移依次组合的变换。 * @param q Rotation quaternion * @param v Translation vector * @param s Scaling vector * @return `this` */ public fromRTS (q: Quat, v: Vec3, s: Vec3) { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; const z2 = z + z; const xx = x * x2; const xy = x * y2; const xz = x * z2; const yy = y * y2; const yz = y * z2; const zz = z * z2; const wx = w * x2; const wy = w * y2; const wz = w * z2; const sx = s.x; const sy = s.y; const sz = s.z; this.m00 = (1 - (yy + zz)) * sx; this.m01 = (xy + wz) * sx; this.m02 = (xz - wy) * sx; this.m03 = 0; this.m04 = (xy - wz) * sy; this.m05 = (1 - (xx + zz)) * sy; this.m06 = (yz + wx) * sy; this.m07 = 0; this.m08 = (xz + wy) * sz; this.m09 = (yz - wx) * sz; this.m10 = (1 - (xx + yy)) * sz; this.m11 = 0; this.m12 = v.x; this.m13 = v.y; this.m14 = v.z; this.m15 = 1; return this; } /** * @en Resets the current matrix from the given quaternion. * @zh 重置当前矩阵的值,使其表示指定四元数表示的旋转变换。 * @param q Rotation quaternion * @return `this` */ public fromQuat (q: Quat) { const x = q.x; const y = q.y; const z = q.z; const w = q.w; const x2 = x + x; const y2 = y + y; const z2 = z + z; const xx = x * x2; const yx = y * x2; const yy = y * y2; const zx = z * x2; const zy = z * y2; const zz = z * z2; const wx = w * x2; const wy = w * y2; const wz = w * z2; this.m00 = 1 - yy - zz; this.m01 = yx + wz; this.m02 = zx - wy; this.m03 = 0; this.m04 = yx - wz; this.m05 = 1 - xx - zz; this.m06 = zy + wx; this.m07 = 0; this.m08 = zx + wy; this.m09 = zy - wx; this.m10 = 1 - xx - yy; this.m11 = 0; this.m12 = 0; this.m13 = 0; this.m14 = 0; this.m15 = 1; return this; } } const v3_1 = new Vec3(); const m3_1 = new Mat3(); CCClass.fastDefine('cc.Mat4', Mat4, { m00: 1, m01: 0, m02: 0, m03: 0, m04: 0, m05: 1, m06: 0, m07: 0, m08: 0, m09: 0, m10: 1, m11: 0, m12: 0, m13: 0, m14: 0, m15: 1, }); legacyCC.Mat4 = Mat4; export function mat4 (other: Mat4): Mat4; export function mat4 ( m00?: number, m01?: number, m02?: number, m03?: number, m10?: number, m11?: number, m12?: number, m13?: number, m20?: number, m21?: number, m22?: number, m23?: number, m30?: number, m31?: number, m32?: number, m33?: number): Mat4; export function mat4 ( m00?: Mat4 | number, m01?, m02?, m03?, m10?, m11?, m12?, m13?, m20?, m21?, m22?, m23?, m30?, m31?, m32?, m33?, ) { return new Mat4(m00 as any, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); } legacyCC.mat4 = mat4;
the_stack
import 'es6-promise/auto'; // polyfill Promise on IE import { expect } from 'chai'; import { generate, simulate } from 'simulate-event'; import { MimeData } from '@phosphor/coreutils'; import { Drag, IDragEvent } from '@phosphor/dragdrop'; import '@phosphor/dragdrop/style/index.css'; class DropTarget { node = document.createElement('div'); events: string[] = []; constructor() { this.node.style.minWidth = '100px'; this.node.style.minHeight = '100px'; this.node.addEventListener('p-dragenter', this); this.node.addEventListener('p-dragover', this); this.node.addEventListener('p-dragleave', this); this.node.addEventListener('p-drop', this); document.body.appendChild(this.node); } dispose(): void { document.body.removeChild(this.node); this.node.removeEventListener('p-dragenter', this); this.node.removeEventListener('p-dragover', this); this.node.removeEventListener('p-dragleave', this); this.node.removeEventListener('p-drop', this); } handleEvent(event: Event): void { this.events.push(event.type); switch (event.type) { case 'p-dragenter': this._evtDragEnter(event as IDragEvent); break; case 'p-dragleave': this._evtDragLeave(event as IDragEvent); break; case 'p-dragover': this._evtDragOver(event as IDragEvent); break; case 'p-drop': this._evtDrop(event as IDragEvent); break; } } private _evtDragEnter(event: IDragEvent): void { event.preventDefault(); event.stopPropagation(); } private _evtDragLeave(event: IDragEvent): void { event.preventDefault(); event.stopPropagation(); } private _evtDragOver(event: IDragEvent): void { event.preventDefault(); event.stopPropagation(); event.dropAction = event.proposedAction; } private _evtDrop(event: IDragEvent): void { event.preventDefault(); event.stopPropagation(); if (event.proposedAction === 'none') { event.dropAction = 'none'; return; } event.dropAction = event.proposedAction; } } describe('@phosphor/dragdrop', () => { describe('Drag', () => { describe('#constructor()', () => { it('should accept an options object', () => { let drag = new Drag({ mimeData: new MimeData() }); expect(drag).to.be.an.instanceof(Drag); }); it('should accept optional options', () => { let dragImage = document.createElement('i'); let source = {}; let mimeData = new MimeData(); let drag = new Drag({ mimeData, dragImage, proposedAction: 'copy', supportedActions: 'copy-link', source }); expect(drag).to.be.an.instanceof(Drag); expect(drag.mimeData).to.equal(mimeData); expect(drag.dragImage).to.equal(dragImage); expect(drag.proposedAction).to.equal('copy'); expect(drag.supportedActions).to.equal('copy-link'); expect(drag.source).to.equal(source); }); }); describe('#dispose()', () => { it('should dispose of the resources held by the drag object', () => { let drag = new Drag({ mimeData: new MimeData() }); drag.dispose(); expect(drag.isDisposed).to.equal(true); }); it('should cancel the drag operation if it is active', (done) => { let drag = new Drag({ mimeData: new MimeData() }); drag.start(0, 0).then(action => { expect(action).to.equal('none'); done(); }); drag.dispose(); }); it('should be a no-op if already disposed', () => { let drag = new Drag({ mimeData: new MimeData() }); drag.dispose(); drag.dispose(); expect(drag.isDisposed).to.equal(true); }); }); describe('#isDisposed()', () => { it('should test whether the drag object is disposed', () => { let drag = new Drag({ mimeData: new MimeData() }); expect(drag.isDisposed).to.equal(false); drag.dispose(); expect(drag.isDisposed).to.equal(true); }); }); describe('#mimeData', () => { it('should get the mime data for the drag object', () => { let mimeData = new MimeData(); let drag = new Drag({ mimeData }); expect(drag.mimeData).to.equal(mimeData); }); }); describe('#dragImage', () => { it('should get the drag image element for the drag object', () => { let dragImage = document.createElement('i'); let drag = new Drag({ mimeData: new MimeData(), dragImage }); expect(drag.dragImage).to.equal(dragImage); }); it('should default to `null`', () => { let drag = new Drag({ mimeData: new MimeData() }); expect(drag.dragImage).to.equal(null); }); }); describe('#proposedAction', () => { it('should get the proposed drop action for the drag object', () => { let drag = new Drag({ mimeData: new MimeData(), proposedAction: 'link' }); expect(drag.proposedAction).to.equal('link'); }); it("should default to `'copy'`", () => { let drag = new Drag({ mimeData: new MimeData() }); expect(drag.proposedAction).to.equal('copy'); }); }); describe('#supportedActions', () => { it('should get the supported drop actions for the drag object', () => { let drag = new Drag({ mimeData: new MimeData(), supportedActions: 'copy-move' }); expect(drag.supportedActions).to.equal('copy-move'); }); it("should default to `'all'`", () => { let drag = new Drag({ mimeData: new MimeData() }); expect(drag.supportedActions).to.equal('all'); }); }); describe('#source', () => { it('should get the drag source for the drag object', () => { let source = {}; let drag = new Drag({ mimeData: new MimeData(), source }); expect(drag.source).to.equal(source); }); it('should default to `null`', () => { let drag = new Drag({ mimeData: new MimeData() }); expect(drag.source).to.equal(null); }); }); describe('#start()', () => { it('should start the drag operation at the specified client position', () => { let dragImage = document.createElement('span'); dragImage.style.minHeight = '10px'; dragImage.style.minWidth = '10px'; let drag = new Drag({ mimeData: new MimeData(), dragImage }); drag.start(10, 20); expect(dragImage.style.top).to.equal('20px'); expect(dragImage.style.left).to.equal('10px'); drag.dispose(); }); it('should return a previous promise if a drag has already been started', () => { let drag = new Drag({ mimeData: new MimeData() }); let promise = drag.start(0, 0); expect(drag.start(10, 10)).to.equal(promise); drag.dispose(); }); it("should resolve to `'none'` if the drag operation has been disposed", (done) => { let drag = new Drag({ mimeData: new MimeData() }); drag.start(0, 0).then(action => { expect(action).to.equal('none'); done(); }); drag.dispose(); }); }); context('Event Handling', () => { let drag: Drag = null!; let child0: DropTarget = null!; let child1: DropTarget = null!; beforeEach(() => { child0 = new DropTarget(); child1 = new DropTarget(); let dragImage = document.createElement('div'); dragImage.style.minHeight = '10px'; dragImage.style.minWidth = '10px'; drag = new Drag({ mimeData: new MimeData(), dragImage }); drag.start(0, 0); }); afterEach(() => { drag.dispose(); child0.dispose(); child1.dispose(); }); describe('mousemove', () => { it('should be prevented during a drag event', () => { let evt = generate('mousemove'); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(true); }); it('should dispatch an enter and leave events', () => { let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mousemove', { clientX: rect.left + 1, clientY: rect.top + 1 } ); expect(child0.events).to.contain('p-dragenter'); child0.events = []; rect = child1.node.getBoundingClientRect(); simulate(child1.node, 'mousemove', { clientX: rect.left + 1, clientY: rect.top + 1 } ); expect(child0.events).to.contain('p-dragleave'); expect(child1.events).to.contain('p-dragenter'); }); it('should dispatch drag over event', () => { let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mousemove', { clientX: rect.left + 1, clientY: rect.top + 1 } ); expect(child0.events).to.contain('p-dragover'); }); it('should move the drag image to the client location', () => { let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mousemove', { clientX: rect.left + 1, clientY: rect.top + 1 } ); let image = drag.dragImage!; expect(image.style.top).to.equal(`${rect.top + 1}px`); expect(image.style.left).to.equal(`${rect.left + 1}px`); }); }); describe('mouseup', () => { it('should be prevented during a drag event', () => { let evt = generate('mouseup'); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(true); }); it('should do nothing if the left button is not released', () => { let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mouseup', { clientX: rect.left + 1, clientY: rect.top + 1, button: 1 } ); expect(child0.events).to.not.contain('p-dragenter'); }); it('should dispatch enter and leave events', () => { let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mousemove', { clientX: rect.left + 1, clientY: rect.top + 1 } ); expect(child0.events).to.contain('p-dragenter'); child0.events = []; rect = child1.node.getBoundingClientRect(); simulate(child1.node, 'mouseup', { clientX: rect.left + 1, clientY: rect.top + 1 } ); expect(child0.events).to.contain('p-dragleave'); expect(child1.events).to.contain('p-dragenter'); }); it("should dispatch a leave event if the last drop action was `'none'", () => { drag.dispose(); drag = new Drag({ mimeData: new MimeData(), supportedActions: 'none' }); drag.start(0, 0); let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mouseup', { clientX: rect.left + 1, clientY: rect.top + 1 } ); expect(child0.events).to.contain('p-dragleave'); }); it("should finalize the drag with `'none' if the last drop action was `'none`", (done) => { drag.dispose(); drag = new Drag({ mimeData: new MimeData(), supportedActions: 'none' }); drag.start(0, 0).then(action => { expect(action).to.equal('none'); done(); }); let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mouseup', { clientX: rect.left + 1, clientY: rect.top + 1 } ); }); it('should dispatch the drop event at the current target', () => { let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mouseup', { clientX: rect.left + 1, clientY: rect.top + 1 } ); expect(child0.events).to.contain('p-drop'); }); it('should resolve with the drop action', (done) => { drag.dispose(); drag = new Drag({ mimeData: new MimeData(), proposedAction: 'link', supportedActions: 'link' }); drag.start(0, 0).then(action => { expect(action).to.equal('link'); done(); }); let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mouseup', { clientX: rect.left + 1, clientY: rect.top + 1 } ); }); it('should handle a `move` action', (done) => { drag.dispose(); drag = new Drag({ mimeData: new MimeData(), proposedAction: 'move', supportedActions: 'copy-move' }); drag.start(0, 0).then(action => { expect(action).to.equal('move'); done(); }); let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mouseup', { clientX: rect.left + 1, clientY: rect.top + 1 } ); }); it('should dispose of the drop', () => { let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mouseup', { clientX: rect.left + 1, clientY: rect.top + 1 } ); expect(drag.isDisposed).to.equal(true); }); it('should detach the drag image', () => { let image = drag.dragImage!; let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mouseup', { clientX: rect.left + 1, clientY: rect.top + 1 } ); expect(document.body.contains(image)).to.equal(false); }); it('should remove event listeners', () => { let rect = child0.node.getBoundingClientRect(); simulate(child0.node, 'mouseup', { clientX: rect.left + 1, clientY: rect.top + 1 } ); ['mousemove', 'keydown', 'contextmenu'].forEach(name => { let evt = generate(name); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(false); }); }); }); describe('keydown', () => { it('should be prevented during a drag event', () => { let evt = generate('keydown'); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(true); }); it('should dispose of the drag if `Escape` is pressed', () => { simulate(document.body, 'keydown', { keyCode: 27 }); expect(drag.isDisposed).to.equal(true); }); }); describe('mouseenter', () => { it('should be prevented during a drag event', () => { let evt = generate('mouseenter', { cancelable: true }); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(true); }); }); describe('mouseleave', () => { it('should be prevented during a drag event', () => { let evt = generate('mouseleave', { cancelable: true }); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(true); }); }); describe('mouseover', () => { it('should be prevented during a drag event', () => { let evt = generate('mouseover'); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(true); }); }); describe('mouseout', () => { it('should be prevented during a drag event', () => { let evt = generate('mouseout'); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(true); }); }); describe('keyup', () => { it('should be prevented during a drag event', () => { let evt = generate('keyup'); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(true); }); }); describe('keypress', () => { it('should be prevented during a drag event', () => { let evt = generate('keypress'); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(true); }); }); describe('contextmenu', () => { it('should be prevented during a drag event', () => { let evt = generate('contextmenu'); let canceled = !document.body.dispatchEvent(evt); expect(canceled).to.equal(true); }); }); }); describe('.overrideCursor()', () => { it('should update the body `cursor` style', () => { expect(document.body.style.cursor).to.equal(''); let override = Drag.overrideCursor('wait'); expect(document.body.style.cursor).to.equal('wait'); override.dispose(); }); it('should add the `p-mod-override-cursor` class to the body', () => { expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(false); let override = Drag.overrideCursor('wait'); expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(true); override.dispose(); }); it('should clear the override when disposed', () => { expect(document.body.style.cursor).to.equal(''); let override = Drag.overrideCursor('wait'); expect(document.body.style.cursor).to.equal('wait'); override.dispose(); expect(document.body.style.cursor).to.equal(''); }); it('should remove the `p-mod-override-cursor` class when disposed', () => { expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(false); let override = Drag.overrideCursor('wait'); expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(true); override.dispose(); expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(false); }); it('should respect the most recent override', () => { expect(document.body.style.cursor).to.equal(''); expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(false); let one = Drag.overrideCursor('wait'); expect(document.body.style.cursor).to.equal('wait'); expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(true); let two = Drag.overrideCursor('default'); expect(document.body.style.cursor).to.equal('default'); expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(true); let three = Drag.overrideCursor('cell'); expect(document.body.style.cursor).to.equal('cell'); expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(true); two.dispose(); expect(document.body.style.cursor).to.equal('cell'); expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(true); one.dispose(); expect(document.body.style.cursor).to.equal('cell'); expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(true); three.dispose(); expect(document.body.style.cursor).to.equal(''); expect(document.body.classList.contains('p-mod-override-cursor')).to.equal(false); }); it('should override the computed cursor for a node', () => { let div = document.createElement('div'); div.style.cursor = 'cell'; document.body.appendChild(div); expect(window.getComputedStyle(div).cursor).to.equal('cell'); let override = Drag.overrideCursor('wait'); expect(window.getComputedStyle(div).cursor).to.equal('wait'); override.dispose(); expect(window.getComputedStyle(div).cursor).to.equal('cell'); document.body.removeChild(div); }); }); }); });
the_stack
import { NavigationType } from './frame-common'; import { NavigationTransition, BackstackEntry } from '.'; // Types. import { Transition } from '../transition'; import { FlipTransition } from '../transition/flip-transition'; import { _resolveAnimationCurve } from '../animation'; import lazy from '../../utils/lazy'; import { Trace } from '../../trace'; interface TransitionListener { new (entry: ExpandedEntry, transition: androidx.transition.Transition): ExpandedTransitionListener; } const defaultInterpolator = lazy(() => new android.view.animation.AccelerateDecelerateInterpolator()); const animFadeIn = 17432576; // android.R.anim.fade_in const animFadeOut = 17432577; // android.R.anim.fade_out export const waitingQueue = new Map<number, Set<ExpandedEntry>>(); export const completedEntries = new Map<number, ExpandedEntry>(); let TransitionListener: TransitionListener; let AnimationListener: android.animation.Animator.AnimatorListener; interface ExpandedTransitionListener extends androidx.transition.Transition.TransitionListener { entry: ExpandedEntry; transition: androidx.transition.Transition; } interface ExpandedAnimator extends android.animation.Animator { entry: ExpandedEntry; backEntry?: BackstackEntry; transitionType?: string; } export interface ExpandedEntry extends BackstackEntry { enterTransitionListener: ExpandedTransitionListener; exitTransitionListener: ExpandedTransitionListener; reenterTransitionListener: ExpandedTransitionListener; returnTransitionListener: ExpandedTransitionListener; enterAnimator: ExpandedAnimator; exitAnimator: ExpandedAnimator; popEnterAnimator: ExpandedAnimator; popExitAnimator: ExpandedAnimator; transition: Transition; transitionName: string; frameId: number; isNestedDefaultTransition: boolean; } export function _setAndroidFragmentTransitions(animated: boolean, navigationTransition: NavigationTransition, currentEntry: ExpandedEntry, newEntry: ExpandedEntry, frameId: number, fragmentTransaction: androidx.fragment.app.FragmentTransaction, isNestedDefaultTransition?: boolean): void { const currentFragment: androidx.fragment.app.Fragment = currentEntry ? currentEntry.fragment : null; const newFragment: androidx.fragment.app.Fragment = newEntry.fragment; const entries = waitingQueue.get(frameId); if (entries && entries.size > 0) { throw new Error('Calling navigation before previous navigation finish.'); } allowTransitionOverlap(currentFragment); allowTransitionOverlap(newFragment); let name = ''; let transition: Transition; if (navigationTransition) { transition = navigationTransition.instance; name = navigationTransition.name ? navigationTransition.name.toLowerCase() : ''; } if (!animated) { name = 'none'; } else if (transition) { name = 'custom'; } else if (name.indexOf('slide') !== 0 && name !== 'fade' && name.indexOf('flip') !== 0 && name.indexOf('explode') !== 0) { // If we are given name that doesn't match any of ours - fallback to default. name = 'default'; } let currentFragmentNeedsDifferentAnimation = false; if (currentEntry) { _updateTransitions(currentEntry); if (currentEntry.transitionName !== name || currentEntry.transition !== transition || isNestedDefaultTransition) { clearExitAndReenterTransitions(currentEntry, true); currentFragmentNeedsDifferentAnimation = true; } } if (name === 'none') { const noTransition = new NoTransition(0, null); // Setup empty/immediate animator when transitioning to nested frame for first time. // Also setup empty/immediate transition to be executed when navigating back to this page. // TODO: Consider removing empty/immediate animator when migrating to official androidx.fragment.app.Fragment:1.2. if (isNestedDefaultTransition) { fragmentTransaction.setCustomAnimations(animFadeIn, animFadeOut); setupAllAnimation(newEntry, noTransition); setupNewFragmentCustomTransition({ duration: 0, curve: null }, newEntry, noTransition); } else { setupNewFragmentCustomTransition({ duration: 0, curve: null }, newEntry, noTransition); } newEntry.isNestedDefaultTransition = isNestedDefaultTransition; if (currentFragmentNeedsDifferentAnimation) { setupCurrentFragmentCustomTransition({ duration: 0, curve: null }, currentEntry, noTransition); } } else if (name === 'custom') { setupNewFragmentCustomTransition( { duration: transition.getDuration(), curve: transition.getCurve(), }, newEntry, transition ); if (currentFragmentNeedsDifferentAnimation) { setupCurrentFragmentCustomTransition( { duration: transition.getDuration(), curve: transition.getCurve(), }, currentEntry, transition ); } } else if (name === 'default') { setupNewFragmentFadeTransition({ duration: 150, curve: null }, newEntry); if (currentFragmentNeedsDifferentAnimation) { setupCurrentFragmentFadeTransition({ duration: 150, curve: null }, currentEntry); } } else if (name.indexOf('slide') === 0) { setupNewFragmentSlideTransition(navigationTransition, newEntry, name); if (currentFragmentNeedsDifferentAnimation) { setupCurrentFragmentSlideTransition(navigationTransition, currentEntry, name); } } else if (name === 'fade') { setupNewFragmentFadeTransition(navigationTransition, newEntry); if (currentFragmentNeedsDifferentAnimation) { setupCurrentFragmentFadeTransition(navigationTransition, currentEntry); } } else if (name === 'explode') { setupNewFragmentExplodeTransition(navigationTransition, newEntry); if (currentFragmentNeedsDifferentAnimation) { setupCurrentFragmentExplodeTransition(navigationTransition, currentEntry); } } else if (name.indexOf('flip') === 0) { const direction = name.substr('flip'.length) || 'right'; //Extract the direction from the string const flipTransition = new FlipTransition(direction, navigationTransition.duration, navigationTransition.curve); setupNewFragmentCustomTransition(navigationTransition, newEntry, flipTransition); if (currentFragmentNeedsDifferentAnimation) { setupCurrentFragmentCustomTransition(navigationTransition, currentEntry, flipTransition); } } newEntry.transitionName = name; if (currentEntry) { currentEntry.transitionName = name; if (name === 'custom') { currentEntry.transition = transition; } } printTransitions(currentEntry); printTransitions(newEntry); } function setupAllAnimation(entry: ExpandedEntry, transition: Transition): void { setupExitAndPopEnterAnimation(entry, transition); const listener = getAnimationListener(); // setupAllAnimation is called only for new fragments so we don't // need to clearAnimationListener for enter & popExit animators. const enterAnimator = <ExpandedAnimator>transition.createAndroidAnimator(Transition.AndroidTransitionType.enter); enterAnimator.transitionType = Transition.AndroidTransitionType.enter; enterAnimator.entry = entry; enterAnimator.addListener(listener); entry.enterAnimator = enterAnimator; const popExitAnimator = <ExpandedAnimator>transition.createAndroidAnimator(Transition.AndroidTransitionType.popExit); popExitAnimator.transitionType = Transition.AndroidTransitionType.popExit; popExitAnimator.entry = entry; popExitAnimator.addListener(listener); entry.popExitAnimator = popExitAnimator; } function setupExitAndPopEnterAnimation(entry: ExpandedEntry, transition: Transition): void { const listener = getAnimationListener(); // remove previous listener if we are changing the animator. clearAnimationListener(entry.exitAnimator, listener); clearAnimationListener(entry.popEnterAnimator, listener); const exitAnimator = <ExpandedAnimator>transition.createAndroidAnimator(Transition.AndroidTransitionType.exit); exitAnimator.transitionType = Transition.AndroidTransitionType.exit; exitAnimator.entry = entry; exitAnimator.addListener(listener); entry.exitAnimator = exitAnimator; const popEnterAnimator = <ExpandedAnimator>transition.createAndroidAnimator(Transition.AndroidTransitionType.popEnter); popEnterAnimator.transitionType = Transition.AndroidTransitionType.popEnter; popEnterAnimator.entry = entry; popEnterAnimator.addListener(listener); entry.popEnterAnimator = popEnterAnimator; } function getAnimationListener(): android.animation.Animator.AnimatorListener { if (!AnimationListener) { @NativeClass @Interfaces([android.animation.Animator.AnimatorListener]) class AnimationListenerImpl extends java.lang.Object implements android.animation.Animator.AnimatorListener { constructor() { super(); return global.__native(this); } onAnimationStart(animator: ExpandedAnimator): void { const entry = animator.entry; addToWaitingQueue(entry); if (Trace.isEnabled()) { Trace.write(`START ${animator.transitionType} for ${entry.fragmentTag}`, Trace.categories.Transition); } } onAnimationRepeat(animator: ExpandedAnimator): void { if (Trace.isEnabled()) { Trace.write(`REPEAT ${animator.transitionType} for ${animator.entry.fragmentTag}`, Trace.categories.Transition); } } onAnimationEnd(animator: ExpandedAnimator): void { if (Trace.isEnabled()) { Trace.write(`END ${animator.transitionType} for ${animator.entry.fragmentTag}`, Trace.categories.Transition); } transitionOrAnimationCompleted(animator.entry, animator.backEntry); } onAnimationCancel(animator: ExpandedAnimator): void { if (Trace.isEnabled()) { Trace.write(`CANCEL ${animator.transitionType} for ${animator.entry.fragmentTag}`, Trace.categories.Transition); } } } AnimationListener = new AnimationListenerImpl(); } return AnimationListener; } function clearAnimationListener(animator: ExpandedAnimator, listener: android.animation.Animator.AnimatorListener): void { if (!animator) { return; } animator.removeListener(listener); if (animator.entry && Trace.isEnabled()) { const entry = animator.entry; Trace.write(`Clear ${animator.transitionType} - ${entry.transition} for ${entry.fragmentTag}`, Trace.categories.Transition); } animator.entry = null; } export function _getAnimatedEntries(frameId: number): Set<BackstackEntry> { return waitingQueue.get(frameId); } export function _updateTransitions(entry: ExpandedEntry): void { const fragment = entry.fragment; const enterTransitionListener = entry.enterTransitionListener; if (enterTransitionListener && fragment) { fragment.setEnterTransition(enterTransitionListener.transition); } const exitTransitionListener = entry.exitTransitionListener; if (exitTransitionListener && fragment) { fragment.setExitTransition(exitTransitionListener.transition); } const reenterTransitionListener = entry.reenterTransitionListener; if (reenterTransitionListener && fragment) { fragment.setReenterTransition(reenterTransitionListener.transition); } const returnTransitionListener = entry.returnTransitionListener; if (returnTransitionListener && fragment) { fragment.setReturnTransition(returnTransitionListener.transition); } } export function _reverseTransitions(previousEntry: ExpandedEntry, currentEntry: ExpandedEntry): boolean { const previousFragment = previousEntry.fragment; const currentFragment = currentEntry.fragment; let transitionUsed = false; const returnTransitionListener = currentEntry.returnTransitionListener; if (returnTransitionListener) { transitionUsed = true; currentFragment.setExitTransition(returnTransitionListener.transition); } else { currentFragment.setExitTransition(null); } const reenterTransitionListener = previousEntry.reenterTransitionListener; if (reenterTransitionListener) { transitionUsed = true; previousFragment.setEnterTransition(reenterTransitionListener.transition); } else { previousFragment.setEnterTransition(null); } return transitionUsed; } // Transition listener can't be static because // android is cloning transitions and we can't expand them :( function getTransitionListener(entry: ExpandedEntry, transition: androidx.transition.Transition): ExpandedTransitionListener { if (!TransitionListener) { @NativeClass @Interfaces([(<any>androidx).transition.Transition.TransitionListener]) class TransitionListenerImpl extends java.lang.Object implements androidx.transition.Transition.TransitionListener { public backEntry?: BackstackEntry; constructor(public entry: ExpandedEntry, public transition: androidx.transition.Transition) { super(); return global.__native(this); } public onTransitionStart(transition: androidx.transition.Transition): void { const entry = this.entry; addToWaitingQueue(entry); if (Trace.isEnabled()) { Trace.write(`START ${toShortString(transition)} transition for ${entry.fragmentTag}`, Trace.categories.Transition); } } onTransitionEnd(transition: androidx.transition.Transition): void { const entry = this.entry; if (Trace.isEnabled()) { Trace.write(`END ${toShortString(transition)} transition for ${entry.fragmentTag}`, Trace.categories.Transition); } transitionOrAnimationCompleted(entry, this.backEntry); } onTransitionResume(transition: androidx.transition.Transition): void { if (Trace.isEnabled()) { const fragment = this.entry.fragmentTag; Trace.write(`RESUME ${toShortString(transition)} transition for ${fragment}`, Trace.categories.Transition); } } onTransitionPause(transition: androidx.transition.Transition): void { if (Trace.isEnabled()) { Trace.write(`PAUSE ${toShortString(transition)} transition for ${this.entry.fragmentTag}`, Trace.categories.Transition); } } onTransitionCancel(transition: androidx.transition.Transition): void { if (Trace.isEnabled()) { Trace.write(`CANCEL ${toShortString(transition)} transition for ${this.entry.fragmentTag}`, Trace.categories.Transition); } } } TransitionListener = TransitionListenerImpl; } return new TransitionListener(entry, transition); } function addToWaitingQueue(entry: ExpandedEntry): void { const frameId = entry.frameId; let entries = waitingQueue.get(frameId); if (!entries) { entries = new Set<ExpandedEntry>(); waitingQueue.set(frameId, entries); } entries.add(entry); } function clearExitAndReenterTransitions(entry: ExpandedEntry, removeListener: boolean): void { const fragment: androidx.fragment.app.Fragment = entry.fragment; const exitListener = entry.exitTransitionListener; if (exitListener) { const exitTransition = fragment.getExitTransition(); if (exitTransition) { if (removeListener) { exitTransition.removeListener(exitListener); } fragment.setExitTransition(null); if (Trace.isEnabled()) { Trace.write(`Cleared Exit ${exitTransition.getClass().getSimpleName()} transition for ${fragment}`, Trace.categories.Transition); } } if (removeListener) { entry.exitTransitionListener = null; } } const reenterListener = entry.reenterTransitionListener; if (reenterListener) { const reenterTransition = fragment.getReenterTransition(); if (reenterTransition) { if (removeListener) { reenterTransition.removeListener(reenterListener); } fragment.setReenterTransition(null); if (Trace.isEnabled()) { Trace.write(`Cleared Reenter ${reenterTransition.getClass().getSimpleName()} transition for ${fragment}`, Trace.categories.Transition); } } if (removeListener) { entry.reenterTransitionListener = null; } } } export function _clearFragment(entry: ExpandedEntry): void { clearEntry(entry, false); } export function _clearEntry(entry: ExpandedEntry): void { clearEntry(entry, true); } function clearEntry(entry: ExpandedEntry, removeListener: boolean): void { clearExitAndReenterTransitions(entry, removeListener); const fragment: androidx.fragment.app.Fragment = entry.fragment; const enterListener = entry.enterTransitionListener; if (enterListener) { const enterTransition = fragment.getEnterTransition(); if (enterTransition) { if (removeListener) { enterTransition.removeListener(enterListener); } fragment.setEnterTransition(null); if (Trace.isEnabled()) { Trace.write(`Cleared Enter ${enterTransition.getClass().getSimpleName()} transition for ${fragment}`, Trace.categories.Transition); } } if (removeListener) { entry.enterTransitionListener = null; } } const returnListener = entry.returnTransitionListener; if (returnListener) { const returnTransition = fragment.getReturnTransition(); if (returnTransition) { if (removeListener) { returnTransition.removeListener(returnListener); } fragment.setReturnTransition(null); if (Trace.isEnabled()) { Trace.write(`Cleared Return ${returnTransition.getClass().getSimpleName()} transition for ${fragment}`, Trace.categories.Transition); } } if (removeListener) { entry.returnTransitionListener = null; } } } function allowTransitionOverlap(fragment: androidx.fragment.app.Fragment): void { if (fragment) { fragment.setAllowEnterTransitionOverlap(true); fragment.setAllowReturnTransitionOverlap(true); } } function setEnterTransition(navigationTransition: NavigationTransition, entry: ExpandedEntry, transition: androidx.transition.Transition): void { setUpNativeTransition(navigationTransition, transition); const listener = addNativeTransitionListener(entry, transition); // attach listener to JS object so that it will be alive as long as entry. entry.enterTransitionListener = listener; const fragment: androidx.fragment.app.Fragment = entry.fragment; fragment.setEnterTransition(transition); } function setExitTransition(navigationTransition: NavigationTransition, entry: ExpandedEntry, transition: androidx.transition.Transition): void { setUpNativeTransition(navigationTransition, transition); const listener = addNativeTransitionListener(entry, transition); // attach listener to JS object so that it will be alive as long as entry. entry.exitTransitionListener = listener; const fragment: androidx.fragment.app.Fragment = entry.fragment; fragment.setExitTransition(transition); } function setReenterTransition(navigationTransition: NavigationTransition, entry: ExpandedEntry, transition: androidx.transition.Transition): void { setUpNativeTransition(navigationTransition, transition); const listener = addNativeTransitionListener(entry, transition); // attach listener to JS object so that it will be alive as long as entry. entry.reenterTransitionListener = listener; const fragment: androidx.fragment.app.Fragment = entry.fragment; fragment.setReenterTransition(transition); } function setReturnTransition(navigationTransition: NavigationTransition, entry: ExpandedEntry, transition: androidx.transition.Transition): void { setUpNativeTransition(navigationTransition, transition); const listener = addNativeTransitionListener(entry, transition); // attach listener to JS object so that it will be alive as long as entry. entry.returnTransitionListener = listener; const fragment: androidx.fragment.app.Fragment = entry.fragment; fragment.setReturnTransition(transition); } function setupNewFragmentSlideTransition(navTransition: NavigationTransition, entry: ExpandedEntry, name: string): void { setupCurrentFragmentSlideTransition(navTransition, entry, name); const direction = name.substr('slide'.length) || 'left'; //Extract the direction from the string switch (direction) { case 'left': setEnterTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.RIGHT)); setReturnTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.RIGHT)); break; case 'right': setEnterTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.LEFT)); setReturnTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.LEFT)); break; case 'top': setEnterTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.BOTTOM)); setReturnTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.BOTTOM)); break; case 'bottom': setEnterTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.TOP)); setReturnTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.TOP)); break; } } function setupCurrentFragmentSlideTransition(navTransition: NavigationTransition, entry: ExpandedEntry, name: string): void { const direction = name.substr('slide'.length) || 'left'; //Extract the direction from the string switch (direction) { case 'left': setExitTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.LEFT)); setReenterTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.LEFT)); break; case 'right': setExitTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.RIGHT)); setReenterTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.RIGHT)); break; case 'top': setExitTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.TOP)); setReenterTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.TOP)); break; case 'bottom': setExitTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.BOTTOM)); setReenterTransition(navTransition, entry, new androidx.transition.Slide(android.view.Gravity.BOTTOM)); break; } } function setupCurrentFragmentCustomTransition(navTransition: NavigationTransition, entry: ExpandedEntry, transition: Transition): void { const exitAnimator = transition.createAndroidAnimator(Transition.AndroidTransitionType.exit); const exitTransition = new org.nativescript.widgets.CustomTransition(exitAnimator, transition.constructor.name + Transition.AndroidTransitionType.exit.toString()); setExitTransition(navTransition, entry, exitTransition); const reenterAnimator = transition.createAndroidAnimator(Transition.AndroidTransitionType.popEnter); const reenterTransition = new org.nativescript.widgets.CustomTransition(reenterAnimator, transition.constructor.name + Transition.AndroidTransitionType.popEnter.toString()); setReenterTransition(navTransition, entry, reenterTransition); } function setupNewFragmentCustomTransition(navTransition: NavigationTransition, entry: ExpandedEntry, transition: Transition): void { setupCurrentFragmentCustomTransition(navTransition, entry, transition); const enterAnimator = transition.createAndroidAnimator(Transition.AndroidTransitionType.enter); const enterTransition = new org.nativescript.widgets.CustomTransition(enterAnimator, transition.constructor.name + Transition.AndroidTransitionType.enter.toString()); setEnterTransition(navTransition, entry, enterTransition); const returnAnimator = transition.createAndroidAnimator(Transition.AndroidTransitionType.popExit); const returnTransition = new org.nativescript.widgets.CustomTransition(returnAnimator, transition.constructor.name + Transition.AndroidTransitionType.popExit.toString()); setReturnTransition(navTransition, entry, returnTransition); } function setupNewFragmentFadeTransition(navTransition: NavigationTransition, entry: ExpandedEntry): void { setupCurrentFragmentFadeTransition(navTransition, entry); const fadeInEnter = new androidx.transition.Fade(androidx.transition.Fade.IN); setEnterTransition(navTransition, entry, fadeInEnter); const fadeOutReturn = new androidx.transition.Fade(androidx.transition.Fade.OUT); setReturnTransition(navTransition, entry, fadeOutReturn); } function setupCurrentFragmentFadeTransition(navTransition: NavigationTransition, entry: ExpandedEntry): void { const fadeOutExit = new androidx.transition.Fade(androidx.transition.Fade.OUT); setExitTransition(navTransition, entry, fadeOutExit); // NOTE: There is a bug in Fade transition so we need to set all 4 // otherwise back navigation will complete immediately (won't run the reverse transition). const fadeInReenter = new androidx.transition.Fade(androidx.transition.Fade.IN); setReenterTransition(navTransition, entry, fadeInReenter); } function setupCurrentFragmentExplodeTransition(navTransition: NavigationTransition, entry: ExpandedEntry): void { setExitTransition(navTransition, entry, new androidx.transition.Explode()); setReenterTransition(navTransition, entry, new androidx.transition.Explode()); } function setupNewFragmentExplodeTransition(navTransition: NavigationTransition, entry: ExpandedEntry): void { setupCurrentFragmentExplodeTransition(navTransition, entry); setEnterTransition(navTransition, entry, new androidx.transition.Explode()); setReturnTransition(navTransition, entry, new androidx.transition.Explode()); } function setUpNativeTransition(navigationTransition: NavigationTransition, nativeTransition: androidx.transition.Transition) { if (navigationTransition.duration) { nativeTransition.setDuration(navigationTransition.duration); } const interpolator = navigationTransition.curve ? _resolveAnimationCurve(navigationTransition.curve) : defaultInterpolator(); nativeTransition.setInterpolator(interpolator); } export function addNativeTransitionListener(entry: ExpandedEntry, nativeTransition: androidx.transition.Transition): ExpandedTransitionListener { const listener = getTransitionListener(entry, nativeTransition); nativeTransition.addListener(listener); return listener; } function transitionOrAnimationCompleted(entry: ExpandedEntry, backEntry: BackstackEntry): void { const frameId = entry.frameId; const entries = waitingQueue.get(frameId); // https://github.com/NativeScript/NativeScript/issues/5759 // https://github.com/NativeScript/NativeScript/issues/5780 // transitionOrAnimationCompleted fires again (probably bug in android) // NOTE: we cannot reproduce this issue so this is a blind fix if (!entries) { return; } entries.delete(entry); if (entries.size === 0) { const frame = entry.resolvedPage.frame; // We have 0 or 1 entry per frameId in completedEntries // So there is no need to make it to Set like waitingQueue const previousCompletedAnimationEntry = completedEntries.get(frameId); completedEntries.delete(frameId); waitingQueue.delete(frameId); const navigationContext = frame._executingContext || { navigationType: NavigationType.back, }; let current = frame.isCurrent(entry) ? previousCompletedAnimationEntry : entry; current = current || entry; // Will be null if Frame is shown modally... // transitionOrAnimationCompleted fires again (probably bug in android). if (current) { setTimeout(() => frame.setCurrent(backEntry || current, navigationContext.navigationType)); } } else { completedEntries.set(frameId, entry); } } function toShortString(nativeTransition: androidx.transition.Transition): string { return `${nativeTransition.getClass().getSimpleName()}@${nativeTransition.hashCode().toString(16)}`; } function printTransitions(entry: ExpandedEntry) { if (entry && Trace.isEnabled()) { let result = `${entry.fragmentTag} Transitions:`; if (entry.transitionName) { result += `transitionName=${entry.transitionName}, `; } const fragment = entry.fragment; result += `${fragment.getEnterTransition() ? ' enter=' + toShortString(fragment.getEnterTransition()) : ''}`; result += `${fragment.getExitTransition() ? ' exit=' + toShortString(fragment.getExitTransition()) : ''}`; result += `${fragment.getReenterTransition() ? ' popEnter=' + toShortString(fragment.getReenterTransition()) : ''}`; result += `${fragment.getReturnTransition() ? ' popExit=' + toShortString(fragment.getReturnTransition()) : ''}`; Trace.write(result, Trace.categories.Transition); } } function javaObjectArray(...params: java.lang.Object[]) { const nativeArray = Array.create(java.lang.Object, params.length); params.forEach((value, i) => (nativeArray[i] = value)); return nativeArray; } function createDummyZeroDurationAnimator(duration: number): android.animation.AnimatorSet { const animatorSet = new android.animation.AnimatorSet(); const objectAnimators = Array.create(android.animation.Animator, 1); const values = Array.create('float', 2); values[0] = 0.0; values[1] = 1.0; const animator = <android.animation.Animator>android.animation.ObjectAnimator.ofFloat(null, 'alpha', values); animator.setDuration(duration); objectAnimators[0] = animator; animatorSet.playTogether(objectAnimators); return animatorSet; } class NoTransition extends Transition { public createAndroidAnimator(transitionType: string): android.animation.AnimatorSet { return createDummyZeroDurationAnimator(this.getDuration()); } }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * @interface * An interface representing UsageName. * The Usage Names. * */ export interface UsageName { /** * @member {string} [value] The name of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly value?: string; /** * @member {string} [localizedValue] The localized name of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly localizedValue?: string; } /** * @interface * An interface representing Usage. * Describes Batch AI Resource Usage. * */ export interface Usage { /** * @member {UsageUnit} [unit] An enum describing the unit of usage * measurement. Possible values include: 'Count' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly unit?: UsageUnit; /** * @member {number} [currentValue] The current usage of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly currentValue?: number; /** * @member {number} [limit] The maximum permitted usage of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly limit?: number; /** * @member {UsageName} [name] The name of the type of usage. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: UsageName; } /** * @interface * An interface representing UserAccountSettings. * Settings for user account that gets created on each on the nodes of a * cluster. * */ export interface UserAccountSettings { /** * @member {string} adminUserName User name. Name of the administrator user * account which can be used to SSH to nodes. */ adminUserName: string; /** * @member {string} [adminUserSshPublicKey] SSH public key. SSH public key of * the administrator user account. */ adminUserSshPublicKey?: string; /** * @member {string} [adminUserPassword] Password. Password of the * administrator user account. */ adminUserPassword?: string; } /** * @interface * An interface representing SshConfiguration. * SSH configuration. * */ export interface SshConfiguration { /** * @member {string[]} [publicIPsToAllow] Allowed public IPs. List of source * IP ranges to allow SSH connection from. The default value is '*' (all * source IPs are allowed). Maximum number of IP ranges that can be specified * is 400. */ publicIPsToAllow?: string[]; /** * @member {UserAccountSettings} userAccountSettings User account settings. * Settings for administrator user account to be created on a node. The * account can be used to establish SSH connection to the node. */ userAccountSettings: UserAccountSettings; } /** * @interface * An interface representing DataDisks. * Data disks settings. * */ export interface DataDisks { /** * @member {number} diskSizeInGB Disk size in GB. Disk size in GB for the * blank data disks. */ diskSizeInGB: number; /** * @member {CachingType} [cachingType] Caching type. Caching type for the * disks. Available values are none (default), readonly, readwrite. Caching * type can be set only for VM sizes supporting premium storage. Possible * values include: 'none', 'readonly', 'readwrite'. Default value: 'none' . */ cachingType?: CachingType; /** * @member {number} diskCount Number of data disks. Number of data disks * attached to the File Server. If multiple disks attached, they will be * configured in RAID level 0. */ diskCount: number; /** * @member {StorageAccountType} storageAccountType Storage account type. Type * of storage account to be used on the disk. Possible values are: * Standard_LRS or Premium_LRS. Premium storage account type can only be used * with VM sizes supporting premium storage. Possible values include: * 'Standard_LRS', 'Premium_LRS' */ storageAccountType: StorageAccountType; } /** * @interface * An interface representing ResourceId. * Represents a resource ID. For example, for a subnet, it is the resource URL * for the subnet. * * @extends BaseResource */ export interface ResourceId extends BaseResource { /** * @member {string} id The ID of the resource */ id: string; } /** * @interface * An interface representing MountSettings. * File Server mount Information. * */ export interface MountSettings { /** * @member {string} [mountPoint] Mount Point. Path where the data disks are * mounted on the File Server. */ mountPoint?: string; /** * @member {string} [fileServerPublicIP] Public IP. Public IP address of the * File Server which can be used to SSH to the node from outside of the * subnet. */ fileServerPublicIP?: string; /** * @member {string} [fileServerInternalIP] Internal IP. Internal IP address * of the File Server which can be used to access the File Server from within * the subnet. */ fileServerInternalIP?: string; } /** * @interface * An interface representing ProxyResource. * A definition of an Azure proxy resource. * * @extends BaseResource */ export interface ProxyResource extends BaseResource { /** * @member {string} [id] The ID of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly id?: string; /** * @member {string} [name] The name of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {string} [type] The type of the resource. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly type?: string; } /** * @interface * An interface representing FileServer. * File Server information. * * @extends ProxyResource */ export interface FileServer extends ProxyResource { /** * @member {string} [vmSize] VM size. VM size of the File Server. */ vmSize?: string; /** * @member {SshConfiguration} [sshConfiguration] SSH configuration. SSH * configuration for accessing the File Server node. */ sshConfiguration?: SshConfiguration; /** * @member {DataDisks} [dataDisks] Data disks configuration. Information * about disks attached to File Server VM. */ dataDisks?: DataDisks; /** * @member {ResourceId} [subnet] Subnet. File Server virtual network subnet * resource ID. */ subnet?: ResourceId; /** * @member {MountSettings} [mountSettings] Mount settings. File Server mount * settings. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly mountSettings?: MountSettings; /** * @member {Date} [provisioningStateTransitionTime] Provisioning State * Transition time. Time when the provisioning state was changed. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningStateTransitionTime?: Date; /** * @member {Date} [creationTime] Creation time. Time when the FileServer was * created. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly creationTime?: Date; /** * @member {FileServerProvisioningState} [provisioningState] Provisioning * state. Provisioning state of the File Server. Possible values: creating - * The File Server is getting created; updating - The File Server creation * has been accepted and it is getting updated; deleting - The user has * requested that the File Server be deleted, and it is in the process of * being deleted; failed - The File Server creation has failed with the * specified error code. Details about the error code are specified in the * message field; succeeded - The File Server creation has succeeded. * Possible values include: 'creating', 'updating', 'deleting', 'succeeded', * 'failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: FileServerProvisioningState; } /** * @interface * An interface representing KeyVaultSecretReference. * Key Vault Secret reference. * */ export interface KeyVaultSecretReference { /** * @member {ResourceId} sourceVault Key Vault resource identifier. Fully * qualified resource indentifier of the Key Vault. */ sourceVault: ResourceId; /** * @member {string} secretUrl Secret URL. The URL referencing a secret in the * Key Vault. */ secretUrl: string; } /** * @interface * An interface representing FileServerCreateParameters. * File Server creation parameters. * */ export interface FileServerCreateParameters { /** * @member {string} vmSize VM size. The size of the virtual machine for the * File Server. For information about available VM sizes from the Virtual * Machines Marketplace, see Sizes for Virtual Machines (Linux). */ vmSize: string; /** * @member {SshConfiguration} sshConfiguration SSH configuration. SSH * configuration for the File Server node. */ sshConfiguration: SshConfiguration; /** * @member {DataDisks} dataDisks Data disks. Settings for the data disks * which will be created for the File Server. */ dataDisks: DataDisks; /** * @member {ResourceId} [subnet] Subnet identifier. Identifier of an existing * virtual network subnet to put the File Server in. If not provided, a new * virtual network and subnet will be created. */ subnet?: ResourceId; } /** * @interface * An interface representing ManualScaleSettings. * Manual scale settings for the cluster. * */ export interface ManualScaleSettings { /** * @member {number} targetNodeCount Target node count. The desired number of * compute nodes in the Cluster. Default is 0. Default value: 0 . */ targetNodeCount: number; /** * @member {DeallocationOption} [nodeDeallocationOption] Node deallocation * options. An action to be performed when the cluster size is decreasing. * The default value is requeue. Possible values include: 'requeue', * 'terminate', 'waitforjobcompletion'. Default value: 'requeue' . */ nodeDeallocationOption?: DeallocationOption; } /** * @interface * An interface representing AutoScaleSettings. * Auto-scale settings for the cluster. The system automatically scales the * cluster up and down (within minimumNodeCount and maximumNodeCount) based on * the number of queued and running jobs assigned to the cluster. * */ export interface AutoScaleSettings { /** * @member {number} minimumNodeCount Minimum node count. The minimum number * of compute nodes the Batch AI service will try to allocate for the * cluster. Note, the actual number of nodes can be less than the specified * value if the subscription has not enough quota to fulfill the request. */ minimumNodeCount: number; /** * @member {number} maximumNodeCount Maximum node count. The maximum number * of compute nodes the cluster can have. */ maximumNodeCount: number; /** * @member {number} [initialNodeCount] Initial node count. The number of * compute nodes to allocate on cluster creation. Note that this value is * used only during cluster creation. Default: 0. Default value: 0 . */ initialNodeCount?: number; } /** * @interface * An interface representing ScaleSettings. * At least one of manual or autoScale settings must be specified. Only one of * manual or autoScale settings can be specified. If autoScale settings are * specified, the system automatically scales the cluster up and down (within * the supplied limits) based on the pending jobs on the cluster. * */ export interface ScaleSettings { /** * @member {ManualScaleSettings} [manual] Manual scale settings. Manual scale * settings for the cluster. */ manual?: ManualScaleSettings; /** * @member {AutoScaleSettings} [autoScale] Auto-scale settings. Auto-scale * settings for the cluster. */ autoScale?: AutoScaleSettings; } /** * @interface * An interface representing ImageReference. * The OS image reference. * */ export interface ImageReference { /** * @member {string} publisher Publisher. Publisher of the image. */ publisher: string; /** * @member {string} offer Offer. Offer of the image. */ offer: string; /** * @member {string} sku SKU. SKU of the image. */ sku: string; /** * @member {string} [version] Version. Version of the image. */ version?: string; /** * @member {string} [virtualMachineImageId] Custom VM image resource ID. The * ARM resource identifier of the virtual machine image for the compute * nodes. This is of the form * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.Compute/images/{imageName}. * The virtual machine image must be in the same region and subscription as * the cluster. For information about the firewall settings for the Batch * node agent to communicate with the Batch service see * https://docs.microsoft.com/en-us/azure/batch/batch-api-basics#virtual-network-vnet-and-firewall-configuration. * Note, you need to provide publisher, offer and sku of the base OS image of * which the custom image has been derived from. */ virtualMachineImageId?: string; } /** * @interface * An interface representing VirtualMachineConfiguration. * VM configuration. * */ export interface VirtualMachineConfiguration { /** * @member {ImageReference} [imageReference] Image reference. OS image * reference for cluster nodes. */ imageReference?: ImageReference; } /** * @interface * An interface representing EnvironmentVariable. * An environment variable definition. * */ export interface EnvironmentVariable { /** * @member {string} name Name. The name of the environment variable. */ name: string; /** * @member {string} value Value. The value of the environment variable. */ value: string; } /** * @interface * An interface representing EnvironmentVariableWithSecretValue. * An environment variable with secret value definition. * */ export interface EnvironmentVariableWithSecretValue { /** * @member {string} name Name. The name of the environment variable to store * the secret value. */ name: string; /** * @member {string} [value] Value. The value of the environment variable. * This value will never be reported back by Batch AI. */ value?: string; /** * @member {KeyVaultSecretReference} [valueSecretReference] KeyVault secret * reference. KeyVault store and secret which contains the value for the * environment variable. One of value or valueSecretReference must be * provided. */ valueSecretReference?: KeyVaultSecretReference; } /** * @interface * An interface representing SetupTask. * Specifies a setup task which can be used to customize the compute nodes of * the cluster. * */ export interface SetupTask { /** * @member {string} commandLine Command line. The command line to be executed * on each cluster's node after it being allocated or rebooted. The command * is executed in a bash subshell as a root. */ commandLine: string; /** * @member {EnvironmentVariable[]} [environmentVariables] Environment * variables. A collection of user defined environment variables to be set * for setup task. */ environmentVariables?: EnvironmentVariable[]; /** * @member {EnvironmentVariableWithSecretValue[]} [secrets] Secrets. A * collection of user defined environment variables with secret values to be * set for the setup task. Server will never report values of these variables * back. */ secrets?: EnvironmentVariableWithSecretValue[]; /** * @member {string} stdOutErrPathPrefix Output path prefix. The prefix of a * path where the Batch AI service will upload the stdout, stderr and * execution log of the setup task. */ stdOutErrPathPrefix: string; /** * @member {string} [stdOutErrPathSuffix] Output path suffix. A path segment * appended by Batch AI to stdOutErrPathPrefix to form a path where stdout, * stderr and execution log of the setup task will be uploaded. Batch AI * creates the setup task output directories under an unique path to avoid * conflicts between different clusters. The full path can be obtained by * concatenation of stdOutErrPathPrefix and stdOutErrPathSuffix. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly stdOutErrPathSuffix?: string; } /** * @interface * An interface representing AzureStorageCredentialsInfo. * Azure storage account credentials. * */ export interface AzureStorageCredentialsInfo { /** * @member {string} [accountKey] Account key. Storage account key. One of * accountKey or accountKeySecretReference must be specified. */ accountKey?: string; /** * @member {KeyVaultSecretReference} [accountKeySecretReference] Account key * secret reference. Information about KeyVault secret storing the storage * account key. One of accountKey or accountKeySecretReference must be * specified. */ accountKeySecretReference?: KeyVaultSecretReference; } /** * @interface * An interface representing AzureFileShareReference. * Azure File Share mounting configuration. * */ export interface AzureFileShareReference { /** * @member {string} accountName Account name. Name of the Azure storage * account. */ accountName: string; /** * @member {string} azureFileUrl Azure File URL. URL to access the Azure * File. */ azureFileUrl: string; /** * @member {AzureStorageCredentialsInfo} credentials Credentials. Information * about the Azure storage credentials. */ credentials: AzureStorageCredentialsInfo; /** * @member {string} relativeMountPath Relative mount path. The relative path * on the compute node where the Azure File share will be mounted. Note that * all cluster level file shares will be mounted under $AZ_BATCHAI_MOUNT_ROOT * location and all job level file shares will be mounted under * $AZ_BATCHAI_JOB_MOUNT_ROOT. */ relativeMountPath: string; /** * @member {string} [fileMode] File mode. File mode for files on the mounted * file share. Default value: 0777. Default value: '0777' . */ fileMode?: string; /** * @member {string} [directoryMode] Directory mode. File mode for directories * on the mounted file share. Default value: 0777. Default value: '0777' . */ directoryMode?: string; } /** * @interface * An interface representing AzureBlobFileSystemReference. * Azure Blob Storage Container mounting configuration. * */ export interface AzureBlobFileSystemReference { /** * @member {string} accountName Account name. Name of the Azure storage * account. */ accountName: string; /** * @member {string} containerName Container name. Name of the Azure Blob * Storage container to mount on the cluster. */ containerName: string; /** * @member {AzureStorageCredentialsInfo} credentials Credentials. Information * about the Azure storage credentials. */ credentials: AzureStorageCredentialsInfo; /** * @member {string} relativeMountPath Relative mount path. The relative path * on the compute node where the Azure File container will be mounted. Note * that all cluster level containers will be mounted under * $AZ_BATCHAI_MOUNT_ROOT location and all job level containers will be * mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. */ relativeMountPath: string; /** * @member {string} [mountOptions] Mount options. Mount options for mounting * blobfuse file system. */ mountOptions?: string; } /** * @interface * An interface representing FileServerReference. * File Server mounting configuration. * */ export interface FileServerReference { /** * @member {ResourceId} fileServer File server. Resource ID of the existing * File Server to be mounted. */ fileServer: ResourceId; /** * @member {string} [sourceDirectory] Source directory. File Server directory * that needs to be mounted. If this property is not specified, the entire * File Server will be mounted. */ sourceDirectory?: string; /** * @member {string} relativeMountPath Relative mount path. The relative path * on the compute node where the File Server will be mounted. Note that all * cluster level file servers will be mounted under $AZ_BATCHAI_MOUNT_ROOT * location and all job level file servers will be mounted under * $AZ_BATCHAI_JOB_MOUNT_ROOT. */ relativeMountPath: string; /** * @member {string} [mountOptions] Mount options. Mount options to be passed * to mount command. */ mountOptions?: string; } /** * @interface * An interface representing UnmanagedFileSystemReference. * Unmananged file system mounting configuration. * */ export interface UnmanagedFileSystemReference { /** * @member {string} mountCommand Mount command. Mount command line. Note, * Batch AI will append mount path to the command on its own. */ mountCommand: string; /** * @member {string} relativeMountPath Relative mount path. The relative path * on the compute node where the unmanaged file system will be mounted. Note * that all cluster level unmanaged file systems will be mounted under * $AZ_BATCHAI_MOUNT_ROOT location and all job level unmanaged file systems * will be mounted under $AZ_BATCHAI_JOB_MOUNT_ROOT. */ relativeMountPath: string; } /** * @interface * An interface representing MountVolumes. * Details of volumes to mount on the cluster. * */ export interface MountVolumes { /** * @member {AzureFileShareReference[]} [azureFileShares] Azure File Shares. A * collection of Azure File Shares that are to be mounted to the cluster * nodes. */ azureFileShares?: AzureFileShareReference[]; /** * @member {AzureBlobFileSystemReference[]} [azureBlobFileSystems] Azure Blob * file systems. A collection of Azure Blob Containers that are to be mounted * to the cluster nodes. */ azureBlobFileSystems?: AzureBlobFileSystemReference[]; /** * @member {FileServerReference[]} [fileServers] File Servers. A collection * of Batch AI File Servers that are to be mounted to the cluster nodes. */ fileServers?: FileServerReference[]; /** * @member {UnmanagedFileSystemReference[]} [unmanagedFileSystems] Unmanaged * file systems. A collection of unmanaged file systems that are to be * mounted to the cluster nodes. */ unmanagedFileSystems?: UnmanagedFileSystemReference[]; } /** * @interface * An interface representing AppInsightsReference. * Azure Application Insights information for performance counters reporting. * */ export interface AppInsightsReference { /** * @member {ResourceId} component Component ID. Azure Application Insights * component resource ID. */ component: ResourceId; /** * @member {string} [instrumentationKey] Instrumentation Key. Value of the * Azure Application Insights instrumentation key. */ instrumentationKey?: string; /** * @member {KeyVaultSecretReference} [instrumentationKeySecretReference] * Instrumentation key KeyVault Secret reference. KeyVault Store and Secret * which contains Azure Application Insights instrumentation key. One of * instrumentationKey or instrumentationKeySecretReference must be specified. */ instrumentationKeySecretReference?: KeyVaultSecretReference; } /** * @interface * An interface representing PerformanceCountersSettings. * Performance counters reporting settings. * */ export interface PerformanceCountersSettings { /** * @member {AppInsightsReference} appInsightsReference Azure Application * Insights reference. Azure Application Insights information for performance * counters reporting. If provided, Batch AI will upload node performance * counters to the corresponding Azure Application Insights account. */ appInsightsReference: AppInsightsReference; } /** * @interface * An interface representing NodeSetup. * Node setup settings. * */ export interface NodeSetup { /** * @member {SetupTask} [setupTask] Setup task. Setup task to run on cluster * nodes when nodes got created or rebooted. The setup task code needs to be * idempotent. Generally the setup task is used to download static data that * is required for all jobs that run on the cluster VMs and/or to * download/install software. */ setupTask?: SetupTask; /** * @member {MountVolumes} [mountVolumes] Mount volumes. Mount volumes to be * available to setup task and all jobs executing on the cluster. The volumes * will be mounted at location specified by $AZ_BATCHAI_MOUNT_ROOT * environment variable. */ mountVolumes?: MountVolumes; /** * @member {PerformanceCountersSettings} [performanceCountersSettings] * Performance counters settings. Settings for performance counters * collecting and uploading. */ performanceCountersSettings?: PerformanceCountersSettings; } /** * @interface * An interface representing NodeStateCounts. * Counts of various compute node states on the cluster. * */ export interface NodeStateCounts { /** * @member {number} [idleNodeCount] Idle node count. Number of compute nodes * in idle state. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly idleNodeCount?: number; /** * @member {number} [runningNodeCount] Running node count. Number of compute * nodes which are running jobs. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly runningNodeCount?: number; /** * @member {number} [preparingNodeCount] Preparing node count. Number of * compute nodes which are being prepared. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly preparingNodeCount?: number; /** * @member {number} [unusableNodeCount] Unusable node count. Number of * compute nodes which are in unusable state. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly unusableNodeCount?: number; /** * @member {number} [leavingNodeCount] Leaving node count. Number of compute * nodes which are leaving the cluster. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly leavingNodeCount?: number; } /** * @interface * An interface representing ClusterCreateParameters. * Cluster creation operation. * */ export interface ClusterCreateParameters { /** * @member {string} vmSize VM size. The size of the virtual machines in the * cluster. All nodes in a cluster have the same VM size. For information * about available VM sizes for clusters using images from the Virtual * Machines Marketplace see Sizes for Virtual Machines (Linux). Batch AI * service supports all Azure VM sizes except STANDARD_A0 and those with * premium storage (STANDARD_GS, STANDARD_DS, and STANDARD_DSV2 series). */ vmSize: string; /** * @member {VmPriority} [vmPriority] VM priority. VM priority. Allowed values * are: dedicated (default) and lowpriority. Possible values include: * 'dedicated', 'lowpriority'. Default value: 'dedicated' . */ vmPriority?: VmPriority; /** * @member {ScaleSettings} [scaleSettings] Scale settings. Scale settings for * the cluster. Batch AI service supports manual and auto scale clusters. */ scaleSettings?: ScaleSettings; /** * @member {VirtualMachineConfiguration} [virtualMachineConfiguration] VM * configuration. OS image configuration for cluster nodes. All nodes in a * cluster have the same OS image. */ virtualMachineConfiguration?: VirtualMachineConfiguration; /** * @member {NodeSetup} [nodeSetup] Node setup. Setup to be performed on each * compute node in the cluster. */ nodeSetup?: NodeSetup; /** * @member {UserAccountSettings} userAccountSettings User account settings. * Settings for an administrator user account that will be created on each * compute node in the cluster. */ userAccountSettings: UserAccountSettings; /** * @member {ResourceId} [subnet] Subnet. Existing virtual network subnet to * put the cluster nodes in. Note, if a File Server mount configured in node * setup, the File Server's subnet will be used automatically. */ subnet?: ResourceId; } /** * @interface * An interface representing ClusterUpdateParameters. * Cluster update parameters. * */ export interface ClusterUpdateParameters { /** * @member {ScaleSettings} [scaleSettings] Scale settings. Desired scale * settings for the cluster. Batch AI service supports manual and auto scale * clusters. */ scaleSettings?: ScaleSettings; } /** * @interface * An interface representing NameValuePair. * Name-value pair. * */ export interface NameValuePair { /** * @member {string} [name] Name. The name in the name-value pair. */ name?: string; /** * @member {string} [value] Value. The value in the name-value pair. */ value?: string; } /** * @interface * An interface representing BatchAIError. * An error response from the Batch AI service. * */ export interface BatchAIError { /** * @member {string} [code] An identifier of the error. Codes are invariant * and are intended to be consumed programmatically. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly code?: string; /** * @member {string} [message] A message describing the error, intended to be * suitable for display in a user interface. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly message?: string; /** * @member {NameValuePair[]} [details] A list of additional details about the * error. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly details?: NameValuePair[]; } /** * @interface * An interface representing Cluster. * Information about a Cluster. * * @extends ProxyResource */ export interface Cluster extends ProxyResource { /** * @member {string} [vmSize] VM size. The size of the virtual machines in the * cluster. All nodes in a cluster have the same VM size. */ vmSize?: string; /** * @member {VmPriority} [vmPriority] VM priority. VM priority of cluster * nodes. Possible values include: 'dedicated', 'lowpriority'. Default value: * 'dedicated' . */ vmPriority?: VmPriority; /** * @member {ScaleSettings} [scaleSettings] Scale settings. Scale settings of * the cluster. */ scaleSettings?: ScaleSettings; /** * @member {VirtualMachineConfiguration} [virtualMachineConfiguration] VM * configuration. Virtual machine configuration (OS image) of the compute * nodes. All nodes in a cluster have the same OS image configuration. */ virtualMachineConfiguration?: VirtualMachineConfiguration; /** * @member {NodeSetup} [nodeSetup] Node setup. Setup (mount file systems, * performance counters settings and custom setup task) to be performed on * each compute node in the cluster. */ nodeSetup?: NodeSetup; /** * @member {UserAccountSettings} [userAccountSettings] User account settings. * Administrator user account settings which can be used to SSH to compute * nodes. */ userAccountSettings?: UserAccountSettings; /** * @member {ResourceId} [subnet] Subnet. Virtual network subnet resource ID * the cluster nodes belong to. */ subnet?: ResourceId; /** * @member {Date} [creationTime] Creation time. The time when the cluster was * created. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly creationTime?: Date; /** * @member {ProvisioningState} [provisioningState] Provisioning state. * Provisioning state of the cluster. Possible value are: creating - * Specifies that the cluster is being created. succeeded - Specifies that * the cluster has been created successfully. failed - Specifies that the * cluster creation has failed. deleting - Specifies that the cluster is * being deleted. Possible values include: 'creating', 'succeeded', 'failed', * 'deleting' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: ProvisioningState; /** * @member {Date} [provisioningStateTransitionTime] Provisioning State * Transition time. Time when the provisioning state was changed. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningStateTransitionTime?: Date; /** * @member {AllocationState} [allocationState] Allocation state. Allocation * state of the cluster. Possible values are: steady - Indicates that the * cluster is not resizing. There are no changes to the number of compute * nodes in the cluster in progress. A cluster enters this state when it is * created and when no operations are being performed on the cluster to * change the number of compute nodes. resizing - Indicates that the cluster * is resizing; that is, compute nodes are being added to or removed from the * cluster. Possible values include: 'steady', 'resizing' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly allocationState?: AllocationState; /** * @member {Date} [allocationStateTransitionTime] Allocation state transition * time. The time at which the cluster entered its current allocation state. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly allocationStateTransitionTime?: Date; /** * @member {BatchAIError[]} [errors] Errors. Collection of errors encountered * by various compute nodes during node setup. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly errors?: BatchAIError[]; /** * @member {number} [currentNodeCount] Current node count. The number of * compute nodes currently assigned to the cluster. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly currentNodeCount?: number; /** * @member {NodeStateCounts} [nodeStateCounts] Node state counts. Counts of * various node states on the cluster. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nodeStateCounts?: NodeStateCounts; } /** * @interface * An interface representing PrivateRegistryCredentials. * Credentials to access a container image in a private repository. * */ export interface PrivateRegistryCredentials { /** * @member {string} username User name. User name to login to the repository. */ username: string; /** * @member {string} [password] Password. User password to login to the docker * repository. One of password or passwordSecretReference must be specified. */ password?: string; /** * @member {KeyVaultSecretReference} [passwordSecretReference] Password * secret reference. KeyVault Secret storing the password. Users can store * their secrets in Azure KeyVault and pass it to the Batch AI service to * integrate with KeyVault. One of password or passwordSecretReference must * be specified. */ passwordSecretReference?: KeyVaultSecretReference; } /** * @interface * An interface representing ImageSourceRegistry. * Information about docker image for the job. * */ export interface ImageSourceRegistry { /** * @member {string} [serverUrl] Server URL. URL for image repository. */ serverUrl?: string; /** * @member {string} image Image. The name of the image in the image * repository. */ image: string; /** * @member {PrivateRegistryCredentials} [credentials] Credentials. * Credentials to access the private docker repository. */ credentials?: PrivateRegistryCredentials; } /** * @interface * An interface representing ContainerSettings. * Docker container settings. * */ export interface ContainerSettings { /** * @member {ImageSourceRegistry} imageSourceRegistry Image source registry. * Information about docker image and docker registry to download the * container from. */ imageSourceRegistry: ImageSourceRegistry; /** * @member {string} [shmSize] /dev/shm size. Size of /dev/shm. Please refer * to docker documentation for supported argument formats. */ shmSize?: string; } /** * @interface * An interface representing CNTKsettings. * CNTK (aka Microsoft Cognitive Toolkit) job settings. * */ export interface CNTKsettings { /** * @member {string} [languageType] Language type. The language to use for * launching CNTK (aka Microsoft Cognitive Toolkit) job. Valid values are * 'BrainScript' or 'Python'. */ languageType?: string; /** * @member {string} [configFilePath] Config file path. Specifies the path of * the BrainScript config file. This property can be specified only if the * languageType is 'BrainScript'. */ configFilePath?: string; /** * @member {string} [pythonScriptFilePath] Python script file path. Python * script to execute. This property can be specified only if the languageType * is 'Python'. */ pythonScriptFilePath?: string; /** * @member {string} [pythonInterpreterPath] Python interpreter path. The path * to the Python interpreter. This property can be specified only if the * languageType is 'Python'. */ pythonInterpreterPath?: string; /** * @member {string} [commandLineArgs] Command line arguments. Command line * arguments that need to be passed to the python script or cntk executable. */ commandLineArgs?: string; /** * @member {number} [processCount] Process count. Number of processes to * launch for the job execution. The default value for this property is equal * to nodeCount property */ processCount?: number; } /** * @interface * An interface representing PyTorchSettings. * pyTorch job settings. * */ export interface PyTorchSettings { /** * @member {string} pythonScriptFilePath Python script file path. The python * script to execute. */ pythonScriptFilePath: string; /** * @member {string} [pythonInterpreterPath] Python interpreter path. The path * to the Python interpreter. */ pythonInterpreterPath?: string; /** * @member {string} [commandLineArgs] Command line arguments. Command line * arguments that need to be passed to the python script. */ commandLineArgs?: string; /** * @member {number} [processCount] Process count. Number of processes to * launch for the job execution. The default value for this property is equal * to nodeCount property */ processCount?: number; /** * @member {string} [communicationBackend] Communication backend. Type of the * communication backend for distributed jobs. Valid values are 'TCP', 'Gloo' * or 'MPI'. Not required for non-distributed jobs. */ communicationBackend?: string; } /** * @interface * An interface representing TensorFlowSettings. * TensorFlow job settings. * */ export interface TensorFlowSettings { /** * @member {string} pythonScriptFilePath Python script file path. The python * script to execute. */ pythonScriptFilePath: string; /** * @member {string} [pythonInterpreterPath] Python interpreter path. The path * to the Python interpreter. */ pythonInterpreterPath?: string; /** * @member {string} [masterCommandLineArgs] Master command line arguments. * Command line arguments that need to be passed to the python script for the * master task. */ masterCommandLineArgs?: string; /** * @member {string} [workerCommandLineArgs] Worker command line arguments. * Command line arguments that need to be passed to the python script for the * worker task. Optional for single process jobs. */ workerCommandLineArgs?: string; /** * @member {string} [parameterServerCommandLineArgs] Parameter server command * line arguments. Command line arguments that need to be passed to the * python script for the parameter server. Optional for single process jobs. */ parameterServerCommandLineArgs?: string; /** * @member {number} [workerCount] Worker count. The number of worker tasks. * If specified, the value must be less than or equal to (nodeCount * * numberOfGPUs per VM). If not specified, the default value is equal to * nodeCount. This property can be specified only for distributed TensorFlow * training. */ workerCount?: number; /** * @member {number} [parameterServerCount] Parameter server count. The number * of parameter server tasks. If specified, the value must be less than or * equal to nodeCount. If not specified, the default value is equal to 1 for * distributed TensorFlow training. This property can be specified only for * distributed TensorFlow training. */ parameterServerCount?: number; } /** * @interface * An interface representing CaffeSettings. * Caffe job settings. * */ export interface CaffeSettings { /** * @member {string} [configFilePath] Config file path. Path of the config * file for the job. This property cannot be specified if * pythonScriptFilePath is specified. */ configFilePath?: string; /** * @member {string} [pythonScriptFilePath] Python script file path. Python * script to execute. This property cannot be specified if configFilePath is * specified. */ pythonScriptFilePath?: string; /** * @member {string} [pythonInterpreterPath] Python interpreter path. The path * to the Python interpreter. The property can be specified only if the * pythonScriptFilePath is specified. */ pythonInterpreterPath?: string; /** * @member {string} [commandLineArgs] Command line arguments. Command line * arguments that need to be passed to the Caffe job. */ commandLineArgs?: string; /** * @member {number} [processCount] Process count. Number of processes to * launch for the job execution. The default value for this property is equal * to nodeCount property */ processCount?: number; } /** * @interface * An interface representing Caffe2Settings. * Caffe2 job settings. * */ export interface Caffe2Settings { /** * @member {string} pythonScriptFilePath Python script file path. The python * script to execute. */ pythonScriptFilePath: string; /** * @member {string} [pythonInterpreterPath] Python interpreter path. The path * to the Python interpreter. */ pythonInterpreterPath?: string; /** * @member {string} [commandLineArgs] Command line arguments. Command line * arguments that need to be passed to the python script. */ commandLineArgs?: string; } /** * @interface * An interface representing ChainerSettings. * Chainer job settings. * */ export interface ChainerSettings { /** * @member {string} pythonScriptFilePath Python script file path. The python * script to execute. */ pythonScriptFilePath: string; /** * @member {string} [pythonInterpreterPath] Python interpreter path. The path * to the Python interpreter. */ pythonInterpreterPath?: string; /** * @member {string} [commandLineArgs] Command line arguments. Command line * arguments that need to be passed to the python script. */ commandLineArgs?: string; /** * @member {number} [processCount] Process count. Number of processes to * launch for the job execution. The default value for this property is equal * to nodeCount property */ processCount?: number; } /** * @interface * An interface representing CustomToolkitSettings. * Custom tool kit job settings. * */ export interface CustomToolkitSettings { /** * @member {string} [commandLine] Command line. The command line to execute * on the master node. */ commandLine?: string; } /** * @interface * An interface representing CustomMpiSettings. * Custom MPI job settings. * */ export interface CustomMpiSettings { /** * @member {string} commandLine Command line. The command line to be executed * by mpi runtime on each compute node. */ commandLine: string; /** * @member {number} [processCount] Process count. Number of processes to * launch for the job execution. The default value for this property is equal * to nodeCount property */ processCount?: number; } /** * @interface * An interface representing HorovodSettings. * Specifies the settings for Horovod job. * */ export interface HorovodSettings { /** * @member {string} pythonScriptFilePath Python script file path. The python * script to execute. */ pythonScriptFilePath: string; /** * @member {string} [pythonInterpreterPath] Python interpreter path. The path * to the Python interpreter. */ pythonInterpreterPath?: string; /** * @member {string} [commandLineArgs] Command line arguments. Command line * arguments that need to be passed to the python script. */ commandLineArgs?: string; /** * @member {number} [processCount] Process count. Number of processes to * launch for the job execution. The default value for this property is equal * to nodeCount property */ processCount?: number; } /** * @interface * An interface representing JobPreparation. * Job preparation settings. * */ export interface JobPreparation { /** * @member {string} commandLine Command line. The command line to execute. If * containerSettings is specified on the job, this commandLine will be * executed in the same container as job. Otherwise it will be executed on * the node. */ commandLine: string; } /** * @interface * An interface representing InputDirectory. * Input directory for the job. * */ export interface InputDirectory { /** * @member {string} id ID. The ID for the input directory. The job can use * AZ_BATCHAI_INPUT_<id> environment variable to find the directory path, * where <id> is the value of id attribute. */ id: string; /** * @member {string} path Path. The path to the input directory. */ path: string; } /** * @interface * An interface representing OutputDirectory. * Output directory for the job. * */ export interface OutputDirectory { /** * @member {string} id ID. The ID of the output directory. The job can use * AZ_BATCHAI_OUTPUT_<id> environment variale to find the directory path, * where <id> is the value of id attribute. */ id: string; /** * @member {string} pathPrefix Path prefix. The prefix path where the output * directory will be created. Note, this is an absolute path to prefix. E.g. * $AZ_BATCHAI_MOUNT_ROOT/MyNFS/MyLogs. The full path to the output directory * by combining pathPrefix, jobOutputDirectoryPathSegment (reported by get * job) and pathSuffix. */ pathPrefix: string; /** * @member {string} [pathSuffix] Path suffix. The suffix path where the * output directory will be created. E.g. models. You can find the full path * to the output directory by combining pathPrefix, * jobOutputDirectoryPathSegment (reported by get job) and pathSuffix. */ pathSuffix?: string; } /** * @interface * An interface representing JobBasePropertiesConstraints. * Constraints associated with the Job. * */ export interface JobBasePropertiesConstraints { /** * @member {string} [maxWallClockTime] Max wall clock time. Max time the job * can run. Default value: 1 week. Default value: '7.00:00:00' . */ maxWallClockTime?: string; } /** * @interface * An interface representing JobCreateParameters. * Job creation parameters. * */ export interface JobCreateParameters { /** * @member {JobPriority} [schedulingPriority] Scheduling priority. Scheduling * priority associated with the job. Possible values: low, normal, high. * Possible values include: 'low', 'normal', 'high'. Default value: 'normal' * . */ schedulingPriority?: JobPriority; /** * @member {ResourceId} cluster Cluster. Resource ID of the cluster on which * this job will run. */ cluster: ResourceId; /** * @member {MountVolumes} [mountVolumes] Mount volumes. Information on mount * volumes to be used by the job. These volumes will be mounted before the * job execution and will be unmouted after the job completion. The volumes * will be mounted at location specified by $AZ_BATCHAI_JOB_MOUNT_ROOT * environment variable. */ mountVolumes?: MountVolumes; /** * @member {number} nodeCount Node count. Number of compute nodes to run the * job on. The job will be gang scheduled on that many compute nodes. */ nodeCount: number; /** * @member {ContainerSettings} [containerSettings] Container settings. Docker * container settings for the job. If not provided, the job will run directly * on the node. */ containerSettings?: ContainerSettings; /** * @member {CNTKsettings} [cntkSettings] CNTK settings. Settings for CNTK * (aka Microsoft Cognitive Toolkit) job. */ cntkSettings?: CNTKsettings; /** * @member {PyTorchSettings} [pyTorchSettings] pyTorch settings. Settings for * pyTorch job. */ pyTorchSettings?: PyTorchSettings; /** * @member {TensorFlowSettings} [tensorFlowSettings] TensorFlow settings. * Settings for Tensor Flow job. */ tensorFlowSettings?: TensorFlowSettings; /** * @member {CaffeSettings} [caffeSettings] Caffe settings. Settings for Caffe * job. */ caffeSettings?: CaffeSettings; /** * @member {Caffe2Settings} [caffe2Settings] Caffe2 settings. Settings for * Caffe2 job. */ caffe2Settings?: Caffe2Settings; /** * @member {ChainerSettings} [chainerSettings] Chainer settings. Settings for * Chainer job. */ chainerSettings?: ChainerSettings; /** * @member {CustomToolkitSettings} [customToolkitSettings] Custom tool kit * job. Settings for custom tool kit job. */ customToolkitSettings?: CustomToolkitSettings; /** * @member {CustomMpiSettings} [customMpiSettings] Custom MPI settings. * Settings for custom MPI job. */ customMpiSettings?: CustomMpiSettings; /** * @member {HorovodSettings} [horovodSettings] Horovod settings. Settings for * Horovod job. */ horovodSettings?: HorovodSettings; /** * @member {JobPreparation} [jobPreparation] Job preparation. A command line * to be executed on each node allocated for the job before tool kit is * launched. */ jobPreparation?: JobPreparation; /** * @member {string} stdOutErrPathPrefix Standard output path prefix. The path * where the Batch AI service will store stdout, stderror and execution log * of the job. */ stdOutErrPathPrefix: string; /** * @member {InputDirectory[]} [inputDirectories] Input directories. A list of * input directories for the job. */ inputDirectories?: InputDirectory[]; /** * @member {OutputDirectory[]} [outputDirectories] Output directories. A list * of output directories for the job. */ outputDirectories?: OutputDirectory[]; /** * @member {EnvironmentVariable[]} [environmentVariables] Environment * variables. A list of user defined environment variables which will be * setup for the job. */ environmentVariables?: EnvironmentVariable[]; /** * @member {EnvironmentVariableWithSecretValue[]} [secrets] Secrets. A list * of user defined environment variables with secret values which will be * setup for the job. Server will never report values of these variables * back. */ secrets?: EnvironmentVariableWithSecretValue[]; /** * @member {JobBasePropertiesConstraints} [constraints] Constraints * associated with the Job. */ constraints?: JobBasePropertiesConstraints; } /** * @interface * An interface representing JobPropertiesConstraints. * Constraints associated with the Job. * */ export interface JobPropertiesConstraints { /** * @member {string} [maxWallClockTime] Max wall clock time. Max time the job * can run. Default value: 1 week. Default value: '7.00:00:00' . */ maxWallClockTime?: string; } /** * @interface * An interface representing JobPropertiesExecutionInfo. * Information about the execution of a job. * */ export interface JobPropertiesExecutionInfo { /** * @member {Date} [startTime] Start time. The time at which the job started * running. 'Running' corresponds to the running state. If the job has been * restarted or retried, this is the most recent time at which the job * started running. This property is present only for job that are in the * running or completed state. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly startTime?: Date; /** * @member {Date} [endTime] End time. The time at which the job completed. * This property is only returned if the job is in completed state. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly endTime?: Date; /** * @member {number} [exitCode] Exit code. The exit code of the job. This * property is only returned if the job is in completed state. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly exitCode?: number; /** * @member {BatchAIError[]} [errors] Errors. A collection of errors * encountered by the service during job execution. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly errors?: BatchAIError[]; } /** * @interface * An interface representing Job. * Information about a Job. * * @extends ProxyResource */ export interface Job extends ProxyResource { /** * @member {JobPriority} [schedulingPriority] Scheduling priority. Scheduling * priority associated with the job. Possible values include: 'low', * 'normal', 'high'. Default value: 'normal' . */ schedulingPriority?: JobPriority; /** * @member {ResourceId} [cluster] Cluster. Resource ID of the cluster * associated with the job. */ cluster?: ResourceId; /** * @member {MountVolumes} [mountVolumes] Mount volumes. Collection of mount * volumes available to the job during execution. These volumes are mounted * before the job execution and unmouted after the job completion. The * volumes are mounted at location specified by $AZ_BATCHAI_JOB_MOUNT_ROOT * environment variable. */ mountVolumes?: MountVolumes; /** * @member {number} [nodeCount] Number of compute nodes to run the job on. * The job will be gang scheduled on that many compute nodes */ nodeCount?: number; /** * @member {ContainerSettings} [containerSettings] If provided the job will * run in the specified container. If the container was downloaded as part of * cluster setup then the same container image will be used. If not provided, * the job will run on the VM. */ containerSettings?: ContainerSettings; /** * @member {ToolType} [toolType] The toolkit type of this job. Possible * values are: cntk, tensorflow, caffe, caffe2, chainer, pytorch, custom, * custommpi, horovod. Possible values include: 'cntk', 'tensorflow', * 'caffe', 'caffe2', 'chainer', 'horovod', 'custommpi', 'custom' */ toolType?: ToolType; /** * @member {CNTKsettings} [cntkSettings] Specifies the settings for CNTK (aka * Microsoft Cognitive Toolkit) job. */ cntkSettings?: CNTKsettings; /** * @member {PyTorchSettings} [pyTorchSettings] Specifies the settings for * pyTorch job. */ pyTorchSettings?: PyTorchSettings; /** * @member {TensorFlowSettings} [tensorFlowSettings] Specifies the settings * for Tensor Flow job. */ tensorFlowSettings?: TensorFlowSettings; /** * @member {CaffeSettings} [caffeSettings] Specifies the settings for Caffe * job. */ caffeSettings?: CaffeSettings; /** * @member {Caffe2Settings} [caffe2Settings] Specifies the settings for * Caffe2 job. */ caffe2Settings?: Caffe2Settings; /** * @member {ChainerSettings} [chainerSettings] Specifies the settings for * Chainer job. */ chainerSettings?: ChainerSettings; /** * @member {CustomToolkitSettings} [customToolkitSettings] Specifies the * settings for custom tool kit job. */ customToolkitSettings?: CustomToolkitSettings; /** * @member {CustomMpiSettings} [customMpiSettings] Specifies the settings for * custom MPI job. */ customMpiSettings?: CustomMpiSettings; /** * @member {HorovodSettings} [horovodSettings] Specifies the settings for * Horovod job. */ horovodSettings?: HorovodSettings; /** * @member {JobPreparation} [jobPreparation] Specifies the actions to be * performed before tool kit is launched. The specified actions will run on * all the nodes that are part of the job */ jobPreparation?: JobPreparation; /** * @member {string} [jobOutputDirectoryPathSegment] Output directory path * segment. A segment of job's output directories path created by Batch AI. * Batch AI creates job's output directories under an unique path to avoid * conflicts between jobs. This value contains a path segment generated by * Batch AI to make the path unique and can be used to find the output * directory on the node or mounted filesystem. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly jobOutputDirectoryPathSegment?: string; /** * @member {string} [stdOutErrPathPrefix] Standard output directory path * prefix. The path where the Batch AI service stores stdout, stderror and * execution log of the job. */ stdOutErrPathPrefix?: string; /** * @member {InputDirectory[]} [inputDirectories] Input directories. A list of * input directories for the job. */ inputDirectories?: InputDirectory[]; /** * @member {OutputDirectory[]} [outputDirectories] Output directories. A list * of output directories for the job. */ outputDirectories?: OutputDirectory[]; /** * @member {EnvironmentVariable[]} [environmentVariables] Environment * variables. A collection of user defined environment variables to be setup * for the job. */ environmentVariables?: EnvironmentVariable[]; /** * @member {EnvironmentVariableWithSecretValue[]} [secrets] Secrets. A * collection of user defined environment variables with secret values to be * setup for the job. Server will never report values of these variables * back. */ secrets?: EnvironmentVariableWithSecretValue[]; /** * @member {JobPropertiesConstraints} [constraints] Constraints associated * with the Job. */ constraints?: JobPropertiesConstraints; /** * @member {Date} [creationTime] Creation time. The creation time of the job. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly creationTime?: Date; /** * @member {ProvisioningState} [provisioningState] Provisioning state. The * provisioned state of the Batch AI job. Possible values include: * 'creating', 'succeeded', 'failed', 'deleting' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: ProvisioningState; /** * @member {Date} [provisioningStateTransitionTime] Provisioning state * transition time. The time at which the job entered its current * provisioning state. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningStateTransitionTime?: Date; /** * @member {ExecutionState} [executionState] Execution state. The current * state of the job. Possible values are: queued - The job is queued and able * to run. A job enters this state when it is created, or when it is awaiting * a retry after a failed run. running - The job is running on a compute * cluster. This includes job-level preparation such as downloading resource * files or set up container specified on the job - it does not necessarily * mean that the job command line has started executing. terminating - The * job is terminated by the user, the terminate operation is in progress. * succeeded - The job has completed running succesfully and exited with exit * code 0. failed - The job has finished unsuccessfully (failed with a * non-zero exit code) and has exhausted its retry limit. A job is also * marked as failed if an error occurred launching the job. Possible values * include: 'queued', 'running', 'terminating', 'succeeded', 'failed' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly executionState?: ExecutionState; /** * @member {Date} [executionStateTransitionTime] Execution state transition * time. The time at which the job entered its current execution state. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly executionStateTransitionTime?: Date; /** * @member {JobPropertiesExecutionInfo} [executionInfo] Information about the * execution of a job. */ executionInfo?: JobPropertiesExecutionInfo; } /** * @interface * An interface representing RemoteLoginInformation. * Login details to SSH to a compute node in cluster. * */ export interface RemoteLoginInformation { /** * @member {string} [nodeId] Node ID. ID of the compute node. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nodeId?: string; /** * @member {string} [ipAddress] IP address. Public IP address of the compute * node. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly ipAddress?: string; /** * @member {number} [port] Port. SSH port number of the node. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly port?: number; } /** * @interface * An interface representing File. * Properties of the file or directory. * */ export interface File { /** * @member {string} [name] Name. Name of the file. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {FileType} [fileType] File type. Type of the file. Possible values * are file and directory. Possible values include: 'file', 'directory' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly fileType?: FileType; /** * @member {string} [downloadUrl] Download URL. URL to download the * corresponding file. The downloadUrl is not returned for directories. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly downloadUrl?: string; /** * @member {Date} [lastModified] Last modified time. The time at which the * file was last modified. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly lastModified?: Date; /** * @member {number} [contentLength] Content length. The file of the size. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly contentLength?: number; } /** * @interface * An interface representing Resource. * A definition of an Azure resource. * * @extends BaseResource */ export interface Resource extends BaseResource { /** * @member {string} [id] The ID of the resource * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly id?: string; /** * @member {string} [name] The name of the resource * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {string} [type] The type of the resource * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly type?: string; /** * @member {string} [location] The location of the resource * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly location?: string; /** * @member {{ [propertyName: string]: string }} [tags] The tags of the * resource * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly tags?: { [propertyName: string]: string }; } /** * @interface * An interface representing OperationDisplay. * The object that describes the operation. * */ export interface OperationDisplay { /** * @member {string} [provider] Friendly name of the resource provider. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provider?: string; /** * @member {string} [operation] The operation type. For example: read, write, * delete, or listKeys/action * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly operation?: string; /** * @member {string} [resource] The resource type on which the operation is * performed. **NOTE: This property will not be serialized. It can only be * populated by the server.** */ readonly resource?: string; /** * @member {string} [description] The friendly name of the operation. **NOTE: * This property will not be serialized. It can only be populated by the * server.** */ readonly description?: string; } /** * @interface * An interface representing Operation. * @summary A REST API operation. * * Details of a REST API operation * */ export interface Operation { /** * @member {string} [name] The operation name. This is of the format * {provider}/{resource}/{operation} * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly name?: string; /** * @member {OperationDisplay} [display] The object that describes the * operation. */ display?: OperationDisplay; /** * @member {string} [origin] The intended executor of the operation. **NOTE: * This property will not be serialized. It can only be populated by the * server.** */ readonly origin?: string; /** * @member {any} [properties] Properties of the operation. */ properties?: any; } /** * @interface * An interface representing Workspace. * Batch AI Workspace information. * * @extends Resource */ export interface Workspace extends Resource { /** * @member {Date} [creationTime] Creation time. Time when the Workspace was * created. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly creationTime?: Date; /** * @member {ProvisioningState} [provisioningState] Provisioning state. The * provisioned state of the Workspace. Possible values include: 'creating', * 'succeeded', 'failed', 'deleting' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: ProvisioningState; /** * @member {Date} [provisioningStateTransitionTime] Provisioning state * transition time. The time at which the workspace entered its current * provisioning state. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningStateTransitionTime?: Date; } /** * @interface * An interface representing WorkspaceCreateParameters. * Workspace creation parameters. * */ export interface WorkspaceCreateParameters { /** * @member {string} location Location. The region in which to create the * Workspace. */ location: string; /** * @member {{ [propertyName: string]: string }} [tags] Tags. The user * specified tags associated with the Workspace. */ tags?: { [propertyName: string]: string }; } /** * @interface * An interface representing WorkspaceUpdateParameters. * Workspace update parameters. * */ export interface WorkspaceUpdateParameters { /** * @member {{ [propertyName: string]: string }} [tags] Tags. The user * specified tags associated with the Workspace. */ tags?: { [propertyName: string]: string }; } /** * @interface * An interface representing Experiment. * Experiment information. * * @extends ProxyResource */ export interface Experiment extends ProxyResource { /** * @member {Date} [creationTime] Creation time. Time when the Experiment was * created. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly creationTime?: Date; /** * @member {ProvisioningState} [provisioningState] Provisioning state. The * provisioned state of the experiment. Possible values include: 'creating', * 'succeeded', 'failed', 'deleting' * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningState?: ProvisioningState; /** * @member {Date} [provisioningStateTransitionTime] Provisioning state * transition time. The time at which the experiment entered its current * provisioning state. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly provisioningStateTransitionTime?: Date; } /** * @interface * An interface representing WorkspacesListOptions. * Additional parameters for list operation. * */ export interface WorkspacesListOptions { /** * @member {number} [maxResults] The maximum number of items to return in the * response. A maximum of 1000 files can be returned. Default value: 1000 . */ maxResults?: number; } /** * @interface * An interface representing WorkspacesListByResourceGroupOptions. * Additional parameters for listByResourceGroup operation. * */ export interface WorkspacesListByResourceGroupOptions { /** * @member {number} [maxResults] The maximum number of items to return in the * response. A maximum of 1000 files can be returned. Default value: 1000 . */ maxResults?: number; } /** * @interface * An interface representing ExperimentsListByWorkspaceOptions. * Additional parameters for listByWorkspace operation. * */ export interface ExperimentsListByWorkspaceOptions { /** * @member {number} [maxResults] The maximum number of items to return in the * response. A maximum of 1000 files can be returned. Default value: 1000 . */ maxResults?: number; } /** * @interface * An interface representing JobsListByExperimentOptions. * Additional parameters for listByExperiment operation. * */ export interface JobsListByExperimentOptions { /** * @member {number} [maxResults] The maximum number of items to return in the * response. A maximum of 1000 files can be returned. Default value: 1000 . */ maxResults?: number; } /** * @interface * An interface representing JobsListOutputFilesOptions. * Additional parameters for listOutputFiles operation. * */ export interface JobsListOutputFilesOptions { /** * @member {string} outputdirectoryid Id of the job output directory. This is * the OutputDirectory-->id parameter that is given by the user during Create * Job. */ outputdirectoryid: string; /** * @member {string} [directory] The path to the directory. Default value: '.' * . */ directory?: string; /** * @member {number} [linkexpiryinminutes] The number of minutes after which * the download link will expire. Default value: 60 . */ linkexpiryinminutes?: number; /** * @member {number} [maxResults] The maximum number of items to return in the * response. A maximum of 1000 files can be returned. Default value: 1000 . */ maxResults?: number; } /** * @interface * An interface representing FileServersListByWorkspaceOptions. * Additional parameters for listByWorkspace operation. * */ export interface FileServersListByWorkspaceOptions { /** * @member {number} [maxResults] The maximum number of items to return in the * response. A maximum of 1000 files can be returned. Default value: 1000 . */ maxResults?: number; } /** * @interface * An interface representing ClustersListByWorkspaceOptions. * Additional parameters for listByWorkspace operation. * */ export interface ClustersListByWorkspaceOptions { /** * @member {number} [maxResults] The maximum number of items to return in the * response. A maximum of 1000 files can be returned. Default value: 1000 . */ maxResults?: number; } /** * @interface * An interface representing WorkspacesListOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface WorkspacesListOptionalParams extends msRest.RequestOptionsBase { /** * @member {WorkspacesListOptions} [workspacesListOptions] Additional * parameters for the operation */ workspacesListOptions?: WorkspacesListOptions; } /** * @interface * An interface representing WorkspacesListByResourceGroupOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface WorkspacesListByResourceGroupOptionalParams extends msRest.RequestOptionsBase { /** * @member {WorkspacesListByResourceGroupOptions} * [workspacesListByResourceGroupOptions] Additional parameters for the * operation */ workspacesListByResourceGroupOptions?: WorkspacesListByResourceGroupOptions; } /** * @interface * An interface representing WorkspacesUpdateOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface WorkspacesUpdateOptionalParams extends msRest.RequestOptionsBase { /** * @member {{ [propertyName: string]: string }} [tags] Tags. The user * specified tags associated with the Workspace. */ tags?: { [propertyName: string]: string }; } /** * @interface * An interface representing ExperimentsListByWorkspaceOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface ExperimentsListByWorkspaceOptionalParams extends msRest.RequestOptionsBase { /** * @member {ExperimentsListByWorkspaceOptions} * [experimentsListByWorkspaceOptions] Additional parameters for the * operation */ experimentsListByWorkspaceOptions?: ExperimentsListByWorkspaceOptions; } /** * @interface * An interface representing JobsListByExperimentOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface JobsListByExperimentOptionalParams extends msRest.RequestOptionsBase { /** * @member {JobsListByExperimentOptions} [jobsListByExperimentOptions] * Additional parameters for the operation */ jobsListByExperimentOptions?: JobsListByExperimentOptions; } /** * @interface * An interface representing FileServersListByWorkspaceOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface FileServersListByWorkspaceOptionalParams extends msRest.RequestOptionsBase { /** * @member {FileServersListByWorkspaceOptions} * [fileServersListByWorkspaceOptions] Additional parameters for the * operation */ fileServersListByWorkspaceOptions?: FileServersListByWorkspaceOptions; } /** * @interface * An interface representing ClustersUpdateOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface ClustersUpdateOptionalParams extends msRest.RequestOptionsBase { /** * @member {ScaleSettings} [scaleSettings] Scale settings. Desired scale * settings for the cluster. Batch AI service supports manual and auto scale * clusters. */ scaleSettings?: ScaleSettings; } /** * @interface * An interface representing ClustersListByWorkspaceOptionalParams. * Optional Parameters. * * @extends RequestOptionsBase */ export interface ClustersListByWorkspaceOptionalParams extends msRest.RequestOptionsBase { /** * @member {ClustersListByWorkspaceOptions} [clustersListByWorkspaceOptions] * Additional parameters for the operation */ clustersListByWorkspaceOptions?: ClustersListByWorkspaceOptions; } /** * @interface * An interface representing BatchAIManagementClientOptions. * @extends AzureServiceClientOptions */ export interface BatchAIManagementClientOptions extends AzureServiceClientOptions { /** * @member {string} [baseUri] */ baseUri?: string; } /** * @interface * An interface representing the OperationListResult. * @summary Result of the request to list REST API operations. It contains a * list of operations and a URL nextLink to get the next set of results. * * Contains the list of all operations supported by BatchAI resource provider * * @extends Array<Operation> */ export interface OperationListResult extends Array<Operation> { /** * @member {string} [nextLink] **NOTE: This property will not be serialized. * It can only be populated by the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the ListUsagesResult. * The List Usages operation response. * * @extends Array<Usage> */ export interface ListUsagesResult extends Array<Usage> { /** * @member {string} [nextLink] The URI to fetch the next page of compute * resource usage information. Call ListNext() with this to fetch the next * page of compute resource usage information. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the WorkspaceListResult. * Values returned by the List operation. * * @extends Array<Workspace> */ export interface WorkspaceListResult extends Array<Workspace> { /** * @member {string} [nextLink] The continuation token. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the ExperimentListResult. * Values returned by the List operation. * * @extends Array<Experiment> */ export interface ExperimentListResult extends Array<Experiment> { /** * @member {string} [nextLink] The continuation token. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the JobListResult. * Values returned by the List operation. * * @extends Array<Job> */ export interface JobListResult extends Array<Job> { /** * @member {string} [nextLink] The continuation token. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the FileListResult. * Values returned by the List operation. * * @extends Array<File> */ export interface FileListResult extends Array<File> { /** * @member {string} [nextLink] The continuation token. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the RemoteLoginInformationListResult. * Values returned by the List operation. * * @extends Array<RemoteLoginInformation> */ export interface RemoteLoginInformationListResult extends Array<RemoteLoginInformation> { /** * @member {string} [nextLink] The continuation token. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the FileServerListResult. * Values returned by the File Server List operation. * * @extends Array<FileServer> */ export interface FileServerListResult extends Array<FileServer> { /** * @member {string} [nextLink] The continuation token. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * @interface * An interface representing the ClusterListResult. * Values returned by the List Clusters operation. * * @extends Array<Cluster> */ export interface ClusterListResult extends Array<Cluster> { /** * @member {string} [nextLink] The continuation token. * **NOTE: This property will not be serialized. It can only be populated by * the server.** */ readonly nextLink?: string; } /** * Defines values for UsageUnit. * Possible values include: 'Count' * @readonly * @enum {string} */ export type UsageUnit = 'Count'; /** * Defines values for CachingType. * Possible values include: 'none', 'readonly', 'readwrite' * @readonly * @enum {string} */ export type CachingType = 'none' | 'readonly' | 'readwrite'; /** * Defines values for StorageAccountType. * Possible values include: 'Standard_LRS', 'Premium_LRS' * @readonly * @enum {string} */ export type StorageAccountType = 'Standard_LRS' | 'Premium_LRS'; /** * Defines values for FileServerProvisioningState. * Possible values include: 'creating', 'updating', 'deleting', 'succeeded', 'failed' * @readonly * @enum {string} */ export type FileServerProvisioningState = 'creating' | 'updating' | 'deleting' | 'succeeded' | 'failed'; /** * Defines values for VmPriority. * Possible values include: 'dedicated', 'lowpriority' * @readonly * @enum {string} */ export type VmPriority = 'dedicated' | 'lowpriority'; /** * Defines values for DeallocationOption. * Possible values include: 'requeue', 'terminate', 'waitforjobcompletion' * @readonly * @enum {string} */ export type DeallocationOption = 'requeue' | 'terminate' | 'waitforjobcompletion'; /** * Defines values for ProvisioningState. * Possible values include: 'creating', 'succeeded', 'failed', 'deleting' * @readonly * @enum {string} */ export type ProvisioningState = 'creating' | 'succeeded' | 'failed' | 'deleting'; /** * Defines values for AllocationState. * Possible values include: 'steady', 'resizing' * @readonly * @enum {string} */ export type AllocationState = 'steady' | 'resizing'; /** * Defines values for JobPriority. * Possible values include: 'low', 'normal', 'high' * @readonly * @enum {string} */ export type JobPriority = 'low' | 'normal' | 'high'; /** * Defines values for ToolType. * Possible values include: 'cntk', 'tensorflow', 'caffe', 'caffe2', 'chainer', 'horovod', * 'custommpi', 'custom' * @readonly * @enum {string} */ export type ToolType = 'cntk' | 'tensorflow' | 'caffe' | 'caffe2' | 'chainer' | 'horovod' | 'custommpi' | 'custom'; /** * Defines values for ExecutionState. * Possible values include: 'queued', 'running', 'terminating', 'succeeded', 'failed' * @readonly * @enum {string} */ export type ExecutionState = 'queued' | 'running' | 'terminating' | 'succeeded' | 'failed'; /** * Defines values for FileType. * Possible values include: 'file', 'directory' * @readonly * @enum {string} */ export type FileType = 'file' | 'directory'; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationListResult; }; }; /** * Contains response data for the list operation. */ export type UsagesListResponse = ListUsagesResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ListUsagesResult; }; }; /** * Contains response data for the listNext operation. */ export type UsagesListNextResponse = ListUsagesResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ListUsagesResult; }; }; /** * Contains response data for the list operation. */ export type WorkspacesListResponse = WorkspaceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WorkspaceListResult; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type WorkspacesListByResourceGroupResponse = WorkspaceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WorkspaceListResult; }; }; /** * Contains response data for the create operation. */ export type WorkspacesCreateResponse = Workspace & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Workspace; }; }; /** * Contains response data for the update operation. */ export type WorkspacesUpdateResponse = Workspace & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Workspace; }; }; /** * Contains response data for the get operation. */ export type WorkspacesGetResponse = Workspace & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Workspace; }; }; /** * Contains response data for the beginCreate operation. */ export type WorkspacesBeginCreateResponse = Workspace & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Workspace; }; }; /** * Contains response data for the listNext operation. */ export type WorkspacesListNextResponse = WorkspaceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WorkspaceListResult; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type WorkspacesListByResourceGroupNextResponse = WorkspaceListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: WorkspaceListResult; }; }; /** * Contains response data for the listByWorkspace operation. */ export type ExperimentsListByWorkspaceResponse = ExperimentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ExperimentListResult; }; }; /** * Contains response data for the create operation. */ export type ExperimentsCreateResponse = Experiment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Experiment; }; }; /** * Contains response data for the get operation. */ export type ExperimentsGetResponse = Experiment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Experiment; }; }; /** * Contains response data for the beginCreate operation. */ export type ExperimentsBeginCreateResponse = Experiment & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Experiment; }; }; /** * Contains response data for the listByWorkspaceNext operation. */ export type ExperimentsListByWorkspaceNextResponse = ExperimentListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ExperimentListResult; }; }; /** * Contains response data for the listByExperiment operation. */ export type JobsListByExperimentResponse = JobListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: JobListResult; }; }; /** * Contains response data for the create operation. */ export type JobsCreateResponse = Job & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Job; }; }; /** * Contains response data for the get operation. */ export type JobsGetResponse = Job & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Job; }; }; /** * Contains response data for the listOutputFiles operation. */ export type JobsListOutputFilesResponse = FileListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FileListResult; }; }; /** * Contains response data for the listRemoteLoginInformation operation. */ export type JobsListRemoteLoginInformationResponse = RemoteLoginInformationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RemoteLoginInformationListResult; }; }; /** * Contains response data for the beginCreate operation. */ export type JobsBeginCreateResponse = Job & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Job; }; }; /** * Contains response data for the listByExperimentNext operation. */ export type JobsListByExperimentNextResponse = JobListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: JobListResult; }; }; /** * Contains response data for the listOutputFilesNext operation. */ export type JobsListOutputFilesNextResponse = FileListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FileListResult; }; }; /** * Contains response data for the listRemoteLoginInformationNext operation. */ export type JobsListRemoteLoginInformationNextResponse = RemoteLoginInformationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RemoteLoginInformationListResult; }; }; /** * Contains response data for the create operation. */ export type FileServersCreateResponse = FileServer & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FileServer; }; }; /** * Contains response data for the get operation. */ export type FileServersGetResponse = FileServer & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FileServer; }; }; /** * Contains response data for the listByWorkspace operation. */ export type FileServersListByWorkspaceResponse = FileServerListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FileServerListResult; }; }; /** * Contains response data for the beginCreate operation. */ export type FileServersBeginCreateResponse = FileServer & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FileServer; }; }; /** * Contains response data for the listByWorkspaceNext operation. */ export type FileServersListByWorkspaceNextResponse = FileServerListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: FileServerListResult; }; }; /** * Contains response data for the create operation. */ export type ClustersCreateResponse = Cluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Cluster; }; }; /** * Contains response data for the update operation. */ export type ClustersUpdateResponse = Cluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Cluster; }; }; /** * Contains response data for the get operation. */ export type ClustersGetResponse = Cluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Cluster; }; }; /** * Contains response data for the listRemoteLoginInformation operation. */ export type ClustersListRemoteLoginInformationResponse = RemoteLoginInformationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RemoteLoginInformationListResult; }; }; /** * Contains response data for the listByWorkspace operation. */ export type ClustersListByWorkspaceResponse = ClusterListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ClusterListResult; }; }; /** * Contains response data for the beginCreate operation. */ export type ClustersBeginCreateResponse = Cluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: Cluster; }; }; /** * Contains response data for the listRemoteLoginInformationNext operation. */ export type ClustersListRemoteLoginInformationNextResponse = RemoteLoginInformationListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: RemoteLoginInformationListResult; }; }; /** * Contains response data for the listByWorkspaceNext operation. */ export type ClustersListByWorkspaceNextResponse = ClusterListResult & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ClusterListResult; }; };
the_stack
import { BodyType } from "../Enumerations/BodyType"; import { Convert, StringHelper } from '../ExtensionMethods'; import { DateTime } from "../DateTime"; import { EwsServiceXmlWriter } from "../Core/EwsServiceXmlWriter"; import { EwsUtilities } from "../Core/EwsUtilities"; import { ExchangeService } from "../Core/ExchangeService"; import { ExchangeVersion } from "../Enumerations/ExchangeVersion"; import { IRefParam } from "../Interfaces/IRefParam"; import { Item } from "../Core/ServiceObjects/Items/Item"; import { Promise } from "../Promise"; import { PropertyDefinitionBase } from '../PropertyDefinitions/PropertyDefinitionBase'; import { Strings } from '../Strings'; import { TypeContainer } from "../TypeContainer"; import { XmlAttributeNames } from "../Core/XmlAttributeNames"; import { XmlElementNames } from "../Core/XmlElementNames"; import { XmlNamespace } from "../Enumerations/XmlNamespace"; import { ComplexProperty } from "./ComplexProperty"; /** * Represents an attachment to an item. */ export class Attachment extends ComplexProperty { private owner: Item = null; private id: string = null; private name: string = null; private contentType: string = null; private contentId: string = null; private contentLocation: string = null; private size: number = 0; private lastModifiedTime: DateTime = null; private isInline: boolean = false; private service: ExchangeService = null; /** * Gets the Id of the attachment. */ get Id(): string { return this.id; } set Id(value: string) { this.id = value; } /*** * Gets or sets the name of the attachment. */ get Name(): string { return this.name; } set Name(value: string) { this.SetFieldValue<string>({ getValue: () => this.name, setValue: (updateValue) => { this.name = updateValue } }, value); } /** * Gets or sets the content type of the attachment. */ get ContentType(): string { return this.contentType; } set ContentType(value: string) { this.SetFieldValue<string>({ getValue: () => this.contentType, setValue: (updateValue) => { this.contentType = updateValue } }, value); } /** * Gets or sets the content Id of the attachment. ContentId can be used as a custom way to identify an attachment in order to reference it from within the body of the item the attachment belongs to. */ get ContentId(): string { return this.contentId; } set ContentId(value: string) { this.SetFieldValue<string>({ getValue: () => this.contentId, setValue: (updateValue) => { this.contentId = updateValue } }, value); } /** * Gets or sets the content location of the attachment. ContentLocation can be used to associate an attachment with a Url defining its location on the Web. */ get ContentLocation(): string { return this.contentLocation; } set ContentLocation(value: string) { this.SetFieldValue<string>({ getValue: () => this.contentLocation, setValue: (updateValue) => { this.contentLocation = updateValue } }, value); } /** * Gets the size of the attachment. */ get Size(): number { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "Size"); return this.size; } set Size(value: number) { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "Size"); this.SetFieldValue<number>({ getValue: () => this.size, setValue: (updateValue) => { this.size = updateValue } }, value); } /** * Gets the date and time when this attachment was last modified. */ get LastModifiedTime(): DateTime { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "LastModifiedTime"); return this.lastModifiedTime; } set LastModifiedTime(value: DateTime) { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "LastModifiedTime"); this.SetFieldValue<DateTime>({ getValue: () => this.lastModifiedTime, setValue: (updateValue) => { this.lastModifiedTime = updateValue } }, value); } /** * Gets or sets a value indicating whether this is an inline attachment. Inline attachments are not visible to end users. */ get IsInline(): boolean { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "IsInline"); return this.isInline; } set IsInline(value: boolean) { EwsUtilities.ValidatePropertyVersion(this.service, ExchangeVersion.Exchange2010, "IsInline"); this.SetFieldValue<boolean>({ getValue: () => this.isInline, setValue: (updateValue) => { this.isInline = updateValue } }, value); } /** * @internal True if the attachment has not yet been saved, false otherwise. */ get IsNew(): boolean { return StringHelper.IsNullOrEmpty(this.Id); } /** * @internal Gets the owner of the attachment. */ get Owner(): Item { return this.owner; } /** * @internal Gets the related exchange service. */ get Service(): ExchangeService { return this.service; } /** * @internal Initializes a new instance of the Attachment class. * * @param {Item} owner The owner. */ constructor(owner: Item); /** * @internal Initializes a new instance of the Attachment class. * * @param {ExchangeService} service The service. */ constructor(service: ExchangeService); /** * @internal @protected unused - only for derived class call */ constructor(ownerOrService: Item | ExchangeService) constructor(ownerOrService: Item | ExchangeService) { super(); if (arguments.length === 1 && (ownerOrService === null || ownerOrService instanceof TypeContainer.Item)) { this.owner = <Item>ownerOrService; if (ownerOrService !== null) { this.service = this.owner.Service; } return; } this.service = <ExchangeService>ownerOrService; } /** * Gets the name of the XML element. * * @return {string} XML element name. */ GetXmlElementName(): string { console.log("Attachment.ts - GetXmlElementName : Abstract - must implement."); return StringHelper.Empty; } /** * @internal Load the attachment. * * @param {BodyType} bodyType Type of the body. * @param {PropertyDefinitionBase[]} additionalProperties The additional properties. */ InternalLoad(bodyType: BodyType, additionalProperties: PropertyDefinitionBase[]): Promise<void> { return this.service.GetAttachment( this, bodyType, additionalProperties); } //InternalToJson(service: ExchangeService): any { throw new Error("Attachment.ts - InternalToJson : Not implemented."); } /** * Loads the attachment. Calling this method results in a call to EWS. */ Load(): Promise<void> { return this.InternalLoad(null, null); } /** * Loads the attachment id from json. * * @param {any} jsonObject The json object. */ private LoadAttachmentIdFromXMLJsObject(jsonObject: any): void { this.id = jsonObject[XmlAttributeNames.Id]; if (this.Owner != null && jsonObject[XmlAttributeNames.RootItemChangeKey]) { var rootItemChangeKey: string = jsonObject[XmlAttributeNames.RootItemChangeKey]; if (!StringHelper.IsNullOrEmpty(rootItemChangeKey)) { this.Owner.RootItemId.ChangeKey = rootItemChangeKey; } } } /** * @internal Loads from XMLjsObject. * * @param {any} jsonObject * @param {ExchangeService} service */ LoadFromXmlJsObject(jsObject: any, service: ExchangeService): void { for (let key in jsObject) { switch (key) { case XmlElementNames.AttachmentId: this.LoadAttachmentIdFromXMLJsObject(jsObject[key]); break; case XmlElementNames.Name: this.name = jsObject[key]; break; case XmlElementNames.ContentType: this.contentType = jsObject[key]; break; case XmlElementNames.ContentId: this.contentId = jsObject[key]; break; case XmlElementNames.ContentLocation: this.contentLocation = jsObject[key]; break; case XmlElementNames.Size: this.size = Convert.toInt(jsObject[key]); break; case XmlElementNames.LastModifiedTime: this.lastModifiedTime = service.ConvertUniversalDateTimeStringToLocalDateTime(jsObject[key]); break; case XmlElementNames.IsInline: this.isInline = Convert.toBool(jsObject[key]); break; default: break; } } } /** * @internal Sets value of field. * * /remarks/ We override the base implementation. Attachments cannot be modified so any attempts the change a property on an existing attachment is an error. * * @param {IRefParam<T>} field The field. * @param {T} value The value. */ SetFieldValue<T>(field: IRefParam<T>, value: T): void { this.ThrowIfThisIsNotNew(); super.SetFieldValue(field, value); } /** * @internal Throws exception if this is not a new service object. */ ThrowIfThisIsNotNew(): void { if (!this.IsNew) { throw new Error(Strings.AttachmentCannotBeUpdated);//InvalidOperationException } } //ReadElementsFromXmlJsObject(reader: any): boolean { throw new Error("Attachment.ts - TryReadElementFromXmlJsObject : Not implemented."); } /** * @internal Validates this instance. * * @param {number} attachmentIndex Index of this attachment. */ Validate(attachmentIndex?: number): void { } /** * @internal Writes elements to XML. * * @param {EwsServiceXmlWriter} writer The writer. */ WriteElementsToXml(writer: EwsServiceXmlWriter): void { writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.Name, this.Name); writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ContentType, this.ContentType); writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ContentId, this.ContentId); writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.ContentLocation, this.ContentLocation); if (writer.Service.RequestedServerVersion > ExchangeVersion.Exchange2007_SP1) { writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.IsInline, this.IsInline); } } }
the_stack
import Taro from '@tarojs/taro'; import { stringify } from 'qs'; import { BaseHttpService, HttpServiceBuilderWithMeta, PickPayload, PickResponse, HttpServiceBuilderWithMetas, PickData, PickMeta, IBaseRequestAction, BaseHttpServiceConfig, HttpTransform, METHOD, RequestSuccessAction, RequestPrepareAction, FetchHandle as SuperFetchHandle, storeHelper, RequestFailAction } from '@redux-model/core'; import PromiseListenCatch from 'promise-listen-catch'; import { RequestAction } from '../actions/RequestAction'; import { getTaro } from '../utils/getTaro'; import { parseFetch } from '../utils/parseFetch'; export type TaroRequestConfig<T = any> = Partial<Taro.request.Option<T>>; export type HttpResponse<T = any> = Taro.request.SuccessCallbackResult<T> & { config: Taro.request.Option; }; export type HttpCanceler = () => void; export interface FetchHandle<Response = any, Payload = any> extends SuperFetchHandle<Response, Payload, HttpCanceler> {} export interface HttpServiceConfig<ErrorData> extends BaseHttpServiceConfig { /** * Taro original config */ requestOptions?: TaroRequestConfig; /** * Collect http-status, error-message and business-code to meta. And error-message will display by invoke method `onShowError`. * * ```javascript * { * onRespondError(httpResponse, meta) { * if (httpResponse.data && httpResponse.data.errMsg) { * meta.message = httpResponse.data.errMsg; * } * * // If http-status is always 200 and the api put real http-status into your data. * if (httpResponse.data && httpResponse.data.status) { * meta.httpStatus = httpResponse.data.status; * } * } * } * ``` * * And how to get error information in your component? * ```javascript * const meta = xModel.yAction.useMeta(); // object includes message, httpStatus, businessCode... * ``` */ onRespondError: (httpResponse: HttpResponse<ErrorData>, meta: HttpTransform) => void; /** * Transform your data globally. * * Consider that you have common struct for most api `{ data: {...} }`, you are boring to use literal `data` again and again, so you want to strip it. * ```javascript * { * onRespondSuccess(httpResponse) { * if (httpResponse.data.data) { * httpResponse.data = httpResponse.data.data; * } * } * } * ``` */ onRespondSuccess?: (httpResponse: HttpResponse) => void; /** * Inject headers for every request. * ```javascript * import type { TokenModel } from '../../models/TokenModel'; * * { * headers() { * const token = (require('../../models/TokenModel').tokenModel as TokenModel).data.access_token; * * return { * Authorization: `Bearer ${token}`, * Accept: 'application/json', * 'Content-Encoding': 'application/json', * }; * } * } * ``` */ headers: (action: IRequestAction) => object; /** * Before request, you can inject or modify data as your wish. */ beforeSend?: (action: IRequestAction) => void; /** * When the api puts httpStatus to your data struct such as `{ status: 400, msg: ..., data: ... }`, unfortunately, we only recognize standard httpStatus. At this time, you have to judge by yourself. * * ```javascript * { * isSuccess(httpResponse) { * const status = httpResponse.data && httpResponse.data.status; * * return status >= 200 && status < 300; * } * } * ``` */ isSuccess?: (httpResponse: HttpResponse) => boolean; } export interface IRequestAction<Data = any, Response = any, Payload = any> extends IBaseRequestAction<Data, Response, Payload> { requestOptions: TaroRequestConfig; } export class HttpService<ErrorData = any> extends BaseHttpService<HttpServiceConfig<ErrorData>, HttpCanceler> { protected readonly request: typeof Taro.request; constructor(config: HttpServiceConfig<ErrorData>) { super(config); this.request = getTaro().request; } public clone<NewErrorData = ErrorData>(config: Partial<HttpServiceConfig<NewErrorData>>): HttpService<NewErrorData> { // @ts-ignore // @ts-expect-error return new HttpService({ ...this.config, ...config, }); } public action<Fn extends (...args: any[]) => HttpServiceBuilderWithMeta<Data, Response, Payload, TaroRequestConfig>, Data = PickData<Fn>, Response = PickResponse<Fn>, Payload = PickPayload<Fn>>( fn: Fn ): ((...args: Parameters<Fn>) => FetchHandle<Response, Payload>) & Omit<RequestAction<Data, Fn, Response, Payload, true>, 'metas' | 'loadings' | 'useMetas' | 'useLoadings'>; public action<Fn extends (...args: any[]) => HttpServiceBuilderWithMetas<Data, Response, Payload, TaroRequestConfig, M>, Data = PickData<Fn>, Response = PickResponse<Fn>, Payload = PickPayload<Fn>, M = PickMeta<Fn>>( fn: Fn ): ((...args: Parameters<Fn>) => FetchHandle<Response, Payload>) & Omit<RequestAction<Data, Fn, Response, Payload, M>, 'meta' | 'loading' | 'useMeta' | 'useLoading'>; public action(fn: any): any { return new RequestAction(fn, this); } public/*protected*/ runAction(action: IRequestAction): FetchHandle { const config = this.config; config.beforeSend && config.beforeSend(action); // For service.xxxAsync(), prepare, success and fail are all empty string. const { prepare, success, fail } = action.type; const requestOptions: Taro.request.Option = { url: action.uri, method: action.method as any, ...config.requestOptions, ...action.requestOptions, header: { ...config.headers(action), ...action.requestOptions.header, }, }; let url = requestOptions.url; // Make sure url is not absolute link if (!~url.indexOf('://')) { url = config.baseUrl + url; } const throttleUrl = url; if (action.query) { const isArg = ~url.indexOf('?') ? '&' : '?'; const args = stringify(action.query, { arrayFormat: 'brackets', encodeValuesOnly: true, }); url += `${isArg}${args}`; } requestOptions.url = url; // For GET request, `requestOptions.data` will convert to queryString. if (action.method !== METHOD.get && action.body) { requestOptions.data = action.body; } prepare && storeHelper.dispatch<RequestPrepareAction>({ ...action, type: prepare, loading: true, effect: action.onPrepare, after: action.afterPrepare, afterDuration: action.afterPrepareDuration, }); const throttleData = this.getThrottleData(action, { url: throttleUrl, actionName: action.actionName, method: action.method, body: action.body, query: action.query, headers: requestOptions.header!, transfer: action.throttle.transfer, }); if (throttleData) { return throttleData; } let successInvoked = false; let canceler: HttpCanceler | undefined; let fetchAbort: AbortController | undefined; // H5 fetch() doesn't support abort if (process.env.TARO_ENV === 'h5' && typeof AbortController === 'function') { fetchAbort = new AbortController(); // @ts-ignore requestOptions.signal = fetchAbort.signal; // Be careful to keep scope canceler = fetchAbort.abort.bind(fetchAbort); } const task = this.request(requestOptions); // H5 fetch() doesn't support abort if (!canceler && task.abort) { canceler = task.abort.bind(task); } const promise = task .then((value) => { const httpResponse: HttpResponse = { ...value, config: requestOptions }; if (httpResponse.statusCode < 200 || httpResponse.statusCode >= 300 || (config.isSuccess && !config.isSuccess(httpResponse))) { return Promise.reject(httpResponse); } if (config.onRespondSuccess) { config.onRespondSuccess(httpResponse); } const okAction: RequestSuccessAction = { ...action, type: success, loading: false, response: httpResponse.data, effect: action.onSuccess, after: action.afterSuccess, afterDuration: action.afterSuccessDuration, }; successInvoked = true; success && storeHelper.dispatch(okAction); this.setThrottle(okAction); this.triggerShowSuccess(okAction, action.successText); return Promise.resolve(okAction); }) .catch((error: Taro.request.SuccessCallbackResult & { status?: number } & Response) => { if (successInvoked) { return Promise.reject(error); } // H5 ok => statusCode | error => status // Weapp ok => statusCode | error => statusCode // ... if (error.status && !error.statusCode) { error.statusCode = error.status; } /** * H5 throws original response when fail. * @see ./node_modules/@tarojs/taro-h5/src/api/request/index.js **/ if (error.statusCode && !error.hasOwnProperty('data')) { return new Promise((_, reject) => { parseFetch(requestOptions, error).then((data) => { error.data = data; reject(error); }); }); } return Promise.reject(error); }) .catch((error: Taro.request.SuccessCallbackResult) => { if (successInvoked) { return Promise.reject(error); } const errMsg = error.errMsg; let isCancel: boolean = false; let errorMessage: string; let httpStatus: number | undefined; let businessCode: string | undefined; if ( // @ts-ignore (fetchAbort && error.name === 'AbortError') || (errMsg && /abort/i.test(errMsg)) ) { isCancel = true; } if (isCancel) { errorMessage = 'Aborted'; } else if (error.statusCode) { const meta: HttpTransform = { httpStatus: error.statusCode, }; config.onRespondError({ ...error, config: requestOptions }, meta); errorMessage = action.failText || meta.message || 'Fail to fetch api'; httpStatus = meta.httpStatus; businessCode = meta.businessCode; } else { errorMessage = 'Fail to request api'; if (errMsg) { if (/timeout/i.test(errMsg)) { errorMessage = config.timeoutMessage ? config.timeoutMessage(errMsg): errMsg; } else if (/fail/i.test(errMsg)) { errorMessage = config.networkErrorMessage ? config.networkErrorMessage(errMsg) : errMsg; } } } const errorResponse: RequestFailAction = { ...action, response: error.data, type: fail, loading: false, message: errorMessage, httpStatus, businessCode, effect: action.onFail, after: action.afterFail, afterDuration: action.afterFailDuration, }; fail && storeHelper.dispatch(errorResponse); if (!isCancel) { this.triggerShowError(errorResponse, action.hideError); } if (listener.canReject()) { return Promise.reject(errorResponse); } return; }); const listener = new PromiseListenCatch(promise); // @ts-ignore const fakePromise: FetchHandle<any, any> = listener; fakePromise.cancel = canceler || (() => {}); return fakePromise; } }
the_stack
import 'core-js/es/reflect'; // tslint:disable-line:no-submodule-imports import { WorkspaceSchema } from '@schematics/angular/utility/workspace-models'; // tslint:disable-line:no-submodule-imports ordered-imports import chalk from 'chalk'; import { mkdir, readFile, writeFile } from 'fs'; import { dirname, join, sep } from 'path'; import { cwd } from 'process'; import { promisify } from 'util'; import { INestedParameterValuesMap, IPartialExpressResponse, IPartialHapiResponse, IScullyConfig } from '../interfaces'; import { TEnableProdModeFunction, TPlugins, TReadPropertyFunction, TTargetSpecifier } from '../types'; import { bindRenderFunction } from './bind-render-function'; import { mapRoutes } from './map-routes'; import { preserveIndexHtml } from './preserve-index-html'; import { resolveRoutes } from './resolve-routes'; import { retrieveRoutes } from './retrieve-routes'; import { unbundleTokens } from './unbundle-tokens'; const mkdirAsync = promisify(mkdir); const readFileAsync = promisify(readFile); const writeFileAsync = promisify(writeFile); export const prerender = async ( browserTarget: TTargetSpecifier, config: string, enableProdMode: TEnableProdModeFunction, excludeRoutes: string[], expressResponseToken: any, hapiResponseToken: any, includeRoutes: string[], isVerbose: boolean, nestedParameterValues: INestedParameterValuesMap | INestedParameterValuesMap[], readProperty: TReadPropertyFunction, scullyConfig: null | IScullyConfig, scullyPlugins: null | TPlugins, serverTarget: TTargetSpecifier, shouldIgnoreStatusCode: boolean, shouldPreserveIndexHtml: boolean ) => { enableProdMode(); if (isVerbose) { console.log(chalk`{gray The path of the angular.json config file is "${config}".}`); // tslint:disable-line:max-line-length no-console } const { defaultProject, projects } = <WorkspaceSchema>require(config); const browserOutputPath = join(dirname(config), readProperty(projects, defaultProject, browserTarget, 'outputPath'), sep); const serverOutputPath = join(dirname(config), readProperty(projects, defaultProject, serverTarget, 'outputPath'), sep); if (isVerbose) { console.log(chalk`{gray The resolved output path of the browser target is "${browserOutputPath}".}`); // tslint:disable-line:max-line-length no-console console.log(chalk`{gray The resolved output path of the server target is "${serverOutputPath}".}`); // tslint:disable-line:max-line-length no-console } const main = join(serverOutputPath, 'main'); if (isVerbose) { console.log(chalk`{gray The path of the main.js file is "${main}".}`); // tslint:disable-line:max-line-length no-console } const unbundledMain = await unbundleTokens(expressResponseToken, hapiResponseToken, main); if (isVerbose && main !== unbundledMain) { console.log(chalk`{gray The main.js contains bundled tokens which have been replaced with classic require statements.}`); // tslint:disable-line:max-line-length no-console } const render = bindRenderFunction(unbundledMain); const index = join(browserOutputPath, 'index.html'); if (isVerbose) { console.log(chalk`{gray The path of the index.html file is "${index}".}`); // tslint:disable-line:max-line-length no-console } const document = await readFileAsync(index, 'utf8'); const tsConfig = join(cwd(), readProperty(projects, defaultProject, browserTarget, 'tsConfig')); if (isVerbose) { console.log(chalk`{gray The path of the tsconfig.json file used to retrieve the routes is "${tsConfig}".}`); // tslint:disable-line:max-line-length no-console } const retrievedRoutes = retrieveRoutes( tsConfig, // tslint:disable-next-line no-console (err) => console.log(chalk`{yellow Retrieving the routes statically threw an error with the following message "${err.message}".}`) ); if (includeRoutes.length === 0 && retrievedRoutes.length === 0) { // tslint:disable-next-line no-console console.log( chalk`{yellow No routes could be retrieved and no routes are included manually thus the default route at "/" will be added.}` ); retrievedRoutes.push('/'); } const mappedRoutes = mapRoutes([...includeRoutes, ...retrievedRoutes], nestedParameterValues); const renderableRoutesWithParameters = mappedRoutes.filter(({ parameterValueMaps, route }) => { if (route.match(/\*\*/) !== null) { console.log(chalk`{yellow The route at "${route}" will not be rendered because it contains a wildcard.}`); // tslint:disable-line:max-line-length no-console return false; } if (excludeRoutes.includes(route)) { console.log(chalk`{yellow The route at "${route}" was excluded.}`); // tslint:disable-line:max-line-length no-console return false; } return ( parameterValueMaps.length === 0 || parameterValueMaps.every((parameterValueMap) => Object.entries(parameterValueMap).every(([parameter, values]) => { if (values.length === 0) { // tslint:disable-next-line no-console console.log( chalk`{yellow The route at "${route}" will not be rendered because it contains a segement with an unspecified parameter "${parameter}".}` ); return false; } return true; }) ) ); }); const resolvedRoutes = resolveRoutes(renderableRoutesWithParameters); const routeProcessPlugins = scullyPlugins === null ? [] : scullyPlugins.get('routeProcess') ?? []; const routeProcessPluginEntries = Array.from(routeProcessPlugins.entries()); routeProcessPluginEntries.sort(([a], [b]) => a - b); const processedRoutes = await routeProcessPluginEntries .map(([, nameAndPlugin]) => nameAndPlugin.map(([, plugin]) => plugin)) .flat() .reduce( (promisedRoutes, routeProcessPlugin) => promisedRoutes.then((partiallyProcessedRoutes) => routeProcessPlugin({ outDir: browserOutputPath, distFolder: browserOutputPath }, partiallyProcessedRoutes) ), Promise.resolve(resolvedRoutes.map((route) => ({ route }))) ) .then((handledRoutes) => handledRoutes.map(({ route }) => route)); for (const route of processedRoutes) { const path = join(browserOutputPath, route, sep); await mkdirAsync(path, { recursive: true }); let statusCode = 200; const expressResponse: IPartialExpressResponse = { status: (value) => { statusCode = value; return expressResponse; } }; const hapiResponse: IPartialHapiResponse = { code: (value) => { statusCode = value; return hapiResponse; } }; const html = await render({ document, extraProviders: [ expressResponseToken === null ? [] : { provide: expressResponseToken, useValue: expressResponse }, hapiResponseToken === null ? [] : { provide: hapiResponseToken, useValue: hapiResponse } ], url: route }); const transformedHtml = scullyConfig !== null && scullyPlugins !== null ? await scullyConfig.defaultPostRenderers.reduce<Promise<string>>((promisedHtml, pluginName) => { const postProcessPlugins = scullyPlugins.get('postProcessByHtml'); if (postProcessPlugins === undefined) { return promisedHtml; } const postProcessPluginsWithADefaultPriority = postProcessPlugins.get(100); if (postProcessPluginsWithADefaultPriority === undefined) { return promisedHtml; } const [, postProcessPlugin] = postProcessPluginsWithADefaultPriority.find(([name]) => name === pluginName) ?? []; if (postProcessPlugin === undefined) { return promisedHtml; } return promisedHtml.then((partiallyTransformedHtml) => postProcessPlugin({ outDir: browserOutputPath, distFolder: browserOutputPath }, partiallyTransformedHtml, { route }) ); }, Promise.resolve(html)) : html; if (shouldIgnoreStatusCode || statusCode < 300) { if (path === browserOutputPath) { if (shouldPreserveIndexHtml) { // tslint:disable-next-line no-console console.log( chalk`{green The index.html file will be preserved as start.html because it would otherwise be overwritten.}` ); const didUpdateNgServiceWorker = await preserveIndexHtml(browserOutputPath, document, readFileAsync, writeFileAsync); if (didUpdateNgServiceWorker) { console.log(chalk`{green The ngsw.json file was updated to replace index.html with start.html.}`); // tslint:disable-line:max-line-length no-console } } else { // tslint:disable-next-line no-console console.log( chalk`{yellow The index.html file will be overwritten by the following route. This can be prevented by using the --preserve-index-html flag.}` ); } } await writeFileAsync(join(path, 'index.html'), transformedHtml); console.log(chalk`{green The route at "${route}" was rendered successfully.}`); // tslint:disable-line:no-console } else { console.log(chalk`{yellow The route at "${route}" was skipped because it's status code was ${statusCode}.}`); // tslint:disable-line:max-line-length no-console } } };
the_stack
'use strict'; declare function require(n:string):any /*eslint-disable no-use-before-define*/ var common = require('./common'); var YAMLException = require('./exception'); var DEFAULT_FULL_SCHEMA = require('./schema/default_full'); var DEFAULT_SAFE_SCHEMA = require('./schema/default_safe'); var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var CHAR_TAB = 0x09; /* Tab */ var CHAR_LINE_FEED = 0x0A; /* LF */ var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ var CHAR_SPACE = 0x20; /* Space */ var CHAR_EXCLAMATION = 0x21; /* ! */ var CHAR_DOUBLE_QUOTE = 0x22; /* " */ var CHAR_SHARP = 0x23; /* # */ var CHAR_PERCENT = 0x25; /* % */ var CHAR_AMPERSAND = 0x26; /* & */ var CHAR_SINGLE_QUOTE = 0x27; /* ' */ var CHAR_ASTERISK = 0x2A; /* * */ var CHAR_COMMA = 0x2C; /* , */ var CHAR_MINUS = 0x2D; /* - */ var CHAR_COLON = 0x3A; /* : */ var CHAR_GREATER_THAN = 0x3E; /* > */ var CHAR_QUESTION = 0x3F; /* ? */ var CHAR_COMMERCIAL_AT = 0x40; /* @ */ var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ var CHAR_GRAVE_ACCENT = 0x60; /* ` */ var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ var CHAR_VERTICAL_LINE = 0x7C; /* | */ var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ var ESCAPE_SEQUENCES = {}; ESCAPE_SEQUENCES[0x00] = '\\0'; ESCAPE_SEQUENCES[0x07] = '\\a'; ESCAPE_SEQUENCES[0x08] = '\\b'; ESCAPE_SEQUENCES[0x09] = '\\t'; ESCAPE_SEQUENCES[0x0A] = '\\n'; ESCAPE_SEQUENCES[0x0B] = '\\v'; ESCAPE_SEQUENCES[0x0C] = '\\f'; ESCAPE_SEQUENCES[0x0D] = '\\r'; ESCAPE_SEQUENCES[0x1B] = '\\e'; ESCAPE_SEQUENCES[0x22] = '\\"'; ESCAPE_SEQUENCES[0x5C] = '\\\\'; ESCAPE_SEQUENCES[0x85] = '\\N'; ESCAPE_SEQUENCES[0xA0] = '\\_'; ESCAPE_SEQUENCES[0x2028] = '\\L'; ESCAPE_SEQUENCES[0x2029] = '\\P'; var DEPRECATED_BOOLEANS_SYNTAX = [ 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' ]; function compileStyleMap(schema, map) { var result, keys, index, length, tag, style, type; if (null === map) { return {}; } result = {}; keys = Object.keys(map); for (index = 0, length = keys.length; index < length; index += 1) { tag = keys[index]; style = String(map[tag]); if ('!!' === tag.slice(0, 2)) { tag = 'tag:yaml.org,2002:' + tag.slice(2); } type = schema.compiledTypeMap[tag]; if (type && _hasOwnProperty.call(type.styleAliases, style)) { style = type.styleAliases[style]; } result[tag] = style; } return result; } function encodeHex(character) { var string, handle, length; string = character.toString(16).toUpperCase(); if (character <= 0xFF) { handle = 'x'; length = 2; } else if (character <= 0xFFFF) { handle = 'u'; length = 4; } else if (character <= 0xFFFFFFFF) { handle = 'U'; length = 8; } else { throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); } return '\\' + handle + common.repeat('0', length - string.length) + string; } function State(options) { this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; this.indent = Math.max(1, (options['indent'] || 2)); this.skipInvalid = options['skipInvalid'] || false; this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); this.styleMap = compileStyleMap(this.schema, options['styles'] || null); this.implicitTypes = this.schema.compiledImplicit; this.explicitTypes = this.schema.compiledExplicit; this.tag = null; this.result = ''; this.duplicates = []; this.usedDuplicates = null; } function indentString(string:string, spaces) { var ind = common.repeat(' ', spaces), position = 0, next = -1, result = '', line, length = string.length; while (position < length) { next = string.indexOf('\n', position); if (next === -1) { line = string.slice(position); position = length; } else { line = string.slice(position, next + 1); position = next + 1; } if (line.length && line !== '\n') { result += ind; } result += line; } return result; } function generateNextLine(state, level) { return '\n' + common.repeat(' ', state.indent * level); } function testImplicitResolving(state, str) { var index, length, type; for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { type = state.implicitTypes[index]; if (type.resolve(str)) { return true; } } return false; } function StringBuilder(source) { this.source = source; this.result = ''; this.checkpoint = 0; } StringBuilder.prototype.takeUpTo = function (position) { var er; if (position < this.checkpoint) { er = new Error('position should be > checkpoint'); er.position = position; er.checkpoint = this.checkpoint; throw er; } this.result += this.source.slice(this.checkpoint, position); this.checkpoint = position; return this; }; StringBuilder.prototype.escapeChar = function () { var character, esc; character = this.source.charCodeAt(this.checkpoint); esc = ESCAPE_SEQUENCES[character] || encodeHex(character); this.result += esc; this.checkpoint += 1; return this; }; StringBuilder.prototype.finish = function () { if (this.source.length > this.checkpoint) { this.takeUpTo(this.source.length); } }; function writeScalar(state, object, level) { var simple, first, spaceWrap, folded, literal, single, double, sawLineFeed, linePosition, longestLine, indent, max, character, position, escapeSeq, hexEsc, previous, lineLength, modifier, trailingLineBreaks, result; if (0 === object.length) { state.dump = "''"; return; } if (object.indexOf("!include")==0){ state.dump=""+object;//FIXME return; } if (object.indexOf("!$$$novalue")==0){ state.dump="";//FIXME return; } if (-1 !== DEPRECATED_BOOLEANS_SYNTAX.indexOf(object)) { state.dump = "'" + object + "'"; return; } simple = true; first = object.length ? object.charCodeAt(0) : 0; spaceWrap = (CHAR_SPACE === first || CHAR_SPACE === object.charCodeAt(object.length - 1)); // Simplified check for restricted first characters // http://www.yaml.org/spec/1.2/spec.html#ns-plain-first%28c%29 if (CHAR_MINUS === first || CHAR_QUESTION === first || CHAR_COMMERCIAL_AT === first || CHAR_GRAVE_ACCENT === first) { simple = false; } // can only use > and | if not wrapped in spaces. if (spaceWrap) { simple = false; folded = false; literal = false; } else { folded = true; literal = true; } single = true; double = new StringBuilder(object); sawLineFeed = false; linePosition = 0; longestLine = 0; indent = state.indent * level; max = 80; if (indent < 40) { max -= indent; } else { max = 40; } for (position = 0; position < object.length; position++) { character = object.charCodeAt(position); if (simple) { // Characters that can never appear in the simple scalar if (!simpleChar(character)) { simple = false; } else { // Still simple. If we make it all the way through like // this, then we can just dump the string as-is. continue; } } if (single && character === CHAR_SINGLE_QUOTE) { single = false; } escapeSeq = ESCAPE_SEQUENCES[character]; hexEsc = needsHexEscape(character); if (!escapeSeq && !hexEsc) { continue; } if (character !== CHAR_LINE_FEED && character !== CHAR_DOUBLE_QUOTE && character !== CHAR_SINGLE_QUOTE) { folded = false; literal = false; } else if (character === CHAR_LINE_FEED) { sawLineFeed = true; single = false; if (position > 0) { previous = object.charCodeAt(position - 1); if (previous === CHAR_SPACE) { literal = false; folded = false; } } if (folded) { lineLength = position - linePosition; linePosition = position; if (lineLength > longestLine) { longestLine = lineLength; } } } if (character !== CHAR_DOUBLE_QUOTE) { single = false; } double.takeUpTo(position); double.escapeChar(); } if (simple && testImplicitResolving(state, object)) { simple = false; } modifier = ''; if (folded || literal) { trailingLineBreaks = 0; if (object.charCodeAt(object.length - 1) === CHAR_LINE_FEED) { trailingLineBreaks += 1; if (object.charCodeAt(object.length - 2) === CHAR_LINE_FEED) { trailingLineBreaks += 1; } } if (trailingLineBreaks === 0) { modifier = '-'; } else if (trailingLineBreaks === 2) { modifier = '+'; } } if (literal && longestLine < max) { folded = false; } // If it's literally one line, then don't bother with the literal. // We may still want to do a fold, though, if it's a super long line. if (!sawLineFeed) { literal = false; } if (simple) { state.dump = object; } else if (single) { state.dump = '\'' + object + '\''; } else if (folded) { result = fold(object, max); state.dump = '>' + modifier + '\n' + indentString(result, indent); } else if (literal) { if (!modifier) { object = object.replace(/\n$/, ''); } state.dump = '|' + modifier + '\n' + indentString(object, indent); } else if (double) { double.finish(); state.dump = '"' + double.result + '"'; } else { throw new Error('Failed to dump scalar value'); } return; } // The `trailing` var is a regexp match of any trailing `\n` characters. // // There are three cases we care about: // // 1. One trailing `\n` on the string. Just use `|` or `>`. // This is the assumed default. (trailing = null) // 2. No trailing `\n` on the string. Use `|-` or `>-` to "chomp" the end. // 3. More than one trailing `\n` on the string. Use `|+` or `>+`. // // In the case of `>+`, these line breaks are *not* doubled (like the line // breaks within the string), so it's important to only end with the exact // same number as we started. function fold(object, max) { var result = '', position = 0, length = object.length, trailing = /\n+$/.exec(object), newLine; if (trailing) { length = trailing.index + 1; } while (position < length) { newLine = object.indexOf('\n', position); if (newLine > length || newLine === -1) { if (result) { result += '\n\n'; } result += foldLine(object.slice(position, length), max); position = length; } else { if (result) { result += '\n\n'; } result += foldLine(object.slice(position, newLine), max); position = newLine + 1; } } if (trailing && trailing[0] !== '\n') { result += trailing[0]; } return result; } function foldLine(line, max) { if (line === '') { return line; } var foldRe = /[^\s] [^\s]/g, result = '', prevMatch = 0, foldStart = 0, match = foldRe.exec(line), index, foldEnd, folded; while (match) { index = match.index; // when we cross the max len, if the previous match would've // been ok, use that one, and carry on. If there was no previous // match on this fold section, then just have a long line. if (index - foldStart > max) { if (prevMatch !== foldStart) { foldEnd = prevMatch; } else { foldEnd = index; } if (result) { result += '\n'; } folded = line.slice(foldStart, foldEnd); result += folded; foldStart = foldEnd + 1; } prevMatch = index + 1; match = foldRe.exec(line); } if (result) { result += '\n'; } // if we end up with one last word at the end, then the last bit might // be slightly bigger than we wanted, because we exited out of the loop. if (foldStart !== prevMatch && line.length - foldStart > max) { result += line.slice(foldStart, prevMatch) + '\n' + line.slice(prevMatch + 1); } else { result += line.slice(foldStart); } return result; } // Returns true if character can be found in a simple scalar function simpleChar(character) { return CHAR_TAB !== character && CHAR_LINE_FEED !== character && CHAR_CARRIAGE_RETURN !== character && CHAR_COMMA !== character && CHAR_LEFT_SQUARE_BRACKET !== character && CHAR_RIGHT_SQUARE_BRACKET !== character && CHAR_LEFT_CURLY_BRACKET !== character && CHAR_RIGHT_CURLY_BRACKET !== character && CHAR_SHARP !== character && CHAR_AMPERSAND !== character && CHAR_ASTERISK !== character && CHAR_EXCLAMATION !== character && CHAR_VERTICAL_LINE !== character && CHAR_GREATER_THAN !== character && CHAR_SINGLE_QUOTE !== character && CHAR_DOUBLE_QUOTE !== character && CHAR_PERCENT !== character && CHAR_COLON !== character && !ESCAPE_SEQUENCES[character] && !needsHexEscape(character); } // Returns true if the character code needs to be escaped. function needsHexEscape(character) { return !((0x00020 <= character && character <= 0x00007E) || (0x00085 === character) || (0x000A0 <= character && character <= 0x00D7FF) || (0x0E000 <= character && character <= 0x00FFFD) || (0x10000 <= character && character <= 0x10FFFF)); } function writeFlowSequence(state, level, object) { var _result = '', _tag = state.tag, index, length; for (index = 0, length = object.length; index < length; index += 1) { // Write only valid elements. if (writeNode(state, level, object[index], false, false)) { if (0 !== index) { _result += ', '; } _result += state.dump; } } state.tag = _tag; state.dump = '[' + _result + ']'; } function writeBlockSequence(state, level, object, compact) { var _result = '', _tag = state.tag, index, length; for (index = 0, length = object.length; index < length; index += 1) { // Write only valid elements. if (writeNode(state, level + 1, object[index], true, true)) { if (!compact || 0 !== index) { _result += generateNextLine(state, level); } _result += '- ' + state.dump; } } state.tag = _tag; state.dump = _result || '[]'; // Empty sequence if no valid values. } function writeFlowMapping(state, level, object) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, pairBuffer; for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (0 !== index) { pairBuffer += ', '; } objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (!writeNode(state, level, objectKey, false, false)) { continue; // Skip this pair because of invalid key; } if (state.dump.length > 1024) { pairBuffer += '? '; } pairBuffer += state.dump + ': '; if (!writeNode(state, level, objectValue, false, false)) { continue; // Skip this pair because of invalid value. } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = '{' + _result + '}'; } function writeBlockMapping(state, level, object, compact) { var _result = '', _tag = state.tag, objectKeyList = Object.keys(object), index, length, objectKey, objectValue, explicitPair, pairBuffer; for (index = 0, length = objectKeyList.length; index < length; index += 1) { pairBuffer = ''; if (!compact || 0 !== index) { pairBuffer += generateNextLine(state, level); } objectKey = objectKeyList[index]; objectValue = object[objectKey]; if (!writeNode(state, level + 1, objectKey, true, true)) { continue; // Skip this pair because of invalid key. } explicitPair = (null !== state.tag && '?' !== state.tag) || (state.dump && state.dump.length > 1024); if (explicitPair) { if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += '?'; } else { pairBuffer += '? '; } } pairBuffer += state.dump; if (explicitPair) { pairBuffer += generateNextLine(state, level); } if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { continue; // Skip this pair because of invalid value. } if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { pairBuffer += ':'; } else { pairBuffer += ': '; } pairBuffer += state.dump; // Both key and value are valid. _result += pairBuffer; } state.tag = _tag; state.dump = _result || '{}'; // Empty mapping if no valid pairs. } function detectType(state, object, explicit) { var _result, typeList, index, length, type, style; typeList = explicit ? state.explicitTypes : state.implicitTypes; for (index = 0, length = typeList.length; index < length; index += 1) { type = typeList[index]; if ((type.instanceOf || type.predicate) && (!type.instanceOf || (('object' === typeof object) && (object instanceof type.instanceOf))) && (!type.predicate || type.predicate(object))) { state.tag = explicit ? type.tag : '?'; if (type.represent) { style = state.styleMap[type.tag] || type.defaultStyle; if ('[object Function]' === _toString.call(type.represent)) { _result = type.represent(object, style); } else if (_hasOwnProperty.call(type.represent, style)) { _result = type.represent[style](object, style); } else { throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); } state.dump = _result; } return true; } } return false; } // Serializes `object` and writes it to global `result`. // Returns true on success, or false on invalid object. // function writeNode(state, level, object, block, compact) { state.tag = null; state.dump = object; if (!detectType(state, object, false)) { detectType(state, object, true); } var type = _toString.call(state.dump); if (block) { block = (0 > state.flowLevel || state.flowLevel > level); } if ((null !== state.tag && '?' !== state.tag) || (2 !== state.indent && level > 0)) { compact = false; } var objectOrArray = '[object Object]' === type || '[object Array]' === type, duplicateIndex, duplicate; if (objectOrArray) { duplicateIndex = state.duplicates.indexOf(object); duplicate = duplicateIndex !== -1; } if (duplicate && state.usedDuplicates[duplicateIndex]) { state.dump = '*ref_' + duplicateIndex; } else { if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { state.usedDuplicates[duplicateIndex] = true; } if ('[object Object]' === type) { if (block && (0 !== Object.keys(state.dump).length)) { writeBlockMapping(state, level, state.dump, compact); if (duplicate) { state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump; } } else { writeFlowMapping(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if ('[object Array]' === type) { if (block && (0 !== state.dump.length)) { writeBlockSequence(state, level, state.dump, compact); if (duplicate) { state.dump = '&ref_' + duplicateIndex + (0 === level ? '\n' : '') + state.dump; } } else { writeFlowSequence(state, level, state.dump); if (duplicate) { state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } } } else if ('[object String]' === type) { if ('?' !== state.tag) { writeScalar(state, state.dump, level); } } else { if (state.skipInvalid) { return false; } throw new YAMLException('unacceptable kind of an object to dump ' + type); } if (null !== state.tag && '?' !== state.tag) { state.dump = '!<' + state.tag + '> ' + state.dump; } } return true; } function getDuplicateReferences(object, state) { var objects = [], duplicatesIndexes = [], index, length; inspectNode(object, objects, duplicatesIndexes); for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { state.duplicates.push(objects[duplicatesIndexes[index]]); } state.usedDuplicates = new Array(length); } function inspectNode(object, objects, duplicatesIndexes) { var type = _toString.call(object), objectKeyList, index, length; if (null !== object && 'object' === typeof object) { index = objects.indexOf(object); if (-1 !== index) { if (-1 === duplicatesIndexes.indexOf(index)) { duplicatesIndexes.push(index); } } else { objects.push(object); if (Array.isArray(object)) { for (index = 0, length = object.length; index < length; index += 1) { inspectNode(object[index], objects, duplicatesIndexes); } } else { objectKeyList = Object.keys(object); for (index = 0, length = objectKeyList.length; index < length; index += 1) { inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); } } } } } export function dump(input, options) { options = options || {}; var state = new State(options); getDuplicateReferences(input, state); if (writeNode(state, 0, input, true, true)) { return state.dump + '\n'; } return ''; } export function safeDump(input, options) { return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); }
the_stack
import { existsSync, mkdirSync } from 'fs'; import { join, relative } from 'path'; import test, { ExecutionContext } from 'ava'; import del from 'del'; import execa from 'execa'; import globby from 'globby'; import md5File from 'md5-file'; import meow from 'meow'; import { cloneRepo, Placeholders, Tasks } from '../tasks'; import { typescriptStarter } from '../typescript-starter'; import { normalizePath, Runner } from '../utils'; /** * NOTE: many of the tests below validate file modification. The filesystem is * not mocked, and these tests make real changes. Proceed with caution. * * Filesystem changes made by these tests should be contained in the `build` * directory for easier clean up. */ const branch = execa.sync('git', [ 'rev-parse', '--symbolic-full-name', '--abbrev-ref', 'HEAD', ]).stdout; const repoInfo = { // if local repo is in a detached HEAD state, providing --branch to `git clone` will fail. branch: branch === 'HEAD' ? '.' : branch, repo: process.cwd(), }; const testDir = join(process.cwd(), 'test'); if (existsSync(testDir)) { del.sync(testDir); } mkdirSync(testDir); const env = { TYPESCRIPT_STARTER_REPO_BRANCH: repoInfo.branch, TYPESCRIPT_STARTER_REPO_URL: repoInfo.repo, }; enum TestDirectories { one = 'test-1', two = 'test-2', three = 'test-3', four = 'test-4', five = 'test-5', six = 'test-6', } test('returns version', async (t) => { const expected = meow('').pkg.version; t.truthy(typeof expected === 'string'); const { stdout } = await execa(`./bin/typescript-starter`, ['--version']); t.is(stdout, expected); }); test('returns help/usage', async (t) => { const { stdout } = await execa(`./bin/typescript-starter`, ['--help']); t.regex(stdout, /Usage/); }); test('errors if project name collides with an existing path', async (t) => { const existingDir = 'build'; const error = await t.throwsAsync<execa.ExecaError>( execa(`./bin/typescript-starter`, [existingDir]) ); t.regex(error.stderr, /"build" path already exists/); }); test('errors if project name is not in kebab-case', async (t) => { const error = await t.throwsAsync<execa.ExecaError>( execa(`./bin/typescript-starter`, ['name with spaces']) ); t.regex(error.stderr, /should be in-kebab-case/); }); async function hashAllTheThings( projectName: string, sandboxed = false ): Promise<{ readonly [filename: string]: string }> { const projectDir = normalizePath(join(testDir, projectName)); const rawFilePaths: ReadonlyArray<string> = await globby( [projectDir, `!${projectDir}/.git`], { dot: true, } ); const filePaths = sandboxed ? rawFilePaths : rawFilePaths.filter( (path) => // When not sandboxed, these files will change based on git config !['LICENSE', 'package.json'].includes(relative(projectDir, path)) ); const hashAll = filePaths.map<Promise<string>>((path) => md5File(path)); const hashes = await Promise.all(hashAll); return hashes.reduce<{ readonly [filename: string]: string }>( (acc, hash, i) => { const trimmedNormalizedFilePath = normalizePath( relative(testDir, filePaths[i]) ); return { ...acc, [trimmedNormalizedFilePath]: hash, }; }, {} ); } /** * Since we're using Dependabot to keep dependencies fresh, including * `package.json` in these file fingerprint tests guarantees that every * Dependabot PR will trigger a false-positive test failure. * * Here we trade complete assurance that `package.json` is correct for much less * noisy build results. */ const ignorePackageJson = (map: { readonly [file: string]: string }) => Object.entries(map) .filter((entry) => !entry[0].includes('package.json')) .reduce((ret, [path, hash]) => ({ ...ret, [path]: hash }), {}); test(`${TestDirectories.one}: parses CLI arguments, handles default options`, async (t) => { const description = 'example description 1'; const { stdout } = await execa( `../bin/typescript-starter`, [ `${TestDirectories.one}`, // (user entered `-d='example description 1'`) `-d=${description}`, '--no-install', ], { cwd: testDir, env, } ); t.regex(stdout, new RegExp(`Created ${TestDirectories.one} 🎉`)); const map = await hashAllTheThings(TestDirectories.one); t.deepEqual(map, { 'test-1/.circleci/config.yml': '44d2fd424c93d381d41030f789efabba', 'test-1/.cspell.json': '61bbd8ed98375a94cbd1063ab498959f', 'test-1/.editorconfig': '44a3e6c69d9267b0f756986fd970a8f4', 'test-1/.eslintrc.json': '4e74756d24eaccb7f28d4999e4bd6f0d', 'test-1/.github/CONTRIBUTING.md': '5f0dfa7fdf9bf828e3a3aa8fcaeece08', 'test-1/.github/ISSUE_TEMPLATE.md': 'e70a0b70402765682b1a961af855040e', 'test-1/.github/PULL_REQUEST_TEMPLATE.md': '70f4b97f3914e2f399bcc5868e072c29', 'test-1/.gitignore': 'a053cd9512af2ebf8ffac400b14034eb', 'test-1/.prettierignore': '1da1ce4fdb868f0939608fafd38f9683', 'test-1/.vscode/extensions.json': '2d26a716ba181656faac4cd2d38ec139', 'test-1/.vscode/launch.json': '140e17d591e03b8850c456ade3aefb1f', 'test-1/.vscode/settings.json': '1671948882faee285f18d7491f0fc913', 'test-1/README.md': '7a9f4efa9213266c3800f3cc82a53ba7', 'test-1/src/index.ts': '5025093b4dc30524d349fd1cc465ed30', 'test-1/src/lib/number.spec.ts': '0592001d71aa3b3e6bf72f4cd95dc1b9', 'test-1/src/lib/number.ts': 'dcbcc98fea337d07e81728c1a6526a1e', 'test-1/src/types/example.d.ts': '76642861732b16754b0110fb1de49823', 'test-1/tsconfig.json': '4228782ef56faca96f8123a88bf26dc2', 'test-1/tsconfig.module.json': '2fda4c8760c6cfa3462b40df0645850d', }); }); test(`${TestDirectories.two}: parses CLI arguments, handles all options`, async (t) => { const description = 'example description 2'; const { stdout } = await execa( `../bin/typescript-starter`, [ `${TestDirectories.two}`, // (user entered `--description 'example description 2'`) `--description`, `${description}`, '--yarn', '--node', '--dom', '--no-install', ], { cwd: testDir, env, } ); t.regex(stdout, new RegExp(`Created ${TestDirectories.two} 🎉`)); const map = await hashAllTheThings(TestDirectories.two); t.deepEqual(map, { 'test-2/.circleci/config.yml': '44d2fd424c93d381d41030f789efabba', 'test-2/.cspell.json': '61bbd8ed98375a94cbd1063ab498959f', 'test-2/.editorconfig': '44a3e6c69d9267b0f756986fd970a8f4', 'test-2/.eslintrc.json': '4e74756d24eaccb7f28d4999e4bd6f0d', 'test-2/.github/CONTRIBUTING.md': '5f0dfa7fdf9bf828e3a3aa8fcaeece08', 'test-2/.github/ISSUE_TEMPLATE.md': 'e70a0b70402765682b1a961af855040e', 'test-2/.github/PULL_REQUEST_TEMPLATE.md': '70f4b97f3914e2f399bcc5868e072c29', 'test-2/.gitignore': '703beedaf3cabd7f7fd7d3f57408ec61', 'test-2/.prettierignore': '1da1ce4fdb868f0939608fafd38f9683', 'test-2/.vscode/extensions.json': '2d26a716ba181656faac4cd2d38ec139', 'test-2/.vscode/launch.json': '140e17d591e03b8850c456ade3aefb1f', 'test-2/.vscode/settings.json': '1671948882faee285f18d7491f0fc913', 'test-2/README.md': 'ddaf27da4cc4ca5225785f0ac8f4da58', 'test-2/src/index.ts': 'fbc67c2cbf3a7d37e4e02583bf06eec9', 'test-2/src/lib/async.spec.ts': '65b10546885ebad41c098318b896f23c', 'test-2/src/lib/async.ts': '926732fef1285cb0abb5c6e287ed24df', 'test-2/src/lib/hash.spec.ts': '06f6bfc1b03f893a16448bb6d6806ea2', 'test-2/src/lib/hash.ts': 'cf3659937ff3162bc525c8bfac18b7cf', 'test-2/src/lib/number.spec.ts': '0592001d71aa3b3e6bf72f4cd95dc1b9', 'test-2/src/lib/number.ts': 'dcbcc98fea337d07e81728c1a6526a1e', 'test-2/src/types/example.d.ts': '76642861732b16754b0110fb1de49823', 'test-2/tsconfig.json': '7a9481f033cb07985ee1b903ad42b167', 'test-2/tsconfig.module.json': '2fda4c8760c6cfa3462b40df0645850d', }); }); const down = '\x1B\x5B\x42'; const up = '\x1B\x5B\x41'; const enter = '\x0D'; const ms = (milliseconds: number) => new Promise<void>((resolve) => setTimeout(resolve, milliseconds)); async function testInteractive( projectName: string, entry: ReadonlyArray<string | ReadonlyArray<string>> ): Promise<execa.ExecaReturnValue<string>> { const typeDefs = entry[3] !== ''; const proc = execa(`../bin/typescript-starter`, ['--no-install'], { cwd: testDir, env, }); // TODO: missing in Node.js type definition's ChildProcess.stdin? // https://nodejs.org/api/process.html#process_process_stdin // proc.stdin.setEncoding('utf8'); const type = (input: string) => proc.stdin?.write(input); // wait for first chunk to be emitted await new Promise((resolve) => { proc.stdout?.once('data', resolve); }); await ms(200); type(`${projectName}${enter}`); await ms(200); type(`${entry[0][0]}${enter}`); await ms(200); type(`${entry[1]}${enter}`); await ms(200); type(`${entry[2][0]}${enter}`); await ms(200); if (typeDefs) { type(`${entry[3][0]}${enter}`); await ms(200); } type(`${entry[4][0]}${enter}`); await ms(200); return proc; } test(`${TestDirectories.three}: interactive mode: javascript library`, async (t) => { const proc = await testInteractive(`${TestDirectories.three}`, [ [`${down}${up}${down}`, `Javascript library`], `integration test 3 description`, [`${down}${up}${down}${enter}`, `yarn`], [`${down}${down}${down}${enter}`, `Both Node.js and DOM`], [ ' ', 'stricter type-checking[\\s\\S]*eslint-plugin-functional[\\s\\S]*VS Code', ], ]); await proc; const map = await hashAllTheThings(TestDirectories.three); t.deepEqual(map, { 'test-3/.circleci/config.yml': '44d2fd424c93d381d41030f789efabba', 'test-3/.cspell.json': '61bbd8ed98375a94cbd1063ab498959f', 'test-3/.editorconfig': '44a3e6c69d9267b0f756986fd970a8f4', 'test-3/.eslintrc.json': '4e74756d24eaccb7f28d4999e4bd6f0d', 'test-3/.github/CONTRIBUTING.md': '5f0dfa7fdf9bf828e3a3aa8fcaeece08', 'test-3/.github/ISSUE_TEMPLATE.md': 'e70a0b70402765682b1a961af855040e', 'test-3/.github/PULL_REQUEST_TEMPLATE.md': '70f4b97f3914e2f399bcc5868e072c29', 'test-3/.gitignore': '703beedaf3cabd7f7fd7d3f57408ec61', 'test-3/.prettierignore': '1da1ce4fdb868f0939608fafd38f9683', 'test-3/.vscode/extensions.json': '2d26a716ba181656faac4cd2d38ec139', 'test-3/.vscode/launch.json': '140e17d591e03b8850c456ade3aefb1f', 'test-3/.vscode/settings.json': '1671948882faee285f18d7491f0fc913', 'test-3/README.md': 'c52631ebf78f6b030af9a109b769b647', 'test-3/src/index.ts': 'fbc67c2cbf3a7d37e4e02583bf06eec9', 'test-3/src/lib/async.spec.ts': '65b10546885ebad41c098318b896f23c', 'test-3/src/lib/async.ts': '926732fef1285cb0abb5c6e287ed24df', 'test-3/src/lib/hash.spec.ts': '06f6bfc1b03f893a16448bb6d6806ea2', 'test-3/src/lib/hash.ts': 'cf3659937ff3162bc525c8bfac18b7cf', 'test-3/src/lib/number.spec.ts': '0592001d71aa3b3e6bf72f4cd95dc1b9', 'test-3/src/lib/number.ts': 'dcbcc98fea337d07e81728c1a6526a1e', 'test-3/src/types/example.d.ts': '76642861732b16754b0110fb1de49823', 'test-3/tsconfig.json': '472791a7b88cee5b9369207216fe7f98', 'test-3/tsconfig.module.json': '2fda4c8760c6cfa3462b40df0645850d', }); }); test(`${TestDirectories.four}: interactive mode: node.js application`, async (t) => { const proc = await testInteractive(`${TestDirectories.four}`, [ [`${down}${up}`, `Node.js application`], `integration test 4 description`, [`${down}${up}${enter}`, `npm`], '', [`${down} `, 'VS Code'], ]); await proc; const map = await hashAllTheThings(TestDirectories.four); t.deepEqual(map, { 'test-4/.circleci/config.yml': '44d2fd424c93d381d41030f789efabba', 'test-4/.cspell.json': '61bbd8ed98375a94cbd1063ab498959f', 'test-4/.editorconfig': '44a3e6c69d9267b0f756986fd970a8f4', 'test-4/.eslintrc.json': '941448b089cd055bbe476a84c8f96cfe', 'test-4/.github/CONTRIBUTING.md': '5f0dfa7fdf9bf828e3a3aa8fcaeece08', 'test-4/.github/ISSUE_TEMPLATE.md': 'e70a0b70402765682b1a961af855040e', 'test-4/.github/PULL_REQUEST_TEMPLATE.md': '70f4b97f3914e2f399bcc5868e072c29', 'test-4/.gitignore': 'a053cd9512af2ebf8ffac400b14034eb', 'test-4/.prettierignore': '1da1ce4fdb868f0939608fafd38f9683', 'test-4/.vscode/extensions.json': '2d26a716ba181656faac4cd2d38ec139', 'test-4/.vscode/launch.json': '140e17d591e03b8850c456ade3aefb1f', 'test-4/.vscode/settings.json': '1671948882faee285f18d7491f0fc913', 'test-4/README.md': 'a3e0699b39498df4843c9dde95f1e000', 'test-4/src/index.ts': '5991bedc40ac87a01d880c6db16fe349', 'test-4/src/lib/async.spec.ts': '65b10546885ebad41c098318b896f23c', 'test-4/src/lib/async.ts': '926732fef1285cb0abb5c6e287ed24df', 'test-4/src/lib/number.spec.ts': '0592001d71aa3b3e6bf72f4cd95dc1b9', 'test-4/src/lib/number.ts': 'dcbcc98fea337d07e81728c1a6526a1e', 'test-4/src/types/example.d.ts': '76642861732b16754b0110fb1de49823', 'test-4/tsconfig.json': 'b4786d3cf1c3e6bd51253c036bfc6e8a', 'test-4/tsconfig.module.json': '2fda4c8760c6cfa3462b40df0645850d', }); }); const sandboxTasks = ( t: ExecutionContext<unknown>, commit: boolean, install: boolean ): Tasks => { return { cloneRepo: cloneRepo(execa, true), initialCommit: async () => { commit ? t.pass() : t.fail(); }, install: async () => { install ? t.pass() : t.fail(); }, }; }; const sandboxOptions = { description: 'this is an example description', githubUsername: 'SOME_GITHUB_USERNAME', repoInfo, workingDirectory: testDir, }; const silenceConsole = (console: Console) => { // eslint-disable-next-line functional/immutable-data console.log = () => { // mock console.log to silence it return; }; }; test(`${TestDirectories.five}: Sandboxed: npm install, initial commit`, async (t) => { t.plan(3); const options = { ...sandboxOptions, appveyor: false, circleci: false, cspell: false, domDefinitions: false, editorconfig: false, email: 'email@example.com', // cspell: disable-next-line fullName: 'Satoshi Nakamoto', functional: true, install: true, nodeDefinitions: false, projectName: TestDirectories.five, runner: Runner.Npm, strict: true, travis: false, vscode: false, }; silenceConsole(console); await typescriptStarter(options, sandboxTasks(t, true, true)); const map = await hashAllTheThings(TestDirectories.five, true); t.deepEqual(ignorePackageJson(map), { 'test-5/.eslintrc.json': '4e74756d24eaccb7f28d4999e4bd6f0d', 'test-5/.github/CONTRIBUTING.md': '5f0dfa7fdf9bf828e3a3aa8fcaeece08', 'test-5/.github/ISSUE_TEMPLATE.md': 'e70a0b70402765682b1a961af855040e', 'test-5/.github/PULL_REQUEST_TEMPLATE.md': '70f4b97f3914e2f399bcc5868e072c29', 'test-5/.gitignore': 'a053cd9512af2ebf8ffac400b14034eb', 'test-5/.prettierignore': '1da1ce4fdb868f0939608fafd38f9683', 'test-5/LICENSE': '317693126d229a3cdd19725a624a56fc', 'test-5/README.md': '8fc7ecb21d7d47289e4b2469eea4db39', 'test-5/src/index.ts': '5025093b4dc30524d349fd1cc465ed30', 'test-5/src/lib/number.spec.ts': '0592001d71aa3b3e6bf72f4cd95dc1b9', 'test-5/src/lib/number.ts': 'dcbcc98fea337d07e81728c1a6526a1e', 'test-5/src/types/example.d.ts': '76642861732b16754b0110fb1de49823', 'test-5/tsconfig.json': '5ea2a8356e00e9407dd4641007fd3940', 'test-5/tsconfig.module.json': '2fda4c8760c6cfa3462b40df0645850d', }); }); test(`${TestDirectories.six}: Sandboxed: yarn, no initial commit`, async (t) => { t.plan(2); const options = { ...sandboxOptions, appveyor: true, circleci: true, cspell: false, domDefinitions: true, editorconfig: true, email: Placeholders.email, fullName: Placeholders.name, functional: true, install: true, nodeDefinitions: true, projectName: TestDirectories.six, runner: Runner.Yarn, strict: false, travis: true, vscode: true, }; silenceConsole(console); await typescriptStarter(options, sandboxTasks(t, false, true)); const map = await hashAllTheThings(TestDirectories.six, true); t.deepEqual(ignorePackageJson(map), { 'test-6/.circleci/config.yml': '44d2fd424c93d381d41030f789efabba', 'test-6/.editorconfig': '44a3e6c69d9267b0f756986fd970a8f4', 'test-6/.eslintrc.json': '4e74756d24eaccb7f28d4999e4bd6f0d', 'test-6/.github/CONTRIBUTING.md': '5f0dfa7fdf9bf828e3a3aa8fcaeece08', 'test-6/.github/ISSUE_TEMPLATE.md': 'e70a0b70402765682b1a961af855040e', 'test-6/.github/PULL_REQUEST_TEMPLATE.md': '70f4b97f3914e2f399bcc5868e072c29', 'test-6/.gitignore': '703beedaf3cabd7f7fd7d3f57408ec61', 'test-6/.prettierignore': '1da1ce4fdb868f0939608fafd38f9683', 'test-6/.travis.yml': '91976af7b86cffb6960db8c35b27b7d0', 'test-6/.vscode/extensions.json': '2d26a716ba181656faac4cd2d38ec139', 'test-6/.vscode/launch.json': '140e17d591e03b8850c456ade3aefb1f', 'test-6/.vscode/settings.json': 'f70eb64341e74d24d901055a26dc8242', 'test-6/LICENSE': '03ffa741a4f7e356b69353efa4937d2b', 'test-6/README.md': 'd809bcbf240f44b51b575a3d49936232', 'test-6/appveyor.yml': '70a91379874bffbf5b27ecbd2fb52ead', 'test-6/src/index.ts': 'fbc67c2cbf3a7d37e4e02583bf06eec9', 'test-6/src/lib/async.spec.ts': '65b10546885ebad41c098318b896f23c', 'test-6/src/lib/async.ts': '926732fef1285cb0abb5c6e287ed24df', 'test-6/src/lib/hash.spec.ts': '06f6bfc1b03f893a16448bb6d6806ea2', 'test-6/src/lib/hash.ts': 'cf3659937ff3162bc525c8bfac18b7cf', 'test-6/src/lib/number.spec.ts': '0592001d71aa3b3e6bf72f4cd95dc1b9', 'test-6/src/lib/number.ts': 'dcbcc98fea337d07e81728c1a6526a1e', 'test-6/src/types/example.d.ts': '76642861732b16754b0110fb1de49823', 'test-6/tsconfig.json': '7a9481f033cb07985ee1b903ad42b167', 'test-6/tsconfig.module.json': '2fda4c8760c6cfa3462b40df0645850d', }); });
the_stack
import { SerializedEntityState } from './common' import { defined, Entity, JulianDate, PerspectiveFrustum, PerspectiveOffCenterFrustum, PositionProperty, ConstantPositionProperty, OrientationProperty, ConstantProperty, Quaternion, Cartesian3, ReferenceFrame, Matrix4, Transforms, Cartographic, sampleTerrain } from './cesium/cesium-imports' import { MapzenTerrariumTerrainProvider } from './cesium/MapzenTerrariumTerrainProvider' export * from './utils/command-queue'; export * from './utils/event'; export * from './utils/message-channel'; export {default as getEventSynthesizier} from './utils/ui-event-synthesizer'; export {default as createEventForwarder} from './utils/ui-event-forwarder'; const reNative = /\{\s*\[native code\]\s*\}/; export function isNativeFunction(f:Function) { return typeof f === 'function' && reNative.test(Function.prototype.toString.call(f)) } export const hasNativeWebVRImplementation = typeof navigator !== 'undefined' && isNativeFunction(navigator.getVRDisplays) && !Object.getOwnPropertyDescriptor(navigator, "getVRDisplays"); export const suggestedWebGLContextAntialiasAttribute = hasNativeWebVRImplementation; export function stringIdentifierFromReferenceFrame(referenceFrame: string | ReferenceFrame | Entity): string { const rf = referenceFrame as Entity; return defined(rf.id) ? rf.id : '' + rf; } export function jsonEquals(left?:{}, right?:{}) { return JSON.stringify(left) === JSON.stringify(right); } /** * Computes a 4x4 transformation matrix from a reference frame with an east-up-south axes centered at the provided origin to the provided ellipsoid's fixed reference frame. The local axes are defined as: * The x axis points in the local east direction. * The y axis points in the points in the direction of the ellipsoid surface normal which passes through the position.. * The z axis points in the local south direction. */ export const eastUpSouthToFixedFrame = Transforms.localFrameToFixedFrameGenerator('east','up'); /** * Get array of ancestor reference frames of a Cesium Entity, ordered from * farthest ancestor to the passed frame, excluding the passed frame. * @param frame A Cesium Entity to get ancestor reference frames. * @param frames An array of reference frames of the Cesium Entity. */ export function getAncestorReferenceFrames(frame: Entity, result=[]) { const frames: Array<Entity | ReferenceFrame> = result; frames.length = 0; let f: Entity | ReferenceFrame | undefined = frame; do { let position: PositionProperty | undefined = (f as Entity).position; f = position && position.referenceFrame; if (defined(f)) frames.unshift(f); } while (defined(f)) return frames } var scratchAncestorCartesian = new Cartesian3; var scratchAncestorQuaternion = new Quaternion; /** * Get array of ancestor reference frames of a Cesium Entity, ordered from * farthest ancestor which has a valid pose to the passed frame, excluding the passed frame. * @param frame A Cesium Entity to get ancestor reference frames. * @param frames An array of reference frames of the Cesium Entity. */ export function getReachableAncestorReferenceFrames(frame: Entity, time:JulianDate, result=[]) { const frames: Array<Entity | ReferenceFrame> = result; frames.length = 0; let f: Entity | ReferenceFrame | undefined = frame; let isValid = false; do { const position: PositionProperty | undefined = (f as Entity).position; const orientation = f && (f as Entity).orientation; f = position && position.referenceFrame; const hasParentFrame = defined(f); const pValue = hasParentFrame && position && position.getValueInReferenceFrame(time, f!, scratchAncestorCartesian); const oValue = hasParentFrame && pValue && orientation && orientation.getValue(time, scratchAncestorQuaternion); isValid = pValue && oValue; if (isValid) frames.unshift(f!); } while (isValid) return frames } /** * Gets the value of the Position property at the provided time and in the provided reference frame. * @param entity The entity to get position. * @param time The time for which to retrieve the value. * @param referenceFrame The desired referenceFrame of the result. * @param result The object to store the value into. * @return The modified result parameter. */ export function getEntityPositionInReferenceFrame( entity: Entity, time: JulianDate, referenceFrame: Entity | ReferenceFrame, result: Cartesian3): Cartesian3 | undefined { return entity.position && entity.position.getValueInReferenceFrame(time, referenceFrame, result) } /** * Alias of getEntityPositionInReferenceFrame */ export const getEntityPosition = getEntityPositionInReferenceFrame; /** * Get the value of the Orientation property at the provided time and in the provided reference frame. * @param entity The entity to get position. * @param time The time for which to retrieve the value. * @param referenceFrame The desired referenceFrame of the result. * @param result The object to store the value into. * @return The modified result parameter. */ export function getEntityOrientationInReferenceFrame( entity: Entity, time: JulianDate, referenceFrame: ReferenceFrame | Entity, result: Quaternion): Quaternion | undefined { const entityFrame = entity.position && entity.position.referenceFrame if (!defined(entityFrame)) return undefined let orientation: Quaternion = entity.orientation && entity.orientation.getValue(time, result) if (!defined(orientation)) return undefined; return OrientationProperty.convertToReferenceFrame(time, orientation, entityFrame, referenceFrame, result) } /** * Alias of getEntityOrientationInReferenceFrame */ export const getEntityOrientation = getEntityOrientationInReferenceFrame; // const scratchCartesianPositionFIXED = new Cartesian3 // const scratchMatrix4 = new Matrix4 // const scratchMatrix3 = new Matrix3 // { // // if no orientation is available, calculate an orientation based on position // const entityPositionFIXED = getEntityPositionInReferenceFrame(entity, time, ReferenceFrame.FIXED, scratchCartesianPositionFIXED) // if (!entityPositionFIXED) return Quaternion.clone(Quaternion.IDENTITY, result) // if (Cartesian3.ZERO.equals(entityPositionFIXED)) throw new Error('invalid cartographic position') // const transform = Transforms.eastNorthUpToFixedFrame(entityPositionFIXED, Ellipsoid.WGS84, scratchMatrix4); // const rotation = Matrix4.getRotation(transform, scratchMatrix3); // const fixedOrientation = Quaternion.fromRotationMatrix(rotation, result); // return OrientationProperty.convertToReferenceFrame(time, fixedOrientation, ReferenceFrame.FIXED, referenceFrame, result) // } const _scratchFramesArray = []; const _entityStateCache:{[key:string]:SerializedEntityState} = {}; /** * Create a SerializedEntityPose from a source entity. * @param entity The entity which the serialized pose represents. * @param time The time which to retrieve the pose. * @param referenceFrame The reference frame to use for generating the pose. * If a target reference frame is not provided, the entity pose will be * serialized according to the furthest ancestor frame that resolves to a valid pose. * @return An EntityPose object with orientation, position and referenceFrame. */ export function getSerializedEntityState(entity: Entity, time: JulianDate, frame?: ReferenceFrame | Entity): SerializedEntityState | null { let frames:(ReferenceFrame|Entity|undefined)[]|undefined = undefined; if (!defined(frame)) { frames = getReachableAncestorReferenceFrames(entity, time, _scratchFramesArray); frame = frames[0]; } if (!defined(frame)) return null; if (entity === frame) return null; const key = entity.id + '@' + ((frame as Entity).id ? (frame as Entity).id : frame); let result = _entityStateCache[key]; if (!result) result = <SerializedEntityState> {}, _entityStateCache[key] = result; const p = getEntityPositionInReferenceFrame(entity, time, frame, result.p || {} as Cartesian3); if (!p) return null; const o = getEntityOrientationInReferenceFrame(entity, time, frame, result.o || {} as Quaternion); if (!o) return null; if (p && o) { result.p = p; result.o = o; result.r = typeof frame === 'number' ? frame : frame.id, result.meta = entity['meta']; return result; } return null; } const urlParser = typeof document !== 'undefined' ? document.createElement("a") : undefined /** * If urlParser does not have a value, throw error message "resolveURL requires DOM api". * If inURL is undefined, throw error message "expected inURL". * Otherwise, assign value of inURL to urlParser.href. * @param inURL A URL needed to be resolved. * @returns A URL ready to be parsed. */ export function resolveURL(inURL: string): string { if (!urlParser) throw new Error("resolveURL requires DOM api"); if (inURL === undefined) throw new Error('Expected inURL') urlParser.href = ''; urlParser.href = inURL return urlParser.href } /** * Parse URL to an object describing details of the URL with href, protocol, * hostname, port, pathname, search, hash, host. * @param inURL A URL needed to be parsed. * @return An object showing parsed URL with href, protocol, * hostname, port, pathname, search, hash, host. */ export function parseURL(inURL: string) { if (!urlParser) throw new Error("parseURL requires DOM api"); if (inURL === undefined) throw new Error('Expected inURL') urlParser.href = '' urlParser.href = inURL return { href: urlParser.href, protocol: urlParser.protocol, hostname: urlParser.hostname, port: urlParser.port, pathname: urlParser.pathname, search: urlParser.search, hash: urlParser.hash, host: urlParser.host } } export function resolveElement(elementOrSelector:string|HTMLElement) { if (elementOrSelector instanceof HTMLElement) { return Promise.resolve(elementOrSelector); } else { return new Promise((resolve, reject)=>{ const resolveElement = () => { let e = <HTMLDivElement>document.querySelector(`${elementOrSelector}`); if (!e) reject(new Error(`Unable to resolve element id ${elementOrSelector}`)) else resolve(e); } if (document.readyState == 'loading') { document.addEventListener('DOMContentLoaded', resolveElement); } else { resolveElement(); } }) } } export function decomposePerspectiveOffCenterProjectionMatrix(mat: Matrix4, result: PerspectiveOffCenterFrustum) { const m11 = mat[Matrix4.COLUMN0ROW0]; // const m12 = mat[Matrix4.COLUMN0ROW1]; const m22 = mat[Matrix4.COLUMN1ROW1]; const m31 = mat[Matrix4.COLUMN2ROW0]; const m32 = mat[Matrix4.COLUMN2ROW1]; const m33 = mat[Matrix4.COLUMN2ROW2]; const m43 = mat[Matrix4.COLUMN3ROW2]; const near = result.near = m43 / (m33 - 1); result.far = m43 / (m33 + 1); result.bottom = near * (m32 - 1) / m22; result.top = near * (m32 + 1) / m22; result.left = near * (m31 - 1) / m11; result.right = near * (m31 + 1) / m11; return result; } const scratchPerspectiveOffCenterFrustum = new PerspectiveOffCenterFrustum; export function decomposePerspectiveProjectionMatrix(mat: Matrix4, result: PerspectiveFrustum) { const f = decomposePerspectiveOffCenterProjectionMatrix(mat, scratchPerspectiveOffCenterFrustum); const xOffset = (f.left + f.right) / 2; const yOffset = (f.top + f.bottom) / 2; const near = f.near; const far = f.far; // const left = f.left - xOffset; const right = f.right - xOffset; const top = f.top - yOffset; // const bottom = f.bottom - yOffset; const aspectRatio = right / top; const fovy = 2 * Math.atan(top / near); let fov; if (aspectRatio < 1) { fov = fovy; } else { fov = Math.atan(Math.tan(fovy * 0.5) * aspectRatio) * 2.0 } result.near = near; result.far = far; result.fov = fov; result.aspectRatio = aspectRatio; result.xOffset = xOffset; result.yOffset = yOffset; return result; } var scratchCartesian = new Cartesian3; var scratchOrientation = new Quaternion; /** * Convert an Entity's position and orientation properties to a new reference frame. * The properties must be constant properties. * @param entity The entity to convert. * @param time The time which to retrieve the pose up the reference chain. * @param referenceFrame The reference frame to convert the position and oriention to. * @return a boolean indicating success or failure. Will be false if either property is * not constant, or if either property cannot be converted to the new frame. */ export function convertEntityReferenceFrame(entity:Entity, time:JulianDate, frame:ReferenceFrame|Entity) { if (!entity.position || !(entity.position instanceof ConstantPositionProperty) || !entity.orientation || !(entity.orientation instanceof ConstantProperty)) { return false; } if (!getEntityPositionInReferenceFrame( entity, time, frame, scratchCartesian)) { return false; } if (!getEntityOrientationInReferenceFrame( entity, time, frame, scratchOrientation)) { return false; } entity.position.setValue(scratchCartesian, frame); entity.orientation.setValue(scratchOrientation); return true; } export const isIOS = typeof navigator !== 'undefined' && typeof window !== 'undefined' && /iPad|iPhone|iPod/.test(navigator.userAgent) && !window['MSStream']; export const isAndroid = typeof navigator !== 'undefined' && typeof window !== 'undefined' && /Android/.test(navigator.userAgent) && !window['MSStream']; export function installArgonApp() { if (isIOS) { window.location.href = "https://itunes.apple.com/us/app/argon4/id1089308600?mt=8"; } else if (isAndroid) { window.location.href = "http://play.google.com/store/apps/details?id=edu.gatech.argon4" } } export function openInArgonApp() { if (isIOS) { window.location.href = `argon4://open?url=${encodeURIComponent(window.location.href)}`; } else if (isAndroid) { window.location.href = `intent:/#Intent;scheme=argon4;package=edu.gatech.argon4;S.url=${encodeURIComponent(window.location.href)};end`; } } // requestAnimationFrame / cancelAnimationFrame polyfills var lastTime = 0; const rAF = (typeof window !== 'undefined' && window.requestAnimationFrame) ? window.requestAnimationFrame.bind(window) : (callback) => { var currTime = performance.now(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = <number><any>setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; } const cAF = (typeof window !== 'undefined') ? window.cancelAnimationFrame.bind(window) : clearTimeout; export { rAF as requestAnimationFrame, cAF as cancelAnimationFrame }; export function deprecated(alternative?: string) : MethodDecorator { let didPrintWarning = false; const decorator = (target, name:string, descriptor:PropertyDescriptor) => { const original = descriptor.get || descriptor.value; const originalType = typeof descriptor.value === 'function' ? 'function' : 'property'; let message = `The "${name}" ${originalType} is deprecated. `; if (alternative) { const alternativeType = typeof target[alternative] === 'function' ? 'function' : 'property' message += `Please use the "${alternative}" ${alternativeType} instead.` } const wrapped = function() { if (!didPrintWarning) { console.warn(message); didPrintWarning = true; } return original!.apply(this, arguments); }; if (descriptor.value) descriptor.value = wrapped else descriptor.get = wrapped; return descriptor; }; return decorator; } export const defaultTerrainProvider = new MapzenTerrariumTerrainProvider({ url : 'https://s3.amazonaws.com/elevation-tiles-prod/terrarium/', requestWaterMask : true, requestVertexNormals : true }); export function updateHeightFromTerrain(cartographic : Cartographic) : Promise<Cartographic> { return Promise.resolve(sampleTerrain(defaultTerrainProvider, 15, [cartographic]).then<Cartographic>(_valueAtFirstIndex)); } function _valueAtFirstIndex(array:Cartographic[]) { return array[0]; }
the_stack
import { generateSidebar } from "."; import type { PropSidebarItemCategory, SidebarItemLink, PropSidebarItem, } from "../types"; // npx jest packages/docusaurus-plugin-openapi/src/sidebars/sidebars.test.ts --watch function isCategory(item: PropSidebarItem): item is PropSidebarItemCategory { return item.type === "category"; } function isLink(item: PropSidebarItem): item is SidebarItemLink { return item.type === "link"; } describe("sidebars", () => { const getOpts = () => ({ contentPath: "", sidebarCollapsible: true, sidebarCollapsed: true, }); const getIntro = (overrides = {}) => ({ type: "info" as const, id: "introduction", unversionedId: "introduction", title: "Introduction", description: "Sample description.", slug: "/introduction", frontMatter: {}, info: { title: "YAML Example", version: "1.0.0", description: "Sample description.", }, source: "@site/examples/openapi.yaml", sourceDirName: ".", permalink: "/yaml/introduction", next: { title: "Hello World", permalink: "/yaml/hello-world", }, ...overrides, }); describe("Single Spec - YAML", () => { it("base case - single spec with untagged routes should render flat with a default category", async () => { const input = [ getIntro(), { type: "api" as const, id: "hello-world", title: "Hello World", api: { tags: [], }, source: "@site/examples/openapi.yaml", sourceDirName: ".", permalink: "/yaml/hello-world", }, ]; const output = await generateSidebar(input, getOpts()); // console.log(JSON.stringify(output, null, 2)); // intro.md const info = output.find( (x) => x.type === "link" && x.docId === "introduction" ) as SidebarItemLink; expect(info?.type).toBe("link"); expect(info?.label).toBe("Introduction"); expect(info?.href).toBe("/yaml/introduction"); const category = output.find(isCategory); expect(category?.label).toBe("API"); const api = category?.items.find(isLink); expect(api?.label).toBe("Hello World"); expect(api?.docId).toBe("hello-world"); }); it("single spec tags case - should render root level categories per tag", async () => { const input = [ getIntro(), { type: "api" as const, id: "hello-world", title: "Hello World", api: { tags: ["stuff"], }, source: "@site/examples/openapi.yaml", sourceDirName: ".", permalink: "/yaml/hello-world", }, ]; const output = await generateSidebar(input, getOpts()); // console.log(JSON.stringify(output, null, 2)); // intro.md const info = output.find( (x) => x.type === "link" && x.docId === "introduction" ) as SidebarItemLink; expect(info?.type).toBe("link"); expect(info?.label).toBe("Introduction"); expect(info?.href).toBe("/yaml/introduction"); // swagger rendering const api = output.find( (x) => x.type === "category" ) as PropSidebarItemCategory; expect(api?.label).toBe("stuff"); expect(api?.items).toBeInstanceOf(Array); expect(api?.items).toHaveLength(1); const [helloWorld] = api?.items ?? []; expect(helloWorld.type).toBe("link"); expect(helloWorld.label).toBe("Hello World"); }); }); describe("Multi Spec", () => { it("should leverage the info.title if provided for spec name @ root category", async () => { const input = [ { type: "api" as const, id: "cats", title: "Cats", api: { info: { title: "Cats" }, tags: [], }, source: "@site/examples/cats.yaml", sourceDirName: ".", permalink: "/yaml/cats", }, { type: "api" as const, id: "dogs", title: "Dogs", api: { info: { title: "Dogs" }, tags: [], }, source: "@site/examples/dogs.yaml", sourceDirName: ".", permalink: "/yaml/dogs", }, ]; const output = (await generateSidebar( input, getOpts() )) as PropSidebarItemCategory[]; // console.log(JSON.stringify(output, null, 2)); expect(output).toHaveLength(2); const [cats, dogs] = output; expect(cats.type).toBe("category"); expect(cats.items).toHaveLength(1); const [catApi] = (cats.items ?? []).filter(isCategory); expect(catApi.type).toBe("category"); const [catLink] = catApi?.items; expect(catLink.type).toBe("link"); expect(dogs.type).toBe("category"); expect(dogs.items).toHaveLength(1); expect(dogs.label).toBe("Dogs"); }); it("empty title should render the filename.", async () => { const input = [ { type: "api" as const, id: "cats", title: "Cats", api: { info: { title: "Cats" }, tags: [], }, source: "@site/examples/cats.yaml", sourceDirName: ".", permalink: "/yaml/cats", }, { type: "api" as const, id: "dogs", title: "List Dogs", api: { info: { title: "" }, tags: [], }, source: "@site/examples/dogs.yaml", sourceDirName: ".", permalink: "/yaml/dogs", }, { type: "api" as const, id: "dogs-id", title: "Dog By Id", api: { info: { title: "" }, tags: [], }, source: "@site/examples/dogs.yaml", sourceDirName: ".", permalink: "/yaml/dogs-id", }, ]; const output = (await generateSidebar( input, getOpts() )) as PropSidebarItemCategory[]; // console.log(JSON.stringify(output, null, 2)); const [cats, dogsSpec] = output; expect(cats.items).toHaveLength(1); expect(dogsSpec.type).toBe("category"); const [dogApi] = dogsSpec.items.filter(isCategory); expect(dogApi?.items).toHaveLength(2); expect(dogApi.label).toBe("API"); const [dogsItem] = dogApi.items; expect(dogsItem.label).toBe("List Dogs"); }); it("multi spec, multi tag", async () => { const input = [ { type: "api" as const, id: "tails", title: "List Tails", api: { info: { title: "Cats" }, tags: ["Tails"], }, source: "@site/examples/cats.yaml", sourceDirName: ".", permalink: "/yaml/tails", }, { type: "api" as const, id: "tails-by-id", title: "Tails By Id", api: { info: { title: "Cats" }, tags: ["Tails"], }, source: "@site/examples/cats.yaml", sourceDirName: ".", permalink: "/yaml/tails-by-id", }, { type: "api" as const, id: "whiskers", title: "List whiskers", api: { info: { title: "Cats" }, tags: ["Whiskers"], }, source: "@site/examples/cats.yaml", sourceDirName: ".", permalink: "/yaml/whiskers", }, { type: "api" as const, id: "dogs", title: "List Dogs", api: { info: { title: "Dogs" }, tags: ["Doggos"], }, source: "@site/examples/dogs.yaml", sourceDirName: ".", permalink: "/yaml/dogs", }, { type: "api" as const, id: "dogs-id", title: "Dogs By Id", api: { info: { title: "Dogs" }, tags: ["Doggos"], }, source: "@site/examples/dogs.yaml", sourceDirName: ".", permalink: "/yaml/dogs-id", }, { type: "api" as const, id: "toys", title: "Toys", api: { info: { title: "Dogs" }, tags: ["Toys"], }, source: "@site/examples/dogs.yaml", sourceDirName: ".", permalink: "/yaml/toys", }, ]; const output = (await generateSidebar( input, getOpts() )) as PropSidebarItemCategory[]; // console.log(JSON.stringify(output, null, 2)); const [cats, dogs] = output; expect(cats.type).toBe("category"); expect(cats.items).toHaveLength(3); // extra api item category is included but gets filtered out later const [tails, whiskers] = (cats.items || []).filter(isCategory); expect(tails.type).toBe("category"); expect(whiskers.type).toBe("category"); expect(tails.items).toHaveLength(2); expect(whiskers.items).toHaveLength(1); expect(tails.items?.[0].type).toBe("link"); expect(whiskers.items?.[0].type).toBe("link"); expect(tails.items?.[0].label).toBe("List Tails"); expect(whiskers.items?.[0].label).toBe("List whiskers"); expect(dogs.type).toBe("category"); expect(dogs.items).toHaveLength(3); // extra api item category is included but gets filtered out later expect(dogs.label).toBe("Dogs"); const [doggos, toys] = (dogs.items || []) as PropSidebarItemCategory[]; expect(doggos.type).toBe("category"); expect(toys.type).toBe("category"); expect(doggos.items).toHaveLength(2); expect(toys.items).toHaveLength(1); }); it("child folders", async () => { const input = [ { type: "api" as const, id: "cats", title: "Cats", api: { info: { title: "Cat Store" }, tags: ["Cats"], }, source: "@site/examples/animals/pets/cats.yaml", sourceDirName: "animals/pets", permalink: "/yaml/cats", }, { type: "api" as const, id: "burgers", title: "Burgers", api: { info: { title: "Burger Store" }, tags: ["Burgers"], }, source: "@site/examples/food/fast/burgers.yaml", sourceDirName: "food/fast", permalink: "/yaml/burgers", }, ]; const output = await generateSidebar(input, getOpts()); expect(output).toBeTruthy(); // console.log(JSON.stringify(output, null, 2)); // console.log(output); const [animals, foods] = output; expect(animals.type).toBe("category"); expect(foods.type).toBe("category"); /* animals pets Cat Store cats Foods Buger Store Burger Example burgers */ output.filter(isCategory).forEach((category) => { // console.log(category.label); expect(category.items[0].type).toBe("category"); category.items.filter(isCategory).forEach((subCategory) => { expect(subCategory.items[0].type).toBe("category"); subCategory.items.filter(isCategory).forEach((groupCategory) => { expect(groupCategory.items[0].type).toBe("category"); groupCategory.items.forEach((linkItem) => { expect(linkItem.type).toBe("category"); }); }); }); }); }); it("child folders with no paths", async () => { const input = [ getIntro({ source: "@site/examples/foods/foods.yaml", sourceDirName: "foods", }), getIntro({ source: "@site/examples/animals/animals.yaml", sourceDirName: "animals", }), ]; const output = await generateSidebar(input, getOpts()); expect(output).toBeTruthy(); expect(output[0].type).toBe("category"); }); }); });
the_stack
import { Component } from "./component"; import { Project } from "./project"; import { decamelizeKeysRecursively } from "./util"; import { YamlFile } from "./yaml"; /** * Props for DockerCompose. */ export interface DockerComposeProps { /** * A name to add to the docker-compose.yml filename. * @example 'myname' yields 'docker-compose.myname.yml' * @default - no name is added */ readonly nameSuffix?: string; /** * Docker Compose schema version do be used * @default 3.3 */ readonly schemaVersion?: string; /** * Service descriptions. */ readonly services?: Record<string, DockerComposeServiceDescription>; } /** * Options for port mappings. */ export interface DockerComposePortMappingOptions { /** * Port mapping protocol. * @default DockerComposeProtocol.TCP */ readonly protocol?: DockerComposeProtocol; } /** * Create a docker-compose YAML file. */ export class DockerCompose extends Component { /** * Depends on a service name. */ static serviceName(serviceName: string): IDockerComposeServiceName { return { serviceName, }; } /** * Create a port mapping. * @param publishedPort Published port number * @param targetPort Container's port number * @param options Port mapping options */ static portMapping( publishedPort: number, targetPort: number, options?: DockerComposePortMappingOptions ): DockerComposeServicePort { const protocol = options?.protocol ?? DockerComposeProtocol.TCP; return { target: targetPort, published: publishedPort, protocol: protocol, mode: "host", }; } /** * Create a bind volume that binds a host path to the target path in the container. * @param sourcePath Host path name * @param targetPath Target path name */ static bindVolume( sourcePath: string, targetPath: string ): IDockerComposeVolumeBinding { return { bind(_volumeInfo: IDockerComposeVolumeConfig): DockerComposeVolumeMount { return { type: "bind", source: sourcePath, target: targetPath, }; }, }; } /** * Create a named volume and mount it to the target path. If you use this * named volume in several services, the volume will be shared. In this * case, the volume configuration of the first-provided options are used. * * @param volumeName Name of the volume * @param targetPath Target path * @param options volume configuration (default: docker compose defaults) */ static namedVolume( volumeName: string, targetPath: string, options: DockerComposeVolumeConfig = {} ): IDockerComposeVolumeBinding { return { bind(volumeInfo: IDockerComposeVolumeConfig): DockerComposeVolumeMount { volumeInfo.addVolumeConfiguration(volumeName, options); return { type: "volume", source: volumeName, target: targetPath, }; }, }; } private readonly services: Record<string, DockerComposeService>; private readonly version: string; constructor(project: Project, props?: DockerComposeProps) { super(project); const nameSuffix = props?.nameSuffix ? `${props!.nameSuffix}.yml` : "yml"; new YamlFile(project, `docker-compose.${nameSuffix}`, { committed: true, readonly: true, obj: () => this._synthesizeDockerCompose(), }); if (props?.schemaVersion && !parseFloat(props.schemaVersion)) { throw Error("Version tag needs to be a number"); } this.version = props?.schemaVersion ? props.schemaVersion : "3.3"; this.services = {}; // Add the services provided via the constructor argument. const initialServices = props?.services ?? {}; for (const [name, serviceDescription] of Object.entries(initialServices)) { this.addService(name, serviceDescription); } } /** * Add a service to the docker-compose file. * @param serviceName name of the service * @param description a service description */ public addService( serviceName: string, description: DockerComposeServiceDescription ): DockerComposeService { const service = new DockerComposeService(serviceName, description); this.services[serviceName] = service; return service; } /** * @internal */ _synthesizeDockerCompose(): object { if (Object.keys(this.services).length === 0) { throw new Error("DockerCompose requires at least one service"); } return renderDockerComposeFile(this.services, this.version); } } /** * An interface providing the name of a docker compose service. */ export interface IDockerComposeServiceName { /** * The name of the docker compose service. */ readonly serviceName: string; } /** * Description of a docker-compose.yml service. */ export interface DockerComposeServiceDescription { /** * Use a docker image. * Note: You must specify either `build` or `image` key. * @see imageBuild */ readonly image?: string; /** * Build a docker image. * Note: You must specify either `imageBuild` or `image` key. * @see image */ readonly imageBuild?: DockerComposeBuild; /** * Provide a command to the docker container. * @default - use the container's default command */ readonly command?: string[]; /** * Names of other services this service depends on. * @default - no dependencies */ readonly dependsOn?: IDockerComposeServiceName[]; /** * Mount some volumes into the service. * Use one of the following to create volumes: * @see DockerCompose.bindVolume() to mount a host path * @see DockerCompose.namedVolume() to create & mount a named volume */ readonly volumes?: IDockerComposeVolumeBinding[]; /** * Map some ports. * @default - no ports are mapped */ readonly ports?: DockerComposeServicePort[]; /** * Add environment variables. * @default - no environment variables are provided */ readonly environment?: Record<string, string>; } /** * A docker-compose service. */ export class DockerComposeService implements IDockerComposeServiceName { /** * Name of the service. */ public readonly serviceName: string; /** * Docker image. */ public readonly image?: string; /** * Docker image build instructions. */ public readonly imageBuild?: DockerComposeBuild; /** * Command to run in the container. */ public readonly command?: string[]; /** * Other services that this service depends on. */ public readonly dependsOn: IDockerComposeServiceName[]; /** * Volumes mounted in the container. */ public readonly volumes: IDockerComposeVolumeBinding[]; /** * Published ports. */ public readonly ports: DockerComposeServicePort[]; /** * Environment variables. */ public readonly environment: Record<string, string>; constructor( serviceName: string, serviceDescription: DockerComposeServiceDescription ) { if ( (!serviceDescription.imageBuild && !serviceDescription.image) || (serviceDescription.imageBuild && serviceDescription.image) ) { throw new Error( `A service ${serviceName} requires exactly one of a \`imageBuild\` or \`image\` key` ); } this.serviceName = serviceName; this.command = serviceDescription.command; this.image = serviceDescription.image; this.imageBuild = serviceDescription.imageBuild; this.dependsOn = serviceDescription.dependsOn ?? []; this.volumes = serviceDescription.volumes ?? []; this.ports = serviceDescription.ports ?? []; this.environment = serviceDescription.environment ?? {}; } /** * Add a port mapping * @param publishedPort Published port number * @param targetPort Container's port number * @param options Port mapping options */ public addPort( publishedPort: number, targetPort: number, options?: DockerComposePortMappingOptions ) { this.ports?.push( DockerCompose.portMapping(publishedPort, targetPort, options) ); } /** * Add an environment variable * @param name environment variable name * @param value value of the environment variable */ public addEnvironment(name: string, value: string) { this.environment[name] = value; } /** * Make the service depend on another service. * @param serviceName */ public addDependsOn(serviceName: IDockerComposeServiceName) { this.dependsOn.push(serviceName); } /** * Add a volume to the service. * @param volume */ public addVolume(volume: IDockerComposeVolumeBinding) { this.volumes.push(volume); } } /** * A service port mapping */ export interface DockerComposeServicePort { /** * Published port number */ readonly published: number; /** * Target port number */ readonly target: number; /** * Network protocol */ readonly protocol: DockerComposeProtocol; /** * Port mapping mode. */ readonly mode: string; } /** * Network protocol for port mapping */ export enum DockerComposeProtocol { /** * TCP protocol */ TCP = "tcp", /** * UDP protocol */ UDP = "udp", } /** * Build arguments for creating a docker image. */ export interface DockerComposeBuild { /** * Docker build context directory. */ readonly context: string; /** * A dockerfile to build from. * @default "Dockerfile" */ readonly dockerfile?: string; /** * Build args. * @default - none are provided */ readonly args?: Record<string, string>; } /** * Volume configuration */ export interface DockerComposeVolumeConfig { /** * Driver to use for the volume * @default - value is not provided */ readonly driver?: string; /** * Options to provide to the driver. */ readonly driverOpts?: Record<string, string>; /** * Set to true to indicate that the volume is externally created. * @default - unset, indicating that docker-compose creates the volume */ readonly external?: boolean; /** * Name of the volume for when the volume name isn't going to work in YAML. * @default - unset, indicating that docker-compose creates volumes as usual */ readonly name?: string; } /** * Volume binding information. */ export interface IDockerComposeVolumeBinding { /** * Binds the requested volume to the docker-compose volume configuration and * provide mounting instructions for synthesis. * @param volumeConfig the volume configuration * @returns mounting instructions for the service. */ bind(volumeConfig: IDockerComposeVolumeConfig): DockerComposeVolumeMount; } /** * Storage for volume configuration. */ export interface IDockerComposeVolumeConfig { /** * Add volume configuration to the repository. * @param volumeName * @param configuration */ addVolumeConfiguration( volumeName: string, configuration: DockerComposeVolumeConfig ): void; } /** * Service volume mounting information. */ export interface DockerComposeVolumeMount { /** * Type of volume. */ readonly type: string; /** * Volume source */ readonly source: string; /** * Volume target */ readonly target: string; } /** * Structure of a docker compose file before we decamelize. * @internal */ interface DockerComposeFileSchema { version: string; services: Record<string, DockerComposeFileServiceSchema>; volumes?: Record<string, DockerComposeVolumeConfig>; } /** * Structure of a docker compose file's service before we decamelize. * @internal */ interface DockerComposeFileServiceSchema { readonly dependsOn?: string[]; readonly build?: DockerComposeBuild; readonly image?: string; readonly command?: string[]; readonly volumes?: DockerComposeVolumeMount[]; readonly ports?: DockerComposeServicePort[]; readonly environment?: Record<string, string>; } function renderDockerComposeFile( serviceDescriptions: Record<string, DockerComposeService>, version: string ): object { // Record volume configuration const volumeConfig: Record<string, DockerComposeVolumeConfig> = {}; const volumeInfo: IDockerComposeVolumeConfig = { addVolumeConfiguration( volumeName: string, configuration: DockerComposeVolumeConfig ) { if (!volumeConfig[volumeName]) { // First volume configuration takes precedence. volumeConfig[volumeName] = configuration; } }, }; // Render service configuration const services: Record<string, DockerComposeFileServiceSchema> = {}; for (const [serviceName, serviceDescription] of Object.entries( serviceDescriptions ?? {} )) { // Resolve the names of each dependency and check that they exist. // Note: They may not exist if the user made a mistake when referencing a // service by name via `DockerCompose.serviceName()`. // @see DockerCompose.serviceName const dependsOn = Array<string>(); for (const dependsOnServiceName of serviceDescription.dependsOn ?? []) { const resolvedServiceName = dependsOnServiceName.serviceName; if (resolvedServiceName === serviceName) { throw new Error(`Service ${serviceName} cannot depend on itself`); } if (!serviceDescriptions[resolvedServiceName]) { throw new Error( `Unable to resolve service named ${resolvedServiceName} for ${serviceName}` ); } dependsOn.push(resolvedServiceName); } // Give each volume binding a chance to bind any necessary volume // configuration and provide volume mount information for the service. const volumes: DockerComposeVolumeMount[] = []; for (const volumeBinding of serviceDescription.volumes ?? []) { volumes.push(volumeBinding.bind(volumeInfo)); } // Create and store the service configuration, taking care not to create // object members with undefined values. services[serviceName] = { ...getObjectWithKeyAndValueIfValueIsDefined( "image", serviceDescription.image ), ...getObjectWithKeyAndValueIfValueIsDefined( "build", serviceDescription.imageBuild ), ...getObjectWithKeyAndValueIfValueIsDefined( "command", serviceDescription.command ), ...(Object.keys(serviceDescription.environment).length > 0 ? { environment: serviceDescription.environment } : {}), ...(serviceDescription.ports.length > 0 ? { ports: serviceDescription.ports } : {}), ...(dependsOn.length > 0 ? { dependsOn } : {}), ...(volumes.length > 0 ? { volumes } : {}), }; } // Explicit with the type here because the decamelize step after this wipes // out types. const input: DockerComposeFileSchema = { version, services, ...(Object.keys(volumeConfig).length > 0 ? { volumes: volumeConfig } : {}), }; // Change most keys to snake case. return decamelizeKeysRecursively(input, { shouldDecamelize: shouldDecamelizeDockerComposeKey, separator: "_", }); } /** * Returns `{ [key]: value }` if `value` is defined, otherwise returns `{}` so * that object spreading can be used to generate a peculiar interface. * @param key * @param value */ function getObjectWithKeyAndValueIfValueIsDefined<K extends string, T>( key: K, value: T ): { K: T } | {} { return value !== undefined ? { [key]: value } : {}; } /** * Determines whether the key at the given path should be decamelized. * Largely, all keys should be snake cased. But, there are some * exceptions for user-provided names for services, volumes, and * environment variables. * * @param path */ function shouldDecamelizeDockerComposeKey(path: string[]) { const poundPath = path.join("#"); // Does not decamelize user's names. // services.namehere: // volumes.namehere: if (/^(services|volumes)#[^#]+$/.test(poundPath)) { return false; } // Does not decamelize environment variables // services.namehere.environment.* if (/^services#[^#]+#environment#/.test(poundPath)) { return false; } // Does not decamelize build arguments // services.namehere.build.args.* if (/^services#[^#]+#build#args#/.test(poundPath)) { return false; } // Otherwise, let it all decamelize. return true; }
the_stack
import PF from 'pathfinding' import U from './util' import { IVisualization } from './index' // FD.entities.pumpjack.output_fluid_box.pipe_connections[0].positions // define this here so we don't have to import FD const PUMPJACK_PLUGS = [ { x: 1, y: -2 }, { x: 2, y: -1 }, { x: -1, y: 2 }, { x: -2, y: 1 }, ] // if there are groups that couldn't get connected, try x more times - every try increase maxTurns const MAX_TRIES = 3 let MIN_GAP_BETWEEN_UNDERGROUNDS = 1 const MAX_GAP_BETWEEN_UNDERGROUNDS = 9 const GRID_MARGIN = 2 interface IPlug extends IPoint { dir: number } interface ILine { endpoints: IPumpjack[] connections: { plugs: IPlug[] path: IPoint[] distance: number }[] avgDistance: number } interface IPumpjack extends IPoint { entity_number: number plugs: IPlug[] plug?: IPlug dir?: number } interface IGroup extends IPoint { entities: IPumpjack[] paths: IPoint[][] } /* How the algorithm works: 1. form lines between pumpjacks (DT) a line can only be formed if the 2 pumpjacks have a way of connecting in a straight line 2. form groups from the lines prioritizing (most to least important): - group building (line contains an already added pumpjack) - how close a line is to the middle - line connections (the nr of ways the 2 pumpjacks in a line can be connected) - average distance of line connections 3. connect groups together (DT) prioritizing groups with least nr of paths 4. add leftover pumpjacks (those that couldn't form lines with any other pumpjack) to the group 5. generate pipes and underground pipes DT = using delaunay triangulation to form lines between x (for optimization) */ function generatePipes( pumpjacks: { entity_number: number; position: IPoint }[], minGapBetweenUndergrounds = MIN_GAP_BETWEEN_UNDERGROUNDS ): { pumpjacksToRotate: { entity_number: number direction: number }[] pipes: { name: string position: IPoint direction: number }[] info: { nrOfPipes: number nrOfUPipes: number nrOfPipesReplacedByUPipes: number } visualizations: IVisualization[] } { MIN_GAP_BETWEEN_UNDERGROUNDS = minGapBetweenUndergrounds const visualizations: IVisualization[] = [] function addVisualization(path: IPoint[], size = 32, alpha = 1, color?: number): void { visualizations.push({ path: path.map(localToGlobal), size, alpha, color }) } const globalCoords = pumpjacks .map(e => [Math.floor(e.position.x), Math.floor(e.position.y)]) .flatMap(pos => U.range(0, 9) .map(i => [(i % 3) - 1, Math.floor(i / 3) - 1]) .map<IPoint>(offset => ({ x: pos[0] + offset[0], y: pos[1] + offset[1], })) ) const minX = globalCoords.reduce((pV, cV) => Math.min(pV, cV.x), Infinity) const minY = globalCoords.reduce((pV, cV) => Math.min(pV, cV.y), Infinity) const maxX = globalCoords.reduce((pV, cV) => Math.max(pV, cV.x), -Infinity) + 1 const maxY = globalCoords.reduce((pV, cV) => Math.max(pV, cV.y), -Infinity) + 1 const middle = { x: (maxX - minX) / 2, y: (maxY - minY) / 2 } const isPumpjackAtPos = new Set(globalCoords.map(globalToLocal).map(U.hashPoint)) const grid = U.range(0, maxY - minY + GRID_MARGIN * 2).map(y => U.range(0, maxX - minX + GRID_MARGIN * 2).map(x => isPumpjackAtPos.has(`${x},${y}`) ? 1 : 0 ) ) const dataset: IPumpjack[] = pumpjacks .map(e => { const pos = globalToLocal(e.position) const plugs = PUMPJACK_PLUGS.map((o, i) => ({ dir: i * 2, x: pos.x + o.x, y: pos.y + o.y, })).filter(p => !isPumpjackAtPos.has(U.hashPoint(p))) return { entity_number: e.entity_number, x: pos.x, y: pos.y, plugs } }) .filter(e => e.plugs.length) // GENERATE LINES let LINES: ILine[] = U.pointsToLines(dataset) .map(line => { const conn = line[0].plugs .flatMap(p => line[1].plugs.map(p2 => [p, p2])) .filter(l => l[0].x === l[1].x || l[0].y === l[1].y) .map(l => ({ ...generatePathFromLine(l), plugs: l })) // check for other pumpjack collision .filter(l => l.path.every(p => !grid[p.y][p.x])) return { endpoints: line, connections: conn, avgDistance: conn.reduce((acc, val) => acc + val.distance, 0) / conn.length, } }) .filter(l => l.connections.length !== 0) // .filter(l => l.avgDistance < 12) // GENERATE GROUPS let groups: IGroup[] = [] const addedPumpjacks: IPumpjack[] = [] while (LINES.length) { LINES = LINES.sort((a, b) => a.avgDistance - b.avgDistance) .sort((a, b) => a.connections.length - b.connections.length) .sort((a, b) => { const A = U.manhattenDistance(a.endpoints[0], middle) + U.manhattenDistance(a.endpoints[1], middle) const B = U.manhattenDistance(b.endpoints[0], middle) + U.manhattenDistance(b.endpoints[1], middle) return B - A }) // promote group building .sort((a, b) => { const lineContainsAnAddedPumpjack = (ent: ILine): boolean => !!addedPumpjacks.find( e => ent.endpoints .map(endP => endP.entity_number) .includes(e.entity_number) && !!ent.connections.find(t => t.plugs.map(endP => endP.dir).includes(e.plug.dir) ) ) if (lineContainsAnAddedPumpjack(a)) return -10 if (lineContainsAnAddedPumpjack(b)) return 10 return 0 }) const l = LINES.shift() const addedEnt1 = addedPumpjacks.find(e => e.entity_number === l.endpoints[0].entity_number) const addedEnt2 = addedPumpjacks.find(e => e.entity_number === l.endpoints[1].entity_number) l.connections // sort outside edges by how close they are to the middle .sort( (a, b) => U.manhattenDistance(a.plugs[0], middle) - U.manhattenDistance(b.plugs[0], middle) ) .sort((a, b) => a.distance - b.distance) for (const t of l.connections) { const entities = [ { ...l.endpoints[0], plug: t.plugs[0] }, { ...l.endpoints[1], plug: t.plugs[1] }, ] if (!addedEnt1 && !addedEnt2) { groups.push({ entities, paths: [t.path], x: 0, y: 0 }) addedPumpjacks.push(...entities) break } if (!addedEnt1 && addedEnt2 && addedEnt2.plug.dir === t.plugs[1].dir) { const g = groups.find(g => g.entities.includes(addedEnt2)) g.entities.push(entities[0]) g.paths.push(t.path) addedPumpjacks.push(entities[0]) break } if (!addedEnt2 && addedEnt1 && addedEnt1.plug.dir === t.plugs[0].dir) { const g = groups.find(g => g.entities.includes(addedEnt1)) g.entities.push(entities[1]) g.paths.push(t.path) addedPumpjacks.push(entities[1]) break } } } // if no LINES were generated, add 2 pumpjacks to a group here // this will only happen when only a few pumpjacks need to be connected if (groups.length === 0) { const line = U.pointsToLines(dataset) .map(line => { const conn = line[0].plugs .flatMap(p => line[1].plugs.map(p2 => [p, p2])) .map(l => { const path = new PF.BreadthFirstFinder() .findPath(l[0].x, l[0].y, l[1].x, l[1].y, new PF.Grid(grid)) .map(U.arrayToPoint) return { path, distance: path.length, plugs: l, } }) .sort((a, b) => a.distance - b.distance)[0] return { endpoints: line.map((p, i) => ({ ...p, plug: conn.plugs[i] })), conn, } }) .sort((a, b) => a.conn.distance - b.conn.distance)[0] groups.push({ entities: line.endpoints, paths: [line.conn.path], x: 0, y: 0, }) } groups.map(g => g.paths.flat()).forEach(p => addVisualization(p, 32, 0.5)) // CONNECT GROUPS let tries = MAX_TRIES let aloneGroups: IGroup[] = [] let finalGroup: IGroup while (groups.length) { for (const g of groups) { g.x = g.entities.reduce((acc, e) => acc + e.x, 0) / g.entities.length g.y = g.entities.reduce((acc, e) => acc + e.y, 0) / g.entities.length } groups = groups.sort( (a, b) => a.paths.reduce((acc, p) => acc + p.length, 0) - b.paths.reduce((acc, p) => acc + p.length, 0) ) const groupsCopy = [...groups] const group = groups.shift() if (!groups.length) { if (aloneGroups.length && tries) { groups.push(...aloneGroups, group) aloneGroups = [] tries -= 1 continue } finalGroup = group break } const conn = getPathBetweenGroups( grid, U.pointsToLines(groupsCopy) .filter(l => l.includes(group)) .map(l => l.find(g => g !== group)), group, 2 + MAX_TRIES - tries ) if (conn) { conn.toGroup.entities.push(...group.entities) conn.toGroup.paths.push(...group.paths, conn.path) } else { aloneGroups.push(group) continue } addVisualization(conn.path, 16, 0.5) } // ADD LEFTOVER PUMPJACKS TO GROUP const leftoverPumpjacks = dataset .filter(ent => !addedPumpjacks.find(e => e.entity_number === ent.entity_number)) .sort((a, b) => U.manhattenDistance(a, middle) - U.manhattenDistance(b, middle)) while (leftoverPumpjacks.length) { const ent = leftoverPumpjacks.shift() const conn = getPathBetweenGroups( grid, // Fake some group data - getPathBetweenGroups only cares about group.paths ent.plugs.map(p => ({ x: 0, y: 0, paths: [[{ x: p.x, y: p.y }]], entities: [{ x: 0, y: 0, entity_number: 0, plugs: [p], plug: p }], })), finalGroup ) finalGroup.entities.push({ ...ent, plug: conn.toGroup.entities[0].plug }) finalGroup.paths.push(conn.path) addVisualization(conn.path, 8, 0.5) } let pipePositions = U.uniqPoints(finalGroup.paths.flat()) // GENERATE ALL INTERSECTION POINTS (WILL INCLUDE ALL PUMPJACKS PLUGS TOO) const intersectionPositions = U.uniqPoints( finalGroup.paths.flatMap(p => PF.Util.compressPath(p.map(U.pointToArray)).map(U.arrayToPoint) ) ) // addVisualization(intersectionPositions) // GENERATE ALL VALID POSITIONS (THAT COINCIDE WITH PLUGS) WHERE AN UNDERGROUND PIPE CAN SPAWN const validCoordsForUPipes = finalGroup.entities .map(e => e.plug) // filter out overlapping plugs .sort((a, b) => (a.x - b.x ? a.x - b.x : a.y - b.y)) .filter( (v, i, arr) => (i === 0 || !(v.x === arr[i - 1].x && v.y === arr[i - 1].y)) && (i === arr.length - 1 || !(v.x === arr[i + 1].x && v.y === arr[i + 1].y)) ) // return true if there are no pipes to the left and right of the plug .filter(plug => { return [2, 6] .map(dir => posFromDir(plug, dir)) .every(pos => !pipePositions.find(U.equalPoints(pos))) function posFromDir(plug: IPlug, dir: number): IPoint { switch ((plug.dir + dir) % 8) { case 0: return { x: plug.x, y: plug.y - 1 } case 2: return { x: plug.x + 1, y: plug.y } case 4: return { x: plug.x, y: plug.y + 1 } case 6: return { x: plug.x - 1, y: plug.y } } } }) // addVisualization(validStraightPipeEnds) // GENERATE ALL STRAIGHT PATHS const straightPaths = finalGroup.paths // not length - 4 because one of the ends might be in validStraightPipeEnds .filter(p => p.length - 3 >= MIN_GAP_BETWEEN_UNDERGROUNDS) .flatMap(p => p // find intersections in path .filter(pos => intersectionPositions.find(U.equalPoints(pos))) // map intersections in path to indexes on the path .map(iPos => p.findIndex(U.equalPoints(iPos))) // transform indexes array into pairs of indexes .flatMap((_, i, arr) => (i === 0 ? [] : [[arr[i - 1], arr[i]]])) // map pairs of indexes to the corresponding part of path .map(pair => p.slice(pair[0], pair[1] + 1)) ) // remove ends of pipes if they are not in validStraightPipeEnds .map(path => path.filter((pos, i, arr) => { if (i > 0 && i < arr.length - 1) return true return validCoordsForUPipes.find(U.equalPoints(pos)) }) ) .filter(p => p.length - 2 >= MIN_GAP_BETWEEN_UNDERGROUNDS) // GENERATE UNDERGROUND PIPE DATA const undergroundPipes = straightPaths .flatMap(path => { const HOR = path[0].y === path[1].y const PATH = path.sort((a, b) => (HOR ? a.x - b.x : a.y - b.y)) // if path is longer than MAX_GAP_BETWEEN_UNDERGROUNDS + 2 then generate inbetween underground pipes const segments = Math.ceil(PATH.length / (MAX_GAP_BETWEEN_UNDERGROUNDS + 2)) const segmentLength = PATH.length / segments return U.range(0, segments) .map(i => ({ start: Math.floor(segmentLength * i), end: Math.floor(segmentLength * (i + 1)) - 1, })) .flatMap<IPlug>(segment => [ { ...PATH[segment.start], dir: HOR ? 6 : 0 }, { ...PATH[segment.end], dir: HOR ? 2 : 4 }, ]) }) .map(localToGlobal) const straightPathsCoords = straightPaths.flat() // addVisualization(straightPathsCoords) // GENERATE PIPE DATA pipePositions = pipePositions .filter(coord => !straightPathsCoords.find(U.equalPoints(coord))) .map(localToGlobal) const pumpjacksToRotate = finalGroup.entities.map(e => ({ entity_number: e.entity_number, direction: e.plug.dir, })) // UNIFY PIPE DATA const pipes = [ ...pipePositions.map(pos => ({ name: 'pipe', position: pos, direction: 0 })), ...undergroundPipes.map(e => ({ name: 'pipe_to_ground', position: { x: e.x, y: e.y }, direction: e.dir, })), ] const info = { nrOfPipes: pipePositions.length, nrOfUPipes: undergroundPipes.length, nrOfPipesReplacedByUPipes: straightPathsCoords.length, } return { pumpjacksToRotate, pipes, info, visualizations, } function globalToLocal<T extends IPoint>(point: T): T { return { ...point, x: Math.floor(point.x) - minX + GRID_MARGIN, y: Math.floor(point.y) - minY + GRID_MARGIN, } } function localToGlobal<T extends IPoint>(point: T): T { return { ...point, x: point.x + minX - GRID_MARGIN + 0.5, y: point.y + minY - GRID_MARGIN + 0.5, } } } function generatePathFromLine( l: IPoint[] ): { path: IPoint[] distance: number } { const dX = Math.abs(l[0].x - l[1].x) const dY = Math.abs(l[0].y - l[1].y) const minX = Math.min(l[0].x, l[1].x) const minY = Math.min(l[0].y, l[1].y) const path: IPoint[] = dX ? U.range(0, dX + 1).map(i => ({ x: i + minX, y: l[0].y })) : U.range(0, dY + 1).map(i => ({ x: l[0].x, y: i + minY })) return { path, distance: dX + dY, } } /** Returns the shortest path between the given group and one group from the given array */ function getPathBetweenGroups( grid: number[][], GROUPS: IGroup[], group: IGroup, maxTurns = 2 ): { path: IPoint[] toGroup: IGroup } { const ret = GROUPS.map(g => connect2Groups(grid, g, group, maxTurns)) .filter(p => p.lines.length) .sort((a, b) => a.minDistance - b.minDistance)[0] if (!ret) return return { toGroup: ret.firstGroup, path: ret.lines[0].path, } function connect2Groups( grid: number[][], g0: IGroup, g1: IGroup, maxTurns = 2 ): { lines: { endpoints: IPoint[] turns: number path: IPoint[] distance: number }[] minDistance: number firstGroup: IGroup } { const path0 = g0.paths.flat() const path1 = g1.paths.flat() const lines = path0 .flatMap(coord => path1.filter(p => p.x === coord.x || p.y === coord.y).map(found => [found, coord]) ) .map(l => ({ ...generatePathFromLine(l), endpoints: l, turns: 0 })) // check for other pumpjack collision .filter(l => l.path.every(p => !grid[p.y][p.x])) // if (!lines.length || (lines[0] && lines[0].distance > 7)) { // optimization for spread out pumpjacks const PATH1 = path0.length === 1 ? path1 .sort( (a, b) => U.manhattenDistance(a, path0[0]) - U.manhattenDistance(b, path0[0]) ) .slice(0, 20) : path1 const L = U.pointsToLines([...path0, ...PATH1]) // filter out lines that are in the same group .filter( l => !( (path0.includes(l[0]) && path0.includes(l[1])) || (path1.includes(l[0]) && path1.includes(l[1])) ) ) .sort((a, b) => U.manhattenDistance(a[0], a[1]) - U.manhattenDistance(b[0], b[1])) .slice(0, 5) .map(l => { const path = new PF.BreadthFirstFinder().findPath( l[0].x, l[0].y, l[1].x, l[1].y, new PF.Grid(grid) ) return { endpoints: l, distance: path.length, path: path.map(U.arrayToPoint), turns: PF.Util.compressPath(path).length - 2, } }) // .filter(l => l.distance > 9) .filter(l => l.turns > 0 && l.turns <= maxTurns) .sort((a, b) => a.turns - b.turns) lines.push(...L) // } return { lines: lines.sort((a, b) => a.distance - b.distance), minDistance: lines.reduce((acc, l) => Math.min(acc, l.distance), Infinity), firstGroup: g0, } } } export { generatePipes }
the_stack
import * as mockDataConfig from 'tests/data/simple-data.json'; import { createMockCellInfo, getContainer, sleep } from 'tests/util/helpers'; import { PivotSheet, SpreadSheet } from '@/sheet-type'; import type { CellMeta, InteractionOptions, S2Options, } from '@/common/interface'; import { InteractionStateName, InterceptType, OriginEventType, S2Event, ScrollbarPositionType, } from '@/common/constant'; const s2Options: S2Options = { width: 200, height: 200, hierarchyType: 'grid', // display scroll bar style: { colCfg: { height: 60, }, cellCfg: { width: 100, height: 50, }, }, }; describe('Scroll By Group Tests', () => { let s2: SpreadSheet; let canvas: HTMLCanvasElement; beforeEach(() => { jest .spyOn(SpreadSheet.prototype, 'getCell') .mockImplementation(() => createMockCellInfo('testId').mockCell as any); s2 = new PivotSheet(getContainer(), mockDataConfig, s2Options); s2.render(); canvas = s2.getCanvasElement(); }); afterEach(() => { s2.destroy(); canvas.remove(); }); test('should hide tooltip when start scroll', () => { const hideTooltipSpy = jest .spyOn(s2, 'hideTooltip') .mockImplementation(() => {}); canvas.dispatchEvent(new WheelEvent('wheel', { deltaX: 20, deltaY: 0 })); expect(hideTooltipSpy).toHaveBeenCalledTimes(1); }); test('should clear hover timer when start scroll', () => { const clearHoverTimerSpy = jest .spyOn(s2.interaction, 'clearHoverTimer') .mockImplementation(() => {}); canvas.dispatchEvent(new WheelEvent('wheel', { deltaX: 20, deltaY: 0 })); expect(clearHoverTimerSpy).toHaveBeenCalledTimes(1); }); test('should not trigger scroll if not scroll over the viewport', () => { const onScroll = jest.fn(); s2.on(S2Event.LAYOUT_CELL_SCROLL, onScroll); canvas.dispatchEvent(new WheelEvent('wheel', { deltaX: 20, deltaY: 20 })); expect(s2.interaction.hasIntercepts([InterceptType.HOVER])).toBeFalsy(); expect(onScroll).not.toHaveBeenCalled(); }); test('should not trigger scroll if scroll over the corner header', () => { const onScroll = jest.fn(); s2.on(S2Event.LAYOUT_CELL_SCROLL, onScroll); canvas.dispatchEvent( new WheelEvent('wheel', { deltaX: 20, deltaY: 0, }), ); expect(s2.interaction.hasIntercepts([InterceptType.HOVER])).toBeFalsy(); expect(onScroll).not.toHaveBeenCalled(); }); test.each([ { type: 'horizontal', offset: { scrollX: 20, scrollY: 0, }, frozenRowHeader: true, }, { type: 'vertical', offset: { scrollX: 0, scrollY: 20, }, frozenRowHeader: true, }, { type: 'horizontal', offset: { scrollX: 20, scrollY: 0, }, frozenRowHeader: false, }, { type: 'vertical', offset: { scrollX: 0, scrollY: 20, }, frozenRowHeader: false, }, ])( 'should scroll if scroll over the panel viewport by %o', async ({ type, offset, frozenRowHeader }) => { // toggle frozenRowHeader mode s2.setOptions({ frozenRowHeader }); s2.render(false); const showHorizontalScrollBarSpy = jest .spyOn(s2.facet, 'showHorizontalScrollBar') .mockImplementation(() => {}); const showVerticalScrollBarSpy = jest .spyOn(s2.facet, 'showVerticalScrollBar') .mockImplementation(() => {}); // mock over the panel viewport s2.facet.cornerBBox.maxY = -9999; s2.facet.panelBBox.minX = -9999; s2.facet.panelBBox.minY = -9999; jest .spyOn(s2.facet, 'isScrollOverTheViewport') .mockImplementation(() => true); const wheelEvent = new WheelEvent('wheel', { deltaX: offset.scrollX, deltaY: offset.scrollY, }); canvas.dispatchEvent(wheelEvent); // disable hover event expect(s2.interaction.hasIntercepts([InterceptType.HOVER])).toBeTruthy(); // wait requestAnimationFrame await sleep(200); if (frozenRowHeader) { // show scrollbar expect( type === 'vertical' ? showVerticalScrollBarSpy : showHorizontalScrollBarSpy, ).toHaveBeenCalled(); expect( type === 'vertical' ? showHorizontalScrollBarSpy : showVerticalScrollBarSpy, ).not.toHaveBeenCalled(); } }, ); test.each([ { type: 'horizontal', offset: { scrollX: 20, scrollY: 0, }, }, { type: 'vertical', offset: { scrollX: 0, scrollY: 20, }, }, ])( 'should disable scroll if no scroll bar and scroll over the panel viewport by %o', async ({ offset }) => { // hide scroll bar s2.changeSheetSize(1000, 300); s2.render(false); const showHorizontalScrollBarSpy = jest .spyOn(s2.facet, 'showHorizontalScrollBar') .mockImplementation(() => {}); const showVerticalScrollBarSpy = jest .spyOn(s2.facet, 'showVerticalScrollBar') .mockImplementation(() => {}); const onScroll = jest.fn(); s2.on(S2Event.LAYOUT_CELL_SCROLL, onScroll); s2.facet.cornerBBox.maxY = -9999; s2.facet.panelBBox.minX = -9999; s2.facet.panelBBox.minY = -9999; const wheelEvent = new WheelEvent('wheel', { deltaX: offset.scrollX, deltaY: offset.scrollY, }); canvas.dispatchEvent(wheelEvent); // disable hover event expect(s2.interaction.hasIntercepts([InterceptType.HOVER])).toBeFalsy(); // wait requestAnimationFrame await sleep(200); expect(showHorizontalScrollBarSpy).not.toHaveBeenCalled(); expect(showVerticalScrollBarSpy).not.toHaveBeenCalled(); await sleep(200); // emit scroll event expect(onScroll).not.toHaveBeenCalled(); }, ); // https://github.com/antvis/S2/issues/904 test.each([ { type: 'horizontal', offset: { scrollX: 20, scrollY: 0, }, }, { type: 'vertical', offset: { scrollX: 0, scrollY: 20, }, }, ])( 'should not clear selected cells when hover cells after scroll by %o', async ({ offset }) => { const dataCellHover = jest.fn(); const cellA = createMockCellInfo('cell-a'); const cellB = createMockCellInfo('cell-b'); s2.on(S2Event.DATA_CELL_HOVER, dataCellHover); s2.facet.cornerBBox.maxY = -9999; s2.facet.panelBBox.minX = -9999; s2.facet.panelBBox.minY = -9999; // selected cells s2.interaction.changeState({ stateName: InteractionStateName.SELECTED, cells: [cellA.mockCellMeta, cellB.mockCellMeta] as CellMeta[], }); const wheelEvent = new WheelEvent('wheel', { deltaX: offset.scrollX, deltaY: offset.scrollY, }); canvas.dispatchEvent(wheelEvent); // wait requestAnimationFrame and debounce await sleep(1000); // emit global canvas hover s2.container.emit(OriginEventType.MOUSE_MOVE, { target: {} }); expect(s2.interaction.getState()).toEqual({ stateName: InteractionStateName.SELECTED, cells: [cellA.mockCellMeta, cellB.mockCellMeta], }); }, ); test('should render correct scroll position', () => { s2.setOptions({ interaction: { scrollbarPosition: ScrollbarPositionType.CONTENT, }, style: { layoutWidthType: 'compact', }, }); s2.changeSheetSize(100, 1000); // 横向滚动条 s2.render(false); expect(s2.facet.hScrollBar.getCanvasBBox().y).toBe(220); expect(s2.facet.hRowScrollBar.getCanvasBBox().y).toBe(220); s2.changeSheetSize(1000, 150); // 纵向滚动条 s2.render(false); expect(s2.facet.vScrollBar.getCanvasBBox().x).toBe(185); s2.setOptions({ interaction: { scrollbarPosition: ScrollbarPositionType.CANVAS, }, }); s2.changeSheetSize(100, 1000); // 横向滚动条 s2.render(false); expect(s2.facet.hScrollBar.getCanvasBBox().y).toBe(994); expect(s2.facet.hRowScrollBar.getCanvasBBox().y).toBe(994); s2.changeSheetSize(1000, 200); // 纵向滚动条 s2.render(false); expect(s2.facet.vScrollBar.getCanvasBBox().x).toBe(994); }); describe('Scroll Overscroll Behavior Tests', () => { const defaultOffset = { scrollX: 10, scrollY: 10, }; const getConfig = ( isScrollOverTheViewport: boolean, stopScrollChainingTimes: number, ) => ({ isScrollOverTheViewport, stopScrollChainingTimes, offset: defaultOffset, }); beforeEach(() => { document.body.style.overscrollBehavior = ''; document.body.style.height = '2000px'; document.body.style.width = '2000px'; s2.facet.cornerBBox.maxY = -9999; s2.facet.panelBBox.minX = -9999; s2.facet.panelBBox.minY = -9999; window.scrollTo(0, 0); }); it.each([ { overscrollBehavior: 'auto', ...getConfig(false, 0), }, { overscrollBehavior: 'auto', ...getConfig(true, 1), }, { overscrollBehavior: 'none', ...getConfig(false, 1), }, { overscrollBehavior: 'none', ...getConfig(true, 1), }, { overscrollBehavior: 'contain', ...getConfig(false, 1), }, { overscrollBehavior: 'contain', ...getConfig(true, 1), }, ])( 'should scroll by overscroll behavior %o', ({ overscrollBehavior, isScrollOverTheViewport, stopScrollChainingTimes, offset, }) => { s2.setOptions({ interaction: { overscrollBehavior: overscrollBehavior as InteractionOptions['overscrollBehavior'], }, }); s2.render(false); jest .spyOn(s2.facet, 'isScrollOverTheViewport') .mockImplementationOnce(() => isScrollOverTheViewport); const stopScrollChainingSpy = jest .spyOn(s2.facet, 'stopScrollChaining' as any) .mockImplementation(() => null); const wheelEvent = new WheelEvent('wheel', { deltaX: offset.scrollX, deltaY: offset.scrollY, }); canvas.dispatchEvent(wheelEvent); expect(stopScrollChainingSpy).toHaveBeenCalledTimes( stopScrollChainingTimes, ); stopScrollChainingSpy.mockRestore(); }, ); it('should not add property to body when render and destroyed if overscrollBehavior is null', () => { const sheet = new PivotSheet(getContainer(), mockDataConfig, { ...s2Options, interaction: { overscrollBehavior: null, }, }); sheet.render(); expect( document.body.style.getPropertyValue('overscroll-behavior'), ).toBeFalsy(); sheet.destroy(); expect( document.body.style.getPropertyValue('overscroll-behavior'), ).toBeFalsy(); }); it('should not change init body overscrollBehavior style when render and destroyed', () => { document.body.style.overscrollBehavior = 'none'; const sheet = new PivotSheet(getContainer(), mockDataConfig, { ...s2Options, interaction: { overscrollBehavior: 'contain', }, }); sheet.render(); expect(sheet.store.get('initOverscrollBehavior')).toEqual('none'); expect(document.body.style.overscrollBehavior).toEqual('none'); sheet.destroy(); expect(document.body.style.overscrollBehavior).toEqual('none'); }); it.each(['auto', 'contain', 'none'])( 'should add %s property to body', (overscrollBehavior: InteractionOptions['overscrollBehavior']) => { document.body.style.overscrollBehavior = ''; const sheet = new PivotSheet(getContainer(), mockDataConfig, { ...s2Options, interaction: { overscrollBehavior, }, }); sheet.render(); expect(sheet.store.get('initOverscrollBehavior')).toBeUndefined(); expect(document.body.style.overscrollBehavior).toEqual( overscrollBehavior, ); sheet.destroy(); expect(document.body.style.overscrollBehavior).toBeFalsy(); }, ); }); });
the_stack
import { FloatArray, ToLinearSpace, ToGammaSpace } from './types' import { Color4 } from './Color4' import { Scalar } from './Scalar' /** * Class used to hold a RBG color * @public */ export class Color3 { /** * Creates a new Color3 object from red, green, blue values, all between 0 and 1 * @param r - defines the red component (between 0 and 1, default is 0) * @param g - defines the green component (between 0 and 1, default is 0) * @param b - defines the blue component (between 0 and 1, default is 0) */ constructor( /** * Defines the red component (between 0 and 1, default is 0) */ public r: number = 0, /** * Defines the green component (between 0 and 1, default is 0) */ public g: number = 0, /** * Defines the blue component (between 0 and 1, default is 0) */ public b: number = 0 ) {} // Statics /** * Creates a new Color3 from the string containing valid hexadecimal values * @param hex - defines a string containing valid hexadecimal values * @returns a new Color3 object */ public static FromHexString(hex: string): Color3 { if (hex.substring(0, 1) !== '#' || hex.length !== 7) { return new Color3(0, 0, 0) } let r = parseInt(hex.substring(1, 3), 16) let g = parseInt(hex.substring(3, 5), 16) let b = parseInt(hex.substring(5, 7), 16) return Color3.FromInts(r, g, b) } /** * Creates a new Vector3 from the starting index of the given array * @param array - defines the source array * @param offset - defines an offset in the source array * @returns a new Color3 object */ public static FromArray(array: ArrayLike<number>, offset: number = 0): Color3 { return new Color3(array[offset], array[offset + 1], array[offset + 2]) } /** * Creates a new Color3 from integer values (less than 256) * @param r - defines the red component to read from (value between 0 and 255) * @param g - defines the green component to read from (value between 0 and 255) * @param b - defines the blue component to read from (value between 0 and 255) * @returns a new Color3 object */ public static FromInts(r: number, g: number, b: number): Color3 { return new Color3(r / 255.0, g / 255.0, b / 255.0) } /** * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3 * @param start - defines the start Color3 value * @param end - defines the end Color3 value * @param amount - defines the gradient value between start and end * @returns a new Color3 object */ public static Lerp(start: Color3, end: Color3, amount: number): Color3 { let result = new Color3(0.0, 0.0, 0.0) Color3.LerpToRef(start, end, amount, result) return result } /** * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3 * @param left - defines the start value * @param right - defines the end value * @param amount - defines the gradient factor * @param result - defines the Color3 object where to store the result */ public static LerpToRef(left: Color3, right: Color3, amount: number, result: Color3): void { result.r = left.r + (right.r - left.r) * amount result.g = left.g + (right.g - left.g) * amount result.b = left.b + (right.b - left.b) * amount } /** * Returns a Color3 value containing a red color * @returns a new Color3 object */ public static Red(): Color3 { return new Color3(1, 0, 0) } /** * Returns a Color3 value containing a green color * @returns a new Color3 object */ public static Green(): Color3 { return new Color3(0, 1, 0) } /** * Returns a Color3 value containing a blue color * @returns a new Color3 object */ public static Blue(): Color3 { return new Color3(0, 0, 1) } /** * Returns a Color3 value containing a black color * @returns a new Color3 object */ public static Black(): Color3 { return new Color3(0, 0, 0) } /** * Returns a Color3 value containing a white color * @returns a new Color3 object */ public static White(): Color3 { return new Color3(1, 1, 1) } /** * Returns a Color3 value containing a purple color * @returns a new Color3 object */ public static Purple(): Color3 { return new Color3(0.5, 0, 0.5) } /** * Returns a Color3 value containing a magenta color * @returns a new Color3 object */ public static Magenta(): Color3 { return new Color3(1, 0, 1) } /** * Returns a Color3 value containing a yellow color * @returns a new Color3 object */ public static Yellow(): Color3 { return new Color3(1, 1, 0) } /** * Returns a Color3 value containing a gray color * @returns a new Color3 object */ public static Gray(): Color3 { return new Color3(0.5, 0.5, 0.5) } /** * Returns a Color3 value containing a teal color * @returns a new Color3 object */ public static Teal(): Color3 { return new Color3(0, 1.0, 1.0) } /** * Returns a Color3 value containing a random color * @returns a new Color3 object */ public static Random(): Color3 { return new Color3(Math.random(), Math.random(), Math.random()) } /** * Creates a string with the Color3 current values * @returns the string representation of the Color3 object */ public toString(): string { return '{R: ' + this.r + ' G:' + this.g + ' B:' + this.b + '}' } /** * Returns the string "Color3" * @returns "Color3" */ public getClassName(): string { return 'Color3' } /** * Compute the Color3 hash code * @returns an unique number that can be used to hash Color3 objects */ public getHashCode(): number { let hash = this.r || 0 hash = (hash * 397) ^ (this.g || 0) hash = (hash * 397) ^ (this.b || 0) return hash } // Operators /** * Stores in the given array from the given starting index the red, green, blue values as successive elements * @param array - defines the array where to store the r,g,b components * @param index - defines an optional index in the target array to define where to start storing values * @returns the current Color3 object */ public toArray(array: FloatArray, index: number = 0): Color3 { array[index] = this.r array[index + 1] = this.g array[index + 2] = this.b return this } /** * Returns a new Color4 object from the current Color3 and the given alpha * @param alpha - defines the alpha component on the new Color4 object (default is 1) * @returns a new Color4 object */ public toColor4(alpha: number = 1): Color4 { return new Color4(this.r, this.g, this.b, alpha) } /** * Returns a new array populated with 3 numeric elements : red, green and blue values * @returns the new array */ public asArray(): number[] { let result = new Array<number>() this.toArray(result, 0) return result } /** * Returns the luminance value * @returns a float value */ public toLuminance(): number { return this.r * 0.3 + this.g * 0.59 + this.b * 0.11 } /** * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object * @param otherColor - defines the second operand * @returns the new Color3 object */ public multiply(otherColor: Color3): Color3 { return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b) } /** * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result" * @param otherColor - defines the second operand * @param result - defines the Color3 object where to store the result * @returns the current Color3 */ public multiplyToRef(otherColor: Color3, result: Color3): Color3 { result.r = this.r * otherColor.r result.g = this.g * otherColor.g result.b = this.b * otherColor.b return this } /** * Determines equality between Color3 objects * @param otherColor - defines the second operand * @returns true if the rgb values are equal to the given ones */ public equals(otherColor: Color3): boolean { return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b } /** * Determines equality between the current Color3 object and a set of r,b,g values * @param r - defines the red component to check * @param g - defines the green component to check * @param b - defines the blue component to check * @returns true if the rgb values are equal to the given ones */ public equalsFloats(r: number, g: number, b: number): boolean { return this.r === r && this.g === g && this.b === b } /** * Multiplies in place each rgb value by scale * @param scale - defines the scaling factor * @returns the updated Color3 */ public scale(scale: number): Color3 { return new Color3(this.r * scale, this.g * scale, this.b * scale) } /** * Multiplies the rgb values by scale and stores the result into "result" * @param scale - defines the scaling factor * @param result - defines the Color3 object where to store the result * @returns the unmodified current Color3 */ public scaleToRef(scale: number, result: Color3): Color3 { result.r = this.r * scale result.g = this.g * scale result.b = this.b * scale return this } /** * Scale the current Color3 values by a factor and add the result to a given Color3 * @param scale - defines the scale factor * @param result - defines color to store the result into * @returns the unmodified current Color3 */ public scaleAndAddToRef(scale: number, result: Color3): Color3 { result.r += this.r * scale result.g += this.g * scale result.b += this.b * scale return this } /** * Clamps the rgb values by the min and max values and stores the result into "result" * @param min - defines minimum clamping value (default is 0) * @param max - defines maximum clamping value (default is 1) * @param result - defines color to store the result into * @returns the original Color3 */ public clampToRef(min: number = 0, max: number = 1, result: Color3): Color3 { result.r = Scalar.Clamp(this.r, min, max) result.g = Scalar.Clamp(this.g, min, max) result.b = Scalar.Clamp(this.b, min, max) return this } /** * Creates a new Color3 set with the added values of the current Color3 and of the given one * @param otherColor - defines the second operand * @returns the new Color3 */ public add(otherColor: Color3): Color3 { return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b) } /** * Stores the result of the addition of the current Color3 and given one rgb values into "result" * @param otherColor - defines the second operand * @param result - defines Color3 object to store the result into * @returns the unmodified current Color3 */ public addToRef(otherColor: Color3, result: Color3): Color3 { result.r = this.r + otherColor.r result.g = this.g + otherColor.g result.b = this.b + otherColor.b return this } /** * Returns a new Color3 set with the subtracted values of the given one from the current Color3 * @param otherColor - defines the second operand * @returns the new Color3 */ public subtract(otherColor: Color3): Color3 { return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b) } /** * Stores the result of the subtraction of given one from the current Color3 rgb values into "result" * @param otherColor - defines the second operand * @param result - defines Color3 object to store the result into * @returns the unmodified current Color3 */ public subtractToRef(otherColor: Color3, result: Color3): Color3 { result.r = this.r - otherColor.r result.g = this.g - otherColor.g result.b = this.b - otherColor.b return this } /** * Copy the current object * @returns a new Color3 copied the current one */ public clone(): Color3 { return new Color3(this.r, this.g, this.b) } /** * Copies the rgb values from the source in the current Color3 * @param source - defines the source Color3 object * @returns the updated Color3 object */ public copyFrom(source: Color3): Color3 { this.r = source.r this.g = source.g this.b = source.b return this } /** * Updates the Color3 rgb values from the given floats * @param r - defines the red component to read from * @param g - defines the green component to read from * @param b - defines the blue component to read from * @returns the current Color3 object */ public copyFromFloats(r: number, g: number, b: number): Color3 { this.r = r this.g = g this.b = b return this } /** * Updates the Color3 rgb values from the given floats * @param r - defines the red component to read from * @param g - defines the green component to read from * @param b - defines the blue component to read from * @returns the current Color3 object */ public set(r: number, g: number, b: number): Color3 { return this.copyFromFloats(r, g, b) } /** * Compute the Color3 hexadecimal code as a string * @returns a string containing the hexadecimal representation of the Color3 object */ public toHexString(): string { let intR = (this.r * 255) | 0 let intG = (this.g * 255) | 0 let intB = (this.b * 255) | 0 return '#' + Scalar.ToHex(intR) + Scalar.ToHex(intG) + Scalar.ToHex(intB) } /** * Computes a new Color3 converted from the current one to linear space * @returns a new Color3 object */ public toLinearSpace(): Color3 { let convertedColor = new Color3() this.toLinearSpaceToRef(convertedColor) return convertedColor } /** * Converts the Color3 values to linear space and stores the result in "convertedColor" * @param convertedColor - defines the Color3 object where to store the linear space version * @returns the unmodified Color3 */ public toLinearSpaceToRef(convertedColor: Color3): Color3 { convertedColor.r = Math.pow(this.r, ToLinearSpace) convertedColor.g = Math.pow(this.g, ToLinearSpace) convertedColor.b = Math.pow(this.b, ToLinearSpace) return this } /** * Computes a new Color3 converted from the current one to gamma space * @returns a new Color3 object */ public toGammaSpace(): Color3 { let convertedColor = new Color3() this.toGammaSpaceToRef(convertedColor) return convertedColor } /** * Converts the Color3 values to gamma space and stores the result in "convertedColor" * @param convertedColor - defines the Color3 object where to store the gamma space version * @returns the unmodified Color3 */ public toGammaSpaceToRef(convertedColor: Color3): Color3 { convertedColor.r = Math.pow(this.r, ToGammaSpace) convertedColor.g = Math.pow(this.g, ToGammaSpace) convertedColor.b = Math.pow(this.b, ToGammaSpace) return this } /** * Serializes Color3 */ public toJSON() { return { r: this.r, g: this.g, b: this.b } } }
the_stack
import _ from 'lodash' import { GeoPackageDataType } from '../db/geoPackageDataType'; import { DBValue } from '../db/dbAdapter'; import { Constraint } from '../db/table/constraint'; import { RawConstraint } from '../db/table/rawConstraint'; import { ConstraintParser } from '../db/table/constraintParser'; import { ColumnConstraints } from '../db/table/columnConstraints'; import { ConstraintType } from '../db/table/constraintType'; import { UserTableDefaults } from './userTableDefaults'; import { Constraints } from '../db/table/constraints'; /** * A `UserColumn` is meta-data about a single column from a {@link module:/user/userTable~UserTable}. * * @class * @param {Number} index column index * @param {string} name column name * @param {module:db/geoPackageDataType~GPKGDataType} dataType data type of the column * @param {?Number} max max value * @param {Boolean} notNull not null * @param {?Object} defaultValue default value or null * @param {Boolean} primaryKey `true` if this column is part of the table's primary key */ export class UserColumn { static readonly NO_INDEX = -1; /** * Not Null Constraint Order */ static readonly NOT_NULL_CONSTRAINT_ORDER = 1; /** * Default Value Constraint Order */ static readonly DEFAULT_VALUE_CONSTRAINT_ORDER = 2; /** * Primary Key Constraint Order */ static readonly PRIMARY_KEY_CONSTRAINT_ORDER = 3; /** * Autoincrement Constraint Order */ static readonly AUTOINCREMENT_CONSTRAINT_ORDER = 4; /** * Unique Constraint Order */ static readonly UNIQUE_CONSTRAINT_ORDER = 5; constraints: Constraints = new Constraints(); type: string; min: number; constructor( public index: number, public name: string, public dataType: GeoPackageDataType, public max?: number, public notNull?: boolean, public defaultValue?: DBValue, public primaryKey?: boolean, public autoincrement?: boolean, public unique?: boolean, ) { this.validateMax(); this.type = this.getTypeName(name, dataType); this.addDefaultConstraints(); } /** * Validate the data type * @param name column name * @param dataType data type */ static validateDataType(name: string, dataType: GeoPackageDataType) { if (dataType === null || dataType === undefined) { throw new Error('Data Type is required to create column: ' + name); } } /** * Copy the column * @return copied column */ copy(): UserColumn { const userColumnCopy = new UserColumn(this.index, this.name, this.dataType, this.max, this.notNull, this.defaultValue, this.primaryKey, this.unique); userColumnCopy.min = this.min; userColumnCopy.constraints = this.constraints.copy(); return userColumnCopy; } /** * Clears the constraints */ clearConstraints() { return this.constraints.clear(); } getConstraints() { return this.constraints; } setIndex(index: number) { if (this.hasIndex()) { if (!_.isEqual(index, this.index)) { throw new Error('User Column with a valid index may not be changed. Column Name: ' + this.name + ', Index: ' + this.index + ', Attempted Index: ' + this.index); } } else { this.index = index; } } /** * Check if the column has a valid index * @return true if has a valid index */ hasIndex(): boolean { return this.index > UserColumn.NO_INDEX; } /** * Reset the column index */ resetIndex() { this.index = UserColumn.NO_INDEX; } /** * Get the index * * @return index */ getIndex(): number { return this.index; } /** * Set the name * @param name column name */ setName(name: string) { this.name = name; } /** * Get the name * @return name */ getName(): string { return this.name; } /** * Determine if this column is named the provided name * @param name column name * @return true if named the provided name */ isNamed(name: string): boolean { return this.name === name; } /** * Determine if the column has a max value * @return true if has max value */ hasMax(): boolean { return this.max != null; } /** * Set the max * @param max max */ setMax(max: number) { this.max = max; } /** * Get the max * @return max */ getMax(): number { return this.max; } /** * Set the not null flag * @param notNull not null flag */ setNotNull(notNull: boolean) { if (this.notNull !== notNull) { if (notNull) { this.addNotNullConstraint(); } else { this.removeConstraintByType(ConstraintType.NOT_NULL); } } this.notNull = notNull; } /** * Get the is not null flag * @return not null flag */ isNotNull(): boolean { return this.notNull; } /** * Determine if the column has a default value * @return true if has default value */ hasDefaultValue(): boolean { return this.defaultValue !== null && this.defaultValue !== undefined; } /** * Set the default value * @param defaultValue default value */ setDefaultValue(defaultValue: any) { this.removeConstraintByType(ConstraintType.DEFAULT); if (defaultValue !== null && defaultValue !== undefined) { this.addDefaultValueConstraint(defaultValue); } this.defaultValue = defaultValue; } /** * Get the default value * @return default value */ getDefaultValue(): any { return this.defaultValue; } /** * Set the primary key flag * @param primaryKey primary key flag */ setPrimaryKey(primaryKey: boolean) { if (this.primaryKey !== primaryKey) { if (primaryKey) { this.addPrimaryKeyConstraint(); } else { this.autoincrement = false; this.removeConstraintByType(ConstraintType.AUTOINCREMENT); this.removeConstraintByType(ConstraintType.PRIMARY_KEY); } } this.primaryKey = primaryKey; } /** * Get the primary key flag * @return primary key flag */ isPrimaryKey() { return this.primaryKey; } /** * Set the autoincrement flag * @param autoincrement autoincrement flag */ setAutoincrement(autoincrement: boolean) { if (this.autoincrement !== autoincrement) { if (autoincrement) { this.addAutoincrementConstraint(); } else { this.removeConstraintByType(ConstraintType.AUTOINCREMENT); } } this.autoincrement = autoincrement; } /** * Get the autoincrement flag * @return autoincrement flag */ isAutoincrement(): boolean { return this.autoincrement; } /** * Set the unique flag * @param unique autoincrement flag */ protected setUnique(unique: boolean) { if (this.unique !== unique) { if (unique) { this.addUniqueConstraint(); } else { this.removeConstraintByType(ConstraintType.UNIQUE); } } this.unique = unique; } /** * Get the autoincrement flag * @return autoincrement flag */ isUnique(): boolean { return this.unique; } /** * Set the data type * @param dataType data type */ setDataType(dataType: GeoPackageDataType) { this.dataType = dataType; } /** * Get the data type * @return data type */ getDataType(): GeoPackageDataType { return this.dataType; } getTypeName(name: string, dataType: GeoPackageDataType): string { UserColumn.validateDataType(name, dataType); return GeoPackageDataType.nameFromType(dataType); } /** * Validate that if max is set, the data type is text or blob */ validateMax(): boolean { if (this.max && this.dataType !== GeoPackageDataType.TEXT && this.dataType !== GeoPackageDataType.BLOB) { throw new Error( 'Column max is only supported for TEXT and BLOB columns. column: ' + this.name + ', max: ' + this.max + ', type: ' + this.dataType, ); } return true; } /** * Create a new primary key column * * @param {Number} index column index * @param {string} name column name * @param {boolean} autoincrement column autoincrement * * @return {UserColumn} created column */ static createPrimaryKeyColumn(index: number, name: string, autoincrement: boolean = UserTableDefaults.DEFAULT_AUTOINCREMENT): UserColumn { return new UserColumn(index, name, GeoPackageDataType.INTEGER, undefined, true, undefined, true, autoincrement); } /** * Create a new column * * @param {Number} index column index * @param {string} name column name * @param {module:db/geoPackageDataType~GPKGDataType} type data type * @param {Number} max max value * @param {Boolean} notNull not null * @param {Object} defaultValue default value or nil * * @return {module:user/userColumn~UserColumn} created column */ static createColumn( index: number, name: string, type: GeoPackageDataType, notNull = false, defaultValue?: DBValue, max?: number, ): UserColumn { return new UserColumn(index, name, type, max, notNull, defaultValue, false); } /** * Add the default constraints that are enabled (not null, default value, * primary key, autoincrement) from the column properties */ protected addDefaultConstraints() { if (this.isNotNull()) { this.addNotNullConstraint(); } if (this.hasDefaultValue()) { this.addDefaultValueConstraint(this.getDefaultValue()); } if (this.isPrimaryKey()) { this.addPrimaryKeyConstraint(); if (this.isAutoincrement()) { this.addAutoincrementConstraint(); } } if (this.isUnique()) { this.addUniqueConstraint(); } } /** * Add a constraint * @param constraint constraint */ addConstraint(constraint: Constraint) { if (constraint.order === null || constraint.order === undefined) { this.setConstraintOrder(constraint); } this.constraints.add(constraint); } /** * Set the constraint order by constraint type * @param constraint constraint */ setConstraintOrder(constraint: Constraint) { let order = null; switch (constraint.getType()) { case ConstraintType.PRIMARY_KEY: order = UserColumn.PRIMARY_KEY_CONSTRAINT_ORDER; break; case ConstraintType.UNIQUE: order = UserColumn.UNIQUE_CONSTRAINT_ORDER; break; case ConstraintType.NOT_NULL: order = UserColumn.NOT_NULL_CONSTRAINT_ORDER; break; case ConstraintType.DEFAULT: order = UserColumn.DEFAULT_VALUE_CONSTRAINT_ORDER; break; case ConstraintType.AUTOINCREMENT: order = UserColumn.AUTOINCREMENT_CONSTRAINT_ORDER; break; default: } constraint.order = order; } /** * Add a constraint * @param constraint constraint */ addConstraintSql(constraint: string) { const type = ConstraintParser.getType(constraint); const name = ConstraintParser.getName(constraint); this.constraints.add(new RawConstraint(type, name, constraint)); } /** * Add constraints * @param constraints constraints */ addConstraints(constraints: Constraints) { this.constraints.addConstraints(constraints); } /** * Add constraints * @param constraints constraints */ addColumnConstraints(constraints: ColumnConstraints) { this.addConstraints(constraints.getConstraints()); } /** * Add a not null constraint */ private addNotNullConstraint() { this.addConstraint(new RawConstraint(ConstraintType.NOT_NULL, null, "NOT NULL", UserColumn.NOT_NULL_CONSTRAINT_ORDER)); } /** * Add a default value constraint * @param defaultValue default value */ private addDefaultValueConstraint(defaultValue: any) { this.addConstraint(new RawConstraint(ConstraintType.DEFAULT, null, "DEFAULT " + GeoPackageDataType.columnDefaultValue(defaultValue, this.getDataType()), UserColumn.DEFAULT_VALUE_CONSTRAINT_ORDER)); } /** * Add a primary key constraint */ private addPrimaryKeyConstraint() { this.addConstraint(new RawConstraint(ConstraintType.PRIMARY_KEY, null, "PRIMARY KEY", UserColumn.PRIMARY_KEY_CONSTRAINT_ORDER)); } /** * Add an autoincrement constraint */ private addAutoincrementConstraint() { if (this.isPrimaryKey()) { this.addConstraint(new RawConstraint(ConstraintType.AUTOINCREMENT, null, "AUTOINCREMENT", UserColumn.AUTOINCREMENT_CONSTRAINT_ORDER)); } else { throw new Error('Autoincrement may only be set on a primary key column'); } } /** * Add a unique constraint */ private addUniqueConstraint() { this.addConstraint(new RawConstraint(ConstraintType.UNIQUE, null, "UNIQUE", UserColumn.UNIQUE_CONSTRAINT_ORDER)); } /** * Removes constraints by type */ removeConstraintByType(type: ConstraintType) { this.constraints.clearConstraintsByType(type); } getType(): string { return this.type; } hasConstraints() { return this.constraints.has(); } /** * Build the SQL for the constraint * @param constraint constraint * @return SQL or null */ buildConstraintSql(constraint: Constraint): string { let sql = null; if (UserTableDefaults.DEFAULT_PK_NOT_NULL || !this.isPrimaryKey() || constraint.getType() !== ConstraintType.NOT_NULL) { sql = constraint.buildSql(); } return sql; } }
the_stack
import fs from 'fs'; import isBoolean from 'lodash/isBoolean'; import path from 'path'; import pMap from 'p-map'; import pRetry from 'p-retry'; import pWaitFor from 'p-wait-for'; import pump from 'pump'; import querystring from 'querystring'; import { Readable, TransformOptions, PassThrough } from 'stream'; import { deprecate } from 'util'; import { generateChecksumFromStream, validateChecksumFromStream, } from '@cumulus/checksum'; import { InvalidChecksum, UnparsableFileLocationError, } from '@cumulus/errors'; import Logger from '@cumulus/logger'; import * as S3MultipartUploads from './lib/S3MultipartUploads'; import { s3 } from './services'; import { inTestMode } from './test-utils'; import { improveStackTrace } from './utils'; export type GetObjectCreateReadStreamMethod = (params: AWS.S3.GetObjectRequest) => { createReadStream: () => Readable }; export type GetObjectPromiseMethod = (params: AWS.S3.GetObjectRequest) => { promise: () => Promise<AWS.S3.GetObjectOutput> }; export type Object = Required<AWS.S3.Object>; export interface ListObjectsV2Output extends AWS.S3.ListObjectsV2Output { Contents: Object[] } const log = new Logger({ sender: 'aws-client/s3' }); const buildDeprecationMessage = ( name: string, version: string, alternative?: string ) => { let message = `${name} is deprecated after version ${version} and will be removed in a future release.`; if (alternative) message += ` Use ${alternative} instead.`; return log.buildMessage('warn', message); }; const S3_RATE_LIMIT = inTestMode() ? 1 : 20; /** * Join strings into an S3 key without a leading slash * * @param {...string|Array<string>} args - the strings to join * @returns {string} the full S3 key */ export const s3Join = (...args: [string | string[], ...string[]]) => { let tokens: string[]; if (typeof args[0] === 'string') tokens = <string[]>args; else tokens = args[0]; const removeLeadingSlash = (token: string) => token.replace(/^\//, ''); const removeTrailingSlash = (token: string) => token.replace(/\/$/, ''); const isNotEmptyString = (token: string) => token.length > 0; const key = tokens .map(removeLeadingSlash) .map(removeTrailingSlash) .filter(isNotEmptyString) .join('/'); if (tokens[tokens.length - 1].endsWith('/')) return `${key}/`; return key; }; /** * parse an s3 uri to get the bucket and key * * @param {string} uri - must be a uri with the `s3://` protocol * @returns {Object} Returns an object with `Bucket` and `Key` properties **/ export const parseS3Uri = (uri: string) => { const match = uri.match('^s3://([^/]+)/(.*)$'); if (match === null) { throw new TypeError(`Unable to parse S3 URI: ${uri}`); } return { Bucket: match[1], Key: match[2], }; }; /** * Given a bucket and key, return an S3 URI * * @param {string} bucket - an S3 bucket name * @param {string} key - an S3 key * @returns {string} an S3 URI */ export const buildS3Uri = (bucket: string, key: string) => `s3://${bucket}/${key.replace(/^\/+/, '')}`; /** * Convert S3 TagSet Object to query string * e.g. [{ Key: 'tag', Value: 'value }] to 'tag=value' * * @param {Array<Object>} tagset - S3 TagSet array * @returns {string} tags query string */ export const s3TagSetToQueryString = (tagset: AWS.S3.TagSet) => tagset.map(({ Key, Value }) => `${Key}=${Value}`).join('&'); /** * Delete an object from S3 * * @param {string} bucket - bucket where the object exists * @param {string} key - key of the object to be deleted * promise of the object being deleted */ export const deleteS3Object = improveStackTrace( (bucket: string, key: string) => s3().deleteObject({ Bucket: bucket, Key: key }).promise() ); /** * Get an object header from S3 * * @param {string} Bucket - name of bucket * @param {string} Key - key for object (filepath + filename) * @param {Object} retryOptions - options to control retry behavior when an * object does not exist. See https://github.com/tim-kos/node-retry#retryoperationoptions * By default, retries will not be performed * @returns {Promise} returns response from `S3.headObject` as a promise **/ export const headObject = improveStackTrace( (Bucket: string, Key: string, retryOptions: pRetry.Options = { retries: 0 }) => pRetry( async () => { try { return await s3().headObject({ Bucket, Key }).promise(); } catch (error) { if (error.code === 'NotFound') throw error; throw new pRetry.AbortError(error); } }, { maxTimeout: 10000, ...retryOptions } ) ); /** * Test if an object exists in S3 * * @param {Object} params - same params as https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#headObject-property * @returns {Promise<boolean>} a Promise that will resolve to a boolean indicating * if the object exists */ export const s3ObjectExists = (params: { Bucket: string, Key: string }) => headObject(params.Bucket, params.Key) .then(() => true) .catch((error) => { if (error.code === 'NotFound') return false; throw error; }); /** * Wait for an object to exist in S3 * * @param {Object} params * @param {string} params.bucket * @param {string} params.key * @param {number} [params.interval=1000] - interval before retries, in ms * @param {number} [params.timeout=30000] - timeout, in ms * @returns {Promise<undefined>} */ export const waitForObjectToExist = async (params: { bucket: string, key: string, interval: number, timeout: number }) => { const { bucket, key, interval = 1000, timeout = 30 * 1000, } = params; return await pWaitFor( () => s3ObjectExists({ Bucket: bucket, Key: key }), { interval, timeout } ); }; /** * Put an object on S3 * * @param {Object} params - same params as https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property * promise of the object being put **/ export const s3PutObject = improveStackTrace( (params: AWS.S3.PutObjectRequest) => s3().putObject({ ACL: 'private', ...params, }).promise() ); /** * Upload a file to S3 * * @param {string} bucket - the destination S3 bucket * @param {string} key - the destination S3 key * @param {filename} filename - the local file to be uploaded * @returns {Promise} */ export const putFile = (bucket: string, key: string, filename: string) => s3PutObject({ Bucket: bucket, Key: key, Body: fs.createReadStream(filename), }); /** * Copy an object from one location on S3 to another * * @param {Object} params - same params as https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property * @returns {Promise} promise of the object being copied **/ export const s3CopyObject = improveStackTrace( (params: AWS.S3.CopyObjectRequest) => s3().copyObject({ TaggingDirective: 'COPY', ...params, }).promise() ); /** * Upload data to S3 * * Note: This is equivalent to calling `aws.s3().upload(params).promise()` * * @param {Object} params - see [S3.upload()](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property) * @returns {Promise} see [S3.upload()](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property) */ export const promiseS3Upload = improveStackTrace( (params: AWS.S3.PutObjectRequest) => s3().upload(params).promise() ); /** * Upload data to S3 using a stream * * We are not using `s3.upload().promise()` due to errors observed in testing * with uncaught exceptions. By creating our own promise, we can ensure any * errors from the streams or upload cause this promise to reject. * * @param {Readable} uploadStream - Stream of data to upload * @param {Object} uploadParams - see [S3.upload()](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property) * @returns {Promise} */ export const streamS3Upload = ( uploadStream: Readable, uploadParams: AWS.S3.PutObjectRequest ) => new Promise((resolve, reject) => { const pass = new PassThrough(); uploadStream.pipe(pass); uploadStream.on('error', reject); pass.on('error', reject); return s3().upload({ ...uploadParams, Body: pass, }, (err, uploadResponse) => { if (err) { return reject(err); } return resolve(uploadResponse); }); }); /** * Downloads the given s3Obj to the given filename in a streaming manner * * @param {Object} s3Obj - The parameters to send to S3 getObject call * @param {string} filepath - The filepath of the file that is downloaded * @returns {Promise<string>} returns filename if successful */ export const downloadS3File = ( s3Obj: AWS.S3.GetObjectRequest, filepath: string ): Promise<string> => { const fileWriteStream = fs.createWriteStream(filepath); return new Promise((resolve, reject) => { const objectReadStream = s3().getObject(s3Obj).createReadStream(); pump(objectReadStream, fileWriteStream, (err) => { if (err) reject(err); else resolve(filepath); }); }); }; /** * Get the size of an S3 object * * @param {Object} params * @param {string} params.bucket * @param {string} params.key * @param {AWS.S3} params.s3 - an S3 client instance * @returns {Promise<number|undefined>} object size, in bytes */ export const getObjectSize = async ( params: { s3: { headObject: (params: { Bucket: string, Key: string }) => { promise: () => Promise<{ ContentLength?: number }> } }, bucket: string, key: string } ) => { // eslint-disable-next-line no-shadow const { s3: s3Client, bucket, key } = params; const headObjectResponse = await s3Client.headObject({ Bucket: bucket, Key: key, }).promise(); return headObjectResponse.ContentLength; }; /** * Get object Tagging from S3 * * @param {string} bucket - name of bucket * @param {string} key - key for object (filepath + filename) * @returns {Promise<AWS.S3.GetObjectTaggingOutput>} the promised response from `S3.getObjectTagging` **/ export const s3GetObjectTagging = improveStackTrace( (bucket: string, key: string) => s3().getObjectTagging({ Bucket: bucket, Key: key }).promise() ); const getObjectTags = async (bucket: string, key: string) => { const taggingResponse = await s3GetObjectTagging(bucket, key); return taggingResponse.TagSet.reduce( (acc, { Key, Value }) => ({ ...acc, [Key]: Value }), {} ); }; const getObjectTaggingString = async (bucket: string, key: string) => { const tags = await getObjectTags(bucket, key); return querystring.stringify(tags); }; /** * Puts object Tagging in S3 * https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObjectTagging-property * * @param {string} Bucket - name of bucket * @param {string} Key - key for object (filepath + filename) * @param {Object} Tagging - tagging object * @returns {Promise} returns response from `S3.getObjectTagging` as a promise **/ export const s3PutObjectTagging = improveStackTrace( (Bucket: string, Key: string, Tagging: AWS.S3.Tagging) => s3().putObjectTagging({ Bucket, Key, Tagging, }).promise() ); /** * Gets an object from S3. * * @example * const obj = await getObject(s3(), { Bucket: 'b', Key: 'k' }) * * @param {AWS.S3} s3Client - an `AWS.S3` instance * @param {AWS.S3.GetObjectRequest} params - parameters object to pass through * to `AWS.S3.getObject()` * @returns {Promise<AWS.S3.GetObjectOutput>} response from `AWS.S3.getObject()` * as a Promise */ export const getObject = ( // eslint-disable-next-line no-shadow s3Client: { getObject: GetObjectPromiseMethod }, params: AWS.S3.GetObjectRequest ): Promise<AWS.S3.GetObjectOutput> => s3Client.getObject(params).promise(); /** * Get an object from S3, waiting for it to exist and, if specified, have the * correct ETag. * * @param {AWS.S3} s3Client * @param {AWS.S3.GetObjectRequest} params * @param {pRetry.Options} [retryOptions={}] * @returns {Promise<AWS.S3.GetObjectOutput>} */ export const waitForObject = ( s3Client: { getObject: GetObjectPromiseMethod }, params: AWS.S3.GetObjectRequest, retryOptions: pRetry.Options = {} ): Promise<AWS.S3.GetObjectOutput> => pRetry( async () => { try { return await getObject(s3Client, params); } catch (error) { // Retry if the object does not exist if (error.code === 'NoSuchKey') throw error; // Retry if the etag did not match if (params.IfMatch && error.code === 'PreconditionFailed') throw error; // For any other error, fail without retrying throw new pRetry.AbortError(error); } }, retryOptions ); /** * Gets an object from S3. * * @param {string} Bucket - name of bucket * @param {string} Key - key for object (filepath + filename) * @param {Object} retryOptions - options to control retry behavior when an * object does not exist. See https://github.com/tim-kos/node-retry#retryoperationoptions * By default, retries will not be performed * @returns {Promise} returns response from `S3.getObject` as a promise * * @deprecated */ export const getS3Object = deprecate( improveStackTrace( (Bucket: string, Key: string, retryOptions: pRetry.Options = { retries: 0 }) => waitForObject( s3(), { Bucket, Key }, { maxTimeout: 10000, onFailedAttempt: (err) => log.debug(`getS3Object('${Bucket}', '${Key}') failed with ${err.retriesLeft} retries left: ${err.message}`), ...retryOptions, } ) ), buildDeprecationMessage( '@cumulus/aws-client/S3.getS3Object', '2.0.1', '@cumulus/aws-client/S3.getObject or @cumulus/aws-client/S3.waitForObject' ) ); /** * Fetch the contents of an S3 object * * @param {string} bucket - the S3 object's bucket * @param {string} key - the S3 object's key * @returns {Promise<string>} the contents of the S3 object */ export const getTextObject = (bucket: string, key: string) => getS3Object(bucket, key) .then(({ Body }) => { if (Body === undefined) return undefined; return Body.toString(); }); /** * Fetch JSON stored in an S3 object * @param {string} bucket - the S3 object's bucket * @param {string} key - the S3 object's key * @returns {Promise<*>} the contents of the S3 object, parsed as JSON */ export const getJsonS3Object = (bucket: string, key: string) => getTextObject(bucket, key) .then((text) => { if (text === undefined) return undefined; return JSON.parse(text); }); export const putJsonS3Object = (bucket: string, key: string, data: any) => s3PutObject({ Bucket: bucket, Key: key, Body: JSON.stringify(data), }); /** * Get a readable stream for an S3 object * * @param {Object} params * @param {AWS.S3} params.s3 - an AWS.S3 instance * @param {string} params.bucket - the bucket of the requested object * @param {string} params.key - the key of the requested object * @returns {Readable} */ export const getObjectReadStream = (params: { s3: { getObject: GetObjectCreateReadStreamMethod }, bucket: string, key: string }) => { // eslint-disable-next-line no-shadow const { s3: s3Client, bucket, key } = params; return s3Client.getObject({ Bucket: bucket, Key: key }).createReadStream(); }; /** * Check if a file exists in an S3 object * * @param {string} bucket - name of the S3 bucket * @param {string} key - key of the file in the S3 bucket * @returns {Promise} returns the response from `S3.headObject` as a promise **/ export const fileExists = async (bucket: string, key: string) => { try { return await s3().headObject({ Key: key, Bucket: bucket }).promise(); } catch (error) { // if file is not return false if (error.stack.match(/(NotFound)/) || error.stack.match(/(NoSuchBucket)/)) { return false; } throw error; } }; export const downloadS3Files = async ( s3Objs: AWS.S3.GetObjectRequest[], dir: string, s3opts: Partial<AWS.S3.GetObjectRequest> = {} ) => { // Scrub s3Ojbs to avoid errors from the AWS SDK const scrubbedS3Objs = s3Objs.map((s3Obj) => ({ Bucket: s3Obj.Bucket, Key: s3Obj.Key, })); let i = 0; const n = s3Objs.length; log.info(`Starting download of ${n} keys to ${dir}`); const promiseDownload = (s3Obj: AWS.S3.GetObjectRequest) => { const filename = path.join(dir, path.basename(s3Obj.Key)); const file = fs.createWriteStream(filename); const opts = Object.assign(s3Obj, s3opts); return new Promise((resolve, reject) => { s3().getObject(opts) .createReadStream() .pipe(file) .on('finish', () => { log.info(`Progress: [${i} of ${n}] s3://${s3Obj.Bucket}/${s3Obj.Key} -> ${filename}`); i += 1; return resolve(s3Obj.Key); }) .on('error', reject); }); }; return await pMap(scrubbedS3Objs, promiseDownload, { concurrency: S3_RATE_LIMIT }); }; /** * Delete files from S3 * * @param {Array} s3Objs - An array of objects containing keys 'Bucket' and 'Key' * @returns {Promise} A promise that resolves to an Array of the data returned * from the deletion operations */ export const deleteS3Files = async (s3Objs: AWS.S3.DeleteObjectRequest[]) => await pMap( s3Objs, (s3Obj) => s3().deleteObject(s3Obj).promise(), { concurrency: S3_RATE_LIMIT } ); /** * Delete a bucket and all of its objects from S3 * * @param {string} bucket - name of the bucket * @returns {Promise} the promised result of `S3.deleteBucket` **/ export const recursivelyDeleteS3Bucket = improveStackTrace( async (bucket: string) => { const response = await s3().listObjects({ Bucket: bucket }).promise(); const s3Objects: AWS.S3.DeleteObjectRequest[] = (response.Contents || []).map((o) => { if (!o.Key) throw new Error(`Unable to determine S3 key of ${JSON.stringify(o)}`); return { Bucket: bucket, Key: o.Key, }; }); await deleteS3Files(s3Objects); return await s3().deleteBucket({ Bucket: bucket }).promise(); } ); /** * Delete a list of buckets and all of their objects from S3 * * @param {Array} buckets - list of bucket names * @returns {Promise} the promised result of `S3.deleteBucket` **/ export const deleteS3Buckets = async ( buckets: Array<string> ): Promise<any> => await Promise.all(buckets.map(recursivelyDeleteS3Bucket)); type FileInfo = { filename: string, key: string, bucket: string }; export const uploadS3Files = async ( files: Array<string | FileInfo>, defaultBucket: string, keyPath: string | ((x: string) => string), s3opts: Partial<AWS.S3.PutObjectRequest> = {} ) => { let i = 0; const n = files.length; if (n > 1) { log.info(`Starting upload of ${n} keys`); } const promiseUpload = async (file: string | FileInfo) => { let bucket: string; let filename: string; let key: string; if (typeof file === 'string') { bucket = defaultBucket; filename = file; if (typeof keyPath === 'string') { key = s3Join(keyPath, path.basename(file)); } else { key = keyPath(file); } } else { bucket = file.bucket || defaultBucket; filename = file.filename; key = file.key; } await promiseS3Upload({ Bucket: bucket, Key: key, Body: fs.createReadStream(filename), ...s3opts, }); i += 1; log.info(`Progress: [${i} of ${n}] ${filename} -> s3://${bucket}/${key}`); return { key, bucket }; }; return await pMap(files, promiseUpload, { concurrency: S3_RATE_LIMIT }); }; /** * Upload the file associated with the given stream to an S3 bucket * * @param {ReadableStream} fileStream - The stream for the file's contents * @param {string} bucket - The S3 bucket to which the file is to be uploaded * @param {string} key - The key to the file in the bucket * @param {Object} s3opts - Options to pass to the AWS sdk call (defaults to `{}`) * @returns {Promise} A promise */ export const uploadS3FileStream = ( fileStream: Readable, bucket: string, key: string, s3opts: Partial<AWS.S3.PutObjectRequest> = {} ) => promiseS3Upload({ Bucket: bucket, Key: key, Body: fileStream, ...s3opts, }); /** * List the objects in an S3 bucket * * @param {string} bucket - The name of the bucket * @param {string} prefix - Only objects with keys starting with this prefix * will be included (useful for searching folders in buckets, e.g., '/PDR') * @param {boolean} skipFolders - If true don't return objects that are folders * (defaults to true) * @returns {Promise} A promise that resolves to the list of objects. Each S3 * object is represented as a JS object with the following attributes: `Key`, * `ETag`, `LastModified`, `Owner`, `Size`, `StorageClass`. */ export const listS3Objects = async ( bucket: string, prefix?: string, skipFolders: boolean = true ) => { log.info(`Listing objects in s3://${bucket}`); const params: AWS.S3.ListObjectsRequest = { Bucket: bucket, }; if (prefix) params.Prefix = prefix; const data = await s3().listObjects(params).promise(); let contents = data.Contents || []; if (skipFolders) { // Filter out any references to folders contents = contents.filter((obj) => obj.Key !== undefined && !obj.Key.endsWith('/')); } return contents; }; export type ListS3ObjectsV2Result = Promise<Object[]>; /** * Fetch complete list of S3 objects * * listObjectsV2 is limited to 1,000 results per call. This function continues * listing objects until there are no more to be fetched. * * The passed params must be compatible with the listObjectsV2 call. * * https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listObjectsV2-property * * @param {Object} params - params for the s3.listObjectsV2 call * @returns {Promise<Array>} resolves to an array of objects corresponding to * the Contents property of the listObjectsV2 response * * @static */ export const listS3ObjectsV2 = async ( params: AWS.S3.ListObjectsV2Request ): ListS3ObjectsV2Result => { // Fetch the first list of objects from S3 let listObjectsResponse = <ListObjectsV2Output>( await s3().listObjectsV2(params).promise() ); let discoveredObjects = listObjectsResponse.Contents; // Keep listing more objects from S3 until we have all of them while (listObjectsResponse.IsTruncated) { // eslint-disable-next-line no-await-in-loop listObjectsResponse = <ListObjectsV2Output>(await s3().listObjectsV2( // Update the params with a Continuation Token { ...params, ContinuationToken: listObjectsResponse.NextContinuationToken, } ).promise()); discoveredObjects = discoveredObjects.concat(listObjectsResponse.Contents); } return discoveredObjects; }; /** * Calculate the cryptographic hash of an S3 object * * @param {Object} params * @param {AWS.S3} params.s3 - an AWS.S3 instance * @param {string} params.algorithm - `cksum`, or an algorithm listed in * `openssl list -digest-algorithms` * @param {string} params.bucket * @param {string} params.key */ export const calculateObjectHash = async ( params: { s3: { getObject: GetObjectCreateReadStreamMethod }, algorithm: string, bucket: string, key: string } ) => { // eslint-disable-next-line no-shadow const { algorithm, bucket, key, s3: s3Client } = params; const stream = getObjectReadStream({ s3: s3Client, bucket, key, }); return await generateChecksumFromStream(algorithm, stream); }; /** * Validate S3 object checksum against expected sum * * @param {Object} params - params * @param {string} params.algorithm - checksum algorithm * @param {string} params.bucket - S3 bucket * @param {string} params.key - S3 key * @param {number|string} params.expectedSum - expected checksum * @param {Object} [params.options] - crypto.createHash options * * @throws {InvalidChecksum} - Throws error if validation fails * @returns {Promise<boolean>} returns true for success */ export const validateS3ObjectChecksum = async (params: { algorithm: string, bucket: string, key: string, expectedSum: string, options: TransformOptions }) => { const { algorithm, bucket, key, expectedSum, options } = params; const fileStream = getObjectReadStream({ s3: s3(), bucket, key }); if (await validateChecksumFromStream(algorithm, fileStream, expectedSum, options)) { return true; } const msg = `Invalid checksum for S3 object s3://${bucket}/${key} with type ${algorithm} and expected sum ${expectedSum}`; throw new InvalidChecksum(msg); }; /** * Extract the S3 bucket and key from the URL path parameters * * @param {string} pathParams - path parameters from the URL * bucket/key in the form of * @returns {Array<string>} `[Bucket, Key]` */ export const getFileBucketAndKey = (pathParams: string): [string, string] => { const [Bucket, ...fields] = pathParams.split('/'); const Key = fields.join('/'); if (Bucket.length === 0 || Key.length === 0) { throw new UnparsableFileLocationError(`File location "${pathParams}" could not be parsed`); } return [Bucket, Key]; }; /** * Create an S3 bucket * * @param {string} Bucket - the name of the S3 bucket to create * @returns {Promise} */ export const createBucket = (Bucket: string) => s3().createBucket({ Bucket }).promise(); /** * Create multiple S3 buckets * * @param {Array<string>} buckets - the names of the S3 buckets to create * @returns {Promise} */ export const createS3Buckets = async ( buckets: Array<string> ): Promise<any> => await Promise.all(buckets.map(createBucket)); const createMultipartUpload = async ( params: { sourceBucket: string, sourceKey: string, destinationBucket: string, destinationKey: string, ACL?: AWS.S3.ObjectCannedACL, copyTags?: boolean, contentType?: AWS.S3.ContentType } ) => { const uploadParams: AWS.S3.CreateMultipartUploadRequest = { Bucket: params.destinationBucket, Key: params.destinationKey, ACL: params.ACL, ContentType: params.contentType, }; if (params.copyTags) { uploadParams.Tagging = await getObjectTaggingString( params.sourceBucket, params.sourceKey ); } // Create a multi-part upload (copy) and get its UploadId const { UploadId } = await S3MultipartUploads.createMultipartUpload( uploadParams ); if (UploadId === undefined) { throw new Error('Unable to create multipart upload'); } return UploadId; }; // This performs an S3 `uploadPartCopy` call. That response includes an `ETag` // value specific to the part that was uploaded. When `completeMultipartUpload` // is called later, it needs that `ETag` value, as well as the `PartNumber` for // each part. Since the `PartNumber` is not included in the `uploadPartCopy` // response, we are adding it here to make our lives easier when we eventually // call `completeMultipartUpload`. const uploadPartCopy = async ( params: { partNumber: number, start: number, end: number, destinationBucket: string, destinationKey: string, sourceBucket: string, sourceKey: string, uploadId: string } ) => { const response = await S3MultipartUploads.uploadPartCopy({ UploadId: params.uploadId, Bucket: params.destinationBucket, Key: params.destinationKey, PartNumber: params.partNumber, CopySource: `/${params.sourceBucket}/${params.sourceKey}`, CopySourceRange: `bytes=${params.start}-${params.end}`, }); if (response.CopyPartResult === undefined) { throw new Error('Did not get ETag from uploadPartCopy'); } return { ETag: response.CopyPartResult.ETag, PartNumber: params.partNumber, }; }; /** * Copy an S3 object to another location in S3 using a multipart copy * * @param {Object} params * @param {string} params.sourceBucket * @param {string} params.sourceKey * @param {string} params.destinationBucket * @param {string} params.destinationKey * @param {AWS.S3.HeadObjectOutput} [params.sourceObject] * Output from https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#headObject-property * @param {string} [params.ACL] - an [S3 Canned ACL](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl) * @param {boolean} [params.copyTags=false] * @param {number} [params.chunkSize] - chunk size of the S3 multipart uploads * @returns {Promise.<{ etag: string }>} object containing the ETag of the * destination object */ export const multipartCopyObject = async ( params: { sourceBucket: string, sourceKey: string, destinationBucket: string, destinationKey: string, sourceObject?: AWS.S3.HeadObjectOutput, ACL?: AWS.S3.ObjectCannedACL, copyTags?: boolean, chunkSize?: number } ): Promise<{ etag: string }> => { const { sourceBucket, sourceKey, destinationBucket, destinationKey, ACL, copyTags = false, chunkSize, } = params; const sourceObject = params.sourceObject ?? await headObject(sourceBucket, sourceKey); // Create a multi-part upload (copy) and get its UploadId const uploadId = await createMultipartUpload({ sourceBucket, sourceKey, destinationBucket, destinationKey, ACL, copyTags, contentType: sourceObject.ContentType, }); try { // Build the separate parts of the multi-part upload (copy) const objectSize = sourceObject.ContentLength; if (objectSize === undefined) { throw new Error(`Unable to determine size of s3://${sourceBucket}/${sourceKey}`); } const chunks = S3MultipartUploads.createMultipartChunks(objectSize, chunkSize); // Submit all of the upload (copy) parts to S3 const uploadPartCopyResponses = await Promise.all( chunks.map( ({ start, end }, index) => uploadPartCopy({ uploadId, partNumber: index + 1, start, end, sourceBucket, sourceKey, destinationBucket, destinationKey, }) ) ); // Let S3 know that the multi-part upload (copy) is completed const { ETag: etag } = await S3MultipartUploads.completeMultipartUpload({ UploadId: uploadId, Bucket: destinationBucket, Key: destinationKey, MultipartUpload: { Parts: uploadPartCopyResponses, }, }); return { etag }; } catch (error) { // If anything went wrong, make sure that the multi-part upload (copy) // is aborted. await S3MultipartUploads.abortMultipartUpload({ Bucket: destinationBucket, Key: destinationKey, UploadId: uploadId, }); throw error; } }; /** * Move an S3 object to another location in S3 * * @param {Object} params * @param {string} params.sourceBucket * @param {string} params.sourceKey * @param {string} params.destinationBucket * @param {string} params.destinationKey * @param {string} [params.ACL] - an [S3 Canned ACL](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl) * @param {boolean} [params.copyTags=false] * @param {number} [params.chunkSize] - chunk size of the S3 multipart uploads * @returns {Promise<undefined>} */ export const moveObject = async ( params: { sourceBucket: string, sourceKey: string, destinationBucket: string, destinationKey: string, ACL?: AWS.S3.ObjectCannedACL, copyTags?: boolean, chunkSize?: number } ) => { await multipartCopyObject({ sourceBucket: params.sourceBucket, sourceKey: params.sourceKey, destinationBucket: params.destinationBucket, destinationKey: params.destinationKey, ACL: params.ACL, copyTags: isBoolean(params.copyTags) ? params.copyTags : true, chunkSize: params.chunkSize, }); return await deleteS3Object(params.sourceBucket, params.sourceKey); };
the_stack
import * as vscode from "vscode"; import { Repository, store, Tree, TreeItem } from "."; import { getApi } from "../../store/actions"; import { byteArrayToString } from "../../utils"; import { RepoFileSystemProvider } from "../fileSystem"; import { storage } from "../store/storage"; import { promptForTour } from "../tours/actions"; import { focusRepo } from "../tree"; import { sanitizeName } from "../utils"; import { updateTree } from "../wiki/actions"; const base64ToUintArray = require("base64-to-uint8array"); export async function addRepoFile( repoName: string, branch: string, path: string, content = "" ) { const GitHub = require("github-base"); const api = await getApi(GitHub); const response = await api.put(`/repos/${repoName}/contents/${path}`, { message: `Create ${path}`, content, branch }); const repository = store.repos.find((repo) => repo.name === repoName); repository?.tree?.tree.push(response.body.content); await updateRepository(repoName, branch); } export async function createBranch(repo: string, branch: string, sha: string) { const GitHub = require("github-base"); const api = await getApi(GitHub); return api.post(`/repos/${repo}/git/refs`, { ref: `refs/heads/${branch}`, sha }); } export async function createCommit( repo: string, message: string, tree: string, parentCommit: string ) { const GitHub = require("github-base"); const api = await getApi(GitHub); const response = await api.post(`/repos/${repo}/git/commits`, { message, tree, parents: [parentCommit] }); return response.body; } export async function createRepository( repoName: string, isPrivate: boolean = false ) { const GitHub = require("github-base"); const api = await getApi(GitHub); const name = sanitizeName(repoName); const response = await api.post("/user/repos", { name, private: isPrivate }); return response.body; } export async function createRepositoryFromTemplate( template: string, repoName: string, isPrivate: boolean = false ) { const GitHub = require("github-base"); const api = await getApi(GitHub); const name = sanitizeName(repoName); const response = await api.post(`/repos/${template}/generate`, { name, private: isPrivate, headers: { Accept: "application/vnd.github.baptiste-preview+json" } }); return response.body; } export async function createTree(repo: string, baseTree: string, tree: any[]) { const GitHub = require("github-base"); const api = await getApi(GitHub); const response = await api.post(`/repos/${repo}/git/trees`, { base_tree: baseTree, tree }); return response.body; } export async function deleteBranch(repo: string, branch: string) { const GitHub = require("github-base"); const api = await getApi(GitHub); return api.delete(`/repos/${repo}/git/refs/heads/${branch}`); } export async function deleteRepository(repo: string) { const GitHub = require("github-base"); const api = await getApi(GitHub); return api.delete(`/repos/${repo}`); } export async function deleteTreeItem(repo: Repository, treeItem: TreeItem) { return updateTreeItem( repo, treeItem, `Deleting ${treeItem.path}`, ({ path, mode, type }) => [ { path, sha: null, mode, type } ] ); } export async function getBranches(repo: string) { const GitHub = require("github-base"); const api = await getApi(GitHub); const response = await api.get(`/repos/${repo}/branches`); return response.body; } export async function getLatestCommit(repo: string, branch: string) { const GitHub = require("github-base"); const api = await getApi(GitHub); const response = await api.get(`/repos/${repo}/git/refs/heads/${branch}`); return response.body.object.sha; } export async function getRepoFile( repo: string, sha: string ): Promise<Uint8Array> { const GitHub = require("github-base"); const api = await getApi(GitHub); const response = await api.get(`/repos/${repo}/git/blobs/${sha}`); return base64ToUintArray(response.body.content); } export async function getRepo( repo: string, branch: string, etag?: string ): Promise<[] | [Tree, string] | undefined> { const GitHub = require("github-base"); const api = await getApi(GitHub); const options = etag ? { headers: { "If-None-Match": etag } } : {}; try { const response = await api.get( `/repos/${repo}/git/trees/${branch}?recursive=1`, options ); if (response.statusCode === 200) { return [response.body, response.headers.etag]; } else { return []; } } catch (e) { // If the repo is empty (i.e. it has no files yet), then // the call to get the tree will return a 409. // TODO: Indicate when the repository has been // deleted on the server, or the user has lost // access permissions, so we can unmanage it. } } export async function listRepos() { const GitHub = require("github-base"); const api = await getApi(GitHub); const response = await api.get("/user/repos", { affiliation: "owner,collaborator" }); return response.body; } export async function rebaseBranch( repo: string, branch: string, message: string = `Merging ${branch}` ) { // 1) Create a new temp branch that's based on the latest commit on the default branch const commitSha = await getLatestCommit(repo, Repository.DEFAULT_BRANCH); const tempBranch = `temp/${Date.now()}`; await createBranch(repo, tempBranch, commitSha); try { // 2) Merge the changes from the all of the commits on the source branch // onto the temp branch, which will ensure that it includes any changes // that have been made since the branch was started. const mergeCommit = await mergeBranch(repo, branch, tempBranch); // 3) Create a new commit on the default branch, whose tree // refers to the merged commit on the temp branch. This ensure // that the default branch gets all the changes from the source // branch, but without any of the actual commit history. const mergedTree = mergeCommit.commit.tree.sha; const commit = await createCommit(repo, message, mergedTree, commitSha); // 4) Update the default branch to point at the newly committed // changes, and then delete the source and temp branches. await updateBranch(repo, Repository.DEFAULT_BRANCH, commit.sha); await deleteBranch(repo, branch); } catch { vscode.window.showErrorMessage( "Cannot merge branch due to conflicts with the latest changes in the repository." ); } finally { await deleteBranch(repo, tempBranch); } } export async function renameTreeItem( repo: Repository, treeItem: TreeItem, newPath: string ) { return updateTreeItem( repo, treeItem, `Renaming ${treeItem.path} to ${newPath}`, ({ path, mode, sha, type }) => [ { path, sha: null, mode, type }, { path: path.replace(treeItem.path, newPath), mode, sha, type } ] ); } async function updateTreeItem( repo: Repository, treeItem: TreeItem, commitMessage: string, updateFunction: (treeItem: TreeItem) => any[] ) { const files = treeItem.type === "blob" ? [treeItem] : repo.tree!.tree.filter( (item) => item.path.startsWith(treeItem.path) && item.type === "blob" ); const treeChanges = files.flatMap(updateFunction); const commitSha = await getLatestCommit(repo.name, repo.branch); const newTree = await createTree(repo.name, repo.tree!.sha, treeChanges); const commit = await createCommit( repo.name, commitMessage, newTree.sha, commitSha ); await updateBranch(repo.name, repo.branch, commit.sha); return updateRepository(repo.name, repo.branch); } export async function updateBranch(repo: string, branch: string, sha: string) { const GitHub = require("github-base"); const api = await getApi(GitHub); return await api.patch(`/repos/${repo}/git/refs/heads/${branch}`, { sha }); } export async function openRepo(repoName: string, showReadme: boolean = false) { // TODO: Add repo validation const repository = new Repository(repoName); const repos = storage.repos; if (repos.find((repo) => repo === repository.name)) { vscode.window.showInformationMessage( "You've already opened this repository." ); return; } else { repos.push(repoName); storage.repos = repos; } store.repos.push(repository); const repo = await getRepo(repository.name, repository.branch); repository.isLoading = false; // The repo is undefined when it's empty, and therefore, // there's no tree or latest commit to set on it yet. if (repo) { const [tree, etag] = repo; await updateTree(repository, tree!); repository.etag = etag; repository.latestCommit = await getLatestCommit( repository.name, repository.branch ); if (showReadme) { displayReadme(repository); // TODO: Replace this hack with something // better. We're currently doing this because // the repo node might not actually be present // in the tree, in order to focus it yet. setTimeout(() => { focusRepo(repository); }, 1000); promptForTour(repository); } } return repository; } export async function mergeBranch( repo: string, branch: string, baseBranch = Repository.DEFAULT_BRANCH ) { const GitHub = require("github-base"); const api = await getApi(GitHub); const response = await api.post(`/repos/${repo}/merges`, { base: baseBranch, head: branch, commit_message: `Merging ${branch}` }); return response.body; } const REFRESH_INTERVAL = 1000 * 60 * 5; let refreshTimer: NodeJS.Timer; export async function refreshRepositories() { if (storage.repos.length === 0) { return; } if (refreshTimer) { clearInterval(refreshTimer); } store.repos = storage.repos.map((repo) => new Repository(repo)); await updateRepositories(true); setInterval(updateRepositories, REFRESH_INTERVAL); } export async function updateRepositories(isRefreshing: boolean = false) { for (const repo of store.repos) { await updateRepository(repo.name, repo.branch, isRefreshing); } if ( vscode.window.activeTextEditor && !vscode.window.activeTextEditor.document.isDirty && RepoFileSystemProvider.isRepoDocument( vscode.window.activeTextEditor.document ) ) { setTimeout(() => { try { vscode.commands.executeCommand("workbench.action.files.revert"); } catch { // If the file revert fails, it means that the open file was // deleted from the server. So let's simply close it. vscode.commands.executeCommand("workbench.action.closeActiveEditor"); } }, 50); } } export async function updateRepository( repoName: string, branch: string, isRefreshing: boolean = false ) { const repo = store.repos.find((repo) => repo.name === repoName)!; if (isRefreshing) { repo.isLoading = true; } const response = await getRepo(repo.name, repo.branch, repo.etag); if (!response || response.length === 0) { // If the repo became empty on the server, // then we need to delete the local tree. if (!response && repo.tree) { repo.tree = undefined; } repo.isLoading = false; return; } const [tree, etag] = response; await updateTree(repo, tree); repo.etag = etag; repo.isLoading = false; repo.latestCommit = await getLatestCommit(repoName, branch); } export async function closeRepo(repoName: string, branch: string) { storage.repos = storage.repos.filter( (repo) => repo !== repoName && repo !== `${repoName}#${branch}` ); store.repos = store.repos.filter((repo) => repo.name !== repoName); vscode.window.visibleTextEditors.forEach((editor) => { if (RepoFileSystemProvider.isRepoDocument(editor.document, repoName)) { editor.hide(); } }); } async function updateRepoFileInternal( api: any, repo: string, branch: string, path: string, contents: string, sha: string ) { const response = await api.put(`/repos/${repo}/contents/${path}`, { message: `Update ${path}`, content: contents, sha, branch }); const repository = store.repos.find((r) => r.name === repo); const file = repository!.tree!.tree.find((file) => file.path === path); file!.sha = response.body.content.sha; file!.size = response.body.size; return updateRepository(repo, branch); } export async function updateRepoFile( repo: string, branch: string, path: string, contents: Uint8Array, sha: string ) { const GitHub = require("github-base"); const api = await getApi(GitHub); try { await updateRepoFileInternal( api, repo, branch, path, // @ts-ignore contents.toString("base64"), sha ); } catch (e) { const diffMatchPatch = require("diff-match-patch"); const dmp = new diffMatchPatch(); const originalFile = byteArrayToString(await getRepoFile(repo, sha)); const diff = dmp.patch_make(originalFile, contents.toString()); const currentFile = (await api.get(`/repos/${repo}/contents/${path}`)).body; const [merge, success] = dmp.patch_apply( diff, Buffer.from(currentFile.content, "base64").toString() ); if (success) { await updateRepoFileInternal( api, repo, branch, path, Buffer.from(merge).toString("base64"), currentFile.sha ); setTimeout( () => vscode.commands.executeCommand("workbench.action.files.revert"), 50 ); } else { vscode.window.showInformationMessage( "Can't save this file to do an unresoveable conflict with the remote repository." ); } } } export async function displayReadme(repository: Repository) { const readme = repository.readme; if (readme) { const uri = RepoFileSystemProvider.getFileUri(repository.name, readme); vscode.commands.executeCommand("markdown.showPreview", uri); } }
the_stack
declare global { interface Window { AudioContext: AudioContext; webkitAudioContext: any; VideoStreamMerger: VideoStreamMerger; } interface AudioContext { createGainNode: any; } interface HTMLCanvasElement { captureStream(frameRate?: number): MediaStream; } interface HTMLMediaElement { _mediaElementSource: any } interface HTMLVideoElement { playsInline: boolean; } } export interface DrawFunction { ( context: CanvasRenderingContext2D, frame: CanvasImageSource, done: () => void ): void; } export interface AudioEffect { ( sourceNode: AudioNode, destinationNode: MediaStreamAudioDestinationNode ): void; } export interface ConstructorOptions { width: number; height: number; fps: number; clearRect: boolean; audioContext: AudioContext; } export interface AddStreamOptions { x: number; y: number; width: number; height: number; index: number; mute: boolean; muted: boolean; draw: DrawFunction; audioEffect: AudioEffect; } /** * Merges the video of multiple MediaStreams. Also merges the audio via the WebAudio API. * * - Send multiple videos over a single WebRTC MediaConnection * - Hotswap streams without worrying about renegotation or delays * - Crop, scale, and rotate live video * - Add crazy effects through the canvas API */ export class VideoStreamMerger { /** * Width of the merged MediaStream */ public width = 720; /** * Height of the merged MediaStream */ public height = 405; public fps = 25; private _streams: any[] = []; private _frameCount = 0; public clearRect = true; public started = false; /** * The resulting merged MediaStream. Only available after calling merger.start() * Never has more than one Audio and one Video track. */ public result: MediaStream | null = null; public supported: boolean | null = null; private _canvas: HTMLCanvasElement | null = null; private _ctx: CanvasRenderingContext2D | null = null; private _videoSyncDelayNode: DelayNode | null = null; private _audioDestination: MediaStreamAudioDestinationNode | null = null; private _audioCtx: AudioContext | null = null; constructor(options?: ConstructorOptions | undefined) { const AudioContext = window.AudioContext || window.webkitAudioContext; const audioSupport = !!(window.AudioContext && (new AudioContext()).createMediaStreamDestination); const canvasSupport = !!document.createElement('canvas').captureStream; const supported = this.supported = audioSupport && canvasSupport; if (!supported) { return; } this.setOptions(options); const audioCtx = this._audioCtx = new AudioContext(); const audioDestination = this._audioDestination = audioCtx?.createMediaStreamDestination(); // delay node for video sync this._videoSyncDelayNode = audioCtx.createDelay(5.0); this._videoSyncDelayNode.connect(audioDestination); this._setupConstantNode(); // HACK for wowza #7, #10 this.started = false; this.result = null; this._backgroundAudioHack(); } setOptions(options?: ConstructorOptions | undefined): void { options = options || {} as ConstructorOptions; this._audioCtx = (options.audioContext || new AudioContext()); this.width = options.width || this.width; this.height = options.height || this.width; this.fps = options.fps || this.fps; this.clearRect = options.clearRect === undefined ? true : options.clearRect; } /** * Change the size of the canvas and the output video track. */ setOutputSize(width:number, height: number): void { this.width = width; this.height = height; if (this._canvas) { this._canvas.setAttribute('width', this.width.toString()); this._canvas.setAttribute('height', this.height.toString()); } } /** * Get the WebAudio AudioContext being used by the merger. */ getAudioContext(): AudioContext | null { return this._audioCtx; } /** * Get the MediaStreamDestination node that is used by the merger. */ getAudioDestination(): MediaStreamAudioDestinationNode | null { return this._audioDestination; } getCanvasContext(): CanvasRenderingContext2D | null { return this._ctx; } private _backgroundAudioHack() { if (this._audioCtx) { // stop browser from throttling timers by playing almost-silent audio const source = this._createConstantSource(); const gainNode = this._audioCtx.createGain(); if (gainNode && source) { gainNode.gain.value = 0.001; // required to prevent popping on start source.connect(gainNode); gainNode.connect(this._audioCtx.destination); source.start(); } } } private _setupConstantNode() { if (this._audioCtx && this._videoSyncDelayNode) { const constantAudioNode = this._createConstantSource(); if (constantAudioNode) { constantAudioNode.start(); const gain = this._audioCtx.createGain(); // gain node prevents quality drop gain.gain.value = 0; constantAudioNode.connect(gain); gain.connect(this._videoSyncDelayNode); } } } private _createConstantSource() { if (this._audioCtx) { if (this._audioCtx.createConstantSource) { return this._audioCtx.createConstantSource(); } // not really a constantSourceNode, just a looping buffer filled with the offset value const constantSourceNode = this._audioCtx.createBufferSource(); const constantBuffer = this._audioCtx.createBuffer(1, 1, this._audioCtx.sampleRate); const bufferData = constantBuffer.getChannelData(0); bufferData[0] = (0 * 1200) + 10; constantSourceNode.buffer = constantBuffer; constantSourceNode.loop = true; return constantSourceNode; } } /** * Update the z-index (draw order) of an already added stream or data object. Identical to the index option. * If you have added the same MediaStream multiple times, all instances will be updated. */ updateIndex(mediaStream: MediaStream | string | {id: string}, index: number): void { if (typeof mediaStream === 'string') { mediaStream = { id: mediaStream }; } index = index == null ? 0 : index; for (let i = 0; i < this._streams.length; i++) { if (mediaStream.id === this._streams[i].id) { this._streams[i].index = index; } } this._sortStreams(); } private _sortStreams() { this._streams = this._streams.sort((a, b) => a.index - b.index); } /** * A convenience function to merge a HTML5 MediaElement instead of a MediaStream. * * id is a string used to remove or update the index of the stream later. * mediaElement is a playing HTML5 Audio or Video element. * options are identical to the opts for addStream. * Streams from MediaElements can be removed via merger.removeStream(id). */ addMediaElement(id: string, element: HTMLMediaElement, opts: any): void { opts = opts || {}; opts.x = opts.x || 0; opts.y = opts.y || 0; opts.width = opts.width || this.width; opts.height = opts.height || this.height; opts.mute = opts.mute || opts.muted || false; opts.oldDraw = opts.draw; opts.oldAudioEffect = opts.audioEffect; if ( element instanceof HTMLVideoElement || element instanceof HTMLImageElement ) { opts.draw = (ctx: CanvasRenderingContext2D, _: any, done: () => void) => { if (opts.oldDraw) { opts.oldDraw(ctx, element, done); } else { // default draw function const width = opts.width == null ? this.width : opts.width; const height = opts.height == null ? this.height : opts.height; ctx.drawImage(element, opts.x, opts.y, width, height); done(); } }; } else { opts.draw = null; } if (this._audioCtx && !opts.mute) { const audioSource = element._mediaElementSource || this._audioCtx.createMediaElementSource(element); element._mediaElementSource = audioSource; // can only make one source per element, so store it for later (ties the source to the element's garbage collection) audioSource.connect(this._audioCtx.destination); // play audio from original element const gainNode = this._audioCtx.createGain(); audioSource.connect(gainNode); if ( ( element instanceof HTMLVideoElement || element instanceof HTMLAudioElement ) && element.muted ) { // keep the element "muted" while having audio on the merger element.muted = false; element.volume = 0.001; gainNode.gain.value = 1000; } else { gainNode.gain.value = 1; } opts.audioEffect = (_: any, destination: AudioNode) => { if (opts.oldAudioEffect) { opts.oldAudioEffect(gainNode, destination); } else { gainNode.connect(destination); } }; opts.oldAudioEffect = null; } this.addStream(id, opts); } /** * Add a MediaStream to be merged. Use an id string if you only want to provide an effect. * The order that streams are added matters. Streams placed earlier will be behind later streams (use the index option to change this behaviour.) */ addStream(mediaStream: MediaStream | string, opts: AddStreamOptions | undefined): void { if (typeof mediaStream === 'string') { return this._addData(mediaStream, opts); } opts = opts || {} as AddStreamOptions; const stream: any = {}; stream.isData = false; stream.x = opts.x || 0; stream.y = opts.y || 0; stream.width = opts.width; stream.height = opts.height; stream.draw = opts.draw || null; stream.mute = opts.mute || opts.muted || false; stream.audioEffect = opts.audioEffect || null; stream.index = opts.index == null ? 0 : opts.index; stream.hasVideo = mediaStream.getVideoTracks().length > 0; stream.hasAudio = mediaStream.getAudioTracks().length > 0; // If it is the same MediaStream, we can reuse our video element (and ignore sound) let videoElement : HTMLVideoElement | null = null; for (let i = 0; i < this._streams.length; i++) { if (this._streams[i].id === mediaStream.id) { videoElement = this._streams[i].element; } } if (!videoElement) { videoElement = document.createElement('video'); videoElement.autoplay = true; videoElement.muted = true; videoElement.playsInline = true; videoElement.srcObject = mediaStream; videoElement.setAttribute('style', 'position:fixed; left: 0px; top:0px; pointer-events: none; opacity:0;'); document.body.appendChild(videoElement); const res = videoElement.play(); res.catch(null); if (stream.hasAudio && this._audioCtx && !stream.mute) { stream.audioSource = this._audioCtx.createMediaStreamSource(mediaStream); stream.audioOutput = this._audioCtx.createGain(); // Intermediate gain node stream.audioOutput.gain.value = 1; if (stream.audioEffect) { stream.audioEffect(stream.audioSource, stream.audioOutput); } else { stream.audioSource.connect(stream.audioOutput); // Default is direct connect } stream.audioOutput.connect(this._videoSyncDelayNode); } } stream.element = videoElement; stream.id = mediaStream.id || null; this._streams.push(stream); this._sortStreams(); } /** * Remove a MediaStream from the merging. You may also use the ID of the stream. * If you have added the same MediaStream multiple times, all instances will be removed. */ removeStream(mediaStream: MediaStream | string | {id: string}): void { if (typeof mediaStream === 'string') { mediaStream = { id: mediaStream }; } for (let i = 0; i < this._streams.length; i++) { const stream = this._streams[i]; if (mediaStream.id === stream.id) { if (stream.audioSource) { stream.audioSource = null; } if (stream.audioOutput) { stream.audioOutput.disconnect(this._videoSyncDelayNode); stream.audioOutput = null; } if (stream.element) { stream.element.remove(); } this._streams[i] = null; this._streams.splice(i, 1); i--; } } } private _addData(key: string, opts: any) { opts = opts || {}; const stream: any = {}; stream.isData = true; stream.draw = opts.draw || null; stream.audioEffect = opts.audioEffect || null; stream.id = key; stream.element = null; stream.index = opts.index == null ? 0 : opts.index; if (this._videoSyncDelayNode && this._audioCtx && stream.audioEffect) { stream.audioOutput = this._audioCtx.createGain(); // Intermediate gain node stream.audioOutput.gain.value = 1; stream.audioEffect(null, stream.audioOutput); stream.audioOutput.connect(this._videoSyncDelayNode); } this._streams.push(stream); this._sortStreams(); } // Wrapper around requestAnimationFrame and setInterval to avoid background throttling private _requestAnimationFrame(callback: () => void) { let fired = false; const interval = setInterval(() => { if (!fired && document.hidden) { fired = true; clearInterval(interval); callback(); } }, 1000 / this.fps); requestAnimationFrame(() => { if (!fired) { fired = true; clearInterval(interval); callback(); } }); } /** * Start the merging and create merger.result. * You can call this any time, but you only need to call it once. * You will still be able to add/remove streams and the result stream will automatically update. */ start(): void { // Hidden canvas element for merging this._canvas = document.createElement('canvas'); this._canvas.setAttribute('width', this.width.toString()); this._canvas.setAttribute('height', this.height.toString()); this._canvas.setAttribute('style', 'position:fixed; left: 110%; pointer-events: none'); // Push off screen this._ctx = this._canvas.getContext('2d'); this.started = true; this._requestAnimationFrame(this._draw.bind(this)); // Add video this.result = this._canvas?.captureStream(this.fps) || null; // Remove "dead" audio track const deadTrack = this.result?.getAudioTracks()[0]; if (deadTrack) {this.result?.removeTrack(deadTrack);} // Add audio const audioTracks = this._audioDestination?.stream.getAudioTracks(); if (audioTracks && audioTracks.length) { this.result?.addTrack(audioTracks[0]); } } private _updateAudioDelay(delayInMs: number) { if (this._videoSyncDelayNode && this._audioCtx) { this._videoSyncDelayNode.delayTime.setValueAtTime(delayInMs / 1000, this._audioCtx.currentTime); } } private _draw() { if (!this.started) {return;} this._frameCount++; // update video processing delay every 60 frames let t0 = 0; if (this._frameCount % 60 === 0) { t0 = performance.now(); } let awaiting = this._streams.length; const done = () => { awaiting--; if (awaiting <= 0) { if (this._frameCount % 60 === 0) { const t1 = performance.now(); this._updateAudioDelay(t1 - t0); } this._requestAnimationFrame(this._draw.bind(this)); } }; if (this.clearRect) { this._ctx?.clearRect(0, 0, this.width, this.height); } this._streams.forEach((stream) => { if (stream.draw) { // custom frame transform stream.draw(this._ctx, stream.element, done); } else if (!stream.isData && stream.hasVideo) { this._drawVideo(stream.element, stream); done(); } else { done(); } }); if (this._streams.length === 0) { done(); } } private _drawVideo(element: HTMLVideoElement, stream: any) { // default draw function const canvasHeight = this.height; const canvasWidth = this.width; const height = stream.height || canvasHeight; const width = stream.width || canvasWidth; let positionX = stream.x || 0; let positionY = stream.y || 0; try { this._ctx?.drawImage(element, positionX, positionY, width, height); } catch (err) { // Ignore error possible "IndexSizeError (DOM Exception 1): The index is not in the allowed range." due Safari bug. console.error(err); } } /** * Clean up everything and destroy the result stream. */ stop(): void { this.started = false; this._canvas = null; this._ctx = null; this._streams.forEach(stream => { if (stream.element) { stream.element.remove(); } }); this._streams = []; this._audioCtx?.close(); this._audioCtx = null; this._audioDestination = null; this._videoSyncDelayNode = null; this.result?.getTracks().forEach((t) => { t.stop(); }); this.result = null; } destroy() { this.stop(); } } if (typeof window !== "undefined") { (window as any).VideoStreamMerger = VideoStreamMerger; }
the_stack
import { Trans, DateFormat } from "@lingui/macro"; import { i18nMark } from "@lingui/react"; import * as React from "react"; import { Table } from "reactjs-components"; import { findNestedPropertyInObject } from "#SRC/js/utils/Util"; import Units from "#SRC/js/utils/Units"; import DateUtil from "#SRC/js/utils/DateUtil"; import ContainerConstants from "../constants/ContainerConstants"; import ServiceConfigBaseSectionDisplay from "./ServiceConfigBaseSectionDisplay"; import { getColumnClassNameFn, getColumnHeadingFn, getDisplayValue, } from "../utils/ServiceConfigDisplayUtil"; const { type: { DOCKER, MESOS }, labelMap, } = ContainerConstants; class ServiceGeneralConfigSection extends ServiceConfigBaseSectionDisplay { /** * @override */ shouldExcludeItem(row) { const { appConfig } = this.props; switch (row.key) { case "resourceLimits.cpus": return !findNestedPropertyInObject(appConfig, "resourceLimits.cpus"); case "resourceLimits.mem": return !findNestedPropertyInObject(appConfig, "resourceLimits.mem"); case "fetch": return !findNestedPropertyInObject(appConfig, "fetch.length"); case "gpus": return !findNestedPropertyInObject(appConfig, "gpus"); case "backoffSeconds": return !findNestedPropertyInObject(appConfig, "backoffSeconds"); case "backoffFactor": return !findNestedPropertyInObject(appConfig, "backoffFactor"); case "maxLaunchDelaySeconds": return !findNestedPropertyInObject(appConfig, "maxLaunchDelaySeconds"); case "minHealthOpacity": return !findNestedPropertyInObject(appConfig, "minHealthOpacity"); case "maxOverCapacity": return !findNestedPropertyInObject(appConfig, "maxOverCapacity"); case "acceptedResourceRoles": return !findNestedPropertyInObject( appConfig, "acceptedResourceRoles.length" ); case "dependencies": return !findNestedPropertyInObject(appConfig, "dependencies.length"); case "executor": return !findNestedPropertyInObject(appConfig, "executor"); case "user": return !findNestedPropertyInObject(appConfig, "user"); case "args": return !findNestedPropertyInObject(appConfig, "args.length"); case "version": return !findNestedPropertyInObject(appConfig, "version"); default: return false; } } /** * @override */ getMountType() { return "CreateService:ServiceConfigDisplay:App:General"; } /** * @override */ getDefinition() { const { onEditClick } = this.props; return { tabViewID: "services", values: [ { heading: <Trans render="span">Service</Trans>, headingLevel: 1, }, { key: "id", label: <Trans render="span">Service ID</Trans>, }, { heading: <Trans render="span">Resources</Trans>, headingLevel: 2, }, { key: "cpus", label: <Trans render="span">CPU</Trans>, }, { key: "resourceLimits.cpus", label: <Trans render="span">CPU Limit</Trans>, }, { key: "mem", label: <Trans render="span">Memory</Trans>, transformValue(value) { if (value == null) { return value; } return Units.formatResource("mem", value); }, }, { key: "resourceLimits.mem", label: <Trans render="span">Memory Limit</Trans>, transformValue(value) { if (value == null || value === "unlimited") { return value; } return Units.formatResource("mem", value); }, }, { heading: <Trans render="span">General</Trans>, headingLevel: 2, }, { key: "instances", label: <Trans render="span">Instances</Trans>, }, { key: "container.type", label: <Trans render="span">Container Runtime</Trans>, transformValue(runtime) { const transId = labelMap[runtime] || labelMap[MESOS]; return <Trans render="span" id={transId} />; }, }, { key: "disk", label: <Trans render="span">Disk</Trans>, transformValue(value) { if (value == null) { return value; } return Units.formatResource("disk", value); }, }, { key: "gpus", label: <Trans render="span">GPU</Trans>, }, { key: "backoffSeconds", label: <Trans render="span">Backoff Seconds</Trans>, }, { key: "backoffFactor", label: <Trans render="span">Backoff Factor</Trans>, }, { key: "maxLaunchDelaySeconds", label: <Trans render="span">Backoff Max Launch Delay</Trans>, }, { key: "minHealthOpacity", label: <Trans render="span">Upgrade Min Health Capacity</Trans>, }, { key: "maxOverCapacity", label: <Trans render="span">Upgrade Max Overcapacity</Trans>, }, { key: "container.docker.image", label: <Trans render="span">Container Image</Trans>, transformValue(value, appConfig) { const runtime = findNestedPropertyInObject( appConfig, "container.type" ); // Disabled for MESOS return getDisplayValue(value, runtime == null || runtime === MESOS); }, }, { key: "container.docker.privileged", label: <Trans render="span">Extended Runtime Priv.</Trans>, transformValue(value, appConfig) { const runtime = findNestedPropertyInObject( appConfig, "container.type" ); // Disabled for DOCKER if (runtime !== DOCKER && value == null) { return getDisplayValue(null, true); } // Cast boolean as a string. return String(Boolean(value)); }, }, { key: "container.docker.forcePullImage", label: <Trans render="span">Force Pull on Launch</Trans>, transformValue(value, appConfig) { const runtime = findNestedPropertyInObject( appConfig, "container.type" ); // Disabled for DOCKER if (runtime !== DOCKER && value == null) { return getDisplayValue(null, true); } // Cast boolean as a string. return String(Boolean(value)); }, }, { key: "cmd", label: <Trans render="span">Command</Trans>, type: "pre", }, { key: "acceptedResourceRoles", label: <Trans render="span">Resource Roles</Trans>, transformValue(value = []) { return value.join(", "); }, }, { key: "dependencies", label: <Trans render="span">Dependencies</Trans>, transformValue(value = []) { return value.join(", "); }, }, { key: "executor", label: <Trans render="span">Executor</Trans>, }, { key: "user", label: <Trans render="span">User</Trans>, }, { key: "args", label: <Trans render="span">Args</Trans>, transformValue(value = []) { if (!value.length) { return getDisplayValue(null); } const args = value.map((arg, index) => ( <pre key={index} className="flush transparent wrap"> {arg} </pre> )); return <div>{args}</div>; }, }, { key: "version", label: <Trans render="span">Version</Trans>, transformValue(value = []) { const timeString = new Date(value); return ( <DateFormat value={timeString} format={DateUtil.getFormatOptions()} /> ); }, }, { key: "fetch", heading: <Trans render="span">Container Artifacts</Trans>, headingLevel: 2, }, { key: "fetch", render(data) { const columns = [ { heading: getColumnHeadingFn(i18nMark("Artifact Uri")), prop: "uri", render: (prop, row) => { const value = row[prop]; return getDisplayValue(value); }, className: getColumnClassNameFn( "configuration-map-table-label" ), sortable: true, }, ]; if (onEditClick) { columns.push({ heading() { return null; }, className: "configuration-map-action", prop: "edit", render() { return ( <a className="button button-link flush table-display-on-row-hover" onClick={onEditClick.bind(null, "services")} > <Trans>Edit</Trans> </a> ); }, }); } return ( <Table key="artifacts-table" className="table table-flush table-borderless-outer table-borderless-inner-columns vertical-align-top table-break-word table-fixed-layout flush-bottom" columns={columns} data={data} /> ); }, }, ], }; } } export default ServiceGeneralConfigSection;
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace LuckyStar { namespace FormWebApi { interface Header extends DevKit.Controls.IHeader { header_IFRAME_google: DevKit.Controls.IFrame; header_WebResource_HelloWorld: DevKit.Controls.WebResource; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.Controls.Lookup; /** Date and time when the record was created. */ CreatedOn: DevKit.Controls.DateTime; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.Controls.Lookup; devkit_AlternateKey: DevKit.Controls.String; devkit_Currency: DevKit.Controls.Money; /** Value of the Currency in base currency. */ devkit_currency_Base: DevKit.Controls.Money; devkit_CustomerId: DevKit.Controls.Lookup; devkit_DateOnlyDateOnly: DevKit.Controls.Date; devkit_DateOnlyDateOnlyCalculated: DevKit.Controls.Date; devkit_DateOnlyDateOnlyRollup: DevKit.Controls.Date; /** Last Updated time of rollup field Date Only Date Only Rollup. */ devkit_DateOnlyDateOnlyRollup_Date: DevKit.Controls.DateTime; /** State of rollup field Date Only Date Only Rollup. */ devkit_DateOnlyDateOnlyRollup_State: DevKit.Controls.Integer; devkit_DecimalNumber: DevKit.Controls.Decimal; devkit_FloatingPointNumber: DevKit.Controls.Double; devkit_LinkWebApiId: DevKit.Controls.Lookup; devkit_MultipleLiniesofText: DevKit.Controls.String; /** The name of the custom entity. */ devkit_Name: DevKit.Controls.String; devkit_ParentWebApiId: DevKit.Controls.Lookup; devkit_SingleLineofTextEmail: DevKit.Controls.String; devkit_SingleLineofTextPhone: DevKit.Controls.String; devkit_SingleLineofTextText: DevKit.Controls.String; devkit_SingleLineofTextTextArea: DevKit.Controls.String; devkit_SingleLineofTextTickerSymbol: DevKit.Controls.String; devkit_SingleLineofTextUrl: DevKit.Controls.String; devkit_SingleOptionSetCode: DevKit.Controls.OptionSet; devkit_SingleOptionSetCodeCalculated: DevKit.Controls.OptionSet; devkit_TimeZoneDateAndTime: DevKit.Controls.DateTime; devkit_TimeZoneDateAndTimeCalculated: DevKit.Controls.DateTime; devkit_TimeZoneDateAndTimeRollup: DevKit.Controls.DateTime; /** Last Updated time of rollup field TimeZone Date And Time Rollup. */ devkit_TimeZoneDateAndTimeRollup_Date: DevKit.Controls.DateTime; /** State of rollup field TimeZone Date And Time Rollup. */ devkit_TimeZoneDateAndTimeRollup_State: DevKit.Controls.Integer; devkit_TimeZoneDateOnly: DevKit.Controls.Date; devkit_TimeZoneDateOnlyCalculated: DevKit.Controls.Date; devkit_TimeZoneDateOnlyRollup: DevKit.Controls.Date; /** Last Updated time of rollup field TimeZone Date Only Rollup. */ devkit_TimeZoneDateOnlyRollup_Date: DevKit.Controls.DateTime; /** State of rollup field TimeZone Date Only Rollup. */ devkit_TimeZoneDateOnlyRollup_State: DevKit.Controls.Integer; devkit_UserLocalDateAndTime: DevKit.Controls.DateTime; devkit_UserLocalDateAndTimeCalculated: DevKit.Controls.DateTime; devkit_UserLocalDateAndTimeRollup: DevKit.Controls.DateTime; /** Last Updated time of rollup field User Local Date And Time Rollup. */ devkit_UserLocalDateAndTimeRollup_Date: DevKit.Controls.DateTime; /** State of rollup field User Local Date And Time Rollup. */ devkit_UserLocalDateAndTimeRollup_State: DevKit.Controls.Integer; devkit_UserLocalDateOnly: DevKit.Controls.Date; devkit_UserLocalDateOnlyCalculated: DevKit.Controls.Date; devkit_UserLocalDateOnlyRollup: DevKit.Controls.Date; /** Last Updated time of rollup field User Local Date Only Rollup. */ devkit_UserLocalDateOnlyRollup_Date: DevKit.Controls.DateTime; /** State of rollup field User Local Date Only Rollup. */ devkit_UserLocalDateOnlyRollup_State: DevKit.Controls.Integer; devkit_WholeNumberDuration: DevKit.Controls.Integer; devkit_WholeNumberLanguage: DevKit.Controls.Integer; devkit_WholeNumberNone: DevKit.Controls.Integer; devkit_WholeNumberTimeZone: DevKit.Controls.Integer; devkit_YesAndNo: DevKit.Controls.Boolean; devkit_YesAndNoCalculated: DevKit.Controls.Boolean; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.Controls.Decimal; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.Controls.Lookup; /** Date and time when the record was modified. */ ModifiedOn: DevKit.Controls.DateTime; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Status of the WebApi */ statecode: DevKit.Controls.OptionSet; /** Reason for the status of the WebApi */ statuscode: DevKit.Controls.OptionSet; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface tab_WEBAPI_Sections { WEBAPI_section_1: DevKit.Controls.Section; WEBAPI_section_2: DevKit.Controls.Section; } interface tab_NOTE_Sections { NOTE_section_1: DevKit.Controls.Section; } interface tab_TIMER_Sections { TIMER_section_1: DevKit.Controls.Section; } interface tab_OTHERS_Sections { OTHERS_section_1: DevKit.Controls.Section; } interface tab_QUICKVIEW_Sections { QUICKVIEW_section_1: DevKit.Controls.Section; } interface tab_SUBGRID_Sections { SUBGRID_section_1: DevKit.Controls.Section; } interface tab_OPTIONSET_Sections { OPTIONSET_section_1: DevKit.Controls.Section; OPTIONSET_section_3: DevKit.Controls.Section; OPTIONSET_section_5: DevKit.Controls.Section; OPTIONSET_section_2: DevKit.Controls.Section; OPTIONSET_section_4: DevKit.Controls.Section; OPTIONSET_section_6: DevKit.Controls.Section; } interface tab_DATETIME_Sections { DATETIME_section_1: DevKit.Controls.Section; DATETIME_section_3: DevKit.Controls.Section; DATETIME_section_5: DevKit.Controls.Section; DATETIME_section_7: DevKit.Controls.Section; DATETIME_section_2: DevKit.Controls.Section; DATETIME_section_4: DevKit.Controls.Section; DATETIME_section_6: DevKit.Controls.Section; } interface tab_NUMBER_Sections { NUMBER_section_1: DevKit.Controls.Section; NUMBER_section_4: DevKit.Controls.Section; NUMBER_section_2: DevKit.Controls.Section; NUMBER_section_3: DevKit.Controls.Section; } interface tab_STRING_Sections { STRING_section_1: DevKit.Controls.Section; STRING_section_3: DevKit.Controls.Section; STRING_section_2: DevKit.Controls.Section; } interface tab_ADMINISTRATOR_Sections { ADMINISTRATOR_section_1: DevKit.Controls.Section; ADMINISTRATOR_section_2: DevKit.Controls.Section; } interface tab_WEBAPI extends DevKit.Controls.ITab { Section: tab_WEBAPI_Sections; } interface tab_NOTE extends DevKit.Controls.ITab { Section: tab_NOTE_Sections; } interface tab_TIMER extends DevKit.Controls.ITab { Section: tab_TIMER_Sections; } interface tab_OTHERS extends DevKit.Controls.ITab { Section: tab_OTHERS_Sections; } interface tab_QUICKVIEW extends DevKit.Controls.ITab { Section: tab_QUICKVIEW_Sections; } interface tab_SUBGRID extends DevKit.Controls.ITab { Section: tab_SUBGRID_Sections; } interface tab_OPTIONSET extends DevKit.Controls.ITab { Section: tab_OPTIONSET_Sections; } interface tab_DATETIME extends DevKit.Controls.ITab { Section: tab_DATETIME_Sections; } interface tab_NUMBER extends DevKit.Controls.ITab { Section: tab_NUMBER_Sections; } interface tab_STRING extends DevKit.Controls.ITab { Section: tab_STRING_Sections; } interface tab_ADMINISTRATOR extends DevKit.Controls.ITab { Section: tab_ADMINISTRATOR_Sections; } interface Tabs { WEBAPI: tab_WEBAPI; NOTE: tab_NOTE; TIMER: tab_TIMER; OTHERS: tab_OTHERS; QUICKVIEW: tab_QUICKVIEW; SUBGRID: tab_SUBGRID; OPTIONSET: tab_OPTIONSET; DATETIME: tab_DATETIME; NUMBER: tab_NUMBER; STRING: tab_STRING; ADMINISTRATOR: tab_ADMINISTRATOR; } interface Body { Tab: Tabs; notescontrol: DevKit.Controls.Note; tCreatedOn: DevKit.Controls.Timer; WebResource_WORDHELLO: DevKit.Controls.WebResource; IFRAME_GoogleGoogle: DevKit.Controls.IFrame; IFRAME_ACIWIDGET: DevKit.Controls.AciWidget; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.Controls.Lookup; /** Date and time when the record was created. */ CreatedOn: DevKit.Controls.DateTime; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.Controls.Lookup; devkit_AlternateKey: DevKit.Controls.String; devkit_Currency: DevKit.Controls.Money; /** Value of the Currency in base currency. */ devkit_currency_Base: DevKit.Controls.Money; devkit_CustomerId: DevKit.Controls.Lookup; devkit_DateOnlyDateOnly: DevKit.Controls.Date; devkit_DateOnlyDateOnlyCalculated: DevKit.Controls.Date; devkit_DateOnlyDateOnlyRollup: DevKit.Controls.Date; /** Last Updated time of rollup field Date Only Date Only Rollup. */ devkit_DateOnlyDateOnlyRollup_Date: DevKit.Controls.DateTime; /** State of rollup field Date Only Date Only Rollup. */ devkit_DateOnlyDateOnlyRollup_State: DevKit.Controls.Integer; devkit_DecimalNumber: DevKit.Controls.Decimal; devkit_FloatingPointNumber: DevKit.Controls.Double; devkit_LinkWebApiId: DevKit.Controls.Lookup; devkit_LinkWebApiId_1: DevKit.Controls.Lookup; devkit_MultiOptionSetCode: DevKit.Controls.MultiOptionSet; devkit_MultipleLiniesofText: DevKit.Controls.String; /** The name of the custom entity. */ devkit_Name: DevKit.Controls.String; devkit_ParentWebApiId: DevKit.Controls.Lookup; devkit_SingleLineofTextEmail: DevKit.Controls.String; devkit_SingleLineofTextPhone: DevKit.Controls.String; devkit_SingleLineofTextText: DevKit.Controls.String; devkit_SingleLineofTextTextArea: DevKit.Controls.String; devkit_SingleLineofTextTickerSymbol: DevKit.Controls.String; devkit_SingleLineofTextUrl: DevKit.Controls.String; devkit_SingleOptionSetCode: DevKit.Controls.OptionSet; devkit_SingleOptionSetCodeCalculated: DevKit.Controls.OptionSet; devkit_TimeZoneDateAndTime: DevKit.Controls.DateTime; devkit_TimeZoneDateAndTimeCalculated: DevKit.Controls.DateTime; devkit_TimeZoneDateAndTimeRollup: DevKit.Controls.DateTime; /** Last Updated time of rollup field TimeZone Date And Time Rollup. */ devkit_TimeZoneDateAndTimeRollup_Date: DevKit.Controls.DateTime; /** State of rollup field TimeZone Date And Time Rollup. */ devkit_TimeZoneDateAndTimeRollup_State: DevKit.Controls.Integer; devkit_TimeZoneDateOnly: DevKit.Controls.Date; devkit_TimeZoneDateOnlyCalculated: DevKit.Controls.Date; devkit_TimeZoneDateOnlyRollup: DevKit.Controls.Date; /** Last Updated time of rollup field TimeZone Date Only Rollup. */ devkit_TimeZoneDateOnlyRollup_Date: DevKit.Controls.DateTime; /** State of rollup field TimeZone Date Only Rollup. */ devkit_TimeZoneDateOnlyRollup_State: DevKit.Controls.Integer; devkit_UserLocalDateAndTime: DevKit.Controls.DateTime; devkit_UserLocalDateAndTimeCalculated: DevKit.Controls.DateTime; devkit_UserLocalDateAndTimeRollup: DevKit.Controls.DateTime; /** Last Updated time of rollup field User Local Date And Time Rollup. */ devkit_UserLocalDateAndTimeRollup_Date: DevKit.Controls.DateTime; /** State of rollup field User Local Date And Time Rollup. */ devkit_UserLocalDateAndTimeRollup_State: DevKit.Controls.Integer; devkit_UserLocalDateOnly: DevKit.Controls.Date; devkit_UserLocalDateOnlyCalculated: DevKit.Controls.Date; devkit_UserLocalDateOnlyRollup: DevKit.Controls.Date; /** Last Updated time of rollup field User Local Date Only Rollup. */ devkit_UserLocalDateOnlyRollup_Date: DevKit.Controls.DateTime; /** State of rollup field User Local Date Only Rollup. */ devkit_UserLocalDateOnlyRollup_State: DevKit.Controls.Integer; devkit_WholeNumberDuration: DevKit.Controls.Integer; devkit_WholeNumberLanguage: DevKit.Controls.Integer; devkit_WholeNumberNone: DevKit.Controls.Integer; devkit_WholeNumberTimeZone: DevKit.Controls.Integer; devkit_YesAndNo: DevKit.Controls.Boolean; devkit_YesAndNoCalculated: DevKit.Controls.Boolean; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.Controls.Decimal; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.Controls.Lookup; /** Date and time when the record was modified. */ ModifiedOn: DevKit.Controls.DateTime; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Status of the WebApi */ statecode: DevKit.Controls.OptionSet; /** Reason for the status of the WebApi */ statuscode: DevKit.Controls.OptionSet; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Footer extends DevKit.Controls.IFooter { /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.Controls.Lookup; /** Date and time when the record was created. */ CreatedOn: DevKit.Controls.DateTime; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.Controls.Lookup; devkit_AlternateKey: DevKit.Controls.String; devkit_Currency: DevKit.Controls.Money; /** Value of the Currency in base currency. */ devkit_currency_Base: DevKit.Controls.Money; devkit_CustomerId: DevKit.Controls.Lookup; devkit_DateOnlyDateOnly: DevKit.Controls.Date; devkit_DateOnlyDateOnlyCalculated: DevKit.Controls.Date; devkit_DateOnlyDateOnlyRollup: DevKit.Controls.Date; /** Last Updated time of rollup field Date Only Date Only Rollup. */ devkit_DateOnlyDateOnlyRollup_Date: DevKit.Controls.DateTime; /** State of rollup field Date Only Date Only Rollup. */ devkit_DateOnlyDateOnlyRollup_State: DevKit.Controls.Integer; devkit_DecimalNumber: DevKit.Controls.Decimal; devkit_FloatingPointNumber: DevKit.Controls.Double; devkit_LinkWebApiId: DevKit.Controls.Lookup; devkit_MultipleLiniesofText: DevKit.Controls.String; /** The name of the custom entity. */ devkit_Name: DevKit.Controls.String; devkit_ParentWebApiId: DevKit.Controls.Lookup; devkit_SingleLineofTextEmail: DevKit.Controls.String; devkit_SingleLineofTextPhone: DevKit.Controls.String; devkit_SingleLineofTextText: DevKit.Controls.String; devkit_SingleLineofTextTextArea: DevKit.Controls.String; devkit_SingleLineofTextTickerSymbol: DevKit.Controls.String; devkit_SingleLineofTextUrl: DevKit.Controls.String; devkit_SingleOptionSetCode: DevKit.Controls.OptionSet; devkit_SingleOptionSetCodeCalculated: DevKit.Controls.OptionSet; devkit_TimeZoneDateAndTime: DevKit.Controls.DateTime; devkit_TimeZoneDateAndTimeCalculated: DevKit.Controls.DateTime; devkit_TimeZoneDateAndTimeRollup: DevKit.Controls.DateTime; /** Last Updated time of rollup field TimeZone Date And Time Rollup. */ devkit_TimeZoneDateAndTimeRollup_Date: DevKit.Controls.DateTime; /** State of rollup field TimeZone Date And Time Rollup. */ devkit_TimeZoneDateAndTimeRollup_State: DevKit.Controls.Integer; devkit_TimeZoneDateOnly: DevKit.Controls.Date; devkit_TimeZoneDateOnlyCalculated: DevKit.Controls.Date; devkit_TimeZoneDateOnlyRollup: DevKit.Controls.Date; /** Last Updated time of rollup field TimeZone Date Only Rollup. */ devkit_TimeZoneDateOnlyRollup_Date: DevKit.Controls.DateTime; /** State of rollup field TimeZone Date Only Rollup. */ devkit_TimeZoneDateOnlyRollup_State: DevKit.Controls.Integer; devkit_UserLocalDateAndTime: DevKit.Controls.DateTime; devkit_UserLocalDateAndTimeCalculated: DevKit.Controls.DateTime; devkit_UserLocalDateAndTimeRollup: DevKit.Controls.DateTime; /** Last Updated time of rollup field User Local Date And Time Rollup. */ devkit_UserLocalDateAndTimeRollup_Date: DevKit.Controls.DateTime; /** State of rollup field User Local Date And Time Rollup. */ devkit_UserLocalDateAndTimeRollup_State: DevKit.Controls.Integer; devkit_UserLocalDateOnly: DevKit.Controls.Date; devkit_UserLocalDateOnlyCalculated: DevKit.Controls.Date; devkit_UserLocalDateOnlyRollup: DevKit.Controls.Date; /** Last Updated time of rollup field User Local Date Only Rollup. */ devkit_UserLocalDateOnlyRollup_Date: DevKit.Controls.DateTime; /** State of rollup field User Local Date Only Rollup. */ devkit_UserLocalDateOnlyRollup_State: DevKit.Controls.Integer; devkit_WholeNumberDuration: DevKit.Controls.Integer; devkit_WholeNumberLanguage: DevKit.Controls.Integer; devkit_WholeNumberNone: DevKit.Controls.Integer; devkit_WholeNumberTimeZone: DevKit.Controls.Integer; devkit_YesAndNo: DevKit.Controls.Boolean; devkit_YesAndNoCalculated: DevKit.Controls.Boolean; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.Controls.Decimal; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.Controls.Lookup; /** Date and time when the record was modified. */ ModifiedOn: DevKit.Controls.DateTime; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.Controls.Lookup; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; /** Status of the WebApi */ statecode: DevKit.Controls.OptionSet; /** Reason for the status of the WebApi */ statuscode: DevKit.Controls.OptionSet; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.Controls.Lookup; } interface Navigation { nav_devkit_devkit_webapi_devkit_webapi_ParentWebApiId: DevKit.Controls.NavigationItem, nav_devkit_devkit_webapi_devkit_webapi_LinkWebApiId: DevKit.Controls.NavigationItem, nav_bpf_devkit_webapi_devkit_processwebapi1: DevKit.Controls.NavigationItem, nav_devkit_devkit_webapi_contact: DevKit.Controls.NavigationItem } interface quickForm_quickViewWebApi_Body { devkit_Name: DevKit.Controls.QuickView; devkit_SingleLineofTextText: DevKit.Controls.QuickView; devkit_YesAndNo: DevKit.Controls.QuickView; OwnerId: DevKit.Controls.QuickView; } interface quickForm_quickViewWebApi extends DevKit.Controls.IQuickView { Body: quickForm_quickViewWebApi_Body; } interface QuickForm { quickViewWebApi: quickForm_quickViewWebApi; } interface ProcessProcess_WebApi_1 { devkit_CustomerId: DevKit.Controls.Lookup; devkit_DecimalNumber: DevKit.Controls.Decimal; devkit_FloatingPointNumber: DevKit.Controls.Double; devkit_MultipleLiniesofText: DevKit.Controls.String; devkit_SingleLineofTextText: DevKit.Controls.String; devkit_SingleLineofTextText_1: DevKit.Controls.String; devkit_SingleOptionSetCode: DevKit.Controls.OptionSet; devkit_UserLocalDateOnly: DevKit.Controls.Date; devkit_WholeNumberNone: DevKit.Controls.Integer; devkit_YesAndNo: DevKit.Controls.Boolean; devkit_YesAndNoCalculated: DevKit.Controls.Boolean; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Process extends DevKit.Controls.IProcess { Process_WebApi_1: ProcessProcess_WebApi_1; } interface Grid { gridSubGridParentWebApi: DevKit.Controls.Grid; } } class FormWebApi extends DevKit.IForm { /** * DynamicsCrm.DevKit form WebApi * @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 WebApi */ Body: LuckyStar.FormWebApi.Body; /** The Footer section of form WebApi */ Footer: LuckyStar.FormWebApi.Footer; /** The Header section of form WebApi */ Header: LuckyStar.FormWebApi.Header; /** The Navigation of form WebApi */ Navigation: LuckyStar.FormWebApi.Navigation; /** The QuickForm of form WebApi */ QuickForm: LuckyStar.FormWebApi.QuickForm; /** The Process of form WebApi */ Process: LuckyStar.FormWebApi.Process; /** The Grid of form WebApi */ Grid: LuckyStar.FormWebApi.Grid; } class devkit_WebApiApi { /** * DynamicsCrm.DevKit devkit_WebApiApi * @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; devkit_AlternateKey: DevKit.WebApi.StringValue; devkit_Currency: DevKit.WebApi.MoneyValue; /** Value of the Currency in base currency. */ devkit_currency_Base: DevKit.WebApi.MoneyValueReadonly; devkit_CustomerId_account: DevKit.WebApi.LookupValue; devkit_CustomerId_contact: DevKit.WebApi.LookupValue; devkit_DateOnlyDateOnly_DateOnly: DevKit.WebApi.DateOnlyValue; devkit_DateOnlyDateOnlyCalculated_DateOnly: DevKit.WebApi.DateOnlyValueReadonly; devkit_DateOnlyDateOnlyRollup_DateOnly: DevKit.WebApi.DateOnlyValueReadonly; /** Last Updated time of rollup field Date Only Date Only Rollup. */ devkit_DateOnlyDateOnlyRollup_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** State of rollup field Date Only Date Only Rollup. */ devkit_DateOnlyDateOnlyRollup_State: DevKit.WebApi.IntegerValueReadonly; devkit_DecimalNumber: DevKit.WebApi.DecimalValue; devkit_FloatingPointNumber: DevKit.WebApi.DoubleValue; devkit_LinkWebApiId: DevKit.WebApi.LookupValue; devkit_MultiOptionSetCode: DevKit.WebApi.MultiOptionSetValue; devkit_MultipleLiniesofText: DevKit.WebApi.StringValue; /** The name of the custom entity. */ devkit_Name: DevKit.WebApi.StringValue; devkit_ParentWebApiId: DevKit.WebApi.LookupValue; devkit_SingleLineofTextEmail: DevKit.WebApi.StringValue; devkit_SingleLineofTextPhone: DevKit.WebApi.StringValue; devkit_SingleLineofTextText: DevKit.WebApi.StringValue; devkit_SingleLineofTextTextArea: DevKit.WebApi.StringValue; devkit_SingleLineofTextTickerSymbol: DevKit.WebApi.StringValue; devkit_SingleLineofTextUrl: DevKit.WebApi.StringValue; devkit_SingleOptionSetCode: DevKit.WebApi.OptionSetValue; devkit_SingleOptionSetCodeCalculated: DevKit.WebApi.OptionSetValueReadonly; devkit_TimeZoneDateAndTime_TimezoneDateAndTime: DevKit.WebApi.TimezoneDateAndTimeValue; devkit_TimeZoneDateAndTimeCalculated_TimezoneDateAndTime: DevKit.WebApi.TimezoneDateAndTimeValueReadonly; devkit_TimeZoneDateAndTimeRollup_TimezoneDateAndTime: DevKit.WebApi.TimezoneDateAndTimeValueReadonly; /** Last Updated time of rollup field TimeZone Date And Time Rollup. */ devkit_TimeZoneDateAndTimeRollup_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** State of rollup field TimeZone Date And Time Rollup. */ devkit_TimeZoneDateAndTimeRollup_State: DevKit.WebApi.IntegerValueReadonly; devkit_TimeZoneDateOnly_TimezoneDateOnly: DevKit.WebApi.TimezoneDateOnlyValue; devkit_TimeZoneDateOnlyCalculated_TimezoneDateOnly: DevKit.WebApi.TimezoneDateOnlyValueReadonly; devkit_TimeZoneDateOnlyRollup_TimezoneDateOnly: DevKit.WebApi.TimezoneDateOnlyValueReadonly; /** Last Updated time of rollup field TimeZone Date Only Rollup. */ devkit_TimeZoneDateOnlyRollup_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** State of rollup field TimeZone Date Only Rollup. */ devkit_TimeZoneDateOnlyRollup_State: DevKit.WebApi.IntegerValueReadonly; devkit_UserLocalDateAndTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; devkit_UserLocalDateAndTimeCalculated_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; devkit_UserLocalDateAndTimeRollup_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Last Updated time of rollup field User Local Date And Time Rollup. */ devkit_UserLocalDateAndTimeRollup_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** State of rollup field User Local Date And Time Rollup. */ devkit_UserLocalDateAndTimeRollup_State: DevKit.WebApi.IntegerValueReadonly; devkit_UserLocalDateOnly_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; devkit_UserLocalDateOnlyCalculated_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly; devkit_UserLocalDateOnlyRollup_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValueReadonly; /** Last Updated time of rollup field User Local Date Only Rollup. */ devkit_UserLocalDateOnlyRollup_Date_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** State of rollup field User Local Date Only Rollup. */ devkit_UserLocalDateOnlyRollup_State: DevKit.WebApi.IntegerValueReadonly; /** Unique identifier for entity instances */ devkit_WebApiId: DevKit.WebApi.GuidValue; devkit_WholeNumberDuration: DevKit.WebApi.IntegerValue; devkit_WholeNumberLanguage: DevKit.WebApi.IntegerValue; devkit_WholeNumberNone: DevKit.WebApi.IntegerValue; devkit_WholeNumberTimeZone: DevKit.WebApi.IntegerValue; devkit_YesAndNo: DevKit.WebApi.BooleanValue; devkit_YesAndNoCalculated: DevKit.WebApi.BooleanValueReadonly; EntityImage: DevKit.WebApi.StringValue; EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly; EntityImage_URL: DevKit.WebApi.StringValueReadonly; EntityImageId: DevKit.WebApi.GuidValueReadonly; /** Exchange rate for the currency associated with the entity with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** 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; /** 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 WebApi */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the WebApi */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the currency associated with the entity. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** 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 devkit_WebApi { enum devkit_MultiOptionSetCode { /** 100000001 */ Crm_2011, /** 100000002 */ Crm_2013, /** 100000003 */ Crm_2015, /** 100000004 */ Crm_2016, /** 100000000 */ Crm_4, /** 100000005 */ Dynamics_365 } enum devkit_SingleOptionSetCode { /** 100000001 */ Crm_2011, /** 100000002 */ Crm_2013, /** 100000003 */ Crm_2015, /** 100000004 */ Crm_2016, /** 100000000 */ Crm_4, /** 100000005 */ Dynamics_365 } enum devkit_SingleOptionSetCodeCalculated { /** 100000001 */ Crm_2011, /** 100000002 */ Crm_2013, /** 100000003 */ Crm_2015, /** 100000004 */ Crm_2016, /** 100000000 */ Crm_4, /** 100000005 */ Dynamics_365 } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 100000000 */ Active_2, /** 100000001 */ Active_3, /** 2 */ Inactive, /** 100000002 */ Inactive_2, /** 100000003 */ Inactive_3 } 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':['WebApi'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.10.31','JsFormVersion':'v2'}
the_stack
import BaseModel from './base'; import { EncodedSignedTransaction } from '../../../../types/transactions/encoded'; import BlockHeader from '../../../../types/blockHeader'; /** * Account information at a given round. * Definition: * data/basics/userBalance.go : AccountData */ export declare class Account extends BaseModel { /** * the account public key */ address: string; /** * (algo) total number of MicroAlgos in the account */ amount: number | bigint; /** * specifies the amount of MicroAlgos in the account, without the pending rewards. */ amountWithoutPendingRewards: number | bigint; /** * amount of MicroAlgos of pending rewards in this account. */ pendingRewards: number | bigint; /** * (ern) total rewards of MicroAlgos the account has received, including pending * rewards. */ rewards: number | bigint; /** * The round for which this information is relevant. */ round: number | bigint; /** * (onl) delegation status of the account's MicroAlgos * * Offline - indicates that the associated account is delegated. * * Online - indicates that the associated account used as part of the delegation * pool. * * NotParticipating - indicates that the associated account is neither a * delegator nor a delegate. */ status: string; /** * (appl) applications local data stored in this account. * Note the raw object uses `map[int] -> AppLocalState` for this type. */ appsLocalState?: ApplicationLocalState[]; /** * (teap) the sum of all extra application program pages for this account. */ appsTotalExtraPages?: number | bigint; /** * (tsch) stores the sum of all of the local schemas and global schemas in this * account. * Note: the raw account uses `StateSchema` for this type. */ appsTotalSchema?: ApplicationStateSchema; /** * (asset) assets held by this account. * Note the raw object uses `map[int] -> AssetHolding` for this type. */ assets?: AssetHolding[]; /** * (spend) the address against which signing should be checked. If empty, the * address of the current account is used. This field can be updated in any * transaction by setting the RekeyTo field. */ authAddr?: string; /** * (appp) parameters of applications created by this account including app global * data. * Note: the raw account uses `map[int] -> AppParams` for this type. */ createdApps?: Application[]; /** * (apar) parameters of assets created by this account. * Note: the raw account uses `map[int] -> Asset` for this type. */ createdAssets?: Asset[]; /** * AccountParticipation describes the parameters used by this account in consensus * protocol. */ participation?: AccountParticipation; /** * (ebase) used as part of the rewards computation. Only applicable to accounts * which are participating. */ rewardBase?: number | bigint; /** * Indicates what type of signature is used by this account, must be one of: * * sig * * msig * * lsig */ sigType?: string; /** * Creates a new `Account` object. * @param address - the account public key * @param amount - (algo) total number of MicroAlgos in the account * @param amountWithoutPendingRewards - specifies the amount of MicroAlgos in the account, without the pending rewards. * @param pendingRewards - amount of MicroAlgos of pending rewards in this account. * @param rewards - (ern) total rewards of MicroAlgos the account has received, including pending * rewards. * @param round - The round for which this information is relevant. * @param status - (onl) delegation status of the account's MicroAlgos * * Offline - indicates that the associated account is delegated. * * Online - indicates that the associated account used as part of the delegation * pool. * * NotParticipating - indicates that the associated account is neither a * delegator nor a delegate. * @param appsLocalState - (appl) applications local data stored in this account. * Note the raw object uses `map[int] -> AppLocalState` for this type. * @param appsTotalExtraPages - (teap) the sum of all extra application program pages for this account. * @param appsTotalSchema - (tsch) stores the sum of all of the local schemas and global schemas in this * account. * Note: the raw account uses `StateSchema` for this type. * @param assets - (asset) assets held by this account. * Note the raw object uses `map[int] -> AssetHolding` for this type. * @param authAddr - (spend) the address against which signing should be checked. If empty, the * address of the current account is used. This field can be updated in any * transaction by setting the RekeyTo field. * @param createdApps - (appp) parameters of applications created by this account including app global * data. * Note: the raw account uses `map[int] -> AppParams` for this type. * @param createdAssets - (apar) parameters of assets created by this account. * Note: the raw account uses `map[int] -> Asset` for this type. * @param participation - AccountParticipation describes the parameters used by this account in consensus * protocol. * @param rewardBase - (ebase) used as part of the rewards computation. Only applicable to accounts * which are participating. * @param sigType - Indicates what type of signature is used by this account, must be one of: * * sig * * msig * * lsig */ constructor({ address, amount, amountWithoutPendingRewards, pendingRewards, rewards, round, status, appsLocalState, appsTotalExtraPages, appsTotalSchema, assets, authAddr, createdApps, createdAssets, participation, rewardBase, sigType, }: { address: string; amount: number | bigint; amountWithoutPendingRewards: number | bigint; pendingRewards: number | bigint; rewards: number | bigint; round: number | bigint; status: string; appsLocalState?: ApplicationLocalState[]; appsTotalExtraPages?: number | bigint; appsTotalSchema?: ApplicationStateSchema; assets?: AssetHolding[]; authAddr?: string; createdApps?: Application[]; createdAssets?: Asset[]; participation?: AccountParticipation; rewardBase?: number | bigint; sigType?: string; }); } /** * AccountParticipation describes the parameters used by this account in consensus * protocol. */ export declare class AccountParticipation extends BaseModel { /** * (sel) Selection public key (if any) currently registered for this round. */ selectionParticipationKey: Uint8Array; /** * (voteFst) First round for which this participation is valid. */ voteFirstValid: number | bigint; /** * (voteKD) Number of subkeys in each batch of participation keys. */ voteKeyDilution: number | bigint; /** * (voteLst) Last round for which this participation is valid. */ voteLastValid: number | bigint; /** * (vote) root participation public key (if any) currently registered for this * round. */ voteParticipationKey: Uint8Array; /** * Creates a new `AccountParticipation` object. * @param selectionParticipationKey - (sel) Selection public key (if any) currently registered for this round. * @param voteFirstValid - (voteFst) First round for which this participation is valid. * @param voteKeyDilution - (voteKD) Number of subkeys in each batch of participation keys. * @param voteLastValid - (voteLst) Last round for which this participation is valid. * @param voteParticipationKey - (vote) root participation public key (if any) currently registered for this * round. */ constructor({ selectionParticipationKey, voteFirstValid, voteKeyDilution, voteLastValid, voteParticipationKey, }: { selectionParticipationKey: string | Uint8Array; voteFirstValid: number | bigint; voteKeyDilution: number | bigint; voteLastValid: number | bigint; voteParticipationKey: string | Uint8Array; }); } /** * Application state delta. */ export declare class AccountStateDelta extends BaseModel { address: string; /** * Application state delta. */ delta: EvalDeltaKeyValue[]; /** * Creates a new `AccountStateDelta` object. * @param address - * @param delta - Application state delta. */ constructor(address: string, delta: EvalDeltaKeyValue[]); } /** * Application index and its parameters */ export declare class Application extends BaseModel { /** * (appidx) application index. */ id: number | bigint; /** * (appparams) application parameters. */ params: ApplicationParams; /** * Creates a new `Application` object. * @param id - (appidx) application index. * @param params - (appparams) application parameters. */ constructor(id: number | bigint, params: ApplicationParams); } /** * Stores local state associated with an application. */ export declare class ApplicationLocalState extends BaseModel { /** * The application which this local state is for. */ id: number | bigint; /** * (hsch) schema. */ schema: ApplicationStateSchema; /** * (tkv) storage. */ keyValue?: TealKeyValue[]; /** * Creates a new `ApplicationLocalState` object. * @param id - The application which this local state is for. * @param schema - (hsch) schema. * @param keyValue - (tkv) storage. */ constructor(id: number | bigint, schema: ApplicationStateSchema, keyValue?: TealKeyValue[]); } /** * Stores the global information associated with an application. */ export declare class ApplicationParams extends BaseModel { /** * (approv) approval program. */ approvalProgram: Uint8Array; /** * (clearp) approval program. */ clearStateProgram: Uint8Array; /** * The address that created this application. This is the address where the * parameters and global state for this application can be found. */ creator: string; /** * (epp) the amount of extra program pages available to this app. */ extraProgramPages?: number | bigint; /** * [\gs) global schema */ globalState?: TealKeyValue[]; /** * [\gsch) global schema */ globalStateSchema?: ApplicationStateSchema; /** * [\lsch) local schema */ localStateSchema?: ApplicationStateSchema; /** * Creates a new `ApplicationParams` object. * @param approvalProgram - (approv) approval program. * @param clearStateProgram - (clearp) approval program. * @param creator - The address that created this application. This is the address where the * parameters and global state for this application can be found. * @param extraProgramPages - (epp) the amount of extra program pages available to this app. * @param globalState - [\gs) global schema * @param globalStateSchema - [\gsch) global schema * @param localStateSchema - [\lsch) local schema */ constructor({ approvalProgram, clearStateProgram, creator, extraProgramPages, globalState, globalStateSchema, localStateSchema, }: { approvalProgram: string | Uint8Array; clearStateProgram: string | Uint8Array; creator: string; extraProgramPages?: number | bigint; globalState?: TealKeyValue[]; globalStateSchema?: ApplicationStateSchema; localStateSchema?: ApplicationStateSchema; }); } /** * Specifies maximums on the number of each type that may be stored. */ export declare class ApplicationStateSchema extends BaseModel { /** * (nui) num of uints. */ numUint: number | bigint; /** * (nbs) num of byte slices. */ numByteSlice: number | bigint; /** * Creates a new `ApplicationStateSchema` object. * @param numUint - (nui) num of uints. * @param numByteSlice - (nbs) num of byte slices. */ constructor(numUint: number | bigint, numByteSlice: number | bigint); } /** * Specifies both the unique identifier and the parameters for an asset */ export declare class Asset extends BaseModel { /** * unique asset identifier */ index: number | bigint; /** * AssetParams specifies the parameters for an asset. * (apar) when part of an AssetConfig transaction. * Definition: * data/transactions/asset.go : AssetParams */ params: AssetParams; /** * Creates a new `Asset` object. * @param index - unique asset identifier * @param params - AssetParams specifies the parameters for an asset. * (apar) when part of an AssetConfig transaction. * Definition: * data/transactions/asset.go : AssetParams */ constructor(index: number | bigint, params: AssetParams); } /** * Describes an asset held by an account. * Definition: * data/basics/userBalance.go : AssetHolding */ export declare class AssetHolding extends BaseModel { /** * (a) number of units held. */ amount: number | bigint; /** * Asset ID of the holding. */ assetId: number | bigint; /** * Address that created this asset. This is the address where the parameters for * this asset can be found, and also the address where unwanted asset units can be * sent in the worst case. */ creator: string; /** * (f) whether or not the holding is frozen. */ isFrozen: boolean; /** * Creates a new `AssetHolding` object. * @param amount - (a) number of units held. * @param assetId - Asset ID of the holding. * @param creator - Address that created this asset. This is the address where the parameters for * this asset can be found, and also the address where unwanted asset units can be * sent in the worst case. * @param isFrozen - (f) whether or not the holding is frozen. */ constructor(amount: number | bigint, assetId: number | bigint, creator: string, isFrozen: boolean); } /** * AssetParams specifies the parameters for an asset. * (apar) when part of an AssetConfig transaction. * Definition: * data/transactions/asset.go : AssetParams */ export declare class AssetParams extends BaseModel { /** * The address that created this asset. This is the address where the parameters * for this asset can be found, and also the address where unwanted asset units can * be sent in the worst case. */ creator: string; /** * (dc) The number of digits to use after the decimal point when displaying this * asset. If 0, the asset is not divisible. If 1, the base unit of the asset is in * tenths. If 2, the base unit of the asset is in hundredths, and so on. This value * must be between 0 and 19 (inclusive). */ decimals: number | bigint; /** * (t) The total number of units of this asset. */ total: number | bigint; /** * (c) Address of account used to clawback holdings of this asset. If empty, * clawback is not permitted. */ clawback?: string; /** * (df) Whether holdings of this asset are frozen by default. */ defaultFrozen?: boolean; /** * (f) Address of account used to freeze holdings of this asset. If empty, freezing * is not permitted. */ freeze?: string; /** * (m) Address of account used to manage the keys of this asset and to destroy it. */ manager?: string; /** * (am) A commitment to some unspecified asset metadata. The format of this * metadata is up to the application. */ metadataHash?: Uint8Array; /** * (an) Name of this asset, as supplied by the creator. Included only when the * asset name is composed of printable utf-8 characters. */ name?: string; /** * Base64 encoded name of this asset, as supplied by the creator. */ nameB64?: Uint8Array; /** * (r) Address of account holding reserve (non-minted) units of this asset. */ reserve?: string; /** * (un) Name of a unit of this asset, as supplied by the creator. Included only * when the name of a unit of this asset is composed of printable utf-8 characters. */ unitName?: string; /** * Base64 encoded name of a unit of this asset, as supplied by the creator. */ unitNameB64?: Uint8Array; /** * (au) URL where more information about the asset can be retrieved. Included only * when the URL is composed of printable utf-8 characters. */ url?: string; /** * Base64 encoded URL where more information about the asset can be retrieved. */ urlB64?: Uint8Array; /** * Creates a new `AssetParams` object. * @param creator - The address that created this asset. This is the address where the parameters * for this asset can be found, and also the address where unwanted asset units can * be sent in the worst case. * @param decimals - (dc) The number of digits to use after the decimal point when displaying this * asset. If 0, the asset is not divisible. If 1, the base unit of the asset is in * tenths. If 2, the base unit of the asset is in hundredths, and so on. This value * must be between 0 and 19 (inclusive). * @param total - (t) The total number of units of this asset. * @param clawback - (c) Address of account used to clawback holdings of this asset. If empty, * clawback is not permitted. * @param defaultFrozen - (df) Whether holdings of this asset are frozen by default. * @param freeze - (f) Address of account used to freeze holdings of this asset. If empty, freezing * is not permitted. * @param manager - (m) Address of account used to manage the keys of this asset and to destroy it. * @param metadataHash - (am) A commitment to some unspecified asset metadata. The format of this * metadata is up to the application. * @param name - (an) Name of this asset, as supplied by the creator. Included only when the * asset name is composed of printable utf-8 characters. * @param nameB64 - Base64 encoded name of this asset, as supplied by the creator. * @param reserve - (r) Address of account holding reserve (non-minted) units of this asset. * @param unitName - (un) Name of a unit of this asset, as supplied by the creator. Included only * when the name of a unit of this asset is composed of printable utf-8 characters. * @param unitNameB64 - Base64 encoded name of a unit of this asset, as supplied by the creator. * @param url - (au) URL where more information about the asset can be retrieved. Included only * when the URL is composed of printable utf-8 characters. * @param urlB64 - Base64 encoded URL where more information about the asset can be retrieved. */ constructor({ creator, decimals, total, clawback, defaultFrozen, freeze, manager, metadataHash, name, nameB64, reserve, unitName, unitNameB64, url, urlB64, }: { creator: string; decimals: number | bigint; total: number | bigint; clawback?: string; defaultFrozen?: boolean; freeze?: string; manager?: string; metadataHash?: string | Uint8Array; name?: string; nameB64?: string | Uint8Array; reserve?: string; unitName?: string; unitNameB64?: string | Uint8Array; url?: string; urlB64?: string | Uint8Array; }); } /** * Encoded block object. */ export declare class BlockResponse extends BaseModel { /** * Block header data. */ block: BlockHeader; /** * Optional certificate object. This is only included when the format is set to * message pack. */ cert?: Record<string, any>; /** * Creates a new `BlockResponse` object. * @param block - Block header data. * @param cert - Optional certificate object. This is only included when the format is set to * message pack. */ constructor(block: BlockHeader, cert?: Record<string, any>); } export declare class BuildVersion extends BaseModel { branch: string; buildNumber: number | bigint; channel: string; commitHash: string; major: number | bigint; minor: number | bigint; /** * Creates a new `BuildVersion` object. * @param branch - * @param buildNumber - * @param channel - * @param commitHash - * @param major - * @param minor - */ constructor({ branch, buildNumber, channel, commitHash, major, minor, }: { branch: string; buildNumber: number | bigint; channel: string; commitHash: string; major: number | bigint; minor: number | bigint; }); } /** * */ export declare class CatchpointAbortResponse extends BaseModel { /** * Catchup abort response string */ catchupMessage: string; /** * Creates a new `CatchpointAbortResponse` object. * @param catchupMessage - Catchup abort response string */ constructor(catchupMessage: string); } /** * */ export declare class CatchpointStartResponse extends BaseModel { /** * Catchup start response string */ catchupMessage: string; /** * Creates a new `CatchpointStartResponse` object. * @param catchupMessage - Catchup start response string */ constructor(catchupMessage: string); } /** * Teal compile Result */ export declare class CompileResponse extends BaseModel { /** * base32 SHA512_256 of program bytes (Address style) */ hash: string; /** * base64 encoded program bytes */ result: string; /** * Creates a new `CompileResponse` object. * @param hash - base32 SHA512_256 of program bytes (Address style) * @param result - base64 encoded program bytes */ constructor(hash: string, result: string); } /** * Request data type for dryrun endpoint. Given the Transactions and simulated * ledger state upload, run TEAL scripts and return debugging information. */ export declare class DryrunRequest extends BaseModel { accounts: Account[]; apps: Application[]; /** * LatestTimestamp is available to some TEAL scripts. Defaults to the latest * confirmed timestamp this algod is attached to. */ latestTimestamp: number | bigint; /** * ProtocolVersion specifies a specific version string to operate under, otherwise * whatever the current protocol of the network this algod is running in. */ protocolVersion: string; /** * Round is available to some TEAL scripts. Defaults to the current round on the * network this algod is attached to. */ round: number | bigint; sources: DryrunSource[]; txns: EncodedSignedTransaction[]; /** * Creates a new `DryrunRequest` object. * @param accounts - * @param apps - * @param latestTimestamp - LatestTimestamp is available to some TEAL scripts. Defaults to the latest * confirmed timestamp this algod is attached to. * @param protocolVersion - ProtocolVersion specifies a specific version string to operate under, otherwise * whatever the current protocol of the network this algod is running in. * @param round - Round is available to some TEAL scripts. Defaults to the current round on the * network this algod is attached to. * @param sources - * @param txns - */ constructor({ accounts, apps, latestTimestamp, protocolVersion, round, sources, txns, }: { accounts: Account[]; apps: Application[]; latestTimestamp: number | bigint; protocolVersion: string; round: number | bigint; sources: DryrunSource[]; txns: EncodedSignedTransaction[]; }); } /** * DryrunResponse contains per-txn debug information from a dryrun. */ export declare class DryrunResponse extends BaseModel { error: string; /** * Protocol version is the protocol version Dryrun was operated under. */ protocolVersion: string; txns: DryrunTxnResult[]; /** * Creates a new `DryrunResponse` object. * @param error - * @param protocolVersion - Protocol version is the protocol version Dryrun was operated under. * @param txns - */ constructor(error: string, protocolVersion: string, txns: DryrunTxnResult[]); } /** * DryrunSource is TEAL source text that gets uploaded, compiled, and inserted into * transactions or application state. */ export declare class DryrunSource extends BaseModel { /** * FieldName is what kind of sources this is. If lsig then it goes into the * transactions[this.TxnIndex].LogicSig. If approv or clearp it goes into the * Approval Program or Clear State Program of application[this.AppIndex]. */ fieldName: string; source: string; txnIndex: number | bigint; appIndex: number | bigint; /** * Creates a new `DryrunSource` object. * @param fieldName - FieldName is what kind of sources this is. If lsig then it goes into the * transactions[this.TxnIndex].LogicSig. If approv or clearp it goes into the * Approval Program or Clear State Program of application[this.AppIndex]. * @param source - * @param txnIndex - * @param appIndex - */ constructor(fieldName: string, source: string, txnIndex: number | bigint, appIndex: number | bigint); } /** * Stores the TEAL eval step data */ export declare class DryrunState extends BaseModel { /** * Line number */ line: number | bigint; /** * Program counter */ pc: number | bigint; stack: TealValue[]; /** * Evaluation error if any */ error?: string; scratch?: TealValue[]; /** * Creates a new `DryrunState` object. * @param line - Line number * @param pc - Program counter * @param stack - * @param error - Evaluation error if any * @param scratch - */ constructor({ line, pc, stack, error, scratch, }: { line: number | bigint; pc: number | bigint; stack: TealValue[]; error?: string; scratch?: TealValue[]; }); } /** * DryrunTxnResult contains any LogicSig or ApplicationCall program debug * information and state updates from a dryrun. */ export declare class DryrunTxnResult extends BaseModel { /** * Disassembled program line by line. */ disassembly: string[]; appCallMessages?: string[]; appCallTrace?: DryrunState[]; /** * Execution cost of app call transaction */ cost?: number | bigint; /** * Application state delta. */ globalDelta?: EvalDeltaKeyValue[]; localDeltas?: AccountStateDelta[]; logicSigMessages?: string[]; logicSigTrace?: DryrunState[]; logs?: Uint8Array[]; /** * Creates a new `DryrunTxnResult` object. * @param disassembly - Disassembled program line by line. * @param appCallMessages - * @param appCallTrace - * @param cost - Execution cost of app call transaction * @param globalDelta - Application state delta. * @param localDeltas - * @param logicSigMessages - * @param logicSigTrace - * @param logs - */ constructor({ disassembly, appCallMessages, appCallTrace, cost, globalDelta, localDeltas, logicSigMessages, logicSigTrace, logs, }: { disassembly: string[]; appCallMessages?: string[]; appCallTrace?: DryrunState[]; cost?: number | bigint; globalDelta?: EvalDeltaKeyValue[]; localDeltas?: AccountStateDelta[]; logicSigMessages?: string[]; logicSigTrace?: DryrunState[]; logs?: Uint8Array[]; }); } /** * An error response with optional data field. */ export declare class ErrorResponse extends BaseModel { message: string; data?: string; /** * Creates a new `ErrorResponse` object. * @param message - * @param data - */ constructor(message: string, data?: string); } /** * Represents a TEAL value delta. */ export declare class EvalDelta extends BaseModel { /** * (at) delta action. */ action: number | bigint; /** * (bs) bytes value. */ bytes?: string; /** * (ui) uint value. */ uint?: number | bigint; /** * Creates a new `EvalDelta` object. * @param action - (at) delta action. * @param bytes - (bs) bytes value. * @param uint - (ui) uint value. */ constructor(action: number | bigint, bytes?: string, uint?: number | bigint); } /** * Key-value pairs for StateDelta. */ export declare class EvalDeltaKeyValue extends BaseModel { key: string; /** * Represents a TEAL value delta. */ value: EvalDelta; /** * Creates a new `EvalDeltaKeyValue` object. * @param key - * @param value - Represents a TEAL value delta. */ constructor(key: string, value: EvalDelta); } /** * */ export declare class NodeStatusResponse extends BaseModel { /** * CatchupTime in nanoseconds */ catchupTime: number | bigint; /** * LastRound indicates the last round seen */ lastRound: number | bigint; /** * LastVersion indicates the last consensus version supported */ lastVersion: string; /** * NextVersion of consensus protocol to use */ nextVersion: string; /** * NextVersionRound is the round at which the next consensus version will apply */ nextVersionRound: number | bigint; /** * NextVersionSupported indicates whether the next consensus version is supported * by this node */ nextVersionSupported: boolean; /** * StoppedAtUnsupportedRound indicates that the node does not support the new * rounds and has stopped making progress */ stoppedAtUnsupportedRound: boolean; /** * TimeSinceLastRound in nanoseconds */ timeSinceLastRound: number | bigint; /** * The current catchpoint that is being caught up to */ catchpoint?: string; /** * The number of blocks that have already been obtained by the node as part of the * catchup */ catchpointAcquiredBlocks?: number | bigint; /** * The number of accounts from the current catchpoint that have been processed so * far as part of the catchup */ catchpointProcessedAccounts?: number | bigint; /** * The total number of accounts included in the current catchpoint */ catchpointTotalAccounts?: number | bigint; /** * The total number of blocks that are required to complete the current catchpoint * catchup */ catchpointTotalBlocks?: number | bigint; /** * The number of accounts from the current catchpoint that have been verified so * far as part of the catchup */ catchpointVerifiedAccounts?: number | bigint; /** * The last catchpoint seen by the node */ lastCatchpoint?: string; /** * Creates a new `NodeStatusResponse` object. * @param catchupTime - CatchupTime in nanoseconds * @param lastRound - LastRound indicates the last round seen * @param lastVersion - LastVersion indicates the last consensus version supported * @param nextVersion - NextVersion of consensus protocol to use * @param nextVersionRound - NextVersionRound is the round at which the next consensus version will apply * @param nextVersionSupported - NextVersionSupported indicates whether the next consensus version is supported * by this node * @param stoppedAtUnsupportedRound - StoppedAtUnsupportedRound indicates that the node does not support the new * rounds and has stopped making progress * @param timeSinceLastRound - TimeSinceLastRound in nanoseconds * @param catchpoint - The current catchpoint that is being caught up to * @param catchpointAcquiredBlocks - The number of blocks that have already been obtained by the node as part of the * catchup * @param catchpointProcessedAccounts - The number of accounts from the current catchpoint that have been processed so * far as part of the catchup * @param catchpointTotalAccounts - The total number of accounts included in the current catchpoint * @param catchpointTotalBlocks - The total number of blocks that are required to complete the current catchpoint * catchup * @param catchpointVerifiedAccounts - The number of accounts from the current catchpoint that have been verified so * far as part of the catchup * @param lastCatchpoint - The last catchpoint seen by the node */ constructor({ catchupTime, lastRound, lastVersion, nextVersion, nextVersionRound, nextVersionSupported, stoppedAtUnsupportedRound, timeSinceLastRound, catchpoint, catchpointAcquiredBlocks, catchpointProcessedAccounts, catchpointTotalAccounts, catchpointTotalBlocks, catchpointVerifiedAccounts, lastCatchpoint, }: { catchupTime: number | bigint; lastRound: number | bigint; lastVersion: string; nextVersion: string; nextVersionRound: number | bigint; nextVersionSupported: boolean; stoppedAtUnsupportedRound: boolean; timeSinceLastRound: number | bigint; catchpoint?: string; catchpointAcquiredBlocks?: number | bigint; catchpointProcessedAccounts?: number | bigint; catchpointTotalAccounts?: number | bigint; catchpointTotalBlocks?: number | bigint; catchpointVerifiedAccounts?: number | bigint; lastCatchpoint?: string; }); } /** * Details about a pending transaction. If the transaction was recently confirmed, * includes confirmation details like the round and reward details. */ export declare class PendingTransactionResponse extends BaseModel { /** * Indicates that the transaction was kicked out of this node's transaction pool * (and specifies why that happened). An empty string indicates the transaction * wasn't kicked out of this node's txpool due to an error. */ poolError: string; /** * The raw signed transaction. */ txn: EncodedSignedTransaction; /** * The application index if the transaction was found and it created an * application. */ applicationIndex?: number | bigint; /** * The number of the asset's unit that were transferred to the close-to address. */ assetClosingAmount?: number | bigint; /** * The asset index if the transaction was found and it created an asset. */ assetIndex?: number | bigint; /** * Rewards in microalgos applied to the close remainder to account. */ closeRewards?: number | bigint; /** * Closing amount for the transaction. */ closingAmount?: number | bigint; /** * The round where this transaction was confirmed, if present. */ confirmedRound?: number | bigint; /** * (gd) Global state key/value changes for the application being executed by this * transaction. */ globalStateDelta?: EvalDeltaKeyValue[]; /** * Inner transactions produced by application execution. */ innerTxns?: PendingTransactionResponse[]; /** * (ld) Local state key/value changes for the application being executed by this * transaction. */ localStateDelta?: AccountStateDelta[]; /** * (lg) Logs for the application being executed by this transaction. */ logs?: Uint8Array[]; /** * Rewards in microalgos applied to the receiver account. */ receiverRewards?: number | bigint; /** * Rewards in microalgos applied to the sender account. */ senderRewards?: number | bigint; /** * Creates a new `PendingTransactionResponse` object. * @param poolError - Indicates that the transaction was kicked out of this node's transaction pool * (and specifies why that happened). An empty string indicates the transaction * wasn't kicked out of this node's txpool due to an error. * @param txn - The raw signed transaction. * @param applicationIndex - The application index if the transaction was found and it created an * application. * @param assetClosingAmount - The number of the asset's unit that were transferred to the close-to address. * @param assetIndex - The asset index if the transaction was found and it created an asset. * @param closeRewards - Rewards in microalgos applied to the close remainder to account. * @param closingAmount - Closing amount for the transaction. * @param confirmedRound - The round where this transaction was confirmed, if present. * @param globalStateDelta - (gd) Global state key/value changes for the application being executed by this * transaction. * @param innerTxns - Inner transactions produced by application execution. * @param localStateDelta - (ld) Local state key/value changes for the application being executed by this * transaction. * @param logs - (lg) Logs for the application being executed by this transaction. * @param receiverRewards - Rewards in microalgos applied to the receiver account. * @param senderRewards - Rewards in microalgos applied to the sender account. */ constructor({ poolError, txn, applicationIndex, assetClosingAmount, assetIndex, closeRewards, closingAmount, confirmedRound, globalStateDelta, innerTxns, localStateDelta, logs, receiverRewards, senderRewards, }: { poolError: string; txn: EncodedSignedTransaction; applicationIndex?: number | bigint; assetClosingAmount?: number | bigint; assetIndex?: number | bigint; closeRewards?: number | bigint; closingAmount?: number | bigint; confirmedRound?: number | bigint; globalStateDelta?: EvalDeltaKeyValue[]; innerTxns?: PendingTransactionResponse[]; localStateDelta?: AccountStateDelta[]; logs?: Uint8Array[]; receiverRewards?: number | bigint; senderRewards?: number | bigint; }); } /** * A potentially truncated list of transactions currently in the node's transaction * pool. You can compute whether or not the list is truncated if the number of * elements in the **top-transactions** array is fewer than **total-transactions**. */ export declare class PendingTransactionsResponse extends BaseModel { /** * An array of signed transaction objects. */ topTransactions: EncodedSignedTransaction[]; /** * Total number of transactions in the pool. */ totalTransactions: number | bigint; /** * Creates a new `PendingTransactionsResponse` object. * @param topTransactions - An array of signed transaction objects. * @param totalTransactions - Total number of transactions in the pool. */ constructor(topTransactions: EncodedSignedTransaction[], totalTransactions: number | bigint); } /** * Transaction ID of the submission. */ export declare class PostTransactionsResponse extends BaseModel { /** * encoding of the transaction hash. */ txid: string; /** * Creates a new `PostTransactionsResponse` object. * @param txid - encoding of the transaction hash. */ constructor(txid: string); } /** * Proof of transaction in a block. */ export declare class ProofResponse extends BaseModel { /** * Index of the transaction in the block's payset. */ idx: number | bigint; /** * Merkle proof of transaction membership. */ proof: Uint8Array; /** * Hash of SignedTxnInBlock for verifying proof. */ stibhash: Uint8Array; /** * Creates a new `ProofResponse` object. * @param idx - Index of the transaction in the block's payset. * @param proof - Merkle proof of transaction membership. * @param stibhash - Hash of SignedTxnInBlock for verifying proof. */ constructor(idx: number | bigint, proof: string | Uint8Array, stibhash: string | Uint8Array); } /** * Supply represents the current supply of MicroAlgos in the system. */ export declare class SupplyResponse extends BaseModel { /** * Round */ currentRound: number | bigint; /** * OnlineMoney */ onlineMoney: number | bigint; /** * TotalMoney */ totalMoney: number | bigint; /** * Creates a new `SupplyResponse` object. * @param currentRound - Round * @param onlineMoney - OnlineMoney * @param totalMoney - TotalMoney */ constructor(currentRound: number | bigint, onlineMoney: number | bigint, totalMoney: number | bigint); } /** * Represents a key-value pair in an application store. */ export declare class TealKeyValue extends BaseModel { key: string; /** * Represents a TEAL value. */ value: TealValue; /** * Creates a new `TealKeyValue` object. * @param key - * @param value - Represents a TEAL value. */ constructor(key: string, value: TealValue); } /** * Represents a TEAL value. */ export declare class TealValue extends BaseModel { /** * (tt) value type. Value `1` refers to **bytes**, value `2` refers to **uint** */ type: number | bigint; /** * (tb) bytes value. */ bytes: string; /** * (ui) uint value. */ uint: number | bigint; /** * Creates a new `TealValue` object. * @param type - (tt) value type. Value `1` refers to **bytes**, value `2` refers to **uint** * @param bytes - (tb) bytes value. * @param uint - (ui) uint value. */ constructor(type: number | bigint, bytes: string, uint: number | bigint); } /** * TransactionParams contains the parameters that help a client construct a new * transaction. */ export declare class TransactionParametersResponse extends BaseModel { /** * ConsensusVersion indicates the consensus protocol version * as of LastRound. */ consensusVersion: string; /** * Fee is the suggested transaction fee * Fee is in units of micro-Algos per byte. * Fee may fall to zero but transactions must still have a fee of * at least MinTxnFee for the current network protocol. */ fee: number | bigint; /** * GenesisHash is the hash of the genesis block. */ genesisHash: Uint8Array; /** * GenesisID is an ID listed in the genesis block. */ genesisId: string; /** * LastRound indicates the last round seen */ lastRound: number | bigint; /** * The minimum transaction fee (not per byte) required for the * txn to validate for the current network protocol. */ minFee: number | bigint; /** * Creates a new `TransactionParametersResponse` object. * @param consensusVersion - ConsensusVersion indicates the consensus protocol version * as of LastRound. * @param fee - Fee is the suggested transaction fee * Fee is in units of micro-Algos per byte. * Fee may fall to zero but transactions must still have a fee of * at least MinTxnFee for the current network protocol. * @param genesisHash - GenesisHash is the hash of the genesis block. * @param genesisId - GenesisID is an ID listed in the genesis block. * @param lastRound - LastRound indicates the last round seen * @param minFee - The minimum transaction fee (not per byte) required for the * txn to validate for the current network protocol. */ constructor({ consensusVersion, fee, genesisHash, genesisId, lastRound, minFee, }: { consensusVersion: string; fee: number | bigint; genesisHash: string | Uint8Array; genesisId: string; lastRound: number | bigint; minFee: number | bigint; }); } /** * algod version information. */ export declare class Version extends BaseModel { build: BuildVersion; genesisHashB64: Uint8Array; genesisId: string; versions: string[]; /** * Creates a new `Version` object. * @param build - * @param genesisHashB64 - * @param genesisId - * @param versions - */ constructor(build: BuildVersion, genesisHashB64: string | Uint8Array, genesisId: string, versions: string[]); }
the_stack
// clang-format off import {webUIListenerCallback} from 'chrome://resources/js/cr.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {PromiseResolver} from 'chrome://resources/js/promise_resolver.m.js'; import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {BioEnrollDialogPage, CredentialManagementDialogPage, CrIconButtonElement, CrInputElement, Ctap2Status, ResetDialogPage, SampleStatus, SecurityKeysBioEnrollProxy, SecurityKeysBioEnrollProxyImpl, SecurityKeysCredentialBrowserProxy, SecurityKeysCredentialBrowserProxyImpl, SecurityKeysPINBrowserProxy, SecurityKeysPINBrowserProxyImpl, SecurityKeysResetBrowserProxy, SecurityKeysResetBrowserProxyImpl, SetPINDialogPage, SettingsSecurityKeysBioEnrollDialogElement, SettingsSecurityKeysCredentialManagementDialogElement, SettingsSecurityKeysResetDialogElement, SettingsSecurityKeysSetPinDialogElement} from 'chrome://settings/lazy_load.js'; import {assertDeepEquals, assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {TestBrowserProxy} from 'chrome://webui-test/test_browser_proxy.js'; import {eventToPromise} from 'chrome://webui-test/test_util.js'; // clang-format on const currentMinPinLength = 6; const newMinPinLength = 8; /** * A base class for all security key subpage test browser proxies to * inherit from. Provides a |promiseMap_| that proxies can be used to * simulation Promise resolution via |setResponseFor| and |handleMethod|. */ class TestSecurityKeysBrowserProxy extends TestBrowserProxy { private promiseMap_: Map<string, Promise<any>>; constructor(methodNames: string[]) { super(methodNames); /** * A map from method names to a promise to return when that method is * called. (If no promise is installed, a never-resolved promise is * returned.) */ this.promiseMap_ = new Map(); } setResponseFor(methodName: string, promise: Promise<any>) { this.promiseMap_.set(methodName, promise); } protected handleMethod(methodName: string, opt_arg?: any): Promise<any> { this.methodCalled(methodName, opt_arg); const promise = this.promiseMap_.get(methodName); if (promise !== undefined) { this.promiseMap_.delete(methodName); return promise; } // Return a Promise that never resolves. return new Promise(() => {}); } } class TestSecurityKeysPINBrowserProxy extends TestSecurityKeysBrowserProxy implements SecurityKeysPINBrowserProxy { constructor() { super([ 'startSetPIN', 'setPIN', 'close', ]); } startSetPIN() { return this.handleMethod('startSetPIN'); } setPIN(oldPIN: string, newPIN: string) { return this.handleMethod('setPIN', {oldPIN, newPIN}); } close() { this.methodCalled('close'); } } class TestSecurityKeysResetBrowserProxy extends TestSecurityKeysBrowserProxy implements SecurityKeysResetBrowserProxy { constructor() { super([ 'reset', 'completeReset', 'close', ]); } reset() { return this.handleMethod('reset'); } completeReset() { return this.handleMethod('completeReset'); } close() { this.methodCalled('close'); } } class TestSecurityKeysCredentialBrowserProxy extends TestSecurityKeysBrowserProxy implements SecurityKeysCredentialBrowserProxy { constructor() { super([ 'startCredentialManagement', 'providePIN', 'enumerateCredentials', 'deleteCredentials', 'updateUserInformation', 'close', ]); } startCredentialManagement() { return this.handleMethod('startCredentialManagement'); } providePIN(pin: string) { return this.handleMethod('providePIN', pin); } enumerateCredentials() { return this.handleMethod('enumerateCredentials'); } deleteCredentials(ids: Array<string>) { return this.handleMethod('deleteCredentials', ids); } updateUserInformation( credentialId: string, userHandle: string, newUsername: string, newDisplayname: string) { return this.handleMethod( 'updateUserInformation', {credentialId, userHandle, newUsername, newDisplayname}); } close() { this.methodCalled('close'); } } class TestSecurityKeysBioEnrollProxy extends TestSecurityKeysBrowserProxy implements SecurityKeysBioEnrollProxy { constructor() { super([ 'startBioEnroll', 'providePIN', 'getSensorInfo', 'enumerateEnrollments', 'startEnrolling', 'cancelEnrollment', 'deleteEnrollment', 'renameEnrollment', 'close', ]); } startBioEnroll() { return this.handleMethod('startBioEnroll'); } providePIN(pin: string) { return this.handleMethod('providePIN', pin); } getSensorInfo() { return this.handleMethod('getSensorInfo'); } enumerateEnrollments() { return this.handleMethod('enumerateEnrollments'); } startEnrolling() { return this.handleMethod('startEnrolling'); } cancelEnrollment() { return this.methodCalled('cancelEnrollment'); } deleteEnrollment(id: string) { return this.handleMethod('deleteEnrollment', id); } renameEnrollment(id: string, name: string) { return this.handleMethod('renameEnrollment', [id, name]); } close() { this.methodCalled('close'); } } function assertShown( allDivs: string[], dialog: HTMLElement, expectedID: string) { assertTrue(allDivs.includes(expectedID)); const allShown = allDivs.filter(id => { return dialog.shadowRoot!.querySelector(`#${id}`)!.className === 'iron-selected'; }); assertEquals(1, allShown.length); assertEquals(expectedID, allShown[0]); } suite('SecurityKeysResetDialog', function() { let dialog: SettingsSecurityKeysResetDialogElement; let allDivs: string[]; let browserProxy: TestSecurityKeysResetBrowserProxy; setup(function() { browserProxy = new TestSecurityKeysResetBrowserProxy(); SecurityKeysResetBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; dialog = document.createElement('settings-security-keys-reset-dialog'); allDivs = Object.values(ResetDialogPage); }); function assertComplete() { assertEquals(dialog.$.button.textContent!.trim(), 'OK'); assertEquals(dialog.$.button.className, 'action-button'); } function assertNotComplete() { assertEquals(dialog.$.button.textContent!.trim(), 'Cancel'); assertEquals(dialog.$.button.className, 'cancel-button'); } test('Initialization', async function() { document.body.appendChild(dialog); await browserProxy.whenCalled('reset'); assertShown(allDivs, dialog, 'initial'); assertNotComplete(); }); test('Cancel', async function() { document.body.appendChild(dialog); await browserProxy.whenCalled('reset'); assertShown(allDivs, dialog, 'initial'); assertNotComplete(); dialog.$.button.click(); await browserProxy.whenCalled('close'); assertFalse(dialog.$.dialog.open); }); test('NotSupported', async function() { browserProxy.setResponseFor( 'reset', Promise.resolve(1 /* INVALID_COMMAND */)); document.body.appendChild(dialog); await browserProxy.whenCalled('reset'); await browserProxy.whenCalled('close'); assertComplete(); assertShown(allDivs, dialog, 'noReset'); }); test('ImmediateUnknownError', async function() { const error = 1000 /* undefined error code */; browserProxy.setResponseFor('reset', Promise.resolve(error)); document.body.appendChild(dialog); await browserProxy.whenCalled('reset'); await browserProxy.whenCalled('close'); assertComplete(); assertShown(allDivs, dialog, 'resetFailed'); assertTrue( dialog.$.resetFailed.textContent!.trim().includes(error.toString())); }); test('ImmediateUnknownError', async function() { browserProxy.setResponseFor('reset', Promise.resolve(0 /* success */)); const promiseResolver = new PromiseResolver(); browserProxy.setResponseFor('completeReset', promiseResolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('reset'); await browserProxy.whenCalled('completeReset'); assertNotComplete(); assertShown(allDivs, dialog, 'resetConfirm'); promiseResolver.resolve(0 /* success */); await browserProxy.whenCalled('close'); assertComplete(); assertShown(allDivs, dialog, 'resetSuccess'); }); test('UnknownError', async function() { const error = 1000 /* undefined error code */; browserProxy.setResponseFor('reset', Promise.resolve(0 /* success */)); browserProxy.setResponseFor('completeReset', Promise.resolve(error)); document.body.appendChild(dialog); await browserProxy.whenCalled('reset'); await browserProxy.whenCalled('completeReset'); await browserProxy.whenCalled('close'); assertComplete(); assertShown(allDivs, dialog, 'resetFailed'); assertTrue( dialog.$.resetFailed.textContent!.trim().includes(error.toString())); }); test('ResetRejected', async function() { browserProxy.setResponseFor('reset', Promise.resolve(0 /* success */)); browserProxy.setResponseFor( 'completeReset', Promise.resolve(48 /* NOT_ALLOWED */)); document.body.appendChild(dialog); await browserProxy.whenCalled('reset'); await browserProxy.whenCalled('completeReset'); await browserProxy.whenCalled('close'); assertComplete(); assertShown(allDivs, dialog, 'resetNotAllowed'); }); }); suite('SecurityKeysSetPINDialog', function() { const tooShortCurrentPIN = 'abcd'; const validCurrentPIN = 'abcdef'; const tooShortNewPIN = '123456'; const validNewPIN = '12345678'; const anotherValidNewPIN = '87654321'; let dialog: SettingsSecurityKeysSetPinDialogElement; let allDivs: string[]; let browserProxy: TestSecurityKeysPINBrowserProxy; setup(function() { browserProxy = new TestSecurityKeysPINBrowserProxy(); SecurityKeysPINBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; dialog = document.createElement('settings-security-keys-set-pin-dialog'); allDivs = Object.values(SetPINDialogPage); }); function assertComplete() { assertEquals(dialog.$.closeButton.textContent!.trim(), 'OK'); assertEquals(dialog.$.closeButton.className, 'action-button'); assertEquals(dialog.$.pinSubmit.hidden, true); } function assertNotComplete() { assertEquals(dialog.$.closeButton.textContent!.trim(), 'Cancel'); assertEquals(dialog.$.closeButton.className, 'cancel-button'); assertEquals(dialog.$.pinSubmit.hidden, false); } test('Initialization', async function() { document.body.appendChild(dialog); await browserProxy.whenCalled('startSetPIN'); assertShown(allDivs, dialog, 'initial'); assertNotComplete(); }); // Test error codes that are returned immediately. for (const testCase of [ [1 /* INVALID_COMMAND */, 'noPINSupport'], [52 /* temporary lock */, 'reinsert'], [50 /* locked */, 'locked'], [1000 /* invalid error */, 'error']]) { test('ImmediateError' + testCase[0]!.toString(), async function() { browserProxy.setResponseFor( 'startSetPIN', Promise.resolve({done: true, error: testCase[0]})); document.body.appendChild(dialog); await browserProxy.whenCalled('startSetPIN'); await browserProxy.whenCalled('close'); assertComplete(); assertShown(allDivs, dialog, (testCase[1] as string)); if (testCase[1] === 'error') { // Unhandled error codes display the numeric code. assertTrue(dialog.$.error.textContent!.trim().includes( testCase[0]!.toString())); } }); } test('ZeroRetries', async function() { // Authenticators can also signal that they are locked by indicating zero // attempts remaining. browserProxy.setResponseFor('startSetPIN', Promise.resolve({ done: false, error: null, currentMinPinLength, newMinPinLength, retries: 0, })); document.body.appendChild(dialog); await browserProxy.whenCalled('startSetPIN'); await browserProxy.whenCalled('close'); assertComplete(); assertShown(allDivs, dialog, 'locked'); }); function setPINEntry(inputElement: CrInputElement, pinValue: string) { inputElement.value = pinValue; // Dispatch input events to trigger validation and UI updates. inputElement.dispatchEvent( new CustomEvent('input', {bubbles: true, cancelable: true})); } function setNewPINEntries( pinValue: string, confirmPINValue: string): Promise<void> { setPINEntry(dialog.$.newPIN, pinValue); setPINEntry(dialog.$.confirmPIN, confirmPINValue); const ret = eventToPromise('ui-ready', dialog); dialog.$.pinSubmit.click(); return ret; } function setChangePINEntries( currentPINValue: string, pinValue: string, confirmPINValue: string): Promise<void> { setPINEntry(dialog.$.newPIN, pinValue); setPINEntry(dialog.$.confirmPIN, confirmPINValue); setPINEntry(dialog.$.currentPIN, currentPINValue); const ret = eventToPromise('ui-ready', dialog); dialog.$.pinSubmit.click(); return ret; } test('SetPIN', async function() { const startSetPINResolver = new PromiseResolver(); browserProxy.setResponseFor('startSetPIN', startSetPINResolver.promise); document.body.appendChild(dialog); const uiReady = eventToPromise('ui-ready', dialog); await browserProxy.whenCalled('startSetPIN'); startSetPINResolver.resolve({ done: false, error: null, currentMinPinLength, newMinPinLength, retries: null, }); await uiReady; assertNotComplete(); assertShown(allDivs, dialog, 'pinPrompt'); assertTrue(dialog.$.currentPINEntry.hidden); await setNewPINEntries(tooShortNewPIN, ''); assertTrue(dialog.$.newPIN.invalid); assertFalse(dialog.$.confirmPIN.invalid); await setNewPINEntries(tooShortNewPIN, tooShortNewPIN); assertTrue(dialog.$.newPIN.invalid); assertFalse(dialog.$.confirmPIN.invalid); await setNewPINEntries(validNewPIN, anotherValidNewPIN); assertFalse(dialog.$.newPIN.invalid); assertTrue(dialog.$.confirmPIN.invalid); const setPINResolver = new PromiseResolver(); browserProxy.setResponseFor('setPIN', setPINResolver.promise); setNewPINEntries(validNewPIN, validNewPIN); const {oldPIN, newPIN} = await browserProxy.whenCalled('setPIN'); assertTrue(dialog.$.pinSubmit.disabled); assertEquals(oldPIN, ''); assertEquals(newPIN, validNewPIN); setPINResolver.resolve({done: true, error: 0}); await browserProxy.whenCalled('close'); assertShown(allDivs, dialog, 'success'); assertComplete(); }); // Test error codes that are only returned after attempting to set a PIN. for (const testCase of [ [52 /* temporary lock */, 'reinsert'], [50 /* locked */, 'locked'], [1000 /* invalid error */, 'error']]) { test('Error' + testCase[0]!.toString(), async function() { const startSetPINResolver = new PromiseResolver(); browserProxy.setResponseFor('startSetPIN', startSetPINResolver.promise); document.body.appendChild(dialog); const uiReady = eventToPromise('ui-ready', dialog); await browserProxy.whenCalled('startSetPIN'); startSetPINResolver.resolve({ done: false, error: null, currentMinPinLength, newMinPinLength, retries: null, }); await uiReady; browserProxy.setResponseFor( 'setPIN', Promise.resolve({done: true, error: testCase[0]})); setNewPINEntries(validNewPIN, validNewPIN); await browserProxy.whenCalled('setPIN'); await browserProxy.whenCalled('close'); assertComplete(); assertShown(allDivs, dialog, (testCase[1] as string)); if (testCase[1] === 'error') { // Unhandled error codes display the numeric code. assertTrue(dialog.$.error.textContent!.trim().includes( testCase[0]!.toString())); } }); } test('ChangePIN', async function() { const startSetPINResolver = new PromiseResolver(); browserProxy.setResponseFor('startSetPIN', startSetPINResolver.promise); document.body.appendChild(dialog); let uiReady = eventToPromise('ui-ready', dialog); await browserProxy.whenCalled('startSetPIN'); startSetPINResolver.resolve({ done: false, error: null, currentMinPinLength, newMinPinLength, retries: 2, }); await uiReady; assertNotComplete(); assertShown(allDivs, dialog, 'pinPrompt'); assertFalse(dialog.$.currentPINEntry.hidden); setChangePINEntries(tooShortCurrentPIN, '', ''); assertTrue(dialog.$.currentPIN.invalid); assertFalse(dialog.$.newPIN.invalid); assertFalse(dialog.$.confirmPIN.invalid); setChangePINEntries(tooShortCurrentPIN, tooShortNewPIN, ''); assertTrue(dialog.$.currentPIN.invalid); assertFalse(dialog.$.newPIN.invalid); assertFalse(dialog.$.confirmPIN.invalid); setChangePINEntries(validCurrentPIN, tooShortNewPIN, validNewPIN); assertFalse(dialog.$.currentPIN.invalid); assertTrue(dialog.$.newPIN.invalid); assertFalse(dialog.$.confirmPIN.invalid); setChangePINEntries(tooShortCurrentPIN, validNewPIN, validNewPIN); assertTrue(dialog.$.currentPIN.invalid); assertFalse(dialog.$.newPIN.invalid); assertFalse(dialog.$.confirmPIN.invalid); setChangePINEntries(validNewPIN, validNewPIN, validNewPIN); assertFalse(dialog.$.currentPIN.invalid); assertTrue(dialog.$.newPIN.invalid); assertEquals( dialog.$.newPIN.errorMessage, loadTimeData.getString('securityKeysSamePINAsCurrent')); assertFalse(dialog.$.confirmPIN.invalid); let setPINResolver = new PromiseResolver(); browserProxy.setResponseFor('setPIN', setPINResolver.promise); setPINEntry(dialog.$.currentPIN, validCurrentPIN); setPINEntry(dialog.$.newPIN, validNewPIN); setPINEntry(dialog.$.confirmPIN, validNewPIN); dialog.$.pinSubmit.click(); let {oldPIN, newPIN} = await browserProxy.whenCalled('setPIN'); assertShown(allDivs, dialog, 'pinPrompt'); assertNotComplete(); assertTrue(dialog.$.pinSubmit.disabled); assertEquals(oldPIN, validCurrentPIN); assertEquals(newPIN, validNewPIN); // Simulate an incorrect PIN. uiReady = eventToPromise('ui-ready', dialog); setPINResolver.resolve({done: true, error: 49}); await uiReady; assertTrue(dialog.$.currentPIN.invalid); // Text box for current PIN should not be cleared. assertEquals(dialog.$.currentPIN.value, validCurrentPIN); setPINEntry(dialog.$.currentPIN, anotherValidNewPIN); browserProxy.resetResolver('setPIN'); setPINResolver = new PromiseResolver(); browserProxy.setResponseFor('setPIN', setPINResolver.promise); dialog.$.pinSubmit.click(); ({oldPIN, newPIN} = await browserProxy.whenCalled('setPIN')); assertTrue(dialog.$.pinSubmit.disabled); assertEquals(oldPIN, anotherValidNewPIN); assertEquals(newPIN, validNewPIN); setPINResolver.resolve({done: true, error: 0}); await browserProxy.whenCalled('close'); assertShown(allDivs, dialog, 'success'); assertComplete(); }); }); suite('SecurityKeysCredentialManagement', function() { let dialog: SettingsSecurityKeysCredentialManagementDialogElement; let allDivs: string[]; let browserProxy: TestSecurityKeysCredentialBrowserProxy; setup(function() { browserProxy = new TestSecurityKeysCredentialBrowserProxy(); SecurityKeysCredentialBrowserProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; dialog = document.createElement( 'settings-security-keys-credential-management-dialog'); allDivs = Object.values(CredentialManagementDialogPage); }); test('Initialization', async function() { document.body.appendChild(dialog); await browserProxy.whenCalled('startCredentialManagement'); assertShown(allDivs, dialog, 'initial'); }); test('Cancel', async function() { document.body.appendChild(dialog); await browserProxy.whenCalled('startCredentialManagement'); assertShown(allDivs, dialog, 'initial'); dialog.$.cancelButton.click(); await browserProxy.whenCalled('close'); assertFalse(dialog.$.dialog.open); }); test('Finished', async function() { const startResolver = new PromiseResolver(); browserProxy.setResponseFor( 'startCredentialManagement', startResolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('startCredentialManagement'); assertShown(allDivs, dialog, 'initial'); startResolver.resolve({ minPinLength: currentMinPinLength, supportsUpdateUserInformation: true, }); const error = 'foo bar baz'; webUIListenerCallback( 'security-keys-credential-management-finished', error); assertShown(allDivs, dialog, 'pinError'); assertTrue(dialog.$.error.textContent!.trim().includes(error)); }); test('PINChangeError', async function() { const startResolver = new PromiseResolver(); browserProxy.setResponseFor( 'startCredentialManagement', startResolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('startCredentialManagement'); assertShown(allDivs, dialog, 'initial'); startResolver.resolve({ minPinLength: currentMinPinLength, supportsUpdateUserInformation: true, }); const error = 'foo bar baz'; webUIListenerCallback( 'security-keys-credential-management-finished', error, true /* requiresPINChange */); assertShown(allDivs, dialog, 'pinError'); assertFalse(dialog.$.confirmButton.hidden); assertFalse(dialog.$.confirmButton.disabled); assertTrue(dialog.$.pinError.textContent!.trim().includes(error)); const setPinEvent = eventToPromise('credential-management-set-pin', dialog); dialog.$.confirmButton.click(); await setPinEvent; }); test('UpdateNotSupported', async function() { const startCredentialManagementResolver = new PromiseResolver(); browserProxy.setResponseFor( 'startCredentialManagement', startCredentialManagementResolver.promise); const pinResolver = new PromiseResolver(); browserProxy.setResponseFor('providePIN', pinResolver.promise); const enumerateResolver = new PromiseResolver(); browserProxy.setResponseFor( 'enumerateCredentials', enumerateResolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('startCredentialManagement'); assertShown(allDivs, dialog, 'initial'); // Simulate PIN entry. let uiReady = eventToPromise( 'credential-management-dialog-ready-for-testing', dialog); startCredentialManagementResolver.resolve({ minPinLength: currentMinPinLength, supportsUpdateUserInformation: false, }); await uiReady; assertShown(allDivs, dialog, 'pinPrompt'); assertEquals(currentMinPinLength, dialog.$.pin.minPinLength); dialog.$.pin.$.pin.value = '000000'; dialog.$.confirmButton.click(); const pin = await browserProxy.whenCalled('providePIN'); assertEquals(pin, '000000'); // Show a credential. pinResolver.resolve(null); await browserProxy.whenCalled('enumerateCredentials'); uiReady = eventToPromise( 'credential-management-dialog-ready-for-testing', dialog); const credentials = [ { credentialId: 'aaaaaa', relyingPartyId: 'acme.com', userHandle: 'userausera', userName: 'userA@example.com', userDisplayName: 'User Aaa', }, ]; enumerateResolver.resolve(credentials); await uiReady; assertShown(allDivs, dialog, 'credentials'); assertEquals(dialog.$.credentialList.items, credentials); // Check that the edit button is disabled. flush(); const editButtons: Array<CrIconButtonElement> = Array.from(dialog.$.credentialList.querySelectorAll('.edit-button')); assertEquals(editButtons.length, 1); assertTrue(editButtons[0]!.hidden); }); test('Credentials', async function() { const startCredentialManagementResolver = new PromiseResolver(); browserProxy.setResponseFor( 'startCredentialManagement', startCredentialManagementResolver.promise); const pinResolver = new PromiseResolver(); browserProxy.setResponseFor('providePIN', pinResolver.promise); const enumerateResolver = new PromiseResolver(); browserProxy.setResponseFor( 'enumerateCredentials', enumerateResolver.promise); const deleteResolver = new PromiseResolver(); browserProxy.setResponseFor('deleteCredentials', deleteResolver.promise); const updateUserInformationResolver = new PromiseResolver(); browserProxy.setResponseFor( 'updateUserInformation', updateUserInformationResolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('startCredentialManagement'); assertShown(allDivs, dialog, 'initial'); // Simulate PIN entry. let uiReady = eventToPromise( 'credential-management-dialog-ready-for-testing', dialog); startCredentialManagementResolver.resolve({ minPinLength: currentMinPinLength, supportsUpdateUserInformation: true, }); await uiReady; assertShown(allDivs, dialog, 'pinPrompt'); assertEquals(currentMinPinLength, dialog.$.pin.minPinLength); dialog.$.pin.$.pin.value = '000000'; dialog.$.confirmButton.click(); const pin = await browserProxy.whenCalled('providePIN'); assertEquals(pin, '000000'); // Show a list of three credentials. pinResolver.resolve(null); await browserProxy.whenCalled('enumerateCredentials'); uiReady = eventToPromise( 'credential-management-dialog-ready-for-testing', dialog); const credentials = [ { credentialId: 'aaaaaa', relyingPartyId: 'acme.com', userHandle: 'userausera', userName: 'userA@example.com', userDisplayName: 'User Aaa', }, { credentialId: 'bbbbbb', relyingPartyId: 'acme.com', userHandle: 'userbuserb', userName: 'userB@example.com', userDisplayName: 'User Bbb', }, { credentialId: 'cccccc', relyingPartyId: 'acme.com', userHandle: 'usercuserc', userName: 'userC@example.com', userDisplayName: 'User Ccc', }, ]; enumerateResolver.resolve(credentials); await uiReady; assertShown(allDivs, dialog, 'credentials'); assertEquals(dialog.$.credentialList.items, credentials); // Update a credential flush(); const editButtons: Array<CrIconButtonElement> = Array.from(dialog.$.credentialList.querySelectorAll('.edit-button')); assertEquals(editButtons.length, 3); editButtons.forEach(button => assertFalse(button.hidden)); editButtons[0]!.click(); assertShown(allDivs, dialog, 'edit'); dialog.$.displayNameInput.value = 'Bobby Example'; dialog.$.userNameInput.value = 'bobby@example.com'; dialog.$.confirmButton.click(); credentials[0]!.userDisplayName = 'Bobby Example'; credentials[0]!.userName = 'bobby@example.com'; updateUserInformationResolver.resolve({success: true, message: 'updated'}); assertShown(allDivs, dialog, 'credentials'); assertDeepEquals(dialog.$.credentialList.items, credentials); // Delete a credential. flush(); const deleteButtons: Array<CrIconButtonElement> = Array.from(dialog.$.credentialList.querySelectorAll('.delete-button')); assertEquals(deleteButtons.length, 3); deleteButtons[0]!.click(); assertShown(allDivs, dialog, 'confirm'); dialog.$.confirmButton.click(); const credentialIds = await browserProxy.whenCalled('deleteCredentials'); assertDeepEquals(credentialIds, ['aaaaaa']); uiReady = eventToPromise( 'credential-management-dialog-ready-for-testing', dialog); deleteResolver.resolve({success: true, message: 'foobar'}); await uiReady; assertShown(allDivs, dialog, 'credentials'); }); }); suite('SecurityKeysBioEnrollment', function() { let dialog: SettingsSecurityKeysBioEnrollDialogElement; let allDivs: string[]; let browserProxy: TestSecurityKeysBioEnrollProxy; setup(function() { browserProxy = new TestSecurityKeysBioEnrollProxy(); SecurityKeysBioEnrollProxyImpl.setInstance(browserProxy); document.body.innerHTML = ''; dialog = document.createElement('settings-security-keys-bio-enroll-dialog'); allDivs = Object.values(BioEnrollDialogPage); }); test('Initialization', async function() { document.body.appendChild(dialog); await browserProxy.whenCalled('startBioEnroll'); assertShown(allDivs, dialog, 'initial'); assertFalse(dialog.$.cancelButton.hidden); }); test('Cancel', async function() { document.body.appendChild(dialog); await browserProxy.whenCalled('startBioEnroll'); assertShown(allDivs, dialog, 'initial'); dialog.$.cancelButton.click(); await browserProxy.whenCalled('close'); assertFalse(dialog.$.dialog.open); }); test('Finished', async function() { const resolver = new PromiseResolver(); browserProxy.setResponseFor('startBioEnroll', resolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('startBioEnroll'); assertShown(allDivs, dialog, 'initial'); resolver.resolve([currentMinPinLength]); const error = 'foo bar baz'; webUIListenerCallback('security-keys-bio-enroll-error', error); assertShown(allDivs, dialog, 'error'); assertTrue(dialog.$.confirmButton.hidden); assertTrue(dialog.$.error.textContent!.trim().includes(error)); }); test('PINChangeError', async function() { const resolver = new PromiseResolver(); browserProxy.setResponseFor('startBioEnroll', resolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('startBioEnroll'); assertShown(allDivs, dialog, 'initial'); resolver.resolve([currentMinPinLength]); const error = 'something about setting a new PIN'; webUIListenerCallback( 'security-keys-bio-enroll-error', error, true /* requiresPINChange */); assertShown(allDivs, dialog, 'error'); assertFalse(dialog.$.confirmButton.hidden); assertFalse(dialog.$.confirmButton.disabled); assertTrue(dialog.$.error.textContent!.trim().includes(error)); const setPinEvent = eventToPromise('bio-enroll-set-pin', dialog); dialog.$.confirmButton.click(); await setPinEvent; }); test('Enrollments', async function() { const startResolver = new PromiseResolver(); browserProxy.setResponseFor('startBioEnroll', startResolver.promise); const pinResolver = new PromiseResolver(); browserProxy.setResponseFor('providePIN', pinResolver.promise); const getSensorInfoResolver = new PromiseResolver(); browserProxy.setResponseFor('getSensorInfo', getSensorInfoResolver.promise); const enumerateResolver = new PromiseResolver(); browserProxy.setResponseFor( 'enumerateEnrollments', enumerateResolver.promise); const deleteResolver = new PromiseResolver(); browserProxy.setResponseFor('deleteEnrollment', deleteResolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('startBioEnroll'); assertShown(allDivs, dialog, 'initial'); // Simulate PIN entry. let uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); startResolver.resolve([currentMinPinLength]); await uiReady; assertShown(allDivs, dialog, 'pinPrompt'); assertEquals(currentMinPinLength, dialog.$.pin.minPinLength); dialog.$.pin.$.pin.value = '000000'; dialog.$.confirmButton.click(); const pin = await browserProxy.whenCalled('providePIN'); assertEquals(pin, '000000'); pinResolver.resolve(null); await browserProxy.whenCalled('getSensorInfo'); getSensorInfoResolver.resolve({ maxTemplateFriendlyName: 10, }); // Show a list of three enrollments. await browserProxy.whenCalled('enumerateEnrollments'); uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); const fingerprintA = { name: 'FingerprintA', id: '1234', }; const fingerprintB = { name: 'FingerprintB', id: '4321', }; const fingerprintC = { name: 'FingerprintC', id: '000000', }; const enrollments = [fingerprintC, fingerprintB, fingerprintA]; const sortedEnrollments = [fingerprintA, fingerprintB, fingerprintC]; enumerateResolver.resolve(enrollments); await uiReady; assertShown(allDivs, dialog, 'enrollments'); assertDeepEquals(dialog.$.enrollmentList.items, sortedEnrollments); // Delete the second enrollments and refresh the list. flush(); dialog.$.enrollmentList.querySelectorAll('cr-icon-button')[1]!.click(); const id = await browserProxy.whenCalled('deleteEnrollment'); assertEquals(sortedEnrollments[1]!.id, id); sortedEnrollments.splice(1, 1); enrollments.splice(1, 1); deleteResolver.resolve(enrollments); await uiReady; assertShown(allDivs, dialog, 'enrollments'); assertDeepEquals(dialog.$.enrollmentList.items, sortedEnrollments); }); test('AddEnrollment', async function() { const startResolver = new PromiseResolver(); browserProxy.setResponseFor('startBioEnroll', startResolver.promise); const pinResolver = new PromiseResolver(); browserProxy.setResponseFor('providePIN', pinResolver.promise); const getSensorInfoResolver = new PromiseResolver(); browserProxy.setResponseFor('getSensorInfo', getSensorInfoResolver.promise); const enumerateResolver = new PromiseResolver(); browserProxy.setResponseFor( 'enumerateEnrollments', enumerateResolver.promise); const enrollingResolver = new PromiseResolver(); browserProxy.setResponseFor('startEnrolling', enrollingResolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('startBioEnroll'); assertShown(allDivs, dialog, 'initial'); // Simulate PIN entry. let uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); startResolver.resolve([currentMinPinLength]); await uiReady; assertShown(allDivs, dialog, 'pinPrompt'); assertEquals(currentMinPinLength, dialog.$.pin.minPinLength); dialog.$.pin.$.pin.value = '000000'; dialog.$.confirmButton.click(); const pin = await browserProxy.whenCalled('providePIN'); assertEquals(pin, '000000'); pinResolver.resolve(null); await browserProxy.whenCalled('getSensorInfo'); getSensorInfoResolver.resolve({ maxTemplateFriendlyName: 20, }); // Ensure no enrollments exist. await browserProxy.whenCalled('enumerateEnrollments'); uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); enumerateResolver.resolve([]); await uiReady; assertShown(allDivs, dialog, 'enrollments'); assertEquals(dialog.$.enrollmentList.items!.length, 0); // Simulate add enrollment. assertFalse(dialog.$.addButton.hidden); uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); dialog.$.addButton.click(); await browserProxy.whenCalled('startEnrolling'); await uiReady; assertShown(allDivs, dialog, 'enroll'); webUIListenerCallback( 'security-keys-bio-enroll-status', {status: SampleStatus.OK, remaining: 1}); flush(); assertFalse(dialog.$.arc.isComplete()); assertFalse(dialog.$.cancelButton.hidden); assertTrue(dialog.$.confirmButton.hidden); uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); const enrollmentId = 'someId'; const enrollmentName = 'New Fingerprint'; enrollingResolver.resolve({ code: 0, enrollment: { id: enrollmentId, name: enrollmentName, }, }); await uiReady; assertTrue(dialog.$.arc.isComplete()); assertTrue(dialog.$.cancelButton.hidden); assertFalse(dialog.$.confirmButton.hidden); // Proceeding brings up rename dialog page. uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); dialog.$.confirmButton.click(); await uiReady; // Try renaming with a name that's longer than |maxTemplateFriendlyName|. assertShown(allDivs, dialog, 'chooseName'); assertEquals(dialog.$.enrollmentName.value, enrollmentName); const invalidNewEnrollmentName = '21 bytes long string!'; dialog.$.enrollmentName.value = invalidNewEnrollmentName; assertFalse(dialog.$.confirmButton.hidden); assertFalse(dialog.$.confirmButton.disabled); assertFalse(dialog.$.enrollmentName.invalid); dialog.$.confirmButton.click(); assertTrue(dialog.$.enrollmentName.invalid); assertEquals(browserProxy.getCallCount('renameEnrollment'), 0); // Try renaming to a valid name. assertShown(allDivs, dialog, 'chooseName'); const newEnrollmentName = '20 bytes long string'; dialog.$.enrollmentName.value = newEnrollmentName; assertFalse(dialog.$.confirmButton.hidden); assertFalse(dialog.$.confirmButton.disabled); // Proceeding renames the enrollment and returns to the enrollment overview. uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); const renameEnrollmentResolver = new PromiseResolver(); browserProxy.setResponseFor( 'renameEnrollment', renameEnrollmentResolver.promise); dialog.$.confirmButton.click(); assertFalse(dialog.$.enrollmentName.invalid); const renameArgs = await browserProxy.whenCalled('renameEnrollment'); assertDeepEquals(renameArgs, [enrollmentId, newEnrollmentName]); renameEnrollmentResolver.resolve([]); await uiReady; assertShown(allDivs, dialog, 'enrollments'); }); test('EnrollCancel', async function() { // Simulate starting an enrollment and then cancelling it. browserProxy.setResponseFor('enumerateEnrollments', Promise.resolve([])); const enrollResolver = new PromiseResolver; browserProxy.setResponseFor('startEnrolling', enrollResolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('startBioEnroll'); dialog.setDialogPageForTesting(BioEnrollDialogPage.ENROLLMENTS); // Forcibly disable the cancel button to ensure showing the dialog page // re-enables it. dialog.setCancelButtonDisabledForTesting(true); let uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); dialog.$.addButton.click(); await browserProxy.whenCalled('startEnrolling'); await uiReady; assertShown(allDivs, dialog, 'enroll'); assertFalse(dialog.$.cancelButton.disabled); assertFalse(dialog.$.cancelButton.hidden); uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); dialog.$.cancelButton.click(); await browserProxy.whenCalled('cancelEnrollment'); enrollResolver.resolve({code: Ctap2Status.ERR_KEEPALIVE_CANCEL}); await browserProxy.whenCalled('enumerateEnrollments'); await uiReady; assertShown(allDivs, dialog, 'enrollments'); }); test('EnrollError', async function() { // Test that resolving the startEnrolling promise with a CTAP error brings // up the error page. const enrollResolver = new PromiseResolver; browserProxy.setResponseFor('startEnrolling', enrollResolver.promise); document.body.appendChild(dialog); await browserProxy.whenCalled('startBioEnroll'); dialog.setDialogPageForTesting(BioEnrollDialogPage.ENROLLMENTS); let uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); dialog.$.addButton.click(); await browserProxy.whenCalled('startEnrolling'); await uiReady; uiReady = eventToPromise('bio-enroll-dialog-ready-for-testing', dialog); enrollResolver.resolve({code: Ctap2Status.ERR_INVALID_OPTION}); await uiReady; assertShown(allDivs, dialog, 'error'); }); });
the_stack
import { AfterViewInit, Component, Input, OnChanges } from '@angular/core'; import { ExerciseScoresChartService, ExerciseScoresDTO } from 'app/overview/visualizations/exercise-scores-chart.service'; import { AlertService } from 'app/core/util/alert.service'; import { onError } from 'app/shared/util/global.utils'; import { finalize } from 'rxjs/operators'; import { HttpErrorResponse } from '@angular/common/http'; import { ActivatedRoute } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { cloneDeep, sortBy } from 'lodash-es'; import { Color, ScaleType } from '@swimlane/ngx-charts'; import { round } from 'app/shared/util/utils'; import { ExerciseType } from 'app/entities/exercise.model'; import { faFilter } from '@fortawesome/free-solid-svg-icons'; import { ChartExerciseTypeFilterDirective } from 'app/shared/chart/chart-exercise-type-filter.directive'; import { GraphColors } from 'app/entities/statistics.model'; import { ArtemisNavigationUtilService } from 'app/utils/navigation.utils'; @Component({ selector: 'jhi-exercise-scores-chart', templateUrl: './exercise-scores-chart.component.html', styleUrls: ['./exercise-scores-chart.component.scss'], }) export class ExerciseScoresChartComponent extends ChartExerciseTypeFilterDirective implements AfterViewInit, OnChanges { @Input() filteredExerciseIDs: number[]; courseId: number; isLoading = false; exerciseScores: ExerciseScoresDTO[] = []; excludedExerciseScores: ExerciseScoresDTO[] = []; visibleExerciseScores: ExerciseScoresDTO[] = []; readonly Math = Math; readonly ExerciseType = ExerciseType; readonly convertToMapKey = ChartExerciseTypeFilterDirective.convertToMapKey; // Icons faFilter = faFilter; // ngx ngxData: any[] = []; backUpData: any[] = []; xAxisLabel: string; yAxisLabel: string; ngxColor = { name: 'Performance in Exercises', selectable: true, group: ScaleType.Ordinal, domain: [GraphColors.BLUE, GraphColors.YELLOW, GraphColors.GREEN], } as Color; colorBase = [GraphColors.BLUE, GraphColors.YELLOW, GraphColors.GREEN]; yourScoreLabel: string; averageScoreLabel: string; maximumScoreLabel: string; maxScale = 101; constructor( private navigationUtilService: ArtemisNavigationUtilService, private activatedRoute: ActivatedRoute, private alertService: AlertService, private exerciseScoresChartService: ExerciseScoresChartService, private translateService: TranslateService, ) { super(); this.translateService.onLangChange.subscribe(() => { this.setTranslations(); }); } ngAfterViewInit() { this.activatedRoute.parent?.parent?.params.subscribe((params) => { this.courseId = +params['courseId']; if (this.courseId) { this.loadDataAndInitializeChart(); } }); } ngOnChanges(): void { this.initializeChart(); } private loadDataAndInitializeChart(): void { this.isLoading = true; this.exerciseScoresChartService .getExerciseScoresForCourse(this.courseId) .pipe( finalize(() => { this.isLoading = false; }), ) .subscribe({ next: (exerciseScoresResponse) => { this.exerciseScores = exerciseScoresResponse.body!; this.initializeChart(); }, error: (errorResponse: HttpErrorResponse) => onError(this.alertService, errorResponse), }); } private initializeChart(): void { this.setTranslations(); this.exerciseScores = this.exerciseScores.concat(this.excludedExerciseScores); this.excludedExerciseScores = this.exerciseScores.filter((score) => this.filteredExerciseIDs.includes(score.exerciseId!)); this.exerciseScores = this.exerciseScores.filter((score) => !this.filteredExerciseIDs.includes(score.exerciseId!)); this.visibleExerciseScores = Array.of(...this.exerciseScores); // we show all the exercises ordered by their release data const sortedExerciseScores = sortBy(this.exerciseScores, (exerciseScore) => exerciseScore.releaseDate); this.initializeFilterOptions(sortedExerciseScores); this.addData(sortedExerciseScores); } /** * Converts the exerciseScoresDTOs into dedicated objects that can be processed by ngx-charts in order to * visualize the scores and pushes them to ngxData and backUpData * @param exerciseScoresDTOs array of objects containing the students score, the average score for this exercise and * the max score achieved for this exercise by a student as well as other detailed information of the exericse * @private */ private addData(exerciseScoresDTOs: ExerciseScoresDTO[]): void { this.ngxData = []; const scoreSeries: any[] = []; const averageSeries: any[] = []; const bestScoreSeries: any[] = []; exerciseScoresDTOs.forEach((exerciseScoreDTO) => { const extraInformation = { exerciseId: exerciseScoreDTO.exerciseId, exerciseType: exerciseScoreDTO.exerciseType, }; // adapt the y-axis max this.maxScale = Math.max( round(exerciseScoreDTO.scoreOfStudent!), round(exerciseScoreDTO.averageScoreAchieved!), round(exerciseScoreDTO.maxScoreAchieved!), this.maxScale, ); scoreSeries.push({ name: exerciseScoreDTO.exerciseTitle, value: round(exerciseScoreDTO.scoreOfStudent!) + 1, ...extraInformation }); averageSeries.push({ name: exerciseScoreDTO.exerciseTitle, value: round(exerciseScoreDTO.averageScoreAchieved!) + 1, ...extraInformation }); bestScoreSeries.push({ name: exerciseScoreDTO.exerciseTitle, value: round(exerciseScoreDTO.maxScoreAchieved!) + 1, ...extraInformation }); }); const studentScore = { name: this.yourScoreLabel, series: scoreSeries }; const averageScore = { name: this.averageScoreLabel, series: averageSeries }; const bestScore = { name: this.maximumScoreLabel, series: bestScoreSeries }; this.ngxData.push(studentScore); this.ngxData.push(averageScore); this.ngxData.push(bestScore); this.ngxData = [...this.ngxData]; this.backUpData = [...this.ngxData]; } /** * Provides the functionality when the user interacts with the chart by clicking on it. * If the users click on a node in the chart, they get delegated to the corresponding exercise detail page. * If the users click on an entry in the legend, the corresponding line disappears or reappears depending on its previous state * @param data the event sent by the framework */ onSelect(data: any): void { // delegate to the corresponding exercise if chart node is clicked if (data.exerciseId) { this.navigateToExercise(data.exerciseId); } else { // if a legend label is clicked, the corresponding line has to disappear or reappear const name = JSON.parse(JSON.stringify(data)) as string; // find the affected line in the dataset const index = this.ngxData.findIndex((dataPack: any) => { const dataName = dataPack.name as string; return dataName === name; }); // check whether the line is currently displayed if (this.ngxColor.domain[index] !== 'rgba(255,255,255,0)') { const placeHolder = cloneDeep(this.ngxData[index]); placeHolder.series.forEach((piece: any) => { piece.value = 0; }); // exchange actual line with all-zero line and make color transparent this.ngxData[index] = placeHolder; this.ngxColor.domain[index] = 'rgba(255,255,255,0)'; } else { // if the line is currently hidden, the color and the values are reset this.ngxColor.domain[index] = this.colorBase[index]; this.ngxData[index] = this.backUpData[index]; } // trigger a chart update this.ngxData = [...this.ngxData]; } } /** * We navigate to the exercise sub page in a new tab when the user clicks on a data point */ navigateToExercise(exerciseId: number): void { this.navigationUtilService.routeInNewTab(['courses', this.courseId, 'exercises', exerciseId]); } /** * Handles selection or deselection of specific exercise type * @param type the ExerciseType the user changed the filter for */ toggleType(type: ExerciseType): void { this.visibleExerciseScores = this.toggleExerciseType(type, this.exerciseScores); // we show all the exercises ordered by their release data const sortedExerciseScores = sortBy(this.visibleExerciseScores, (exerciseScore) => exerciseScore.releaseDate); this.addData(sortedExerciseScores); } /** * Auxiliary method that instantiated the translations for the exercise. * As we subscribe to language changes, this ensures that the chart is translated instantly if the user changes the language * @private */ private setTranslations(): void { this.xAxisLabel = this.translateService.instant('artemisApp.exercise-scores-chart.xAxis'); this.yAxisLabel = this.translateService.instant('artemisApp.exercise-scores-chart.yAxis'); this.yourScoreLabel = this.translateService.instant('artemisApp.exercise-scores-chart.yourScoreLabel'); this.averageScoreLabel = this.translateService.instant('artemisApp.exercise-scores-chart.averageScoreLabel'); this.maximumScoreLabel = this.translateService.instant('artemisApp.exercise-scores-chart.maximumScoreLabel'); if (this.ngxData.length > 0) { const labels = [this.yourScoreLabel, this.averageScoreLabel, this.maximumScoreLabel]; labels.forEach((label, index) => { this.ngxData[index].name = label; }); this.ngxData = [...this.ngxData]; } } }
the_stack
import { SearchableModelTransformer } from '@aws-amplify/graphql-searchable-transformer'; import { ModelTransformer } from '@aws-amplify/graphql-model-transformer'; import { ResourceConstants } from 'graphql-transformer-common'; import { AuthTransformer } from '@aws-amplify/graphql-auth-transformer'; import { GraphQLTransform } from '@aws-amplify/graphql-transformer-core'; import AWSAppSyncClient, { AUTH_TYPE } from 'aws-appsync'; import { CloudFormationClient } from '../CloudFormationClient'; import { S3Client } from '../S3Client'; import { Output } from 'aws-sdk/clients/cloudformation'; import { cleanupStackAfterTest, deploy } from '../deployNestedStacks'; import moment from 'moment'; import { S3, CognitoIdentityServiceProvider as CognitoClient, CognitoIdentity } from 'aws-sdk'; import { AWS } from '@aws-amplify/core'; import { Auth } from 'aws-amplify'; import { IAMHelper } from '../IAMHelper'; import gql from 'graphql-tag'; import { addUserToGroup, authenticateUser, configureAmplify, createGroup, createIdentityPool, createUserPool, createUserPoolClient, signupUser, } from '../cognitoUtils'; // to deal with bug in cognito-identity-js (global as any).fetch = require('node-fetch'); // To overcome of the way of how AmplifyJS picks up currentUserCredentials const anyAWS = AWS as any; if (anyAWS && anyAWS.config && anyAWS.config.credentials) { delete anyAWS.config.credentials; } // tslint:disable: no-magic-numbers jest.setTimeout(60000 * 60); const AWS_REGION = 'us-west-2'; const cf = new CloudFormationClient(AWS_REGION); const customS3Client = new S3Client(AWS_REGION); const awsS3Client = new S3({ region: AWS_REGION }); const cognitoClient = new CognitoClient({ apiVersion: '2016-04-19', region: AWS_REGION }); const identityClient = new CognitoIdentity({ apiVersion: '2014-06-30', region: AWS_REGION }); const iamHelper = new IAMHelper(AWS_REGION); const BUILD_TIMESTAMP = moment().format('YYYYMMDDHHmmss'); const STACK_NAME = `SearchableAuthV2Tests-${BUILD_TIMESTAMP}`; const BUCKET_NAME = `searchable-authv2-tests-bucket-${BUILD_TIMESTAMP}`; const LOCAL_FS_BUILD_DIR = '/tmp/searchable_authv2_tests/'; const S3_ROOT_DIR_KEY = 'deployments'; const AUTH_ROLE_NAME = `${STACK_NAME}-authRole`; const UNAUTH_ROLE_NAME = `${STACK_NAME}-unauthRole`; let USER_POOL_ID: string; let IDENTITY_POOL_ID: string; let GRAPHQL_ENDPOINT: string; let API_KEY: string; /** * Client 1 is logged in and has no group memberships. */ let GRAPHQL_CLIENT_1: AWSAppSyncClient<any> = undefined; /** * Client 2 is logged in and is a member of the admin and writer group. */ let GRAPHQL_CLIENT_2: AWSAppSyncClient<any> = undefined; /** * Client 3 is logged in and has no group memberships. */ let GRAPHQL_CLIENT_3: AWSAppSyncClient<any> = undefined; /** * Client 4 is logged in and is a member of the writer group */ let GRAPHQL_CLIENT_4: AWSAppSyncClient<any> = undefined; /** * Auth IAM Client */ let GRAPHQL_IAM_AUTH_CLIENT: AWSAppSyncClient<any> = undefined; /** * API Key Client */ let GRAPHQL_APIKEY_CLIENT: AWSAppSyncClient<any> = undefined; const USERNAME1 = 'user1@test.com'; const USERNAME2 = 'user2@test.com'; const USERNAME3 = 'user3@test.com'; const USERNAME4 = 'user4@test.com'; const TMP_PASSWORD = 'Password123!'; const REAL_PASSWORD = 'Password1234!'; const WRITER_GROUP_NAME = 'writer'; const ADMIN_GROUP_NAME = 'admin'; beforeAll(async () => { const validSchema = ` # Owners and Users in writer group # can execute crud operations their owned records. type Comment @model @searchable @auth(rules: [ { allow: owner } { allow: groups, groups: ["writer"]} ]) { id: ID! content: String } # only users in the admin group are authorized to view entries in DynamicContent type Todo @model @searchable @auth(rules: [ { allow: groups, groupsField: "groups"} ]) { id: ID! groups: String content: String } # users with apikey perform crud operations on Post except for secret # only users with auth role (iam) can view the secret # only private iam roles are allowed to run aggregations type Post @model @searchable @auth(rules: [ { allow: public, provider: apiKey } { allow: private, provider: iam } ]) { id: ID! content: String secret: String @auth(rules: [{ allow: private, provider: iam }]) } # only allow static group and dynamic group to have access on field type Blog @model @searchable @auth(rules: [{ allow: owner }, { allow: groups, groups: ["admin"] }, { allow: groups, groupsField: "groupsField" }]) { id: ID! title: String ups: Int downs: Int percentageUp: Float isPublished: Boolean createdAt: AWSDateTime updatedAt: AWSDateTime owner: String groupsField: String # as a member of admin and member within groupsField I can run aggregations on secret secret: String @auth(rules: [{ allow: groups, groups: ["admin"] }, { allow: groups, groupsField: "groupsField" }]) } `; const transformer = new GraphQLTransform({ authConfig: { defaultAuthentication: { authenticationType: 'AMAZON_COGNITO_USER_POOLS', }, additionalAuthenticationProviders: [ { authenticationType: 'API_KEY', apiKeyConfig: { description: 'E2E Test API Key', apiKeyExpirationDays: 300, }, }, { authenticationType: 'AWS_IAM', }, ], }, transformers: [new ModelTransformer(), new SearchableModelTransformer(), new AuthTransformer()], }); const userPoolResponse = await createUserPool(cognitoClient, `UserPool${STACK_NAME}`); USER_POOL_ID = userPoolResponse.UserPool.Id; const userPoolClientResponse = await createUserPoolClient(cognitoClient, USER_POOL_ID, `UserPool${STACK_NAME}`); const userPoolClientId = userPoolClientResponse.UserPoolClient.ClientId; // create auth and unauthroles const { authRole, unauthRole } = await iamHelper.createRoles(AUTH_ROLE_NAME, UNAUTH_ROLE_NAME); // create identitypool IDENTITY_POOL_ID = await createIdentityPool(identityClient, `IdentityPool${STACK_NAME}`, { authRoleArn: authRole.Arn, unauthRoleArn: unauthRole.Arn, providerName: `cognito-idp.${AWS_REGION}.amazonaws.com/${USER_POOL_ID}`, clientId: userPoolClientId, }); try { await awsS3Client.createBucket({ Bucket: BUCKET_NAME }).promise(); } catch (e) { console.error(`Failed to create bucket: ${e}`); } try { const out = transformer.transform(validSchema); const finishedStack = await deploy( customS3Client, cf, STACK_NAME, out, { AuthCognitoUserPoolId: USER_POOL_ID, authRoleName: authRole.RoleName, unauthRoleName: unauthRole.RoleName }, LOCAL_FS_BUILD_DIR, BUCKET_NAME, S3_ROOT_DIR_KEY, BUILD_TIMESTAMP, ); // Arbitrary wait to make sure everything is ready. await cf.wait(120, () => Promise.resolve()); expect(finishedStack).toBeDefined(); const getApiEndpoint = outputValueSelector(ResourceConstants.OUTPUTS.GraphQLAPIEndpointOutput); const getApiKey = outputValueSelector(ResourceConstants.OUTPUTS.GraphQLAPIApiKeyOutput); GRAPHQL_ENDPOINT = getApiEndpoint(finishedStack.Outputs); API_KEY = getApiKey(finishedStack.Outputs); expect(API_KEY).toBeDefined(); expect(GRAPHQL_ENDPOINT).toBeDefined(); expect(userPoolClientId).toBeTruthy(); // Configure Amplify, create users, and sign in configureAmplify(USER_POOL_ID, userPoolClientId, IDENTITY_POOL_ID); await signupUser(USER_POOL_ID, USERNAME1, TMP_PASSWORD); await signupUser(USER_POOL_ID, USERNAME2, TMP_PASSWORD); await signupUser(USER_POOL_ID, USERNAME3, TMP_PASSWORD); await signupUser(USER_POOL_ID, USERNAME4, TMP_PASSWORD); await createGroup(USER_POOL_ID, WRITER_GROUP_NAME); await createGroup(USER_POOL_ID, ADMIN_GROUP_NAME); await addUserToGroup(WRITER_GROUP_NAME, USERNAME4, USER_POOL_ID); await addUserToGroup(WRITER_GROUP_NAME, USERNAME2, USER_POOL_ID); await addUserToGroup(ADMIN_GROUP_NAME, USERNAME2, USER_POOL_ID); const authResAfterGroup: any = await authenticateUser(USERNAME1, TMP_PASSWORD, REAL_PASSWORD); const idToken = authResAfterGroup.getIdToken().getJwtToken(); GRAPHQL_CLIENT_1 = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, disableOffline: true, auth: { type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS, jwtToken: () => idToken, }, }); const authRes2AfterGroup: any = await authenticateUser(USERNAME2, TMP_PASSWORD, REAL_PASSWORD); const idToken2 = authRes2AfterGroup.getIdToken().getJwtToken(); GRAPHQL_CLIENT_2 = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, disableOffline: true, auth: { type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS, jwtToken: () => idToken2, }, }); const authRes3: any = await authenticateUser(USERNAME3, TMP_PASSWORD, REAL_PASSWORD); const idToken3 = authRes3.getIdToken().getJwtToken(); GRAPHQL_CLIENT_3 = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, disableOffline: true, auth: { type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS, jwtToken: () => idToken3, }, }); const authRes4: any = await authenticateUser(USERNAME4, TMP_PASSWORD, REAL_PASSWORD); const idToken4 = authRes4.getIdToken().getJwtToken(); GRAPHQL_CLIENT_4 = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, disableOffline: true, auth: { type: AUTH_TYPE.AMAZON_COGNITO_USER_POOLS, jwtToken: () => idToken4, }, }); // sign out previous cognito user await Auth.signOut(); await Auth.signIn(USERNAME1, REAL_PASSWORD); const authCreds = await Auth.currentCredentials(); GRAPHQL_IAM_AUTH_CLIENT = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, disableOffline: true, auth: { type: AUTH_TYPE.AWS_IAM, credentials: authCreds, }, }); GRAPHQL_APIKEY_CLIENT = new AWSAppSyncClient({ url: GRAPHQL_ENDPOINT, region: AWS_REGION, auth: { type: AUTH_TYPE.API_KEY, apiKey: API_KEY, }, disableOffline: true, }); // Create sample mutations to test search queries await createEntries(); } catch (e) { console.error(e); throw e; } }); afterAll(async () => { await cleanupStackAfterTest( BUCKET_NAME, STACK_NAME, cf, { cognitoClient, userPoolId: USER_POOL_ID }, { identityClient, identityPoolId: IDENTITY_POOL_ID }, ); try { await iamHelper.deleteRole(AUTH_ROLE_NAME); } catch (e) { console.warn(`Error during auth role cleanup ${e}`); } try { await iamHelper.deleteRole(UNAUTH_ROLE_NAME); } catch (e) { console.warn(`Error during unauth role cleanup ${e}`); } }); /** * Tests */ // cognito owner check test('test Comments as owner', async () => { const ownerResponse: any = await GRAPHQL_CLIENT_1.query({ query: gql` query SearchComments { searchComments { items { id content owner } nextToken } } `, }); expect(ownerResponse.data.searchComments).toBeDefined(); expect(ownerResponse.data.searchComments.items.length).toEqual(1); expect(ownerResponse.data.searchComments.items[0].content).toEqual('ownerContent'); }); // cognito static group check test('test Comments as user in writer group', async () => { const writerResponse: any = await GRAPHQL_CLIENT_2.query({ query: gql` query SearchComments { searchComments { items { id content owner } nextToken } } `, }); expect(writerResponse.data.searchComments).toBeDefined(); expect(writerResponse.data.searchComments.items.length).toEqual(4); // only ownerContent should have the owner name // because the group permission was met we did not populate an owner field // therefore there is no owner expect(writerResponse.data.searchComments.items).toEqual( expect.arrayContaining([ expect.objectContaining({ id: expect.any(String), content: 'ownerContent', owner: USERNAME1, }), expect.objectContaining({ id: expect.any(String), content: 'content1', owner: null, }), expect.objectContaining({ id: expect.any(String), content: 'content1', owner: null, }), expect.objectContaining({ id: expect.any(String), content: 'content3', owner: null, }), ]), ); }); // cognito test as unauthorized user test('test Comments as user that is not an owner nor is in writer group', async () => { const user3Response: any = await GRAPHQL_CLIENT_3.query({ query: gql` query SearchComments { searchComments { items { id content owner } nextToken } } `, }); expect(user3Response.data.searchComments).toBeDefined(); expect(user3Response.data.searchComments.items.length).toEqual(0); expect(user3Response.data.searchComments.nextToken).toBeNull(); }); // cognito dynamic group check test('test Todo as user in the dynamic group admin', async () => { const adminResponse: any = await GRAPHQL_CLIENT_2.query({ query: gql` query SearchTodos { searchTodos { items { id groups content } nextToken } } `, }); expect(adminResponse.data.searchTodos).toBeDefined(); expect(adminResponse.data.searchTodos.items.length).toEqual(3); expect(adminResponse.data.searchTodos.items).toEqual( expect.arrayContaining([ expect.objectContaining({ id: expect.any(String), content: 'adminContent1', groups: ADMIN_GROUP_NAME, }), expect.objectContaining({ id: expect.any(String), content: 'adminContent2', groups: ADMIN_GROUP_NAME, }), expect.objectContaining({ id: expect.any(String), content: 'adminContent3', groups: ADMIN_GROUP_NAME, }), ]), ); }); // iam test test('test Post as authorized user', async () => { const authUser: any = await GRAPHQL_IAM_AUTH_CLIENT.query({ query: gql` query SearchPosts { searchPosts { items { id content secret } nextToken } } `, }); expect(authUser.data.searchPosts).toBeDefined(); expect(authUser.data.searchPosts.items.length).toEqual(4); expect(authUser.data.searchPosts.items).toEqual( expect.arrayContaining([ expect.objectContaining({ id: expect.any(String), content: 'post2', secret: 'post2secret', }), expect.objectContaining({ id: expect.any(String), content: 'post1', secret: 'post1secret', }), expect.objectContaining({ id: expect.any(String), content: 'post3', secret: 'post3secret', }), expect.objectContaining({ id: expect.any(String), content: 'publicPost', secret: null, }), ]), ); }); // test apikey 2nd scenario test('test searchPosts with apikey and secret removed', async () => { const apiKeyResponse: any = await GRAPHQL_APIKEY_CLIENT.query({ query: gql` query SearchPosts { searchPosts { items { id content } nextToken } } `, }); expect(apiKeyResponse.data.searchPosts).toBeDefined(); expect(apiKeyResponse.data.searchPosts.items).toHaveLength(4); expect(apiKeyResponse.data.searchPosts.items).toEqual( expect.arrayContaining([ expect.objectContaining({ id: expect.any(String), content: 'post2', }), expect.objectContaining({ id: expect.any(String), content: 'post1', }), expect.objectContaining({ id: expect.any(String), content: 'post3', }), expect.objectContaining({ id: expect.any(String), content: 'publicPost', }), ]), ); }); // test iam/apiKey schema with unauth user test('test post as an cognito user that is not allowed in this schema', async () => { try { await GRAPHQL_CLIENT_3.query({ query: gql` query SearchPosts { searchPosts { items { id content secret } nextToken } } `, }); } catch (err) { expect(err.graphQLErrors[0].errorType).toEqual('Unauthorized'); expect(err.graphQLErrors[0].message).toEqual('Not Authorized to access searchPosts on type Query'); } }); test('test that apikey is not allowed to query aggregations on secret for post', async () => { try { await GRAPHQL_APIKEY_CLIENT.query({ query: gql` query aggSearch { searchPosts(aggregates: [{ name: "Terms", type: terms, field: secret }]) { aggregateItems { name result { ... on SearchableAggregateBucketResult { buckets { doc_count key } } } } } } `, }); } catch (err) { expect(err.graphQLErrors[0].errorType).toEqual('Unauthorized'); expect(err.graphQLErrors[0].message).toEqual('Unauthorized to run aggregation on field: secret'); } }); test('test that iam can run aggregations on secret field', async () => { try { const response: any = await GRAPHQL_IAM_AUTH_CLIENT.query({ query: gql` query aggSearch { searchPosts(aggregates: [{ name: "Terms", type: terms, field: secret }]) { aggregateItems { name result { ... on SearchableAggregateBucketResult { buckets { doc_count key } } } } } } `, }); expect(response.data.searchPosts).toBeDefined(); expect(response.data.searchPosts.aggregateItems).toHaveLength(1); const aggregateItem = response.data.searchPosts.aggregateItems[0]; expect(aggregateItem.name).toEqual('Terms'); expect(aggregateItem.result.buckets).toHaveLength(3); expect(aggregateItem.result.buckets).toEqual( expect.arrayContaining([ expect.objectContaining({ doc_count: 1, key: 'post1secret', }), expect.objectContaining({ doc_count: 1, key: 'post2secret', }), expect.objectContaining({ doc_count: 1, key: 'post3secret', }), ]), ); } catch (err) { expect(err).not.toBeDefined(); } }); test('test that admin can run aggregate query on protected field', async () => { try { const response: any = await GRAPHQL_CLIENT_2.query({ query: gql` query { searchBlogs(aggregates: [{ name: "Terms", type: terms, field: secret }]) { aggregateItems { name result { ... on SearchableAggregateBucketResult { buckets { doc_count key } } } } } } `, }); expect(response.data.searchBlogs).toBeDefined(); expect(response.data.searchBlogs.aggregateItems); const aggregateItem = response.data.searchBlogs.aggregateItems[0]; expect(aggregateItem.name).toEqual('Terms'); expect(aggregateItem.result.buckets).toHaveLength(2); expect(aggregateItem.result.buckets).toEqual( expect.arrayContaining([ expect.objectContaining({ doc_count: 2, key: `${USERNAME1}secret`, }), expect.objectContaining({ doc_count: 2, key: `${USERNAME4}secret`, }), ]), ); } catch (err) { expect(err).not.toBeDefined(); } }); test('test that member in writer group has writer group auth when running aggregate query', async () => { try { const response: any = await GRAPHQL_CLIENT_4.query({ query: gql` query { searchBlogs(aggregates: [{ name: "Terms", type: terms, field: secret }]) { aggregateItems { name result { ... on SearchableAggregateBucketResult { buckets { doc_count key } } } } } } `, }); expect(response.data.searchBlogs).toBeDefined(); expect(response.data.searchBlogs.aggregateItems); const aggregateItem = response.data.searchBlogs.aggregateItems[0]; expect(aggregateItem.name).toEqual('Terms'); expect(aggregateItem.result.buckets).toHaveLength(2); expect(aggregateItem.result.buckets).toEqual( expect.arrayContaining([ expect.objectContaining({ doc_count: 2, key: `${USERNAME1}secret`, }), expect.objectContaining({ doc_count: 1, key: `${USERNAME4}secret`, }), ]), ); } catch (err) { expect(err).not.toBeDefined(); } }); test('test that an owner does not get any results for the agg query on the secret field', async () => { try { const response: any = await GRAPHQL_CLIENT_1.query({ query: gql` query { searchBlogs(aggregates: [{ name: "Terms", type: terms, field: secret }]) { aggregateItems { name result { ... on SearchableAggregateBucketResult { buckets { doc_count key } } } } } } `, }); expect(response.data.searchBlogs).toBeDefined(); expect(response.data.searchBlogs.aggregateItems); const aggregateItem = response.data.searchBlogs.aggregateItems[0]; expect(aggregateItem.name).toEqual('Terms'); expect(aggregateItem.result.buckets).toHaveLength(0); } catch (err) { expect(err).not.toBeDefined(); } }); test('test that an owner can run aggregations on records which belong to them', async () => { try { const response: any = await GRAPHQL_CLIENT_1.query({ query: gql` query { searchBlogs(aggregates: [{ name: "Terms", type: terms, field: title }]) { aggregateItems { name result { ... on SearchableAggregateBucketResult { buckets { doc_count key } } } } } } `, }); expect(response.data.searchBlogs).toBeDefined(); expect(response.data.searchBlogs.aggregateItems); const aggregateItem = response.data.searchBlogs.aggregateItems[0]; expect(aggregateItem.name).toEqual('Terms'); expect(aggregateItem.result.buckets).toHaveLength(1); expect(aggregateItem.result.buckets).toEqual( expect.arrayContaining([ expect.objectContaining({ doc_count: 2, key: 'cooking', }), ]), ); } catch (err) { expect(err).not.toBeDefined(); } }); /** * Input types * */ type CreateCommentInput = { id?: string | null; content?: string | null; }; type CreateTodoInput = { id?: string | null; groups?: string | null; content?: string | null; }; type CreatePostInput = { id?: string | null; content?: string | null; secret?: string | null; }; export type CreateBlogInput = { id?: string; title?: string; ups?: number; owner?: string; groupsField?: string; secret?: string; }; // mutations async function createComment(client: AWSAppSyncClient<any>, input: CreateCommentInput) { const create = gql` mutation CreateComment($input: CreateCommentInput!) { createComment(input: $input) { id content owner } } `; return await client.mutate({ mutation: create, variables: { input } }); } async function createTodo(client: AWSAppSyncClient<any>, input: CreateTodoInput) { const create = gql` mutation CreateTodo($input: CreateTodoInput!) { createTodo(input: $input) { id groups content } } `; return await client.mutate({ mutation: create, variables: { input } }); } async function createPost(client: AWSAppSyncClient<any>, input: CreatePostInput) { const create = gql` mutation CreatePost($input: CreatePostInput!) { createPost(input: $input) { id content } } `; return await client.mutate({ mutation: create, variables: { input } }); } async function createBlog(client: AWSAppSyncClient<any>, input: CreateBlogInput) { const create = gql` mutation CreateBlog($input: CreateBlogInput!) { createBlog(input: $input) { id title ups downs percentageUp isPublished createdAt updatedAt owner groupsField secret } } `; return await client.mutate({ mutation: create, variables: { input } }); } const createEntries = async () => { await createComment(GRAPHQL_CLIENT_1, { content: 'ownerContent', }); try { await createPost(GRAPHQL_APIKEY_CLIENT, { content: 'publicPost' }); } catch (err) { // will err since the secret is in the fields response though the post should still go through } for (let i = 1; i < 4; i++) { await createComment(GRAPHQL_CLIENT_2, { content: `content${i}` }); await createTodo(GRAPHQL_CLIENT_2, { groups: 'admin', content: `adminContent${i}` }); await createPost(GRAPHQL_IAM_AUTH_CLIENT, { content: `post${i}`, secret: `post${i}secret` }); } await createBlog(GRAPHQL_CLIENT_2, { groupsField: WRITER_GROUP_NAME, owner: USERNAME1, secret: `${USERNAME1}secret`, ups: 10, title: 'cooking', }); await createBlog(GRAPHQL_CLIENT_2, { groupsField: WRITER_GROUP_NAME, owner: USERNAME1, secret: `${USERNAME1}secret`, ups: 10, title: 'cooking', }); await createBlog(GRAPHQL_CLIENT_2, { groupsField: WRITER_GROUP_NAME, owner: USERNAME4, secret: `${USERNAME4}secret`, ups: 25, title: 'golfing', }); await createBlog(GRAPHQL_CLIENT_2, { groupsField: 'editor', owner: USERNAME4, secret: `${USERNAME4}secret`, ups: 10, title: 'cooking' }); // Waiting for the ES Cluster + Streaming Lambda infra to be setup await cf.wait(120, () => Promise.resolve()); }; function outputValueSelector(key: string) { return (outputs: Output[]) => { const output = outputs.find((o: Output) => o.OutputKey === key); return output ? output.OutputValue : null; }; }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Manages an Azure App Configuration Key. * * > **Note:** App Configuration Keys are provisioned using a Data Plane API which requires the role `App Configuration Data Owner` on either the App Configuration or a parent scope (such as the Resource Group/Subscription). [More information can be found in the Azure Documentation for App Configuration](https://docs.microsoft.com/azure/azure-app-configuration/concept-enable-rbac#azure-built-in-roles-for-azure-app-configuration). * * ## Example Usage * ### `Kv` Type * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const rg = new azure.core.ResourceGroup("rg", {location: "West Europe"}); * const appconf = new azure.appconfiguration.ConfigurationStore("appconf", { * resourceGroupName: rg.name, * location: rg.location, * }); * const current = azure.core.getClientConfig({}); * const appconfDataowner = new azure.authorization.Assignment("appconfDataowner", { * scope: appconf.id, * roleDefinitionName: "App Configuration Data Owner", * principalId: current.then(current => current.objectId), * }); * const test = new azure.appconfiguration.ConfigurationKey("test", { * configurationStoreId: appconf.id, * key: "appConfKey1", * label: "somelabel", * value: "a test", * }, { * dependsOn: [appconfDataowner], * }); * ``` * ### `Vault` Type * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const rg = new azure.core.ResourceGroup("rg", {location: "West Europe"}); * const appconf = new azure.appconfiguration.ConfigurationStore("appconf", { * resourceGroupName: rg.name, * location: rg.location, * }); * const current = azure.core.getClientConfig({}); * const kv = new azure.keyvault.KeyVault("kv", { * location: azurerm_resource_group.test.location, * resourceGroupName: azurerm_resource_group.test.name, * tenantId: current.then(current => current.tenantId), * skuName: "premium", * softDeleteRetentionDays: 7, * accessPolicies: [{ * tenantId: current.then(current => current.tenantId), * objectId: current.then(current => current.objectId), * keyPermissions: [ * "create", * "get", * ], * secretPermissions: [ * "set", * "get", * "delete", * "purge", * "recover", * ], * }], * }); * const kvs = new azure.keyvault.Secret("kvs", { * value: "szechuan", * keyVaultId: kv.id, * }); * const appconfDataowner = new azure.authorization.Assignment("appconfDataowner", { * scope: appconf.id, * roleDefinitionName: "App Configuration Data Owner", * principalId: current.then(current => current.objectId), * }); * const test = new azure.appconfiguration.ConfigurationKey("test", { * configurationStoreId: azurerm_app_configuration.test.id, * key: "key1", * type: "vault", * label: "label1", * vaultKeyReference: kvs.id, * }, { * dependsOn: [appconfDataowner], * }); * ``` * * ## Import * * App Configuration Keys can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:appconfiguration/configurationKey:ConfigurationKey test /subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resourceGroup1/providers/Microsoft.AppConfiguration/configurationStores/appConf1/AppConfigurationKey/appConfKey1/Label/label1 * ``` * * If you wish to import a key with an empty label then sustitute the label's name with `%00`, like this * * ```sh * $ pulumi import azure:appconfiguration/configurationKey:ConfigurationKey test /subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resourceGroup1/providers/Microsoft.AppConfiguration/configurationStores/appConf1/AppConfigurationKey/appConfKey1/Label/%00 * ``` */ export class ConfigurationKey extends pulumi.CustomResource { /** * Get an existing ConfigurationKey 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?: ConfigurationKeyState, opts?: pulumi.CustomResourceOptions): ConfigurationKey { return new ConfigurationKey(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:appconfiguration/configurationKey:ConfigurationKey'; /** * Returns true if the given object is an instance of ConfigurationKey. 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 ConfigurationKey { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === ConfigurationKey.__pulumiType; } /** * Specifies the id of the App Configuration. Changing this forces a new resource to be created. */ public readonly configurationStoreId!: pulumi.Output<string>; /** * The content type of the App Configuration Key. This should only be set when type is set to `kv`. */ public readonly contentType!: pulumi.Output<string>; /** * The ETag of the key. */ public readonly etag!: pulumi.Output<string>; /** * The name of the App Configuration Key to create. Changing this forces a new resource to be created. */ public readonly key!: pulumi.Output<string>; /** * The label of the App Configuration Key. Changing this forces a new resource to be created. */ public readonly label!: pulumi.Output<string | undefined>; /** * Should this App Configuration Key be Locked to prevent changes? */ public readonly locked!: pulumi.Output<boolean | undefined>; /** * A mapping of tags to assign to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * The type of the App Configuration Key. It can either be `kv` (simple [key/value](https://docs.microsoft.com/en-us/azure/azure-app-configuration/concept-key-value)) or `vault` (where the value is a reference to a [Key Vault Secret](https://azure.microsoft.com/en-gb/services/key-vault/). */ public readonly type!: pulumi.Output<string | undefined>; /** * The value of the App Configuration Key. This should only be set when type is set to `kv`. */ public readonly value!: pulumi.Output<string>; /** * The ID of the vault secret this App Configuration Key refers to, when `type` is set to `vault`. */ public readonly vaultKeyReference!: pulumi.Output<string | undefined>; /** * Create a ConfigurationKey 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: ConfigurationKeyArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: ConfigurationKeyArgs | ConfigurationKeyState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as ConfigurationKeyState | undefined; inputs["configurationStoreId"] = state ? state.configurationStoreId : undefined; inputs["contentType"] = state ? state.contentType : undefined; inputs["etag"] = state ? state.etag : undefined; inputs["key"] = state ? state.key : undefined; inputs["label"] = state ? state.label : undefined; inputs["locked"] = state ? state.locked : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["type"] = state ? state.type : undefined; inputs["value"] = state ? state.value : undefined; inputs["vaultKeyReference"] = state ? state.vaultKeyReference : undefined; } else { const args = argsOrState as ConfigurationKeyArgs | undefined; if ((!args || args.configurationStoreId === undefined) && !opts.urn) { throw new Error("Missing required property 'configurationStoreId'"); } if ((!args || args.key === undefined) && !opts.urn) { throw new Error("Missing required property 'key'"); } inputs["configurationStoreId"] = args ? args.configurationStoreId : undefined; inputs["contentType"] = args ? args.contentType : undefined; inputs["etag"] = args ? args.etag : undefined; inputs["key"] = args ? args.key : undefined; inputs["label"] = args ? args.label : undefined; inputs["locked"] = args ? args.locked : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["type"] = args ? args.type : undefined; inputs["value"] = args ? args.value : undefined; inputs["vaultKeyReference"] = args ? args.vaultKeyReference : undefined; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(ConfigurationKey.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering ConfigurationKey resources. */ export interface ConfigurationKeyState { /** * Specifies the id of the App Configuration. Changing this forces a new resource to be created. */ configurationStoreId?: pulumi.Input<string>; /** * The content type of the App Configuration Key. This should only be set when type is set to `kv`. */ contentType?: pulumi.Input<string>; /** * The ETag of the key. */ etag?: pulumi.Input<string>; /** * The name of the App Configuration Key to create. Changing this forces a new resource to be created. */ key?: pulumi.Input<string>; /** * The label of the App Configuration Key. Changing this forces a new resource to be created. */ label?: pulumi.Input<string>; /** * Should this App Configuration Key be Locked to prevent changes? */ locked?: pulumi.Input<boolean>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The type of the App Configuration Key. It can either be `kv` (simple [key/value](https://docs.microsoft.com/en-us/azure/azure-app-configuration/concept-key-value)) or `vault` (where the value is a reference to a [Key Vault Secret](https://azure.microsoft.com/en-gb/services/key-vault/). */ type?: pulumi.Input<string>; /** * The value of the App Configuration Key. This should only be set when type is set to `kv`. */ value?: pulumi.Input<string>; /** * The ID of the vault secret this App Configuration Key refers to, when `type` is set to `vault`. */ vaultKeyReference?: pulumi.Input<string>; } /** * The set of arguments for constructing a ConfigurationKey resource. */ export interface ConfigurationKeyArgs { /** * Specifies the id of the App Configuration. Changing this forces a new resource to be created. */ configurationStoreId: pulumi.Input<string>; /** * The content type of the App Configuration Key. This should only be set when type is set to `kv`. */ contentType?: pulumi.Input<string>; /** * The ETag of the key. */ etag?: pulumi.Input<string>; /** * The name of the App Configuration Key to create. Changing this forces a new resource to be created. */ key: pulumi.Input<string>; /** * The label of the App Configuration Key. Changing this forces a new resource to be created. */ label?: pulumi.Input<string>; /** * Should this App Configuration Key be Locked to prevent changes? */ locked?: pulumi.Input<boolean>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The type of the App Configuration Key. It can either be `kv` (simple [key/value](https://docs.microsoft.com/en-us/azure/azure-app-configuration/concept-key-value)) or `vault` (where the value is a reference to a [Key Vault Secret](https://azure.microsoft.com/en-gb/services/key-vault/). */ type?: pulumi.Input<string>; /** * The value of the App Configuration Key. This should only be set when type is set to `kv`. */ value?: pulumi.Input<string>; /** * The ID of the vault secret this App Configuration Key refers to, when `type` is set to `vault`. */ vaultKeyReference?: pulumi.Input<string>; }
the_stack
var utf8 = require('./utf8'); /** * Current protocol version. */ export const protocol = 3; const hasBinary = (packets) => { for (const packet of packets) { if (packet.data instanceof ArrayBuffer || ArrayBuffer.isView(packet.data)) { return true; } } return false; } /** * Packet types. */ export const packets = { open: 0 // non-ws , close: 1 // non-ws , ping: 2 , pong: 3 , message: 4 , upgrade: 5 , noop: 6 }; var packetslist = Object.keys(packets); /** * Premade error packet. */ var err = { type: 'error', data: 'parser error' }; const EMPTY_BUFFER = Buffer.concat([]); /** * Encodes a packet. * * <packet type id> [ <data> ] * * Example: * * 5hello world * 3 * 4 * * Binary is encoded in an identical principle * * @api private */ export function encodePacket (packet, supportsBinary, utf8encode, callback) { if (typeof supportsBinary === 'function') { callback = supportsBinary; supportsBinary = null; } if (typeof utf8encode === 'function') { callback = utf8encode; utf8encode = null; } if (Buffer.isBuffer(packet.data)) { return encodeBuffer(packet, supportsBinary, callback); } else if (packet.data && (packet.data.buffer || packet.data) instanceof ArrayBuffer) { return encodeBuffer({ type: packet.type, data: arrayBufferToBuffer(packet.data) }, supportsBinary, callback); } // Sending data as a utf-8 string var encoded = packets[packet.type]; // data fragment is optional if (undefined !== packet.data) { encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data); } return callback('' + encoded); }; /** * Encode Buffer data */ function encodeBuffer(packet, supportsBinary, callback) { if (!supportsBinary) { return encodeBase64Packet(packet, callback); } var data = packet.data; var typeBuffer = Buffer.allocUnsafe(1); typeBuffer[0] = packets[packet.type]; return callback(Buffer.concat([typeBuffer, data])); } /** * Encodes a packet with binary data in a base64 string * * @param {Object} packet, has `type` and `data` * @return {String} base64 encoded message */ export function encodeBase64Packet (packet, callback){ var data = Buffer.isBuffer(packet.data) ? packet.data : arrayBufferToBuffer(packet.data); var message = 'b' + packets[packet.type]; message += data.toString('base64'); return callback(message); }; /** * Decodes a packet. Data also available as an ArrayBuffer if requested. * * @return {Object} with `type` and `data` (if any) * @api private */ export function decodePacket (data, binaryType, utf8decode) { if (data === undefined) { return err; } var type; // String data if (typeof data === 'string') { type = data.charAt(0); if (type === 'b') { return decodeBase64Packet(data.substr(1), binaryType); } if (utf8decode) { data = tryDecode(data); if (data === false) { return err; } } if (Number(type) != type || !packetslist[type]) { return err; } if (data.length > 1) { return { type: packetslist[type], data: data.substring(1) }; } else { return { type: packetslist[type] }; } } // Binary data if (binaryType === 'arraybuffer') { // wrap Buffer/ArrayBuffer data into an Uint8Array var intArray = new Uint8Array(data); type = intArray[0]; return { type: packetslist[type], data: intArray.buffer.slice(1) }; } if (data instanceof ArrayBuffer) { data = arrayBufferToBuffer(data); } type = data[0]; return { type: packetslist[type], data: data.slice(1) }; }; function tryDecode(data) { try { data = utf8.decode(data, { strict: false }); } catch (e) { return false; } return data; } /** * Decodes a packet encoded in a base64 string. * * @param {String} base64 encoded message * @return {Object} with `type` and `data` (if any) */ export function decodeBase64Packet (msg, binaryType) { var type = packetslist[msg.charAt(0)]; var data = Buffer.from(msg.substr(1), 'base64'); if (binaryType === 'arraybuffer') { var abv = new Uint8Array(data.length); for (var i = 0; i < abv.length; i++){ abv[i] = data[i]; } // @ts-ignore data = abv.buffer; } return { type: type, data: data }; }; /** * Encodes multiple messages (payload). * * <length>:data * * Example: * * 11:hello world2:hi * * If any contents are binary, they will be encoded as base64 strings. Base64 * encoded strings are marked with a b before the length specifier * * @param {Array} packets * @api private */ export function encodePayload (packets, supportsBinary, callback) { if (typeof supportsBinary === 'function') { callback = supportsBinary; supportsBinary = null; } if (supportsBinary && hasBinary(packets)) { return encodePayloadAsBinary(packets, callback); } if (!packets.length) { return callback('0:'); } function encodeOne(packet, doneCallback) { encodePacket(packet, supportsBinary, false, function(message) { doneCallback(null, setLengthHeader(message)); }); } map(packets, encodeOne, function(err, results) { return callback(results.join('')); }); }; function setLengthHeader(message) { return message.length + ':' + message; } /** * Async array map using after */ function map(ary, each, done) { const results = new Array(ary.length); let count = 0; for (let i = 0; i < ary.length; i++) { each(ary[i], (error, msg) => { results[i] = msg; if (++count === ary.length) { done(null, results); } }); } } /* * Decodes data when a payload is maybe expected. Possible binary contents are * decoded from their base64 representation * * @param {String} data, callback method * @api public */ export function decodePayload (data, binaryType, callback) { if (typeof data !== 'string') { return decodePayloadAsBinary(data, binaryType, callback); } if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } if (data === '') { // parser error - ignoring payload return callback(err, 0, 1); } var length = '', n, msg, packet; for (var i = 0, l = data.length; i < l; i++) { var chr = data.charAt(i); if (chr !== ':') { length += chr; continue; } // @ts-ignore if (length === '' || (length != (n = Number(length)))) { // parser error - ignoring payload return callback(err, 0, 1); } msg = data.substr(i + 1, n); if (length != msg.length) { // parser error - ignoring payload return callback(err, 0, 1); } if (msg.length) { packet = decodePacket(msg, binaryType, false); if (err.type === packet.type && err.data === packet.data) { // parser error in individual packet - ignoring payload return callback(err, 0, 1); } var more = callback(packet, i + n, l); if (false === more) return; } // advance cursor i += n; length = ''; } if (length !== '') { // parser error - ignoring payload return callback(err, 0, 1); } }; /** * * Converts a buffer to a utf8.js encoded string * * @api private */ function bufferToString(buffer) { var str = ''; for (var i = 0, l = buffer.length; i < l; i++) { str += String.fromCharCode(buffer[i]); } return str; } /** * * Converts a utf8.js encoded string to a buffer * * @api private */ function stringToBuffer(string) { var buf = Buffer.allocUnsafe(string.length); for (var i = 0, l = string.length; i < l; i++) { buf.writeUInt8(string.charCodeAt(i), i); } return buf; } /** * * Converts an ArrayBuffer to a Buffer * * @api private */ function arrayBufferToBuffer(data) { // data is either an ArrayBuffer or ArrayBufferView. var length = data.byteLength || data.length; var offset = data.byteOffset || 0; return Buffer.from(data.buffer || data, offset, length); } /** * Encodes multiple messages (payload) as binary. * * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number * 255><data> * * Example: * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers * * @param {Array} packets * @return {Buffer} encoded payload * @api private */ export function encodePayloadAsBinary (packets, callback) { if (!packets.length) { return callback(EMPTY_BUFFER); } map(packets, encodeOneBinaryPacket, function(err, results) { return callback(Buffer.concat(results)); }); }; function encodeOneBinaryPacket(p, doneCallback) { function onBinaryPacketEncode(packet) { var encodingLength = '' + packet.length; var sizeBuffer; if (typeof packet === 'string') { sizeBuffer = Buffer.allocUnsafe(encodingLength.length + 2); sizeBuffer[0] = 0; // is a string (not true binary = 0) for (var i = 0; i < encodingLength.length; i++) { sizeBuffer[i + 1] = parseInt(encodingLength[i], 10); } sizeBuffer[sizeBuffer.length - 1] = 255; return doneCallback(null, Buffer.concat([sizeBuffer, stringToBuffer(packet)])); } sizeBuffer = Buffer.allocUnsafe(encodingLength.length + 2); sizeBuffer[0] = 1; // is binary (true binary = 1) for (var i = 0; i < encodingLength.length; i++) { sizeBuffer[i + 1] = parseInt(encodingLength[i], 10); } sizeBuffer[sizeBuffer.length - 1] = 255; doneCallback(null, Buffer.concat([sizeBuffer, packet])); } encodePacket(p, true, true, onBinaryPacketEncode); } /* * Decodes data when a payload is maybe expected. Strings are decoded by * interpreting each byte as a key code for entries marked to start with 0. See * description of encodePayloadAsBinary * @param {Buffer} data, callback method * @api public */ export function decodePayloadAsBinary (data, binaryType, callback) { if (typeof binaryType === 'function') { callback = binaryType; binaryType = null; } var bufferTail = data; var buffers = []; var i; while (bufferTail.length > 0) { var strLen = ''; var isString = bufferTail[0] === 0; for (i = 1; ; i++) { if (bufferTail[i] === 255) break; // 310 = char length of Number.MAX_VALUE if (strLen.length > 310) { return callback(err, 0, 1); } strLen += '' + bufferTail[i]; } bufferTail = bufferTail.slice(strLen.length + 1); var msgLength = parseInt(strLen, 10); var msg = bufferTail.slice(1, msgLength + 1); if (isString) msg = bufferToString(msg); buffers.push(msg); bufferTail = bufferTail.slice(msgLength + 1); } var total = buffers.length; for (i = 0; i < total; i++) { var buffer = buffers[i]; callback(decodePacket(buffer, binaryType, true), i, total); } };
the_stack
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types"; /** * A Cell and its properties */ export interface CellOutput { /** * The arn for the Cell */ CellArn: string | undefined; /** * The name of the Cell */ CellName: string | undefined; /** * A list of Cell arns */ Cells: string[] | undefined; /** * A list of Cell ARNs and/or RecoveryGroup ARNs */ ParentReadinessScopes: string[] | undefined; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace CellOutput { /** * @internal */ export const filterSensitiveLog = (obj: CellOutput): any => ({ ...obj, }); } /** * A collection of rules used in a readiness check */ export interface ListRulesOutput { /** * The resource type the rule applies to. */ ResourceType: string | undefined; /** * A description of the rule */ RuleDescription: string | undefined; /** * The Rule's ID. */ RuleId: string | undefined; } export namespace ListRulesOutput { /** * @internal */ export const filterSensitiveLog = (obj: ListRulesOutput): any => ({ ...obj, }); } /** * Information relating to readiness check status */ export interface Message { /** * The text of a readiness check message */ MessageText?: string; } export namespace Message { /** * @internal */ export const filterSensitiveLog = (obj: Message): any => ({ ...obj, }); } /** * A resource used for checking the readiness of a Resource Set */ export interface ReadinessCheckOutput { /** * Arn associated with ReadinessCheck */ ReadinessCheckArn: string | undefined; /** * Name for a ReadinessCheck */ ReadinessCheckName?: string; /** * Name of the ResourceSet to be checked */ ResourceSet: string | undefined; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace ReadinessCheckOutput { /** * @internal */ export const filterSensitiveLog = (obj: ReadinessCheckOutput): any => ({ ...obj, }); } export enum Readiness { NOT_AUTHORIZED = "NOT_AUTHORIZED", NOT_READY = "NOT_READY", READY = "READY", UNKNOWN = "UNKNOWN", } /** * Summary of ReadinessCheck status, paginated in GetRecoveryGroupReadinessSummary and GetCellReadinessSummary */ export interface ReadinessCheckSummary { /** * The readiness of this ReadinessCheck */ Readiness?: Readiness | string; /** * The name of a ReadinessCheck which is part of the given RecoveryGroup or Cell */ ReadinessCheckName?: string; } export namespace ReadinessCheckSummary { /** * @internal */ export const filterSensitiveLog = (obj: ReadinessCheckSummary): any => ({ ...obj, }); } /** * Guidance for improving Recovery Group resilliancy */ export interface Recommendation { /** * Guidance text for recommendation */ RecommendationText: string | undefined; } export namespace Recommendation { /** * @internal */ export const filterSensitiveLog = (obj: Recommendation): any => ({ ...obj, }); } /** * A Recovery Group generally containing multiple Cells */ export interface RecoveryGroupOutput { /** * A list of Cell arns */ Cells: string[] | undefined; /** * The arn for the RecoveryGroup */ RecoveryGroupArn: string | undefined; /** * The name of the RecoveryGroup */ RecoveryGroupName: string | undefined; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace RecoveryGroupOutput { /** * @internal */ export const filterSensitiveLog = (obj: RecoveryGroupOutput): any => ({ ...obj, }); } /** * The NLB resource a DNS Target Resource points to */ export interface NLBResource { /** * An NLB resource arn */ Arn?: string; } export namespace NLBResource { /** * @internal */ export const filterSensitiveLog = (obj: NLBResource): any => ({ ...obj, }); } /** * The Route 53 resource a DNS Target Resource record points to */ export interface R53ResourceRecord { /** * The DNS target name */ DomainName?: string; /** * The Resource Record set id */ RecordSetId?: string; } export namespace R53ResourceRecord { /** * @internal */ export const filterSensitiveLog = (obj: R53ResourceRecord): any => ({ ...obj, }); } /** * The target resource the R53 record points to */ export interface TargetResource { /** * The NLB resource a DNS Target Resource points to */ NLBResource?: NLBResource; /** * The Route 53 resource a DNS Target Resource record points to */ R53Resource?: R53ResourceRecord; } export namespace TargetResource { /** * @internal */ export const filterSensitiveLog = (obj: TargetResource): any => ({ ...obj, }); } /** * A component for DNS/Routing Control Readiness Checks */ export interface DNSTargetResource { /** * The DNS Name that acts as ingress point to a portion of application */ DomainName?: string; /** * The Hosted Zone ARN that contains the DNS record with the provided name of target resource. */ HostedZoneArn?: string; /** * The R53 Set Id to uniquely identify a record given a Name and a Type */ RecordSetId?: string; /** * The Type of DNS Record of target resource */ RecordType?: string; /** * The target resource the R53 record points to */ TargetResource?: TargetResource; } export namespace DNSTargetResource { /** * @internal */ export const filterSensitiveLog = (obj: DNSTargetResource): any => ({ ...obj, }); } /** * The resource element of a ResourceSet */ export interface Resource { /** * The component id of the resource, generated by the service when dnsTargetResource is used */ ComponentId?: string; /** * A component for DNS/Routing Control Readiness Checks */ DnsTargetResource?: DNSTargetResource; /** * A list of RecoveryGroup ARNs and/or Cell ARNs that this resource is contained within. */ ReadinessScopes?: string[]; /** * The ARN of the AWS resource, can be skipped if dnsTargetResource is used */ ResourceArn?: string; } export namespace Resource { /** * @internal */ export const filterSensitiveLog = (obj: Resource): any => ({ ...obj, }); } /** * Result with status for an individual resource. */ export interface ResourceResult { /** * The component id of the resource */ ComponentId?: string; /** * The time the resource was last checked for readiness, in ISO-8601 format, UTC. */ LastCheckedTimestamp: Date | undefined; /** * The readiness of the resource. */ Readiness: Readiness | string | undefined; /** * The ARN of the resource */ ResourceArn?: string; } export namespace ResourceResult { /** * @internal */ export const filterSensitiveLog = (obj: ResourceResult): any => ({ ...obj, }); } /** * A collection of resources of the same type */ export interface ResourceSetOutput { /** * The arn for the ResourceSet */ ResourceSetArn: string | undefined; /** * The name of the ResourceSet */ ResourceSetName: string | undefined; /** * AWS Resource Type of the resources in the ResourceSet */ ResourceSetType: string | undefined; /** * A list of Resource objects */ Resources: Resource[] | undefined; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace ResourceSetOutput { /** * @internal */ export const filterSensitiveLog = (obj: ResourceSetOutput): any => ({ ...obj, }); } /** * Result with status for an individual rule.. */ export interface RuleResult { /** * The time the resource was last checked for readiness, in ISO-8601 format, UTC. */ LastCheckedTimestamp: Date | undefined; /** * Details about the resource's readiness */ Messages: Message[] | undefined; /** * The readiness at rule level. */ Readiness: Readiness | string | undefined; /** * The identifier of the rule. */ RuleId: string | undefined; } export namespace RuleResult { /** * @internal */ export const filterSensitiveLog = (obj: RuleResult): any => ({ ...obj, }); } /** * User does not have sufficient access to perform this action. */ export interface AccessDeniedException extends __SmithyException, $MetadataBearer { name: "AccessDeniedException"; $fault: "client"; Message?: string; } export namespace AccessDeniedException { /** * @internal */ export const filterSensitiveLog = (obj: AccessDeniedException): any => ({ ...obj, }); } /** * Updating or deleting a resource can cause an inconsistent state. */ export interface ConflictException extends __SmithyException, $MetadataBearer { name: "ConflictException"; $fault: "client"; Message?: string; } export namespace ConflictException { /** * @internal */ export const filterSensitiveLog = (obj: ConflictException): any => ({ ...obj, }); } /** * The Cell to create */ export interface CreateCellRequest { /** * The name of the Cell to create */ CellName: string | undefined; /** * A list of Cell arns contained within this Cell (for use in nested Cells, e.g. regions within which AZs) */ Cells?: string[]; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace CreateCellRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateCellRequest): any => ({ ...obj, }); } export interface CreateCellResponse { /** * The arn for the Cell */ CellArn?: string; /** * The name of the Cell */ CellName?: string; /** * A list of Cell arns */ Cells?: string[]; /** * A list of Cell ARNs and/or RecoveryGroup ARNs */ ParentReadinessScopes?: string[]; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace CreateCellResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateCellResponse): any => ({ ...obj, }); } /** * An unexpected error occurred. */ export interface InternalServerException extends __SmithyException, $MetadataBearer { name: "InternalServerException"; $fault: "server"; Message?: string; } export namespace InternalServerException { /** * @internal */ export const filterSensitiveLog = (obj: InternalServerException): any => ({ ...obj, }); } /** * Request was denied due to request throttling. */ export interface ThrottlingException extends __SmithyException, $MetadataBearer { name: "ThrottlingException"; $fault: "client"; Message?: string; } export namespace ThrottlingException { /** * @internal */ export const filterSensitiveLog = (obj: ThrottlingException): any => ({ ...obj, }); } /** * The input fails to satisfy the constraints specified by an AWS service. */ export interface ValidationException extends __SmithyException, $MetadataBearer { name: "ValidationException"; $fault: "client"; Message?: string; } export namespace ValidationException { /** * @internal */ export const filterSensitiveLog = (obj: ValidationException): any => ({ ...obj, }); } /** * The cross account authorization */ export interface CreateCrossAccountAuthorizationRequest { /** * The cross account authorization */ CrossAccountAuthorization: string | undefined; } export namespace CreateCrossAccountAuthorizationRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateCrossAccountAuthorizationRequest): any => ({ ...obj, }); } export interface CreateCrossAccountAuthorizationResponse { /** * The cross account authorization */ CrossAccountAuthorization?: string; } export namespace CreateCrossAccountAuthorizationResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateCrossAccountAuthorizationResponse): any => ({ ...obj, }); } /** * The ReadinessCheck to create */ export interface CreateReadinessCheckRequest { /** * The name of the ReadinessCheck to create */ ReadinessCheckName: string | undefined; /** * The name of the ResourceSet to check */ ResourceSetName: string | undefined; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace CreateReadinessCheckRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateReadinessCheckRequest): any => ({ ...obj, }); } export interface CreateReadinessCheckResponse { /** * Arn associated with ReadinessCheck */ ReadinessCheckArn?: string; /** * Name for a ReadinessCheck */ ReadinessCheckName?: string; /** * Name of the ResourceSet to be checked */ ResourceSet?: string; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace CreateReadinessCheckResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateReadinessCheckResponse): any => ({ ...obj, }); } /** * The RecoveryGroup to create */ export interface CreateRecoveryGroupRequest { /** * A list of Cell arns */ Cells?: string[]; /** * The name of the RecoveryGroup to create */ RecoveryGroupName: string | undefined; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace CreateRecoveryGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateRecoveryGroupRequest): any => ({ ...obj, }); } export interface CreateRecoveryGroupResponse { /** * A list of Cell arns */ Cells?: string[]; /** * The arn for the RecoveryGroup */ RecoveryGroupArn?: string; /** * The name of the RecoveryGroup */ RecoveryGroupName?: string; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace CreateRecoveryGroupResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateRecoveryGroupResponse): any => ({ ...obj, }); } /** * The ResourceSet to create */ export interface CreateResourceSetRequest { /** * The name of the ResourceSet to create */ ResourceSetName: string | undefined; /** * AWS Resource type of the resources in the ResourceSet */ ResourceSetType: string | undefined; /** * A list of Resource objects */ Resources: Resource[] | undefined; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace CreateResourceSetRequest { /** * @internal */ export const filterSensitiveLog = (obj: CreateResourceSetRequest): any => ({ ...obj, }); } export interface CreateResourceSetResponse { /** * The arn for the ResourceSet */ ResourceSetArn?: string; /** * The name of the ResourceSet */ ResourceSetName?: string; /** * AWS Resource Type of the resources in the ResourceSet */ ResourceSetType?: string; /** * A list of Resource objects */ Resources?: Resource[]; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace CreateResourceSetResponse { /** * @internal */ export const filterSensitiveLog = (obj: CreateResourceSetResponse): any => ({ ...obj, }); } export interface DeleteCellRequest { /** * The Cell to delete */ CellName: string | undefined; } export namespace DeleteCellRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteCellRequest): any => ({ ...obj, }); } /** * The requested resource does not exist. */ export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer { name: "ResourceNotFoundException"; $fault: "client"; Message?: string; } export namespace ResourceNotFoundException { /** * @internal */ export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({ ...obj, }); } export interface DeleteCrossAccountAuthorizationRequest { /** * The cross account authorization */ CrossAccountAuthorization: string | undefined; } export namespace DeleteCrossAccountAuthorizationRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteCrossAccountAuthorizationRequest): any => ({ ...obj, }); } export interface DeleteCrossAccountAuthorizationResponse {} export namespace DeleteCrossAccountAuthorizationResponse { /** * @internal */ export const filterSensitiveLog = (obj: DeleteCrossAccountAuthorizationResponse): any => ({ ...obj, }); } export interface DeleteReadinessCheckRequest { /** * The ReadinessCheck to delete */ ReadinessCheckName: string | undefined; } export namespace DeleteReadinessCheckRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteReadinessCheckRequest): any => ({ ...obj, }); } export interface DeleteRecoveryGroupRequest { /** * The RecoveryGroup to delete */ RecoveryGroupName: string | undefined; } export namespace DeleteRecoveryGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteRecoveryGroupRequest): any => ({ ...obj, }); } export interface DeleteResourceSetRequest { /** * The ResourceSet to delete */ ResourceSetName: string | undefined; } export namespace DeleteResourceSetRequest { /** * @internal */ export const filterSensitiveLog = (obj: DeleteResourceSetRequest): any => ({ ...obj, }); } export interface GetArchitectureRecommendationsRequest { /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; /** * Name of RecoveryGroup (top level resource) to be analyzed. */ RecoveryGroupName: string | undefined; } export namespace GetArchitectureRecommendationsRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetArchitectureRecommendationsRequest): any => ({ ...obj, }); } export interface GetArchitectureRecommendationsResponse { /** * The time a Recovery Group was last assessed for recommendations in UTC ISO-8601 format. */ LastAuditTimestamp?: Date; /** * A token that can be used to resume pagination from the end of the collection */ NextToken?: string; /** * A list of recommendations for the customer's application */ Recommendations?: Recommendation[]; } export namespace GetArchitectureRecommendationsResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetArchitectureRecommendationsResponse): any => ({ ...obj, }); } export interface GetCellRequest { /** * The Cell to get */ CellName: string | undefined; } export namespace GetCellRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetCellRequest): any => ({ ...obj, }); } export interface GetCellResponse { /** * The arn for the Cell */ CellArn?: string; /** * The name of the Cell */ CellName?: string; /** * A list of Cell arns */ Cells?: string[]; /** * A list of Cell ARNs and/or RecoveryGroup ARNs */ ParentReadinessScopes?: string[]; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace GetCellResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetCellResponse): any => ({ ...obj, }); } export interface GetCellReadinessSummaryRequest { /** * The name of the Cell */ CellName: string | undefined; /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: string; } export namespace GetCellReadinessSummaryRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetCellReadinessSummaryRequest): any => ({ ...obj, }); } export interface GetCellReadinessSummaryResponse { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; /** * The readiness at Cell level. */ Readiness?: Readiness | string; /** * Summaries for the ReadinessChecks making up the Cell */ ReadinessChecks?: ReadinessCheckSummary[]; } export namespace GetCellReadinessSummaryResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetCellReadinessSummaryResponse): any => ({ ...obj, }); } export interface GetReadinessCheckRequest { /** * The ReadinessCheck to get */ ReadinessCheckName: string | undefined; } export namespace GetReadinessCheckRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetReadinessCheckRequest): any => ({ ...obj, }); } export interface GetReadinessCheckResponse { /** * Arn associated with ReadinessCheck */ ReadinessCheckArn?: string; /** * Name for a ReadinessCheck */ ReadinessCheckName?: string; /** * Name of the ResourceSet to be checked */ ResourceSet?: string; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace GetReadinessCheckResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetReadinessCheckResponse): any => ({ ...obj, }); } export interface GetReadinessCheckResourceStatusRequest { /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: string; /** * The ReadinessCheck to get */ ReadinessCheckName: string | undefined; /** * The resource ARN or component Id to get */ ResourceIdentifier: string | undefined; } export namespace GetReadinessCheckResourceStatusRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetReadinessCheckResourceStatusRequest): any => ({ ...obj, }); } export interface GetReadinessCheckResourceStatusResponse { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; /** * The readiness at rule level. */ Readiness?: Readiness | string; /** * Details of the rules's results */ Rules?: RuleResult[]; } export namespace GetReadinessCheckResourceStatusResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetReadinessCheckResourceStatusResponse): any => ({ ...obj, }); } export interface GetReadinessCheckStatusRequest { /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: string; /** * The ReadinessCheck to get */ ReadinessCheckName: string | undefined; } export namespace GetReadinessCheckStatusRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetReadinessCheckStatusRequest): any => ({ ...obj, }); } export interface GetReadinessCheckStatusResponse { /** * Top level messages for readiness check status */ Messages?: Message[]; /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; /** * The readiness at rule level. */ Readiness?: Readiness | string; /** * Summary of resources's readiness */ Resources?: ResourceResult[]; } export namespace GetReadinessCheckStatusResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetReadinessCheckStatusResponse): any => ({ ...obj, }); } export interface GetRecoveryGroupRequest { /** * The RecoveryGroup to get */ RecoveryGroupName: string | undefined; } export namespace GetRecoveryGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetRecoveryGroupRequest): any => ({ ...obj, }); } export interface GetRecoveryGroupResponse { /** * A list of Cell arns */ Cells?: string[]; /** * The arn for the RecoveryGroup */ RecoveryGroupArn?: string; /** * The name of the RecoveryGroup */ RecoveryGroupName?: string; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace GetRecoveryGroupResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetRecoveryGroupResponse): any => ({ ...obj, }); } export interface GetRecoveryGroupReadinessSummaryRequest { /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: string; /** * The name of the RecoveryGroup */ RecoveryGroupName: string | undefined; } export namespace GetRecoveryGroupReadinessSummaryRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetRecoveryGroupReadinessSummaryRequest): any => ({ ...obj, }); } export interface GetRecoveryGroupReadinessSummaryResponse { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; /** * The readiness at RecoveryGroup level. */ Readiness?: Readiness | string; /** * Summaries for the ReadinessChecks making up the RecoveryGroup */ ReadinessChecks?: ReadinessCheckSummary[]; } export namespace GetRecoveryGroupReadinessSummaryResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetRecoveryGroupReadinessSummaryResponse): any => ({ ...obj, }); } export interface GetResourceSetRequest { /** * The ResourceSet to get */ ResourceSetName: string | undefined; } export namespace GetResourceSetRequest { /** * @internal */ export const filterSensitiveLog = (obj: GetResourceSetRequest): any => ({ ...obj, }); } export interface GetResourceSetResponse { /** * The arn for the ResourceSet */ ResourceSetArn?: string; /** * The name of the ResourceSet */ ResourceSetName?: string; /** * AWS Resource Type of the resources in the ResourceSet */ ResourceSetType?: string; /** * A list of Resource objects */ Resources?: Resource[]; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace GetResourceSetResponse { /** * @internal */ export const filterSensitiveLog = (obj: GetResourceSetResponse): any => ({ ...obj, }); } export interface ListCellsRequest { /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: string; } export namespace ListCellsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListCellsRequest): any => ({ ...obj, }); } export interface ListCellsResponse { /** * A list of Cells */ Cells?: CellOutput[]; /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; } export namespace ListCellsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListCellsResponse): any => ({ ...obj, }); } export interface ListCrossAccountAuthorizationsRequest { /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: string; } export namespace ListCrossAccountAuthorizationsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListCrossAccountAuthorizationsRequest): any => ({ ...obj, }); } export interface ListCrossAccountAuthorizationsResponse { /** * A list of CrossAccountAuthorizations */ CrossAccountAuthorizations?: string[]; /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; } export namespace ListCrossAccountAuthorizationsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListCrossAccountAuthorizationsResponse): any => ({ ...obj, }); } export interface ListReadinessChecksRequest { /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: string; } export namespace ListReadinessChecksRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListReadinessChecksRequest): any => ({ ...obj, }); } export interface ListReadinessChecksResponse { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; /** * A list of ReadinessCheck associated with the account */ ReadinessChecks?: ReadinessCheckOutput[]; } export namespace ListReadinessChecksResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListReadinessChecksResponse): any => ({ ...obj, }); } export interface ListRecoveryGroupsRequest { /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: string; } export namespace ListRecoveryGroupsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListRecoveryGroupsRequest): any => ({ ...obj, }); } export interface ListRecoveryGroupsResponse { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; /** * A list of RecoveryGroups */ RecoveryGroups?: RecoveryGroupOutput[]; } export namespace ListRecoveryGroupsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListRecoveryGroupsResponse): any => ({ ...obj, }); } export interface ListResourceSetsRequest { /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: string; } export namespace ListResourceSetsRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListResourceSetsRequest): any => ({ ...obj, }); } export interface ListResourceSetsResponse { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; /** * A list of ResourceSets associated with the account */ ResourceSets?: ResourceSetOutput[]; } export namespace ListResourceSetsResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListResourceSetsResponse): any => ({ ...obj, }); } export interface ListRulesRequest { /** * Upper bound on number of records to return. */ MaxResults?: number; /** * A token used to resume pagination from the end of a previous request. */ NextToken?: string; /** * Filter parameter which specifies the rules to return given a resource type. */ ResourceType?: string; } export namespace ListRulesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListRulesRequest): any => ({ ...obj, }); } export interface ListRulesResponse { /** * A token that can be used to resume pagination from the end of the collection. */ NextToken?: string; /** * A list of rules */ Rules?: ListRulesOutput[]; } export namespace ListRulesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListRulesResponse): any => ({ ...obj, }); } export interface ListTagsForResourcesRequest { /** * The Amazon Resource Name (ARN) for the resource. You can get this from the response to any request to the resource. */ ResourceArn: string | undefined; } export namespace ListTagsForResourcesRequest { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourcesRequest): any => ({ ...obj, }); } export interface ListTagsForResourcesResponse { /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace ListTagsForResourcesResponse { /** * @internal */ export const filterSensitiveLog = (obj: ListTagsForResourcesResponse): any => ({ ...obj, }); } export interface TagResourceRequest { /** * The Amazon Resource Name (ARN) for the resource. You can get this from the response to any request to the resource. */ ResourceArn: string | undefined; /** * A collection of tags associated with a resource */ Tags: { [key: string]: string } | undefined; } export namespace TagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceRequest): any => ({ ...obj, }); } export interface TagResourceResponse {} export namespace TagResourceResponse { /** * @internal */ export const filterSensitiveLog = (obj: TagResourceResponse): any => ({ ...obj, }); } export interface UntagResourceRequest { /** * The Amazon Resource Name (ARN) for the resource. You can get this from the response to any request to the resource. */ ResourceArn: string | undefined; /** * A comma-separated list of the tag keys to remove from the resource. */ TagKeys: string[] | undefined; } export namespace UntagResourceRequest { /** * @internal */ export const filterSensitiveLog = (obj: UntagResourceRequest): any => ({ ...obj, }); } /** * Parameters to update for the Cell */ export interface UpdateCellRequest { /** * The Cell to update */ CellName: string | undefined; /** * A list of Cell arns, completely replaces previous list */ Cells: string[] | undefined; } export namespace UpdateCellRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateCellRequest): any => ({ ...obj, }); } export interface UpdateCellResponse { /** * The arn for the Cell */ CellArn?: string; /** * The name of the Cell */ CellName?: string; /** * A list of Cell arns */ Cells?: string[]; /** * A list of Cell ARNs and/or RecoveryGroup ARNs */ ParentReadinessScopes?: string[]; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace UpdateCellResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateCellResponse): any => ({ ...obj, }); } /** * The new Readiness Check values */ export interface UpdateReadinessCheckRequest { /** * The ReadinessCheck to update */ ReadinessCheckName: string | undefined; /** * The name of the ResourceSet to check */ ResourceSetName: string | undefined; } export namespace UpdateReadinessCheckRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateReadinessCheckRequest): any => ({ ...obj, }); } export interface UpdateReadinessCheckResponse { /** * Arn associated with ReadinessCheck */ ReadinessCheckArn?: string; /** * Name for a ReadinessCheck */ ReadinessCheckName?: string; /** * Name of the ResourceSet to be checked */ ResourceSet?: string; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace UpdateReadinessCheckResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateReadinessCheckResponse): any => ({ ...obj, }); } /** * Parameters to update for the RecoveryGroup */ export interface UpdateRecoveryGroupRequest { /** * A list of Cell arns, completely replaces previous list */ Cells: string[] | undefined; /** * The RecoveryGroup to update */ RecoveryGroupName: string | undefined; } export namespace UpdateRecoveryGroupRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateRecoveryGroupRequest): any => ({ ...obj, }); } export interface UpdateRecoveryGroupResponse { /** * A list of Cell arns */ Cells?: string[]; /** * The arn for the RecoveryGroup */ RecoveryGroupArn?: string; /** * The name of the RecoveryGroup */ RecoveryGroupName?: string; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace UpdateRecoveryGroupResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateRecoveryGroupResponse): any => ({ ...obj, }); } /** * configuration for the desired */ export interface UpdateResourceSetRequest { /** * The ResourceSet to update */ ResourceSetName: string | undefined; /** * AWS Resource Type of the resources in the ResourceSet */ ResourceSetType: string | undefined; /** * A list of Resource objects */ Resources: Resource[] | undefined; } export namespace UpdateResourceSetRequest { /** * @internal */ export const filterSensitiveLog = (obj: UpdateResourceSetRequest): any => ({ ...obj, }); } export interface UpdateResourceSetResponse { /** * The arn for the ResourceSet */ ResourceSetArn?: string; /** * The name of the ResourceSet */ ResourceSetName?: string; /** * AWS Resource Type of the resources in the ResourceSet */ ResourceSetType?: string; /** * A list of Resource objects */ Resources?: Resource[]; /** * A collection of tags associated with a resource */ Tags?: { [key: string]: string }; } export namespace UpdateResourceSetResponse { /** * @internal */ export const filterSensitiveLog = (obj: UpdateResourceSetResponse): any => ({ ...obj, }); }
the_stack
import RiotAPI from "../riot/api"; import { Server, User, LeagueAccount, UserRank, UserChampionStat, UserMasteryDelta } from "../database"; import config from "../config"; import debug = require("debug"); import elastic from "../elastic"; import scheduleUpdateLoop from "../util/update-loop"; import redis from "../redis"; import createIPC from "../cluster/worker-ipc"; import getTranslator from "../i18n"; const logUpdate = debug("orianna:updater:update"); const logFetch = debug("orianna:updater:fetch"); const logMastery = debug("orianna:updater:fetch:mastery"); const logRanked = debug("orianna:updater:fetch:ranked"); const logAccounts = debug("orianna:updater:fetch:accounts"); const t = getTranslator("en-US"); /** * The updater is responsible for "updating" user ranks every set interval. * This updater actually runs 3 different updating loops, each at different intervals. * From ran most often to ran least often: * - Update Mastery Scores (level, score) * - Update Ranked Information (ranked tier) * - Update Summoners (check if the summoner was renamed, transferred) * These different intervals are mostly because of the rate limits imposed on us by * the Riot API. Do note that a manual refresh will do all of these at the same time. * * Terminology used: * - fetch: pulling (new) data from the riot API and writing it to a User instance. * this will **not** recalculate roles in discord. * - update: calculate new roles for a user based on their current User instance. * this should be ran when either the role conditions change or the user * was previously fetched (and thus might have new data) */ export default class Updater { private ipc = createIPC(this); constructor(private riotAPI: RiotAPI) {} /** * Updates everything for the specified user instance or snowflake. This * will fetch all the new data and then recompute all roles for the specified user. */ public async fetchAndUpdateAll(user: User | string) { if (typeof user === "string") { const dbUser = await User .query() .where("snowflake", user) .eager("[accounts, stats, ranks]") .first(); if (!dbUser) throw new Error("User " + user + " not found."); user = dbUser; } logFetch("Fetching and updating all for %s (%s)", user.username, user.snowflake); try { // Run the account update and games count first since it may alter the results // of the other fetch queries (if a user transferred). await this.fetchAccounts(user); await Promise.all([ this.fetchMasteryScores(user), this.fetchRanked(user) ]); await this.updateUser(user); } catch (e) { logFetch("Error fetching or updating for user %s (%s): %s", user.username, user.snowflake, e.message); logFetch("%O", e); elastic.reportError(e, "fetchAndUpdateAll"); } } /** * Updates the roles for the specified User on all servers Orianna * shars with them. This will not fetch data, it will just check to * see if the user has all the roles it is supposed to have and * update appropriately. Thus, this should be called after a fetch * or whenever the role configuration for a specific server is updated. */ public async updateUser(user: User) { if (user.ignore) return; logUpdate("Updating roles for user %s (%s)", user.username, user.snowflake); // Load data if not already loaded. if (!user.accounts) await user.$loadRelated("accounts"); if (!user.stats) await user.$loadRelated("stats"); if (!user.ranks) await user.$loadRelated("ranks"); try { // Find all guilds this user is on. const userData = await this.ipc.searchUser(user.snowflake); // Update all of them in parallel. await Promise.all(userData.map(data => { return this.updateUserOnGuild(user, data.roles, data.nick, data.guild); })); } catch (e) { logUpdate("Failed to update roles for user %s (%s): %s", user.username, user.snowflake, e.message); logUpdate("%O", e); throw new Error("Failed to update roles for user: " + e.message); } } /** * Starts the 3 different update loops. */ public startUpdateLoops() { const selectLeastRecentlyUpdated = (field: string) => (amount: number) => User .query() .whereRaw(`(select count(*) from "league_accounts" as "accounts" where "accounts"."user_id" = "users"."id") > 0`) .orderBy(field, "ASC") .eager("[accounts, stats, ranks]") .limit(amount); // Loop 1: Update stats. scheduleUpdateLoop(async user => { try { // Update mastery values. await this.fetchMasteryScores(user); // Now recompute roles. await this.updateUser(user); } catch (e) { // Ignored. } // Update last update time regardless of if we succeeded or not. await user.$query().patch({ last_score_update_timestamp: "" + Date.now() }); }, selectLeastRecentlyUpdated("last_score_update_timestamp"), config.updater.masteryGamesInterval, config.updater.masteryGamesAmount); // Loop 2: Update ranked tiers. scheduleUpdateLoop(async user => { // Fetch ranked tier and recompute roles. // We don't care about the result, and we want to swallow errors. this.fetchRanked(user).catch(() => {}); // Actually, do not recompute roles. // Users that haven't gotten their mastery scores yet will lose their roles. // This is only really an issue just after the migration from Ori v1, but it doesn't // really matter since the roles will still be recomputed on the next mastery loop, which // shouldn't take too long. await user.$query().patch({ last_rank_update_timestamp: "" + Date.now() }); }, selectLeastRecentlyUpdated("last_rank_update_timestamp"), config.updater.rankedTierInterval, config.updater.rankedTierAmount); // Loop 3: Update account state. scheduleUpdateLoop(async user => { // No need to recompute roles here. Thatll happen soon enough. // We don't care about the result, and we want to swallow errors. this.fetchAccounts(user).catch(() => {}); await user.$query().patch({ last_account_update_timestamp: "" + Date.now() }); }, selectLeastRecentlyUpdated("last_account_update_timestamp"), config.updater.accountInterval, config.updater.accountAmount); } /** * Recalculates all the roles for the specified user in the specified * Discord guild. Does nothing if the guild is not registered in the database. */ private async updateUserOnGuild(user: User, userRoles: string[], userNickname: string | null, guildId: string) { const server = await Server .query() .where("snowflake", guildId) .eager("roles.conditions") .first(); if (!server) return; logUpdate("Updating roles and nickname for user %s (%s) on guild %s (%s)", user.username, user.snowflake, server.name, server.snowflake); // Compute all roles that this server may assign, then compute all roles that the user should have. // Subtract those two sets to figure out which roles the user should and shouldn't have, then make // sure that that corresponds with the roles the user currently has on the server. const allRoles = new Set(server.roles!.map(x => x.snowflake)); const shouldHave = new Set(server.roles!.filter(x => x.test(user)).map(x => x.snowflake)); const userHas = new Set(userRoles); for (const role of allRoles) { // We can't fully test if this is a valid role since we don't have guild information here, // but we can at least ensure that if this ID is obviously incorrect that we don't do an attempt. if (!/^\d+$/.test(role)) continue; // User has the role, but should not have it. if (userHas.has(role) && !shouldHave.has(role)) { logUpdate("Removing role %s from user %s (%s) since they do not qualify.", role, user.username, user.snowflake); // Ignore errors if we don't have permissions. this.ipc.removeGuildMemberRole(guildId, user.snowflake, role, "Orianna - User does not meet requirements for this role.").catch(() => {}); } // User does not have the role, but should have it. if (!userHas.has(role) && shouldHave.has(role)) { logUpdate("Adding role %s to user %s (%s) since they qualify.", role, user.username, user.snowflake); // Ignore failures, they'll show in the web interface anyway. const dbRole = server.roles!.find(x => x.snowflake === role)!; this.ipc.addGuildMemberRole(guildId, user.snowflake, role, "Orianna - User meets requirements for role.").then(result => { if (!result || !dbRole.announce) return; // Only announce if giving the role was successful. // Prevents us from announcing promotions if we didn't actually assign the role. this.ipc.announcePromotion(user, dbRole, guildId); }).catch(() => { /* Ignored */ }); } } // Update the user nickname if the server has one and the user has a primary account. const primaryAccount = user.accounts!.find(x => x.primary); if (primaryAccount && server.nickname_pattern) { const targetNick = server.nickname_pattern .replace("{region}", primaryAccount.region) .replace("{username}", primaryAccount.username) .slice(0, 32); logUpdate("Setting the nickname of %s (%s) to %s", user.username, user.snowflake, targetNick); if (userNickname !== targetNick) { this.ipc.setNickname(guildId, user, targetNick); } } else if (!primaryAccount && server.nickname_pattern) { // Reset the nick for this user as they have no primary account but the server mandates one. if (userNickname) { this.ipc.setNickname(guildId, user, ""); } } } /** * Responsible for pulling new mastery score data from Riot and * updating the User instance. This will not recalculate roles. * * @returns whether or not the mastery score changed since the last refresh */ private async fetchMasteryScores(user: User) { if (!user.accounts) user.accounts = await user.$relatedQuery<LeagueAccount>("accounts"); if (!user.stats) user.stats = await user.$relatedQuery<UserChampionStat>("stats"); logMastery("Updating mastery for user %s (%s)", user.username, user.snowflake); // Create a redis pipeline for leaderboard tracking through sorted sets. const pipeline = redis.pipeline(); // Sum scores and max levels for all accounts. const scores = new Map<number, { score: number, level: number }>(); for (const account of user.accounts) { // This may throw. If it does, we don't particularly care. We will just try again later. const masteries = await this.riotAPI.getChampionMastery(account.region, account.summoner_id); for (const mastery of masteries) { const old = scores.get(mastery.championId) || { score: 0, level: 0 }; scores.set(mastery.championId, { score: old.score + mastery.championPoints, level: Math.max(old.level, mastery.championLevel) }); } } // Remove user from Redis leaderboards if they lost their points. for (const stats of user.stats) { if (scores.has(stats.champion_id)) continue; pipeline.zrem("leaderboard:" + stats.champion_id, "" + user.id); } // Remove user from Postgres stats if they lost their points. await user.$relatedQuery("stats").whereNotIn("champion_id", [...scores.keys()]).delete(); let changed; const toInsert = []; for (const [champion, score] of scores) { // Carry over the old games played. Don't update anything if we have no need to. const oldScore = user.stats.find(x => x.champion_id === champion); if (oldScore && score.level === oldScore.level && score.score === oldScore.score) continue; // If we had an older score, we can diff the two and queue a delta for insertion. if (oldScore) { toInsert.push({ user_id: user.id, champion_id: champion, delta: score.score - oldScore.score, value: score.score, timestamp: "" + Date.now() }); await oldScore.$query().delete(); } changed = true; // Insert or update into redis. pipeline.zadd("leaderboard:" + champion, "" + score.score, "" + user.id); await user.$relatedQuery<UserChampionStat>("stats").insert({ champion_id: champion, level: score.level, score: score.score }); } // If we had a change, also update the leaderboard for most total score. if (changed) { const maxScore = Math.max(...[...scores.values()].map(x => x.score)); pipeline.zadd("leaderboard:all", maxScore + "", "" + user.id); } // If we had any changed values, we insert them all at once to avoid having a lot of // individual queries. if (toInsert.length) await UserMasteryDelta.query().insert(toInsert); // Run redis pipeline. await pipeline.exec().catch(() => {}); // ignore errors // Refetch stats now that we updated stuff. user.stats = await user.$relatedQuery<UserChampionStat>("stats"); return changed; } /** * Responsible for pulling new ranked tiers and play counts and * updating the User instance. This will not recalculate roles. */ private async fetchRanked(user: User) { if (!user.accounts) user.accounts = await user.$relatedQuery<LeagueAccount>("accounts"); logRanked("Updating ranked stats for user %s (%s)", user.username, user.snowflake); // Figure out the highest rank in every queue for all the accounts combined. const tiers = new Map<string, number>(); for (const account of user.accounts) { const results = await this.riotAPI.getLoLLeaguePositions(account.region, account.summoner_id); // If we have a TFT ID for this account, concat with the TFT positions. if (account.tft_summoner_id) { const tftRanked = await this.riotAPI.getTFTLeaguePositions(account.region, account.tft_summoner_id); results.push(...tftRanked); } for (const result of results) { const old = tiers.get(result.queueType) || 0; const val = config.riot.tiers.indexOf(result.tier); tiers.set(result.queueType, old > val ? old : val); } } // Nuke all old entries (since there might be a queue where we are no longer ranked), // then append the new values. await user.$relatedQuery<UserRank>("ranks").delete(); user.ranks = []; for (const [queue, tier] of tiers) { await user.$relatedQuery<UserRank>("ranks").insert({ queue, tier: config.riot.tiers[tier] }); } } /** * Responsible for refreshing summoner instances to check if the * user renamed or transferred. This will not recalculate roles. */ private async fetchAccounts(user: User) { if (!user.accounts) user.accounts = await user.$relatedQuery<LeagueAccount>("accounts"); logAccounts("Updating accounts for user %s (%s)", user.username, user.snowflake); // For every account, check if the account still exists and still has the same name. // If the name is different, just silently update. Else, remove the account and message // the user that we removed their account. const copy = user.accounts.slice(); for (const account of copy) { const summoner = await this.riotAPI.getLoLSummonerById(account.region, account.summoner_id); if (!summoner) { logAccounts("User %s (%s) seems to have transferred account %s - %s (%s)", user.username, user.snowflake, account.region, account.username, account.summoner_id); // Delete the account. await account.$query().delete(); user.accounts.slice(user.accounts.indexOf(account), 1); // Potentially notify the user. this.ipc.notify(user.snowflake, { color: 0x0a96de, title: t.transfer_title, description: t.transfer_body({ username: account.username, region: account.region }) }); } else if (summoner.name !== account.username) { logAccounts("User %s (%s) seems to have renamed account %s - %s to %s", user.username, user.snowflake, account.region, account.username, summoner.name); account.username = summoner.name; await account.$query().update({ username: summoner.name }); } // If this account doesn't have a TFT summoner yet, associate it. if (summoner && !account.tft_summoner_id) { const tftSummoner = await this.riotAPI.getTFTSummonerByName(account.region, summoner.name); if (!tftSummoner) return; // ???, should never happen logAccounts("User %s (%s) associated account %s (%s) with TFT account %s.", user.username, user.snowflake, summoner.name, summoner.id, tftSummoner.id); await account.$query().update({ tft_summoner_id: tftSummoner.id, tft_account_id: tftSummoner.accountId, tft_puuid: tftSummoner.puuid }); } } } }
the_stack
import type * as I from '@apollo-elements/core/types'; import type * as S from './schema'; import type { ApolloMutationElement } from '@apollo-elements/core'; import { ApolloClient, ApolloError, InMemoryCache } from '@apollo/client/core'; import { SetupFunction } from './types'; import { aTimeout, expect, defineCE, fixture, } from '@open-wc/testing'; import { match, spy, SinonSpy } from 'sinon'; import { setupClient, teardownClient } from './client'; import { NoParamMutation, NullableParamMutation } from './schema'; import { restoreSpies, stringify, waitForRender } from './helpers'; import { TestableElement } from './types'; export interface DescribeMutationComponentOptions<E extends Omit<ApolloMutationElement<any, any>, 'update'|'updated'> = ApolloMutationElement<any, any>> { /** * Async function which returns an instance of the query element * The element must render a template which contains the following DOM structure * ```html * <output id="called"></output> * <output id="data"></output> * <output id="error"></output> * <output id="errors"></output> * <output id="loading"></output> * ``` * On updates, each `<output>`'s text content should be * set to the `JSON.stringified` representation of it's associated value, * with 2 spaces as tabs. * The element must implement a `hasRendered` method which returns a promise that resolves when the element is finished rendering */ setupFunction: SetupFunction<E & TestableElement>; /** * Optional: the class which setup function uses to generate the component. * Only relevant to class-based libraries */ class?: I.Constructor<Omit<E, 'update'|'updated'> & TestableElement>; } export { setupMutationClass } from './helpers'; export function describeMutation(options: DescribeMutationComponentOptions): void { const { setupFunction } = options; const Klass: typeof ApolloMutationElement = options.class as unknown as typeof ApolloMutationElement; describe(`ApolloMutation interface`, function() { describe('when simply instantiating', function() { beforeEach(teardownClient); let element: ApolloMutationElement & TestableElement; beforeEach(async function setupElement() { ({ element } = await setupFunction()); }); beforeEach(waitForRender(() => element)); it('has default properties', function() { // nullable fields expect(element.client, 'client').to.be.null; expect(element.data, 'data').to.be.null; expect(element.mutation, 'mutation').to.be.null; expect(element.refetchQueries, 'refetchQueries').to.be.null; expect(element.variables, 'variables').to.be.null; // defined fields expect(element.called, 'called').to.be.false; expect(element.ignoreResults, 'ignoreResults').to.be.false; // optional fields expect(element.awaitRefetchQueries, 'awaitRefetchQueries').to.be.undefined; expect(element.errorPolicy, 'errorPolicy').to.be.undefined; expect(element.fetchPolicy, 'fetchPolicy').to.be.undefined; expect(element.onCompleted, 'onCompleted').to.be.undefined; expect(element.onError, 'onError').to.be.undefined; expect(element.optimisticResponse, 'optimisticResponse').to.be.undefined; expect(element.updater, 'updater').to.be.undefined; }); describe('setting observed properties', function() { describe('client', function() { const client = new ApolloClient({ cache: new InMemoryCache(), connectToDevTools: false }); it('renders', async function() { element.client = client; await element.hasRendered(); expect(element.client, 'client') .to.equal(client) .and .to.equal(element.controller.client); element.client = null; await element.hasRendered(); expect(element.client, 'null') .to.be.null .and .to.equal(element.controller.client); }); }); describe('data', function() { const data = { data: 'data' }; it('renders', async function() { element.data = data; await element.hasRendered(); expect(element.data, 'data') .to.equal(data).and .to.equal(element.controller.data); expect(element.shadowRoot!.getElementById('data'), 'data') .lightDom.to.equal(JSON.stringify(data)); element.data = null; await element.hasRendered(); expect(element.data, 'null').to.be.null.and .to.equal(element.controller.data); expect(element.shadowRoot!.getElementById('data'), 'null') .lightDom.to.equal(JSON.stringify(null)); }); }); describe('error', function() { it('renders', async function() { try { element.error = new Error('error'); expect(element.error.message, 'error') .to.equal('error').and .to.equal(element.controller.error?.message); } catch { null; } element.error = null; await element.hasRendered(); expect(element.error, 'null') .to.be.null.and .to.equal(element.controller.error); }); }); describe('loading', function() { it('renders', async function() { element.loading = true; await element.hasRendered(); expect(element.loading, 'true') .to.be.true.and .to.equal(element.controller.loading); element.loading = false; await element.hasRendered(); expect(element.loading, 'false') .to.be.false.and .to.equal(element.controller.loading); }); }); }); describe('setting mutation with NoParam mutation', function() { beforeEach(function setMutation() { element.mutation = NoParamMutation; }); it('sets mutation', function() { expect(element.mutation).to.equal(NoParamMutation); }); }); describe('setting mutation with a malformed mutation', function() { it('throws an error', async function badMutation() { // @ts-expect-error: i'm testing the error handler expect(() => element.mutation = 'foo').to .throw('Mutation must be a parsed GraphQL document.'); expect(element.mutation).to.not.be.ok; }); }); }); // hybrids and haunted don't play nice with custom attributes // eslint-disable-next-line @typescript-eslint/no-invalid-this if (!this.parent?.title.match(/^\[(haunted|hybrids)\]/)) { describe('with await-refetch-queries attribute', function() { let element: ApolloMutationElement; beforeEach(async function() { ({ element } = await setupFunction({ attributes: 'await-refetch-queries' })); }); it('sets awaitRefetchQueries property', function() { expect(element.awaitRefetchQueries).to.be.true; }); }); describe('with refetch-queries="A"', function() { let element: ApolloMutationElement; beforeEach(async function() { ({ element } = await setupFunction({ attributes: 'refetch-queries="A"' })); }); it('sets refetchQueries property', function() { expect(element.refetchQueries).to.deep.equal(['A']); }); describe('changing the attribute', function() { beforeEach(function() { element.setAttribute('refetch-queries', 'B'); }); it('changes the property', function() { expect(element.refetchQueries).to.deep.equal(['B']); }); }); describe('unsetting the attribute', function() { beforeEach(function() { element.removeAttribute('refetch-queries'); }); it('unsets the property', function() { expect(element.refetchQueries).to.be.null; }); }); }); describe('with fetch-policy="no-cache"', function() { let element: ApolloMutationElement; beforeEach(async function() { ({ element } = await setupFunction({ attributes: 'fetch-policy="no-cache"' })); }); it('sets fetchPolicy property', function() { expect(element.fetchPolicy).to.equal('no-cache'); }); }); describe('with refetch-queries="A, B, C "', function() { let element: ApolloMutationElement; beforeEach(async function() { ({ element } = await setupFunction({ attributes: 'refetch-queries="A, B, C "' })); }); it('sets refetchQueries property', function() { expect(element.refetchQueries).to.deep.equal(['A', 'B', 'C']); }); }); } describe('with global client available', function() { beforeEach(setupClient); afterEach(teardownClient); describe('when simply instantiating', function() { let element: ApolloMutationElement; let spies: Record<string | keyof ApolloMutationElement, SinonSpy>; beforeEach(async function setupElement() { ({ element, spies } = await setupFunction({ spy: ['mutate'], })); }); afterEach(restoreSpies(() => spies)); afterEach(function teardownElement() { element?.remove(); // @ts-expect-error: reset the fixture element = undefined; }); describe('when simply instantiating', function() { it('uses global client', function() { expect(element.client).to.equal(window.__APOLLO_CLIENT__); }); }); }); describe('with NoParam mutation property set', function() { let element: ApolloMutationElement<typeof S.NoParamMutation>; let spies: Record<string|keyof ApolloMutationElement, SinonSpy>; beforeEach(async function setupElement() { ({ element, spies } = await setupFunction({ properties: { mutation: NoParamMutation, onCompleted: () => void null, onError: () => void null, }, })); }); beforeEach(function spyClientMutate() { ['onCompleted', 'onError'].forEach(m => { try { spy(element, m as keyof typeof element); } catch { spy(element.controller.options, m as keyof typeof element.controller.options); } }); spy(element.client!, 'mutate'); }); afterEach(function restoreClientMutate() { (element.client?.mutate as SinonSpy).restore?.(); }); afterEach(function teardownElement() { element.remove(); // @ts-expect-error: reset the fixture element = undefined; }); afterEach(restoreSpies(() => spies)); it('sets the mutation property', function() { expect(element.mutation).to.equal(NoParamMutation); }); describe('with optimisticResponse property set as object', function() { const optimisticResponse = { noParam: { noParam: 'instance' } }; beforeEach(function() { element.optimisticResponse = optimisticResponse; }); beforeEach(function callMutate() { element.mutate(); }); it('uses element\'s optimisticResponse', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ optimisticResponse })); }); describe('specifying optimisticResponse', function() { const optimisticResponse = { noParam: { noParam: 'specific' } }; beforeEach(function callMutate() { element.mutate({ optimisticResponse }); }); it('uses specific optimisticResponse', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ optimisticResponse })); }); }); }); describe('with refetchQueries property set as string[]', function() { const refetchQueries = ['A']; beforeEach(function() { element.refetchQueries = refetchQueries; }); beforeEach(function callMutate() { element.mutate(); }); it('uses element\'s refetchQueries', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ refetchQueries })); }); describe('specifying refetchQueries', function() { const refetchQueries = ['B']; beforeEach(function callMutate() { element.mutate({ refetchQueries }); }); it('uses specific refetchQueries', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ refetchQueries })); }); }); }); describe('with awaitRefetchQueries property set', function() { beforeEach(function() { element.awaitRefetchQueries = true; }); beforeEach(function callMutate() { element.mutate(); }); it('uses element\'s awaitRefetchQueries', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ awaitRefetchQueries: true })); }); describe('specifying awaitRefetchQueries', function() { beforeEach(function callMutate() { element.mutate({ awaitRefetchQueries: false }); }); it('uses specific refetchQueries', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ awaitRefetchQueries: false })); }); }); }); describe('with context property set', function() { const context = {}; beforeEach(function() { element.context = context; }); beforeEach(function callMutate() { element.mutate(); }); it('uses element\'s context', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ context })); }); describe('specifying context', function() { const context = { a: 'b' }; beforeEach(function callMutate() { element.mutate({ context }); }); it('uses specific context', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ context })); }); }); }); describe('with errorPolicy property set', function() { const errorPolicy = 'all'; beforeEach(function() { element.errorPolicy = errorPolicy; }); beforeEach(function callMutate() { element.mutate(); }); it('uses element\'s errorPolicy', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ errorPolicy })); }); describe('specifying errorPolicy', function() { const errorPolicy = 'ignore'; beforeEach(function callMutate() { element.mutate({ errorPolicy }); }); it('uses specific errorPolicy', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ errorPolicy })); }); }); }); describe('with fetchPolicy property set', function() { const fetchPolicy = 'no-cache'; beforeEach(function() { element.fetchPolicy = fetchPolicy; }); beforeEach(function callMutate() { element.mutate(); }); it('uses element\'s fetchPolicy', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ fetchPolicy })); }); describe('specifying fetchPolicy', function() { beforeEach(function callMutate() { element.fetchPolicy = undefined; element.mutate({ fetchPolicy }); }); it('uses specific fetchPolicy', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ fetchPolicy })); }); }); }); describe('mutate()', function() { beforeEach(function callMutate() { element.mutate(); }); it('calls client.mutate with element props', function() { expect(element.client!.mutate).to.have.been.calledWithMatch({ awaitRefetchQueries: element.awaitRefetchQueries, context: element.context, errorPolicy: element.errorPolicy, fetchPolicy: element.fetchPolicy, mutation: element.mutation, optimisticResponse: element.optimisticResponse, refetchQueries: element.refetchQueries ?? undefined, update: element.updater, variables: element.variables ?? undefined, }); }); }); describe('mutate({})', function() { beforeEach(function callMutate() { element.mutate({}); }); it('defaults to element\'s mutation', function() { expect(element.client!.mutate).to.have.been.calledWithMatch({ awaitRefetchQueries: element.awaitRefetchQueries, context: element.context, errorPolicy: element.errorPolicy, fetchPolicy: element.fetchPolicy, mutation: element.mutation, optimisticResponse: element.optimisticResponse, refetchQueries: element.refetchQueries ?? undefined, update: element.updater, variables: element.variables ?? undefined, }); }); }); describe('mutate({ refetchQueries })', function() { const refetchQueries = ['B']; beforeEach(function callMutate() { element.mutate({ refetchQueries }); }); it('uses specific refetchQueries', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ refetchQueries })); }); }); describe('mutate({ errorPolicy })', function() { const errorPolicy = 'none'; beforeEach(function callMutate() { element.mutate({ errorPolicy }); }); it('uses specific errorPolicy', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ errorPolicy })); }); }); describe('mutate({ fetchPolicy })', function() { const fetchPolicy = 'no-cache'; beforeEach(function callMutate() { element.mutate({ fetchPolicy }); }); it('uses specific fetchPolicy', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ fetchPolicy })); }); }); describe('mutate({ context })', function() { const context = { a: 'a' }; beforeEach(function callMutate() { element.mutate({ context }); }); it('uses specific context', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ context })); }); }); describe('mutate({ awaitRefetchQueries })', function() { const awaitRefetchQueries = true; beforeEach(function callMutate() { element.mutate({ awaitRefetchQueries }); }); it('uses specific awaitRefetchQueries', function() { expect(element.client!.mutate).to.have.been .calledWithMatch(match({ awaitRefetchQueries })); }); }); describe('mutate({ optimisticResponse, variables, update })', function() { const optimisticResponse = { noParam: { noParam: null } }; const variables = {}; const update = (): void => { null; }; beforeEach(function callMutate() { element.mutate({ optimisticResponse, variables, update }); }); beforeEach(() => element.controller.host.updateComplete); it('uses element\'s mutation', function() { expect(element.client!.mutate).to.have.been .calledWithMatch({ awaitRefetchQueries: element.awaitRefetchQueries, context: element.context, errorPolicy: element.errorPolicy, fetchPolicy: element.fetchPolicy, mutation: element.mutation, optimisticResponse, refetchQueries: element.refetchQueries ?? undefined, update, variables, }); }); }); describe('mutate({ mutation, variables, update })', function() { const mutation = NullableParamMutation; const variables = {}; const update = (): void => { null; }; beforeEach(function callMutate() { element.mutate({ mutation, variables, update }); }); it('uses element\'s optimisticResponse', function() { expect(element.client!.mutate).to.have.been .calledWithMatch({ awaitRefetchQueries: element.awaitRefetchQueries, context: element.context, errorPolicy: element.errorPolicy, fetchPolicy: element.fetchPolicy, optimisticResponse: element.optimisticResponse, refetchQueries: element.refetchQueries ?? undefined, mutation, update, variables, }); }); }); describe('mutate({ mutation, optimisticResponse, variables })', function() { const optimisticResponse = { noParam: { noParam: null } }; const mutation = NullableParamMutation; const variables = {}; beforeEach(function callMutate() { element.mutate({ mutation, optimisticResponse, variables }); }); it('uses element\'s updater', function() { expect(element.client!.mutate).to.have.been .calledWithMatch({ awaitRefetchQueries: element.awaitRefetchQueries, context: element.context, errorPolicy: element.errorPolicy, fetchPolicy: element.fetchPolicy, refetchQueries: element.refetchQueries ?? undefined, update: element.updater, mutation, optimisticResponse, variables, }); }); }); describe('mutate({ mutation, optimisticResponse, update })', function() { const optimisticResponse = { noParam: { noParam: null } }; const mutation = NullableParamMutation; const update = (): void => { null; }; beforeEach(function callMutate() { element.mutate({ mutation, optimisticResponse, update }); }); it('uses element\'s variables', function() { expect(element.client!.mutate).to.have.been .calledWithMatch({ awaitRefetchQueries: element.awaitRefetchQueries, context: element.context, errorPolicy: element.errorPolicy, fetchPolicy: element.fetchPolicy, refetchQueries: element.refetchQueries ?? undefined, variables: element.variables ?? undefined, mutation, optimisticResponse, update, }); }); }); }); describe('with NullableParam mutation property set', function() { let element: TestableElement & ApolloMutationElement<typeof S.NullableParamMutation>; let spies: Record<string | keyof typeof element, SinonSpy>; beforeEach(async function setupElement() { ({ element, spies } = await setupFunction({ properties: { mutation: NullableParamMutation, onCompleted: spy(), onError: spy(), }, })); }); beforeEach(function spyClientMutate() { spy(element.client!, 'mutate'); }); afterEach(function restoreClientMutate() { (element.client?.mutate as SinonSpy).restore?.(); }); afterEach(function teardownElement() { element.remove(); // @ts-expect-error: reset the fixture element = undefined; }); afterEach(restoreSpies(() => spies)); describe('when mutation resolves', function() { let loading: boolean|undefined; beforeEach(async function callMutate() { const p = element.mutate(); ({ loading } = element); await p; }); afterEach(() => loading = undefined); beforeEach(() => element.hasRendered()); it('calls onCompleted with data', function() { expect(element.onCompleted).to.have.been .calledWithMatch({ nullableParam: match({ nullable: 'Hello World' }) }); }); it('sets loading', function() { expect(loading, 'in flight').to.be.true; expect(element.loading, 'after resolves').to.be.false; }); it('sets data', function() { expect(element.data).to.deep.equal({ nullableParam: { nullable: 'Hello World', __typename: 'Nullable', }, }); }); it('renders data', function() { expect(element.shadowRoot!.getElementById('data')!.textContent) .to.equal(stringify({ nullableParam: { nullable: 'Hello World', __typename: 'Nullable', }, })); }); it('sets error', function() { expect(element.error).to.be.null; }); it('sets errors', function() { expect(element.errors).to.be.empty; }); }); describe('when mutation rejects', function() { let error: ApolloError; beforeEach(function setVariablesToError() { element.variables = { nullable: 'error' }; }); beforeEach(async function catchMutateError() { try { await element.mutate(); expect.fail('no error'); } catch (e) { error = e; } }); beforeEach(waitForRender(() => element)); it('calls onError with error', function() { expect(element.onError).to.have.been.calledWithMatch(error); }); it('sets data, error, errors, and loading', function() { expect(element.data, 'data').to.be.null; expect(element.error, 'error').to.equal(error); expect(element.errors, 'errors').to.be.empty; expect(element.loading, 'loading').to.be.false; }); it('renders error', function() { expect(element).shadowDom.to.equal(` <output id="called">true</output> <output id="data">null</output> <output id="error">${stringify(error)}</output> <output id="errors">[]</output> <output id="loading">false</output> `); }); }); describe('mutate()', function() { beforeEach(() => element.mutate()); it('calls onCompleted with result', function() { expect(element.onCompleted) .to.have.been.calledOnce .and .to.have.been.calledWith(match({ nullableParam: { __typename: 'Nullable', nullable: 'Hello World', }, })); }); describe('then calling again', function() { beforeEach(() => aTimeout(50)); beforeEach(() => element.mutate({ variables: { nullable: 'second', }, })); it('calls onCompleted with result', function() { expect(element.onCompleted) .to.have.been.calledTwice.and .to.have.been.calledWithMatch({ nullableParam: { nullable: 'second', }, }); }); }); }); }); }); if (Klass) { describe('ApolloMutation subclasses', function() { describe('with NullableParam mutation in class field', function() { let element: ApolloMutationElement<typeof S.NullableParamMutation>; let spies: Record<Exclude<keyof typeof element, symbol> | string, SinonSpy>; beforeEach(setupClient); beforeEach(async function setupElement() { class Test extends Klass<typeof S.NullableParamMutation> { mutation = NullableParamMutation; } const tag = defineCE(Test); element = await fixture<Test>(`<${tag}></${tag}>`); }); it('sets the mutation property', function() { expect(element.mutation).to.equal(NullableParamMutation); }); describe('with mutation, onCompleted, and onError defined as class methods', function() { beforeEach(async function() { class Test extends Klass<typeof S.NullableParamMutation> { mutation = NullableParamMutation; onError() { null; } onCompleted() { null; } } const tag = defineCE(Test); element = await fixture<Test>(`<${tag}></${tag}>`); }); beforeEach(() => element.controller.host.updateComplete); beforeEach(function spyMethods() { spies = { onError: spy(element, 'onError'), onCompleted: spy(element, 'onCompleted'), ['client.mutate']: spy(element.client!, 'mutate'), }; }); afterEach(restoreSpies(() => spies)); afterEach(function teardownElement() { element.remove(); // @ts-expect-error: reset the fixture element = undefined; }); it('sets the mutation property', function() { expect(element.mutation).to.equal(NullableParamMutation); }); describe('when mutation resolves', function() { beforeEach(() => element.mutate()); it('calls onCompleted with data', function() { expect(element.onCompleted) .to.have.been.calledOnce .and.to.have.been.calledWithMatch({ nullableParam: { nullable: 'Hello World', }, }); }); it('sets loading', async function() { const p = element.mutate(); expect(element.loading).to.be.true; await p; expect(element.loading).to.be.false; }); it('sets data', function() { expect(element.data).to.deep.equal({ nullableParam: { __typename: 'Nullable', nullable: 'Hello World', }, }); }); it('sets error', function() { expect(element.error).to.be.null; }); }); describe('when mutation rejects', function() { let error: ApolloError; beforeEach(function setVariablesToError() { element.variables = { nullable: 'error' }; }); beforeEach(async function catchMutateError() { try { await element.mutate(); expect.fail('no error'); } catch (e) { error = e; } }); it('calls onError with error', function() { expect(element.onError).to.have.been.calledWithMatch(error); }); it('sets data, error, loading', function() { expect(element.data).to.be.null; expect(element.error).to.equal(error); expect(element.loading).to.be.false; }); }); }); describe('with `updater` defined as a class method', function() { let element: ApolloMutationElement<typeof S.NoParamMutation>; beforeEach(async function setupElement() { class Test extends (Klass as unknown as I.Constructor<typeof element>) { mutation = NoParamMutation; updater(): void { '💩'; } } const tag = defineCE(Test); element = await fixture<Test>(`<${tag}></${tag}>`); }); beforeEach(function spyMethods() { spies = { ['client.mutate']: spy(element.client!, 'mutate'), }; }); describe('mutate()', function() { beforeEach(async function callMutate() { await element.mutate(); }); it(`uses element's updater method for mutation's \`update\` option by default`, function() { const update = element.updater; expect(element.client!.mutate).to.have.been.calledWith(match({ update })); }); }); describe('mutate({ update })', function() { const update = () => void null; beforeEach(async function callMutate() { await element.mutate({ update }); }); it('allows passing custom update function', function() { expect(element.client!.mutate).to.have.been.calledWith(match({ update })); }); }); }); }); }); } }); }
the_stack
import { DocumentNode, FragmentDefinitionNode, GraphQLNamedType, GraphQLSchema, Kind, SelectionNode, SelectionSetNode, TypeInfo, getNamedType, isAbstractType, isInterfaceType, visit, visitWithTypeInfo, InlineFragmentNode, GraphQLOutputType, isObjectType, FieldNode, } from 'graphql'; import { implementsAbstractType, getRootTypeNames, memoize2, ASTVisitorKeyMap } from '@graphql-tools/utils'; import { getDocumentMetadata } from './getDocumentMetadata'; import { StitchingInfo } from './types'; export function prepareGatewayDocument( originalDocument: DocumentNode, transformedSchema: GraphQLSchema, returnType: GraphQLOutputType, infoSchema?: GraphQLSchema ): DocumentNode { const wrappedConcreteTypesDocument = wrapConcreteTypes(returnType, transformedSchema, originalDocument); if (infoSchema == null) { return wrappedConcreteTypesDocument; } const { possibleTypesMap, reversePossibleTypesMap, interfaceExtensionsMap, fieldNodesByType, fieldNodesByField, dynamicSelectionSetsByField, } = getSchemaMetaData(infoSchema, transformedSchema); const { operations, fragments, fragmentNames } = getDocumentMetadata(wrappedConcreteTypesDocument); const { expandedFragments, fragmentReplacements } = getExpandedFragments(fragments, fragmentNames, possibleTypesMap); const typeInfo = new TypeInfo(transformedSchema); const expandedDocument: DocumentNode = { kind: Kind.DOCUMENT, definitions: [...operations, ...fragments, ...expandedFragments], }; const visitorKeyMap: ASTVisitorKeyMap = { Document: ['definitions'], OperationDefinition: ['selectionSet'], SelectionSet: ['selections'], Field: ['selectionSet'], InlineFragment: ['selectionSet'], FragmentDefinition: ['selectionSet'], }; return visit( expandedDocument, visitWithTypeInfo(typeInfo, { [Kind.SELECTION_SET]: node => visitSelectionSet( node, fragmentReplacements, transformedSchema, typeInfo, possibleTypesMap, reversePossibleTypesMap, interfaceExtensionsMap, fieldNodesByType, fieldNodesByField, dynamicSelectionSetsByField ), }), // visitorKeys argument usage a la https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js // empty keys cannot be removed only because of typescript errors // will hopefully be fixed in future version of graphql-js to be optional visitorKeyMap as any ); } function visitSelectionSet( node: SelectionSetNode, fragmentReplacements: Record<string, Array<{ fragmentName: string; typeName: string }>>, schema: GraphQLSchema, typeInfo: TypeInfo, possibleTypesMap: Record<string, Array<string>>, reversePossibleTypesMap: Record<string, Array<string>>, interfaceExtensionsMap: Record<string, Record<string, boolean>>, fieldNodesByType: Record<string, Array<FieldNode>>, fieldNodesByField: Record<string, Record<string, Array<FieldNode>>>, dynamicSelectionSetsByField: Record<string, Record<string, Array<(node: FieldNode) => SelectionSetNode>>> ): SelectionSetNode { const newSelections = new Set<SelectionNode>(); const maybeType = typeInfo.getParentType(); if (maybeType != null) { const parentType: GraphQLNamedType = getNamedType(maybeType); const parentTypeName = parentType.name; const fieldNodes = fieldNodesByType[parentTypeName]; if (fieldNodes) { for (const fieldNode of fieldNodes) { newSelections.add(fieldNode); } } const interfaceExtensions = interfaceExtensionsMap[parentType.name]; const interfaceExtensionFields: Array<SelectionNode> = []; for (const selection of node.selections) { if (selection.kind === Kind.INLINE_FRAGMENT) { if (selection.typeCondition != null) { const possibleTypes = possibleTypesMap[selection.typeCondition.name.value]; if (possibleTypes == null) { newSelections.add(selection); continue; } for (const possibleTypeName of possibleTypes) { const maybePossibleType = schema.getType(possibleTypeName); if (maybePossibleType != null && implementsAbstractType(schema, parentType, maybePossibleType)) { newSelections.add(generateInlineFragment(possibleTypeName, selection.selectionSet)); } } } } else if (selection.kind === Kind.FRAGMENT_SPREAD) { const fragmentName = selection.name.value; if (!fragmentReplacements[fragmentName]) { newSelections.add(selection); continue; } for (const replacement of fragmentReplacements[fragmentName]) { const typeName = replacement.typeName; const maybeReplacementType = schema.getType(typeName); if (maybeReplacementType != null && implementsAbstractType(schema, parentType, maybeType)) { newSelections.add({ kind: Kind.FRAGMENT_SPREAD, name: { kind: Kind.NAME, value: replacement.fragmentName, }, }); } } } else { const fieldName = selection.name.value; const fieldNodes = fieldNodesByField[parentTypeName]?.[fieldName]; if (fieldNodes != null) { for (const fieldNode of fieldNodes) { newSelections.add(fieldNode); } } const dynamicSelectionSets = dynamicSelectionSetsByField[parentTypeName]?.[fieldName]; if (dynamicSelectionSets != null) { for (const selectionSetFn of dynamicSelectionSets) { const selectionSet = selectionSetFn(selection); if (selectionSet != null) { for (const selection of selectionSet.selections) { newSelections.add(selection); } } } } if (interfaceExtensions?.[fieldName]) { interfaceExtensionFields.push(selection); } else { newSelections.add(selection); } } } if (reversePossibleTypesMap[parentType.name]) { newSelections.add({ kind: Kind.FIELD, name: { kind: Kind.NAME, value: '__typename', }, }); } if (interfaceExtensionFields.length) { const possibleTypes = possibleTypesMap[parentType.name]; if (possibleTypes != null) { for (const possibleType of possibleTypes) { newSelections.add( generateInlineFragment(possibleType, { kind: Kind.SELECTION_SET, selections: interfaceExtensionFields, }) ); } } } return { ...node, selections: Array.from(newSelections), }; } return node; } function generateInlineFragment(typeName: string, selectionSet: SelectionSetNode): InlineFragmentNode { return { kind: Kind.INLINE_FRAGMENT, typeCondition: { kind: Kind.NAMED_TYPE, name: { kind: Kind.NAME, value: typeName, }, }, selectionSet, }; } const getSchemaMetaData = memoize2( ( sourceSchema: GraphQLSchema, targetSchema: GraphQLSchema ): { possibleTypesMap: Record<string, Array<string>>; reversePossibleTypesMap: Record<string, Array<string>>; interfaceExtensionsMap: Record<string, Record<string, boolean>>; fieldNodesByType: Record<string, Array<FieldNode>>; fieldNodesByField: Record<string, Record<string, Array<FieldNode>>>; dynamicSelectionSetsByField: Record<string, Record<string, Array<(node: FieldNode) => SelectionSetNode>>>; } => { const typeMap = sourceSchema.getTypeMap(); const targetTypeMap = targetSchema.getTypeMap(); const possibleTypesMap: Record<string, Array<string>> = Object.create(null); const interfaceExtensionsMap: Record<string, Record<string, boolean>> = Object.create(null); for (const typeName in typeMap) { const type = typeMap[typeName]; if (isAbstractType(type)) { const targetType = targetTypeMap[typeName]; if (isInterfaceType(type) && isInterfaceType(targetType)) { const targetTypeFields = targetType.getFields(); const sourceTypeFields = type.getFields(); const extensionFields: Record<string, boolean> = Object.create(null); let isExtensionFieldsEmpty = true; for (const fieldName in sourceTypeFields) { if (!targetTypeFields[fieldName]) { extensionFields[fieldName] = true; isExtensionFieldsEmpty = false; } } if (!isExtensionFieldsEmpty) { interfaceExtensionsMap[typeName] = extensionFields; } } if (interfaceExtensionsMap[typeName] || !isAbstractType(targetType)) { const implementations = sourceSchema.getPossibleTypes(type); possibleTypesMap[typeName] = []; for (const impl of implementations) { if (targetTypeMap[impl.name]) { possibleTypesMap[typeName].push(impl.name); } } } } } const stitchingInfo = sourceSchema.extensions?.['stitchingInfo'] as StitchingInfo; return { possibleTypesMap, reversePossibleTypesMap: reversePossibleTypesMap(possibleTypesMap), interfaceExtensionsMap, fieldNodesByType: stitchingInfo?.fieldNodesByType ?? {}, fieldNodesByField: stitchingInfo?.fieldNodesByField ?? {}, dynamicSelectionSetsByField: stitchingInfo?.dynamicSelectionSetsByField ?? {}, }; } ); function reversePossibleTypesMap(possibleTypesMap: Record<string, Array<string>>): Record<string, Array<string>> { const result: Record<string, Array<string>> = Object.create(null); for (const typeName in possibleTypesMap) { const toTypeNames = possibleTypesMap[typeName]; for (const toTypeName of toTypeNames) { if (!result[toTypeName]) { result[toTypeName] = []; } result[toTypeName].push(typeName); } } return result; } function getExpandedFragments( fragments: Array<FragmentDefinitionNode>, fragmentNames: Set<string>, possibleTypesMap: Record<string, Array<string>> ): { expandedFragments: Array<FragmentDefinitionNode>; fragmentReplacements: Record<string, Array<{ fragmentName: string; typeName: string }>>; } { let fragmentCounter = 0; function generateFragmentName(typeName: string): string { let fragmentName: string; do { fragmentName = `_${typeName}_Fragment${fragmentCounter.toString()}`; fragmentCounter++; } while (fragmentNames.has(fragmentName)); return fragmentName; } const expandedFragments: Array<FragmentDefinitionNode> = []; const fragmentReplacements: Record<string, Array<{ fragmentName: string; typeName: string }>> = Object.create(null); for (const fragment of fragments) { const possibleTypes = possibleTypesMap[fragment.typeCondition.name.value]; if (possibleTypes != null) { const fragmentName = fragment.name.value; fragmentReplacements[fragmentName] = []; for (const possibleTypeName of possibleTypes) { const name = generateFragmentName(possibleTypeName); fragmentNames.add(name); expandedFragments.push({ kind: Kind.FRAGMENT_DEFINITION, name: { kind: Kind.NAME, value: name, }, typeCondition: { kind: Kind.NAMED_TYPE, name: { kind: Kind.NAME, value: possibleTypeName, }, }, selectionSet: fragment.selectionSet, }); fragmentReplacements[fragmentName].push({ fragmentName: name, typeName: possibleTypeName, }); } } } return { expandedFragments, fragmentReplacements, }; } function wrapConcreteTypes( returnType: GraphQLOutputType, targetSchema: GraphQLSchema, document: DocumentNode ): DocumentNode { const namedType = getNamedType(returnType); if (!isObjectType(namedType)) { return document; } const rootTypeNames = getRootTypeNames(targetSchema); const typeInfo = new TypeInfo(targetSchema); const visitorKeys: ASTVisitorKeyMap = { Document: ['definitions'], OperationDefinition: ['selectionSet'], SelectionSet: ['selections'], InlineFragment: ['selectionSet'], FragmentDefinition: ['selectionSet'], }; return visit( document, visitWithTypeInfo(typeInfo, { [Kind.FRAGMENT_DEFINITION]: (node: FragmentDefinitionNode) => { const typeName = node.typeCondition.name.value; if (!rootTypeNames.has(typeName)) { return false; } }, [Kind.FIELD]: (node: FieldNode) => { const type = typeInfo.getType(); if (type != null && isAbstractType(getNamedType(type))) { return { ...node, selectionSet: { kind: Kind.SELECTION_SET, selections: [ { kind: Kind.INLINE_FRAGMENT, typeCondition: { kind: Kind.NAMED_TYPE, name: { kind: Kind.NAME, value: namedType.name, }, }, selectionSet: node.selectionSet, }, ], }, }; } }, }), // visitorKeys argument usage a la https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby-source-graphql/src/batching/merge-queries.js // empty keys cannot be removed only because of typescript errors // will hopefully be fixed in future version of graphql-js to be optional visitorKeys as any ); }
the_stack
import { useActionSheet } from "@expo/react-native-action-sheet" import { StackScreenProps } from "@react-navigation/stack" import { FancyModalHeader } from "lib/Components/FancyModal/FancyModalHeader" import { GlobalStore } from "lib/store/GlobalStore" import { showPhotoActionSheet } from "lib/utils/requestPhotos" import { isEmpty } from "lodash" import { Box, Button, Flex, Input, Join, Sans, Separator, Spacer, Text } from "palette" import { Select } from "palette/elements/Select" import React from "react" import { ScrollView, TouchableOpacity } from "react-native" import { ScreenMargin } from "../../../Components/ScreenMargin" import { ArrowDetails } from "../Components/ArrowDetails" import { ArtistAutosuggest } from "../Components/ArtistAutosuggest" import { Dimensions } from "../Components/Dimensions" import { MediumPicker } from "../Components/MediumPicker" import { useArtworkForm } from "../Form/useArtworkForm" import { ArtworkFormScreen } from "../MyCollectionArtworkForm" const SHOW_FORM_VALIDATION_ERRORS_IN_DEV = false export const MyCollectionArtworkFormMain: React.FC<StackScreenProps<ArtworkFormScreen, "ArtworkForm">> = ({ navigation, route, }) => { const artworkActions = GlobalStore.actions.myCollection.artwork const artworkState = GlobalStore.useAppState((state) => state.myCollection.artwork) const { formik } = useArtworkForm() const { showActionSheetWithOptions } = useActionSheet() const modalType = route.params.mode const addOrEditLabel = modalType === "edit" ? "Edit" : "Add" const formikValues = formik?.values const isFormDirty = () => { // if you fill an empty field then delete it again, it changes from null to "" const isEqual = (aVal: any, bVal: any) => (aVal === "" || aVal === null) && (bVal === "" || bVal === null) ? true : aVal === bVal const { formValues, dirtyFormCheckValues } = artworkState.sessionState return Object.getOwnPropertyNames(dirtyFormCheckValues).reduce( (accum: boolean, key: string) => accum || !isEqual((formValues as { [key: string]: any })[key], (dirtyFormCheckValues as { [key: string]: any })[key]), false ) } return ( <> <FancyModalHeader onLeftButtonPress={route.params.onHeaderBackButtonPress} rightButtonText={isFormDirty() ? "Clear" : undefined} onRightButtonPress={isFormDirty() ? () => route.params.clearForm() : undefined} > {addOrEditLabel} Artwork </FancyModalHeader> <ScrollView keyboardDismissMode="on-drag" keyboardShouldPersistTaps="handled"> <Spacer my={1} /> <Text textAlign="center"> {addOrEditLabel} details about your artwork to access {"\n"} price and market insights. </Text> <Spacer my="1" /> <ScreenMargin> <Join separator={<Spacer my={1} />}> <ArtistAutosuggest /> </Join> </ScreenMargin> <Flex p={2}> <Join separator={<Spacer my={1} />}> <Input title="TITLE" placeholder="Title" onChangeText={formik.handleChange("title")} onBlur={formik.handleBlur("title")} testID="TitleInput" required accessibilityLabel="Title" value={formikValues.title} /> <Input title="YEAR" keyboardType="number-pad" placeholder="Year created" onChangeText={formik.handleChange("date")} onBlur={formik.handleBlur("date")} testID="DateInput" accessibilityLabel="Year" value={formikValues.date} /> <MediumPicker /> <Input title="MATERIALS" placeholder="Materials" onChangeText={formik.handleChange("category")} onBlur={formik.handleBlur("category")} testID="MaterialsInput" accessibilityLabel="Materials" value={formikValues.category} /> <Dimensions /> <Input title="PRICE PAID" placeholder="Price paid" keyboardType="decimal-pad" accessibilityLabel="Price paid" onChangeText={formik.handleChange("pricePaidDollars")} onBlur={formik.handleBlur("pricePaidDollars")} testID="PricePaidInput" value={formikValues.pricePaidDollars} /> <Select title="Currency" placeholder="Currency" options={pricePaidCurrencySelectOptions} value={formikValues.pricePaidCurrency} enableSearch={false} showTitleLabel={false} onSelectValue={(value) => { formik.handleChange("pricePaidCurrency")(value) }} testID="CurrencyPicker" /> <Input title="LOCATION" placeholder="Enter City Where Artwork is Located" onChangeText={formik.handleChange("artworkLocation")} onBlur={formik.handleBlur("artworkLocation")} testID="LocationInput" accessibilityLabel="Enter City Where the Artwork is Located" value={formikValues.artworkLocation} /> <Input multiline title="PROVENANCE" placeholder="Describe How You Acquired the Artwork" value={formikValues.provenance} accessibilityLabel="Describe How You Acquired the Artwork" onChangeText={formik.handleChange("provenance")} testID="ProvenanceInput" /> </Join> </Flex> <Spacer mt={1} /> <PhotosButton testID="PhotosButton" onPress={() => { if (isEmpty(artworkState.sessionState.formValues.photos)) { showPhotoActionSheet(showActionSheetWithOptions, true).then((photos) => { artworkActions.addPhotos(photos) }) } else { navigation.navigate("AddPhotos", { onHeaderBackButtonPress: route.params.onHeaderBackButtonPress }) } }} /> <Spacer mt={2} mb={1} /> <ScreenMargin> <Button disabled={!formik.isValid || !isFormDirty()} block onPress={formik.handleSubmit} testID="CompleteButton" haptic > {modalType === "edit" ? "Save changes" : "Complete"} </Button> {modalType === "edit" && ( <Button mt={1} variant="outline" block onPress={() => { showActionSheetWithOptions( { title: "Delete artwork?", options: ["Delete", "Cancel"], destructiveButtonIndex: 0, cancelButtonIndex: 1, useModal: true, }, (buttonIndex) => { if (buttonIndex === 0) { route.params.onDelete?.() } } ) }} testID="DeleteButton" > Delete artwork </Button> )} <Spacer mt={4} /> </ScreenMargin> {/* Show validation errors during development */} {!!(SHOW_FORM_VALIDATION_ERRORS_IN_DEV && __DEV__ && formik.errors) && ( <ScreenMargin> <Box my={2}> <Sans size="3">Errors: {JSON.stringify(formik.errors)}</Sans> </Box> </ScreenMargin> )} </ScrollView> </> ) } const pricePaidCurrencySelectOptions: Array<{ label: string value: string }> = [ { label: "$ USD", value: "USD" }, { label: "€ EUR", value: "EUR" }, { label: "£ GBP", value: "GBP" }, // Gravity supports the following, however for the prototype // we're only supporting the three above. // { label: "AED", value: "AED" }, // { label: "ARS", value: "ARS" }, // { label: "AUD", value: "AUD" }, // { label: "BRL", value: "BRL" }, // { label: "CAD", value: "CAD" }, // { label: "CDF", value: "CDF" }, // { label: "CHF", value: "CHF" }, // { label: "CNY", value: "CNY" }, // { label: "COP", value: "COP" }, // { label: "DKK", value: "DKK" }, // { label: "ERN", value: "ERN" }, // { label: "ETB", value: "ETB" }, // { label: "HKD", value: "HKD" }, // { label: "IDR", value: "IDR" }, // { label: "ILS", value: "ILS" }, // { label: "INR", value: "INR" }, // { label: "ISK", value: "ISK" }, // { label: "JPY", value: "JPY" }, // { label: "KRW", value: "KRW" }, // { label: "MXN", value: "MXN" }, // { label: "NOK", value: "NOK" }, // { label: "NZD", value: "NZD" }, // { label: "PHP", value: "PHP" }, // { label: "RUB", value: "RUB" }, // { label: "SEK", value: "SEK" }, // { label: "SGD", value: "SGD" }, // { label: "SZL", value: "SZL" }, // { label: "TOP", value: "TOP" }, // { label: "TRY", value: "TRY" }, // { label: "TWD", value: "TWD" }, // { label: "TZS", value: "TZS" }, // { label: "VND", value: "VND" }, // { label: "WST", value: "WST" }, // { label: "ZAR", value: "ZAR" }, ] const PhotosButton: React.FC<{ onPress: () => void; testID?: string }> = ({ onPress, testID }) => { const artworkState = GlobalStore.useAppState((state) => state.myCollection.artwork) const photos = artworkState.sessionState.formValues.photos return ( <> <Separator /> <TouchableOpacity onPress={onPress} testID={testID}> <Spacer mt={2} /> <ScreenMargin> <ArrowDetails> <Flex flexDirection="row"> <Text variant="xs">PHOTOS</Text> </Flex> {photos.length > 0 && ( <> {photos.length === 1 ? ( <Text variant="xs" testID="onePhoto"> 1 photo added </Text> ) : ( <Text variant="xs" testID="multiplePhotos"> {photos.length} photos added </Text> )} </> )} </ArrowDetails> </ScreenMargin> <Spacer mb={2} /> </TouchableOpacity> <Separator /> </> ) }
the_stack
import {Direction} from '@angular/cdk/bidi'; import {ElementRef} from '@angular/core'; import {coerceElement} from '@angular/cdk/coercion'; import {DragDropRegistry} from '../drag-drop-registry'; import {moveItemInArray} from '../drag-utils'; import {combineTransforms} from '../dom/styling'; import {adjustClientRect, getMutableClientRect, isInsideClientRect} from '../dom/client-rect'; import { DropListSortStrategy, DropListSortStrategyItem, SortPredicate, } from './drop-list-sort-strategy'; /** * Entry in the position cache for draggable items. * @docs-private */ interface CachedItemPosition<T> { /** Instance of the drag item. */ drag: T; /** Dimensions of the item. */ clientRect: ClientRect; /** Amount by which the item has been moved since dragging started. */ offset: number; /** Inline transform that the drag item had when dragging started. */ initialTransform: string; } /** * Strategy that only supports sorting along a single axis. * Items are reordered using CSS transforms which allows for sorting to be animated. * @docs-private */ export class SingleAxisSortStrategy<T extends DropListSortStrategyItem> implements DropListSortStrategy<T> { /** Function used to determine if an item can be sorted into a specific index. */ private _sortPredicate: SortPredicate<T>; /** Cache of the dimensions of all the items inside the container. */ private _itemPositions: CachedItemPosition<T>[] = []; /** * Draggable items that are currently active inside the container. Includes the items * that were there at the start of the sequence, as well as any items that have been dragged * in, but haven't been dropped yet. */ private _activeDraggables: T[]; /** Direction in which the list is oriented. */ orientation: 'vertical' | 'horizontal' = 'vertical'; /** Layout direction of the drop list. */ direction: Direction; constructor( private _element: HTMLElement | ElementRef<HTMLElement>, private _dragDropRegistry: DragDropRegistry<T, unknown>, ) {} /** * Keeps track of the item that was last swapped with the dragged item, as well as what direction * the pointer was moving in when the swap occured and whether the user's pointer continued to * overlap with the swapped item after the swapping occurred. */ private _previousSwap = { drag: null as T | null, delta: 0, overlaps: false, }; /** * To be called when the drag sequence starts. * @param items Items that are currently in the list. */ start(items: readonly T[]) { this.withItems(items); } /** * To be called when an item is being sorted. * @param item Item to be sorted. * @param pointerX Position of the item along the X axis. * @param pointerY Position of the item along the Y axis. * @param pointerDelta Direction in which the pointer is moving along each axis. */ sort(item: T, pointerX: number, pointerY: number, pointerDelta: {x: number; y: number}) { const siblings = this._itemPositions; const newIndex = this._getItemIndexFromPointerPosition(item, pointerX, pointerY, pointerDelta); if (newIndex === -1 && siblings.length > 0) { return null; } const isHorizontal = this.orientation === 'horizontal'; const currentIndex = siblings.findIndex(currentItem => currentItem.drag === item); const siblingAtNewPosition = siblings[newIndex]; const currentPosition = siblings[currentIndex].clientRect; const newPosition = siblingAtNewPosition.clientRect; const delta = currentIndex > newIndex ? 1 : -1; // How many pixels the item's placeholder should be offset. const itemOffset = this._getItemOffsetPx(currentPosition, newPosition, delta); // How many pixels all the other items should be offset. const siblingOffset = this._getSiblingOffsetPx(currentIndex, siblings, delta); // Save the previous order of the items before moving the item to its new index. // We use this to check whether an item has been moved as a result of the sorting. const oldOrder = siblings.slice(); // Shuffle the array in place. moveItemInArray(siblings, currentIndex, newIndex); siblings.forEach((sibling, index) => { // Don't do anything if the position hasn't changed. if (oldOrder[index] === sibling) { return; } const isDraggedItem = sibling.drag === item; const offset = isDraggedItem ? itemOffset : siblingOffset; const elementToOffset = isDraggedItem ? item.getPlaceholderElement() : sibling.drag.getRootElement(); // Update the offset to reflect the new position. sibling.offset += offset; // Since we're moving the items with a `transform`, we need to adjust their cached // client rects to reflect their new position, as well as swap their positions in the cache. // Note that we shouldn't use `getBoundingClientRect` here to update the cache, because the // elements may be mid-animation which will give us a wrong result. if (isHorizontal) { // Round the transforms since some browsers will // blur the elements, for sub-pixel transforms. elementToOffset.style.transform = combineTransforms( `translate3d(${Math.round(sibling.offset)}px, 0, 0)`, sibling.initialTransform, ); adjustClientRect(sibling.clientRect, 0, offset); } else { elementToOffset.style.transform = combineTransforms( `translate3d(0, ${Math.round(sibling.offset)}px, 0)`, sibling.initialTransform, ); adjustClientRect(sibling.clientRect, offset, 0); } }); // Note that it's important that we do this after the client rects have been adjusted. this._previousSwap.overlaps = isInsideClientRect(newPosition, pointerX, pointerY); this._previousSwap.drag = siblingAtNewPosition.drag; this._previousSwap.delta = isHorizontal ? pointerDelta.x : pointerDelta.y; return {previousIndex: currentIndex, currentIndex: newIndex}; } /** * Called when an item is being moved into the container. * @param item Item that was moved into the container. * @param pointerX Position of the item along the X axis. * @param pointerY Position of the item along the Y axis. * @param index Index at which the item entered. If omitted, the container will try to figure it * out automatically. */ enter(item: T, pointerX: number, pointerY: number, index?: number): void { const newIndex = index == null || index < 0 ? // We use the coordinates of where the item entered the drop // zone to figure out at which index it should be inserted. this._getItemIndexFromPointerPosition(item, pointerX, pointerY) : index; const activeDraggables = this._activeDraggables; const currentIndex = activeDraggables.indexOf(item); const placeholder = item.getPlaceholderElement(); let newPositionReference: T | undefined = activeDraggables[newIndex]; // If the item at the new position is the same as the item that is being dragged, // it means that we're trying to restore the item to its initial position. In this // case we should use the next item from the list as the reference. if (newPositionReference === item) { newPositionReference = activeDraggables[newIndex + 1]; } // If we didn't find a new position reference, it means that either the item didn't start off // in this container, or that the item requested to be inserted at the end of the list. if ( !newPositionReference && (newIndex == null || newIndex === -1 || newIndex < activeDraggables.length - 1) && this._shouldEnterAsFirstChild(pointerX, pointerY) ) { newPositionReference = activeDraggables[0]; } // Since the item may be in the `activeDraggables` already (e.g. if the user dragged it // into another container and back again), we have to ensure that it isn't duplicated. if (currentIndex > -1) { activeDraggables.splice(currentIndex, 1); } // Don't use items that are being dragged as a reference, because // their element has been moved down to the bottom of the body. if (newPositionReference && !this._dragDropRegistry.isDragging(newPositionReference)) { const element = newPositionReference.getRootElement(); element.parentElement!.insertBefore(placeholder, element); activeDraggables.splice(newIndex, 0, item); } else { coerceElement(this._element).appendChild(placeholder); activeDraggables.push(item); } // The transform needs to be cleared so it doesn't throw off the measurements. placeholder.style.transform = ''; // Note that usually `start` is called together with `enter` when an item goes into a new // container. This will cache item positions, but we need to refresh them since the amount // of items has changed. this._cacheItemPositions(); } /** Sets the items that are currently part of the list. */ withItems(items: readonly T[]): void { this._activeDraggables = items.slice(); this._cacheItemPositions(); } /** Assigns a sort predicate to the strategy. */ withSortPredicate(predicate: SortPredicate<T>): void { this._sortPredicate = predicate; } /** Resets the strategy to its initial state before dragging was started. */ reset() { // TODO(crisbeto): may have to wait for the animations to finish. this._activeDraggables.forEach(item => { const rootElement = item.getRootElement(); if (rootElement) { const initialTransform = this._itemPositions.find(p => p.drag === item)?.initialTransform; rootElement.style.transform = initialTransform || ''; } }); this._itemPositions = []; this._activeDraggables = []; this._previousSwap.drag = null; this._previousSwap.delta = 0; this._previousSwap.overlaps = false; } /** * Gets a snapshot of items currently in the list. * Can include items that we dragged in from another list. */ getActiveItemsSnapshot(): readonly T[] { return this._activeDraggables; } /** Gets the index of a specific item. */ getItemIndex(item: T): number { // Items are sorted always by top/left in the cache, however they flow differently in RTL. // The rest of the logic still stands no matter what orientation we're in, however // we need to invert the array when determining the index. const items = this.orientation === 'horizontal' && this.direction === 'rtl' ? this._itemPositions.slice().reverse() : this._itemPositions; return items.findIndex(currentItem => currentItem.drag === item); } /** Used to notify the strategy that the scroll position has changed. */ updateOnScroll(topDifference: number, leftDifference: number) { // Since we know the amount that the user has scrolled we can shift all of the // client rectangles ourselves. This is cheaper than re-measuring everything and // we can avoid inconsistent behavior where we might be measuring the element before // its position has changed. this._itemPositions.forEach(({clientRect}) => { adjustClientRect(clientRect, topDifference, leftDifference); }); // We need two loops for this, because we want all of the cached // positions to be up-to-date before we re-sort the item. this._itemPositions.forEach(({drag}) => { if (this._dragDropRegistry.isDragging(drag)) { // We need to re-sort the item manually, because the pointer move // events won't be dispatched while the user is scrolling. drag._sortFromLastPointerPosition(); } }); } /** Refreshes the position cache of the items and sibling containers. */ private _cacheItemPositions() { const isHorizontal = this.orientation === 'horizontal'; this._itemPositions = this._activeDraggables .map(drag => { const elementToMeasure = drag.getVisibleElement(); return { drag, offset: 0, initialTransform: elementToMeasure.style.transform || '', clientRect: getMutableClientRect(elementToMeasure), }; }) .sort((a, b) => { return isHorizontal ? a.clientRect.left - b.clientRect.left : a.clientRect.top - b.clientRect.top; }); } /** * Gets the offset in pixels by which the item that is being dragged should be moved. * @param currentPosition Current position of the item. * @param newPosition Position of the item where the current item should be moved. * @param delta Direction in which the user is moving. */ private _getItemOffsetPx(currentPosition: ClientRect, newPosition: ClientRect, delta: 1 | -1) { const isHorizontal = this.orientation === 'horizontal'; let itemOffset = isHorizontal ? newPosition.left - currentPosition.left : newPosition.top - currentPosition.top; // Account for differences in the item width/height. if (delta === -1) { itemOffset += isHorizontal ? newPosition.width - currentPosition.width : newPosition.height - currentPosition.height; } return itemOffset; } /** * Gets the offset in pixels by which the items that aren't being dragged should be moved. * @param currentIndex Index of the item currently being dragged. * @param siblings All of the items in the list. * @param delta Direction in which the user is moving. */ private _getSiblingOffsetPx( currentIndex: number, siblings: CachedItemPosition<T>[], delta: 1 | -1, ) { const isHorizontal = this.orientation === 'horizontal'; const currentPosition = siblings[currentIndex].clientRect; const immediateSibling = siblings[currentIndex + delta * -1]; let siblingOffset = currentPosition[isHorizontal ? 'width' : 'height'] * delta; if (immediateSibling) { const start = isHorizontal ? 'left' : 'top'; const end = isHorizontal ? 'right' : 'bottom'; // Get the spacing between the start of the current item and the end of the one immediately // after it in the direction in which the user is dragging, or vice versa. We add it to the // offset in order to push the element to where it will be when it's inline and is influenced // by the `margin` of its siblings. if (delta === -1) { siblingOffset -= immediateSibling.clientRect[start] - currentPosition[end]; } else { siblingOffset += currentPosition[start] - immediateSibling.clientRect[end]; } } return siblingOffset; } /** * Checks if pointer is entering in the first position * @param pointerX Position of the user's pointer along the X axis. * @param pointerY Position of the user's pointer along the Y axis. */ private _shouldEnterAsFirstChild(pointerX: number, pointerY: number) { if (!this._activeDraggables.length) { return false; } const itemPositions = this._itemPositions; const isHorizontal = this.orientation === 'horizontal'; // `itemPositions` are sorted by position while `activeDraggables` are sorted by child index // check if container is using some sort of "reverse" ordering (eg: flex-direction: row-reverse) const reversed = itemPositions[0].drag !== this._activeDraggables[0]; if (reversed) { const lastItemRect = itemPositions[itemPositions.length - 1].clientRect; return isHorizontal ? pointerX >= lastItemRect.right : pointerY >= lastItemRect.bottom; } else { const firstItemRect = itemPositions[0].clientRect; return isHorizontal ? pointerX <= firstItemRect.left : pointerY <= firstItemRect.top; } } /** * Gets the index of an item in the drop container, based on the position of the user's pointer. * @param item Item that is being sorted. * @param pointerX Position of the user's pointer along the X axis. * @param pointerY Position of the user's pointer along the Y axis. * @param delta Direction in which the user is moving their pointer. */ private _getItemIndexFromPointerPosition( item: T, pointerX: number, pointerY: number, delta?: {x: number; y: number}, ): number { const isHorizontal = this.orientation === 'horizontal'; const index = this._itemPositions.findIndex(({drag, clientRect}) => { // Skip the item itself. if (drag === item) { return false; } if (delta) { const direction = isHorizontal ? delta.x : delta.y; // If the user is still hovering over the same item as last time, their cursor hasn't left // the item after we made the swap, and they didn't change the direction in which they're // dragging, we don't consider it a direction swap. if ( drag === this._previousSwap.drag && this._previousSwap.overlaps && direction === this._previousSwap.delta ) { return false; } } return isHorizontal ? // Round these down since most browsers report client rects with // sub-pixel precision, whereas the pointer coordinates are rounded to pixels. pointerX >= Math.floor(clientRect.left) && pointerX < Math.floor(clientRect.right) : pointerY >= Math.floor(clientRect.top) && pointerY < Math.floor(clientRect.bottom); }); return index === -1 || !this._sortPredicate(index, item) ? -1 : index; } }
the_stack
import { HttpResponse, HttpEvent } from '@angular/common/http'; import { Observable } from 'rxjs';import { HttpOptions } from './types'; import * as models from './models'; export interface APIClientInterface { /** * Arguments object for method `getPetById`. */ getPetByIdParams?: { /** ID of pet to return */ petId: number, }; /** * Find pet by ID * Returns a single pet * Response generated for [ 200 ] HTTP response code. */ getPetById( args: Exclude<APIClientInterface['getPetByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Pet>; getPetById( args: Exclude<APIClientInterface['getPetByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Pet>>; getPetById( args: Exclude<APIClientInterface['getPetByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Pet>>; /** * Arguments object for method `updatePetWithForm`. */ updatePetWithFormParams?: { /** ID of pet that needs to be updated */ petId: number, /** Updated name of the pet */ name?: string, /** Updated status of the pet */ status?: string, }; /** * Updates a pet in the store with form data * Response generated for [ default ] HTTP response code. */ updatePetWithForm( args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; updatePetWithForm( args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; updatePetWithForm( args: Exclude<APIClientInterface['updatePetWithFormParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `deletePet`. */ deletePetParams?: { apiKey?: string, /** Pet id to delete */ petId: number, }; /** * Deletes a pet * Response generated for [ default ] HTTP response code. */ deletePet( args: Exclude<APIClientInterface['deletePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deletePet( args: Exclude<APIClientInterface['deletePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deletePet( args: Exclude<APIClientInterface['deletePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `uploadFile`. */ uploadFileParams?: { /** ID of pet to update */ petId: number, /** Additional data to pass to server */ additionalMetadata?: string, /** file to upload */ file?: File, }; /** * uploads an image * Response generated for [ 200 ] HTTP response code. */ uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.ApiResponse>; uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.ApiResponse>>; uploadFile( args: Exclude<APIClientInterface['uploadFileParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.ApiResponse>>; /** * Arguments object for method `addPet`. */ addPetParams?: { /** Pet object that needs to be added to the store */ body: models.Pet, }; /** * Add a new pet to the store * Response generated for [ default ] HTTP response code. */ addPet( args: Exclude<APIClientInterface['addPetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; addPet( args: Exclude<APIClientInterface['addPetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; addPet( args: Exclude<APIClientInterface['addPetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `updatePet`. */ updatePetParams?: { /** Pet object that needs to be added to the store */ body: models.Pet, }; /** * Update an existing pet * Response generated for [ default ] HTTP response code. */ updatePet( args: Exclude<APIClientInterface['updatePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; updatePet( args: Exclude<APIClientInterface['updatePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; updatePet( args: Exclude<APIClientInterface['updatePetParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `findPetsByStatus`. */ findPetsByStatusParams?: { /** Status values that need to be considered for filter */ status: ('available' | 'pending' | 'sold')[], }; /** * Finds Pets by status * Multiple status values can be provided with comma separated strings * Response generated for [ 200 ] HTTP response code. */ findPetsByStatus( args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Pet[]>; findPetsByStatus( args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Pet[]>>; findPetsByStatus( args: Exclude<APIClientInterface['findPetsByStatusParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Pet[]>>; /** * Arguments object for method `findPetsByTags`. */ findPetsByTagsParams?: { /** Tags to filter by */ tags: string[], }; /** * Finds Pets by tags * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * @deprecated this method has been deprecated and may be removed in future. * Response generated for [ 200 ] HTTP response code. */ findPetsByTags( args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Pet[]>; findPetsByTags( args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Pet[]>>; findPetsByTags( args: Exclude<APIClientInterface['findPetsByTagsParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Pet[]>>; /** * Returns pet inventories by status * Returns a map of status codes to quantities * Response generated for [ 200 ] HTTP response code. */ getInventory( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<{ [key: string]: number }>; getInventory( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<{ [key: string]: number }>>; getInventory( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<{ [key: string]: number }>>; /** * Arguments object for method `getOrderById`. */ getOrderByIdParams?: { /** ID of pet that needs to be fetched */ orderId: number, }; /** * Find purchase order by ID * For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions * Response generated for [ 200 ] HTTP response code. */ getOrderById( args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Order>; getOrderById( args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Order>>; getOrderById( args: Exclude<APIClientInterface['getOrderByIdParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Order>>; /** * Arguments object for method `deleteOrder`. */ deleteOrderParams?: { /** ID of the order that needs to be deleted */ orderId: number, }; /** * Delete purchase order by ID * For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors * Response generated for [ default ] HTTP response code. */ deleteOrder( args: Exclude<APIClientInterface['deleteOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteOrder( args: Exclude<APIClientInterface['deleteOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteOrder( args: Exclude<APIClientInterface['deleteOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `placeOrder`. */ placeOrderParams?: { /** order placed for purchasing the pet */ body: models.Order, }; /** * Place an order for a pet * Response generated for [ 200 ] HTTP response code. */ placeOrder( args: Exclude<APIClientInterface['placeOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.Order>; placeOrder( args: Exclude<APIClientInterface['placeOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.Order>>; placeOrder( args: Exclude<APIClientInterface['placeOrderParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.Order>>; /** * Arguments object for method `getUserByName`. */ getUserByNameParams?: { /** The name that needs to be fetched. Use user1 for testing. */ username: string, }; /** * Get user by user name * Response generated for [ 200 ] HTTP response code. */ getUserByName( args: Exclude<APIClientInterface['getUserByNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<models.User>; getUserByName( args: Exclude<APIClientInterface['getUserByNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<models.User>>; getUserByName( args: Exclude<APIClientInterface['getUserByNameParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<models.User>>; /** * Arguments object for method `updateUser`. */ updateUserParams?: { /** name that need to be updated */ username: string, /** Updated user object */ body: models.User, }; /** * Updated user * This can only be done by the logged in user. * Response generated for [ default ] HTTP response code. */ updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; updateUser( args: Exclude<APIClientInterface['updateUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `deleteUser`. */ deleteUserParams?: { /** The name that needs to be deleted */ username: string, }; /** * Delete user * This can only be done by the logged in user. * Response generated for [ default ] HTTP response code. */ deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; deleteUser( args: Exclude<APIClientInterface['deleteUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `loginUser`. */ loginUserParams?: { /** The user name for login */ username: string, /** The password for login in clear text */ password: string, }; /** * Logs user into the system * Response generated for [ 200 ] HTTP response code. */ loginUser( args: Exclude<APIClientInterface['loginUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<string>; loginUser( args: Exclude<APIClientInterface['loginUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<string>>; loginUser( args: Exclude<APIClientInterface['loginUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<string>>; /** * Logs out current logged in user session * Response generated for [ default ] HTTP response code. */ logoutUser( requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; logoutUser( requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; logoutUser( requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `createUser`. */ createUserParams?: { /** Created user object */ body: models.User, }; /** * Create user * This can only be done by the logged in user. * Response generated for [ default ] HTTP response code. */ createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; createUser( args: Exclude<APIClientInterface['createUserParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `createUsersWithArrayInput`. */ createUsersWithArrayInputParams?: { /** List of user object */ body: models.User[], }; /** * Creates list of users with given input array * Response generated for [ default ] HTTP response code. */ createUsersWithArrayInput( args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; createUsersWithArrayInput( args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; createUsersWithArrayInput( args: Exclude<APIClientInterface['createUsersWithArrayInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; /** * Arguments object for method `createUsersWithListInput`. */ createUsersWithListInputParams?: { /** List of user object */ body: models.User[], }; /** * Creates list of users with given input array * Response generated for [ default ] HTTP response code. */ createUsersWithListInput( args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'body', ): Observable<void>; createUsersWithListInput( args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'response', ): Observable<HttpResponse<void>>; createUsersWithListInput( args: Exclude<APIClientInterface['createUsersWithListInputParams'], undefined>, requestHttpOptions?: HttpOptions, observe?: 'events', ): Observable<HttpEvent<void>>; }
the_stack
import {fileURLToPath} from './url.js'; import { InvalidModuleSpecifierError, InvalidPackageConfigError, InvalidPackageTargetError, PackagePathNotExportedError, } from './errors.js'; import type { PackageExports, PackageExportsPathOrConditionMap, PackageExportsTarget, PackageJsonWithExports, } from '../util.js'; function emitFolderMapDeprecation( match: string, pjsonUrl: URL, isExports: boolean, base: string ): void { const pjsonPath = fileURLToPath(pjsonUrl); console.warn( `Use of deprecated folder mapping "${match}" in the ${ isExports ? '"exports"' : '"imports"' } field module resolution of the package at ${pjsonPath}${ base ? ` imported from ${base}` : '' }.\n` + `Update this package.json to use a subpath pattern like "${match}*".`, 'DeprecationWarning', 'DEP0148' ); } function makeExportsNotFoundError( subpath: string, packageJSONUrl: URL, base: string ): PackagePathNotExportedError { return new PackagePathNotExportedError( fileURLToPath(new URL('.', packageJSONUrl)), subpath, base ); } function makeInvalidSubpathError( subpath: string, packageJSONUrl: URL, internal: boolean, base: string ) { const reason = `request is not a valid subpath for the "${ internal ? 'imports' : 'exports' }" resolution of ${fileURLToPath(packageJSONUrl)}`; return new InvalidModuleSpecifierError(subpath, reason, base); } function makeInvalidPackageTargetError( subpath: string, target: PackageExportsTarget, packageJSONUrl: URL, internal: boolean, base: string ) { if (typeof target === 'object' && target !== null) { target = JSON.stringify(target, null, ''); } else { target = `${target}`; } return new InvalidPackageTargetError( packageJSONUrl, subpath, target, internal, base ); } const invalidSegmentRegEx = /(^|\\|\/)(\.\.?|node_modules)(\\|\/|$)/; const patternRegEx = /\*/g; function resolvePackageTargetString( target: string, subpath: string, match: string, packageJSONUrl: URL, base: string, pattern: boolean, internal: boolean, // eslint-disable-next-line @typescript-eslint/no-unused-vars _conditions: Set<string> ): URL { if (subpath !== '' && !pattern && target[target.length - 1] !== '/') { throw makeInvalidPackageTargetError( match, target, packageJSONUrl, internal, base ); } if (!target.startsWith('./')) { // TODO(aomarks) Add when support here for package "imports" is added. throw makeInvalidPackageTargetError( match, target, packageJSONUrl, internal, base ); } if (invalidSegmentRegEx.test(target.slice(2))) { throw makeInvalidPackageTargetError( match, target, packageJSONUrl, internal, base ); } const resolved = new URL(target, packageJSONUrl); const resolvedPath = resolved.pathname; const packagePath = new URL('.', packageJSONUrl).pathname; if (!resolvedPath.startsWith(packagePath)) { throw makeInvalidPackageTargetError( match, target, packageJSONUrl, internal, base ); } if (subpath === '') { return resolved; } if (invalidSegmentRegEx.test(subpath)) { throw makeInvalidSubpathError( match + subpath, packageJSONUrl, internal, base ); } if (pattern) { return new URL(resolved.href.replace(patternRegEx, subpath)); } return new URL(subpath, resolved); } function isArrayIndex(key: string): boolean { const keyNum = +key; if (`${keyNum}` !== key) { return false; } return keyNum >= 0 && keyNum < 0xffff_ffff; } function resolvePackageTarget( packageJSONUrl: URL, target: PackageExportsTarget, subpath: string, packageSubpath: string, base: string, pattern: boolean, internal: boolean, conditions: Set<string> ): URL | null | undefined { if (typeof target === 'string') { return resolvePackageTargetString( target, subpath, packageSubpath, packageJSONUrl, base, pattern, internal, conditions ); } else if (Array.isArray(target)) { if (target.length === 0) { return null; } let lastException; for (let i = 0; i < target.length; i++) { const targetItem = target[i]; let resolved; try { resolved = resolvePackageTarget( packageJSONUrl, targetItem, subpath, packageSubpath, base, pattern, internal, conditions ); } catch (e) { lastException = e; if (e instanceof InvalidPackageTargetError) { continue; } throw e; } if (resolved === undefined) continue; if (resolved === null) { lastException = null; continue; } return resolved; } if (lastException === undefined || lastException === null) { return lastException; } throw lastException; } else if (typeof target === 'object' && target !== null) { const keys = Object.getOwnPropertyNames(target); for (let i = 0; i < keys.length; i++) { const key = keys[i]; if (isArrayIndex(key)) { throw new InvalidPackageConfigError( fileURLToPath(packageJSONUrl), base, '"exports" cannot contain numeric property keys.' ); } } for (let i = 0; i < keys.length; i++) { const key = keys[i]; if (key === 'default' || conditions.has(key)) { const conditionalTarget = target[key]; const resolved = resolvePackageTarget( packageJSONUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, conditions ); if (resolved === undefined) continue; return resolved; } } return undefined; } else if (target === null) { return null; } throw makeInvalidPackageTargetError( packageSubpath, target, packageJSONUrl, internal, base ); } function isConditionalExportsMainSugar( exports: PackageExports, packageJSONUrl: URL, base: string ): boolean { if (typeof exports === 'string' || Array.isArray(exports)) { return true; } if (typeof exports !== 'object' || exports === null) { return false; } const keys = Object.getOwnPropertyNames(exports); let isConditionalSugar = false; let i = 0; for (let j = 0; j < keys.length; j++) { const key = keys[j]; const curIsConditionalSugar = key === '' || key[0] !== '.'; if (i++ === 0) { isConditionalSugar = curIsConditionalSugar; } else if (isConditionalSugar !== curIsConditionalSugar) { throw new InvalidPackageConfigError( fileURLToPath(packageJSONUrl), base, '"exports" cannot contain some keys starting with \'.\' and some not.' + ' The exports object must either be an object of package subpath keys' + ' or an object of main entry condition name keys only.' ); } } return isConditionalSugar; } export function packageExportsResolve( packageJSONUrl: URL, packageSubpath: string, packageConfig: PackageJsonWithExports, base: string, conditions: Set<string> ): URL { let exports = packageConfig.exports; if (isConditionalExportsMainSugar(exports, packageJSONUrl, base)) { exports = {'.': exports}; } exports = exports as PackageExportsPathOrConditionMap; if ( Object.prototype.hasOwnProperty.call(exports, packageSubpath) && !packageSubpath.includes('*') && !packageSubpath.endsWith('/') ) { const target = exports[packageSubpath]; const resolved = resolvePackageTarget( packageJSONUrl, target, '', packageSubpath, base, false, false, conditions ); if (resolved === null || resolved === undefined) { throw makeExportsNotFoundError(packageSubpath, packageJSONUrl, base); } return resolved; } let bestMatch = ''; let bestMatchSubpath: string | undefined = undefined; for (const key of Object.keys(exports)) { const patternIndex = key.indexOf('*'); if ( patternIndex !== -1 && packageSubpath.startsWith(key.slice(0, patternIndex)) ) { const patternTrailer = key.slice(patternIndex + 1); if ( packageSubpath.length >= key.length && packageSubpath.endsWith(patternTrailer) && patternKeyCompare(bestMatch, key) === 1 && key.lastIndexOf('*') === patternIndex ) { bestMatch = key; bestMatchSubpath = packageSubpath.slice( patternIndex, packageSubpath.length - patternTrailer.length ); } } else if ( key.endsWith('/') && packageSubpath.startsWith(key) && patternKeyCompare(bestMatch, key) === 1 ) { bestMatch = key; bestMatchSubpath = packageSubpath.slice(key.length); } } if (bestMatch) { const target = exports[bestMatch]; const pattern = bestMatch.includes('*'); const resolved = resolvePackageTarget( packageJSONUrl, target, // bestMatchSubpath must be defined when bestMatch is not empty string bestMatchSubpath!, bestMatch, base, pattern, false, conditions ); if (resolved === null || resolved === undefined) { throw makeExportsNotFoundError(packageSubpath, packageJSONUrl, base); } if (!pattern) { emitFolderMapDeprecation(bestMatch, packageJSONUrl, true, base); } return resolved; } throw makeExportsNotFoundError(packageSubpath, packageJSONUrl, base); } function patternKeyCompare(a: string, b: string): -1 | 0 | 1 { const aPatternIndex = a.indexOf('*'); const bPatternIndex = b.indexOf('*'); const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; if (baseLenA > baseLenB) return -1; if (baseLenB > baseLenA) return 1; if (aPatternIndex === -1) return 1; if (bPatternIndex === -1) return -1; if (a.length > b.length) return -1; if (b.length > a.length) return 1; return 0; }
the_stack
import { isNote, shuffle, expandStr } from './utils'; import { chord } from 'harmonics'; const defaultSubdiv = '4n'; const defaultDur = '8n'; /** * Get default params for a clip, such as root note, pattern etc * @return {Object} */ const getDefaultParams = (): ClipParams => ({ notes: ['C4'], pattern: 'x', shuffle: false, sizzle: false, sizzleReps: 1, arpegiate: false, subdiv: '4n', amp: 100, accentLow: 70, randomNotes: null, effects: [], offlineRendering: false, }); /** * HDR speed is denoted by the number of ticks per note * By default this is set to a quarter note (4n) to be in line with Tone.js' default subdivision * Technically a bar is 512 ticks long. So it's HDR speed is 512 * @type {Object} */ const hdr: NVP<number> = { '1m': 2048, '2m': 4096, '3m': 6144, '4m': 8192, '1n': 512, '2n': 256, '4n': 128, '8n': 64, '16n': 32, }; const convertChordsToNotes = (el: any) => { if (isNote(el as string)) { // A note needs to be an array so that it can accomodate chords or single notes with a single interface return [el]; } if (Array.isArray(el)) { // This could be a chord provided as an array // make sure it uses valid notes el.forEach(n => { if (!isNote(n)) { throw new TypeError('array must comprise valid notes'); } }); return el; } if (!Array.isArray(el)) { const c = chord(el); if (c && c.length) { return c; } } throw new Error(`Chord ${el} not found`); }; const random = (num = 1) => Math.round(Math.random() * num); const getNote = (el: string, params: ClipParams, counter: number) => { return el === 'R' && params.randomNotes ? params.randomNotes[random(params.randomNotes.length - 1)] : params.notes[counter % params.notes.length]; }; const getDuration = (params: ClipParams, counter: number) => { return params.durations ? params.durations[counter % params.durations.length] : params.dur || params.subdiv || defaultDur; }; /** * @param {Object} * @return {Function} * Take an object literal which has a Tone.js instrument and return a function that can be used * as the callback in Tone.Sequence https://tonejs.github.io/docs/Sequence */ const getSeqFn = (params: ClipParams): SeqFn => { let counter = 0; if (params.instrument instanceof Tone.Player) { return (time: string, el: string) => { if (el === 'x' || el === 'R') { params.instrument.start(time); counter++; } }; } else if ( params.instrument instanceof Tone.PolySynth || params.instrument instanceof Tone.Sampler ) { return (time: string, el: string) => { if (el === 'x' || el === 'R') { params.instrument.triggerAttackRelease( getNote(el, params, counter), getDuration(params, counter), time ); counter++; } }; } else if (params.instrument instanceof Tone.NoiseSynth) { return (time: string, el: string) => { if (el === 'x' || el === 'R') { params.instrument.triggerAttackRelease( getDuration(params, counter), time ); counter++; } }; } else { return (time: string, el: string) => { if (el === 'x' || el === 'R') { params.instrument.triggerAttackRelease( getNote(el, params, counter)[0], getDuration(params, counter), time ); counter++; } }; } }; export const recursivelyApplyPatternToDurations = ( patternArr: string[], length: number, durations: number[] = [] ) => { patternArr.forEach(char => { if (typeof char === 'string') { if (char === 'x' || char === 'R') { durations.push(length); } if (char === '_' && durations.length) { durations[durations.length - 1] += length; } } if (Array.isArray(char)) { recursivelyApplyPatternToDurations(char, length / char.length, durations); } }); return durations; }; const generateSequence = (params: ClipParams, context?: any) => { context = context || Tone.getContext(); if (!params.pattern) { throw new Error('No pattern provided!'); } if ( !params.player && !params.instrument && !params.sample && !params.buffer && !params.synth && !params.sampler && !params.samples ) { throw new Error('No player or instrument provided!'); } if (!params.durations && !params.dur) { params.durations = recursivelyApplyPatternToDurations( expandStr(params.pattern), Tone.Ticks(params.subdiv || defaultSubdiv).toSeconds() ); } /* 1. The params object can be used to pass a sample (sound source) OR a synth(Synth/FMSynth/AMSynth etc) or samples. Scribbletune will then create a Tone.js Player or Tone.js Instrument or Tone.js Sampler respectively 2. It can also be used to pass a Tone.js Player object or instrument that was created elsewhere (mostly by Scribbletune itself in the channel creation method) Either ways, a pattern is required and it will be used to create a playable Tone.js Sequence */ let effects = []; const createEffect = (eff: any) => { const effect: any = typeof eff === 'string' ? new Tone[eff]({ context }) : eff.context !== context ? recreateToneObjectInContext(eff, context) : eff; return effect.toDestination(); }; const startEffect = (eff: any) => { return typeof eff.start === 'function' ? eff.start() : eff; }; if (params.effects) { if (!Array.isArray(params.effects)) { params.effects = [params.effects]; } effects = params.effects.map(createEffect).map(startEffect); } if (params.synth && !params.instrument) { params.instrument = params.synth; console.warn( 'The "synth" parameter will be deprecated in the future. Please use the "instrument" parameter instead.' ); } params.instrument = params.sample || params.buffer ? new Tone.Player({ url: params.sample || params.buffer, context, }) : params.sampler ? params.sampler : params.player ? params.player : params.samples ? new Tone.Sampler({ url: params.samples, context }) : typeof params.instrument === 'string' ? new Tone[params.instrument]({ context }) : params.instrument; if (params.instrument.context !== context) { params.instrument = recreateToneObjectInContext(params.instrument, context); } if (params.volume) { params.instrument.volume.value = params.volume; } params.instrument.chain(...effects).toDestination(); return new Tone.Sequence({ callback: getSeqFn(params), events: expandStr(params.pattern), subdivision: params.subdiv || defaultSubdiv, context, }); }; export const totalPatternDuration = ( pattern: string, subdivOrLength: string | number ) => { return typeof subdivOrLength === 'number' ? subdivOrLength * expandStr(pattern).length : Tone.Ticks(subdivOrLength).toSeconds() * expandStr(pattern).length; }; const leastCommonMultiple = (n1: number, n2: number): number => { const [smallest, largest] = n1 < n2 ? [n1, n2] : [n2, n1]; let i = largest; while (i % smallest !== 0) { i += largest; } return i; }; export const renderingDuration = ( pattern: string, subdivOrLength: string | number, notes: string | (string | string[])[], randomNotes: undefined | null | string | (string | string[])[] ) => { const patternRegularNotesCount = pattern.split('').filter(c => { return c === 'x'; }).length; const patternRandomNotesCount = pattern.split('').filter(c => { return c === 'R'; }).length; const patternNotesCount = randomNotes?.length ? patternRegularNotesCount : patternRegularNotesCount + patternRandomNotesCount; const notesCount = notes.length || 1; return ( (totalPatternDuration(pattern, subdivOrLength) / patternNotesCount) * leastCommonMultiple(notesCount, patternNotesCount) ); }; let ongoingRenderingCounter = 0; let originalContext: any; const recreateToneObjectInContext = (toneObject: any, context: any) => { if (toneObject instanceof Tone.PolySynth) { return new Tone.PolySynth(Tone[toneObject._dummyVoice.name], { ...toneObject.get(), context, }); } else if (toneObject instanceof Tone.Player) { return new Tone.Player({ url: toneObject._buffer, context }); } else if (toneObject instanceof Tone.Sampler) { const { attack, curve, release, volume } = toneObject.get(); const paramsFromSampler = { attack, curve, release, volume }; const paramsFromBuffers = { baseUrl: toneObject._buffers.baseUrl, urls: Object.fromEntries(toneObject._buffers._buffers.entries()), }; return new Tone.Sampler({ ...paramsFromSampler, ...paramsFromBuffers, context, }); } else { return new Tone[toneObject.name]({ ...toneObject.get(), context, }); } }; const offlineRenderClip = (params: ClipParams, duration: number) => { if (!originalContext) { originalContext = Tone.getContext(); } ongoingRenderingCounter++; const player = new Tone.Player({ context: originalContext, loop: true }); Tone.Offline(async (context: any): Promise<void> => { const sequence = generateSequence(params, context); await Tone.loaded(); sequence.start(); context.transport.start(); }, duration).then((buffer: any) => { player.buffer = buffer; ongoingRenderingCounter--; if (ongoingRenderingCounter === 0) { Tone.setContext(originalContext); params.offlineRenderingCallback?.(); } }); player.toDestination(); player.sync(); return player; }; /** * @param {Object} * @return {Tone.js Sequence Object} * Take a object literal that may have a Tone.js player OR instrument * or simply a sample or synth with a pattern and return a Tone.js sequence */ export const clip = (params: ClipParams) => { params = { ...getDefaultParams(), ...(params || {}) }; // If notes is a string, split it into an array if (typeof params.notes === 'string') { // Remove any accidental double spaces params.notes = params.notes.replace(/\s{2,}/g, ' '); params.notes = params.notes.split(' '); } params.notes = params.notes.map(convertChordsToNotes); if (/[^x\-_\[\]R]/.test(params.pattern)) { throw new TypeError( `pattern can only comprise x - _ [ ], found ${params.pattern}` ); } if (params.shuffle) { params.notes = shuffle(params.notes); } if (params.randomNotes && typeof params.randomNotes === 'string') { params.randomNotes = params.randomNotes.replace(/\s{2,}/g, ' ').split(/\s/); } if (params.randomNotes) { params.randomNotes = (params.randomNotes as string[]).map( convertChordsToNotes ); } if (params.offlineRendering) { return offlineRenderClip( params, renderingDuration( params.pattern, params.subdiv || defaultSubdiv, params.notes, params.randomNotes ) ); } return generateSequence(params, originalContext); };
the_stack
import { hexToBin, utf8ToBin } from '../../format/format'; import { bigIntToScriptNumber } from '../../vm/instruction-sets/instruction-sets'; import { AnyCompilationEnvironment, CompilationData, CompilationEnvironment, CompilerOperation, CompilerOperationResult, } from '../compiler-types'; import { AuthenticationTemplateVariable } from '../template-types'; import { compileScriptRaw } from './compile'; import { BtlScriptSegment, CompilationResultSuccess, IdentifierResolutionErrorType, IdentifierResolutionFunction, IdentifierResolutionType, MarkedNode, Range, ResolvedScript, ResolvedSegment, } from './language-types'; import { stringifyErrors } from './language-utils'; const pluckRange = (node: MarkedNode): Range => ({ endColumn: node.end.column, endLineNumber: node.end.line, startColumn: node.start.column, startLineNumber: node.start.line, }); const removeNumericSeparators = (numericLiteral: string) => numericLiteral.replace(/_/gu, ''); export const resolveScriptSegment = ( segment: BtlScriptSegment, resolveIdentifiers: IdentifierResolutionFunction ): ResolvedScript => { // eslint-disable-next-line complexity const resolved = segment.value.map<ResolvedSegment>((child) => { const range = pluckRange(child); switch (child.name) { case 'Identifier': { const identifier = child.value; const result = resolveIdentifiers(identifier); const ret = result.status ? { range, type: 'bytecode' as const, value: result.bytecode, ...(result.type === IdentifierResolutionType.opcode ? { opcode: identifier, } : result.type === IdentifierResolutionType.variable ? { ...('debug' in result ? { debug: result.debug } : {}), ...('signature' in result ? { signature: result.signature } : {}), variable: identifier, } : // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition result.type === IdentifierResolutionType.script ? { script: identifier, source: result.source } : ({ unknown: identifier } as never)), } : { ...('debug' in result ? { debug: result.debug } : {}), ...('recoverable' in result && result.recoverable ? { missingIdentifier: identifier, owningEntity: result.entityOwnership, } : {}), range, type: 'error' as const, value: result.error, }; return ret; } case 'Push': return { range, type: 'push' as const, value: resolveScriptSegment(child.value, resolveIdentifiers), }; case 'Evaluation': return { range, type: 'evaluation' as const, value: resolveScriptSegment(child.value, resolveIdentifiers), }; case 'BigIntLiteral': return { literal: child.value, literalType: 'BigIntLiteral' as const, range, type: 'bytecode' as const, value: bigIntToScriptNumber( BigInt(removeNumericSeparators(child.value)) ), }; case 'BinaryLiteral': return { literal: child.value, literalType: 'BinaryLiteral' as const, range, type: 'bytecode' as const, value: bigIntToScriptNumber( BigInt(`0b${removeNumericSeparators(child.value)}`) ), }; case 'HexLiteral': return { literal: child.value, literalType: 'HexLiteral' as const, range, type: 'bytecode' as const, value: hexToBin(removeNumericSeparators(child.value)), }; case 'UTF8Literal': return { literal: child.value, literalType: 'UTF8Literal' as const, range, type: 'bytecode' as const, value: utf8ToBin(child.value), }; case 'Comment': return { range, type: 'comment' as const, value: child.value, }; default: return { range, type: 'error' as const, value: `Unrecognized segment: ${(child as { name: string }).name}`, }; } }); return resolved.length === 0 ? [{ range: pluckRange(segment), type: 'comment' as const, value: '' }] : resolved; }; export enum BuiltInVariables { currentBlockTime = 'current_block_time', currentBlockHeight = 'current_block_height', signingSerialization = 'signing_serialization', } const attemptCompilerOperation = < TransactionContext, Environment extends AnyCompilationEnvironment<TransactionContext> >({ data, environment, identifier, matchingOperations, operationExample = 'operation_identifier', operationId, variableId, variableType, }: { data: CompilationData<TransactionContext>; environment: Environment; identifier: string; matchingOperations: | { [x: string]: CompilerOperation<TransactionContext> | undefined; } | CompilerOperation<TransactionContext> | undefined; operationId: string | undefined; variableId: string; variableType: string; operationExample?: string; }): CompilerOperationResult<true> => { if (matchingOperations === undefined) { return { error: `The "${variableId}" variable type can not be resolved because the "${variableType}" operation has not been included in this compiler's CompilationEnvironment.`, status: 'error', }; } if (typeof matchingOperations === 'function') { const operation = matchingOperations; return operation(identifier, data, environment); } if (operationId === undefined) { return { error: `This "${variableId}" variable could not be resolved because this compiler's "${variableType}" operations require an operation identifier, e.g. '${variableId}.${operationExample}'.`, status: 'error', }; } const operation = (matchingOperations as { [x: string]: CompilerOperation<TransactionContext> | undefined; })[operationId]; if (operation === undefined) { return { error: `The identifier "${identifier}" could not be resolved because the "${variableId}.${operationId}" operation is not available to this compiler.`, status: 'error', }; } return operation(identifier, data, environment); }; /** * If the identifer can be successfully resolved as a variable, the result is * returned as a Uint8Array. If the identifier references a known variable, but * an error occurs in resolving it, the error is returned as a string. * Otherwise, the identifier is not recognized as a variable, and this method * simply returns `false`. * * @param identifier - The full identifier used to describe this operation, e.g. * `owner.signature.all_outputs`. * @param data - The `CompilationData` provided to the compiler * @param environment - The `CompilationEnvironment` provided to the compiler */ export const resolveVariableIdentifier = < TransactionContext, Environment extends AnyCompilationEnvironment<TransactionContext> >({ data, environment, identifier, }: { data: CompilationData<TransactionContext>; environment: Environment; identifier: string; }): CompilerOperationResult<true> => { const [variableId, operationId] = identifier.split('.') as [ string, string | undefined ]; switch (variableId) { case BuiltInVariables.currentBlockHeight: return attemptCompilerOperation({ data, environment, identifier, matchingOperations: environment.operations?.currentBlockHeight, operationId, variableId, variableType: 'currentBlockHeight', }); case BuiltInVariables.currentBlockTime: return attemptCompilerOperation({ data, environment, identifier, matchingOperations: environment.operations?.currentBlockTime, operationId, variableId, variableType: 'currentBlockTime', }); case BuiltInVariables.signingSerialization: return attemptCompilerOperation({ data, environment, identifier, matchingOperations: environment.operations?.signingSerialization, operationExample: 'version', operationId, variableId, variableType: 'signingSerialization', }); default: { const expectedVariable: AuthenticationTemplateVariable | undefined = environment.variables?.[variableId]; if (expectedVariable === undefined) { return { status: 'skip' }; } return attemptCompilerOperation({ data, environment, identifier, operationId, variableId, ...{ // eslint-disable-next-line @typescript-eslint/naming-convention AddressData: { matchingOperations: environment.operations?.addressData, variableType: 'addressData', }, // eslint-disable-next-line @typescript-eslint/naming-convention HdKey: { matchingOperations: environment.operations?.hdKey, operationExample: 'public_key', variableType: 'hdKey', }, // eslint-disable-next-line @typescript-eslint/naming-convention Key: { matchingOperations: environment.operations?.key, operationExample: 'public_key', variableType: 'key', }, // eslint-disable-next-line @typescript-eslint/naming-convention WalletData: { matchingOperations: environment.operations?.walletData, variableType: 'walletData', }, }[expectedVariable.type], }); } } }; /** * Compile an internal script identifier. * * @remarks * If the identifer can be successfully resolved as a script, the script is * compiled and returned as a CompilationResultSuccess. If an error occurs in * compiling it, the error is returned as a string. * * Otherwise, the identifier is not recognized as a script, and this method * simply returns `false`. * * @param identifier - the identifier of the script to be resolved * @param data - the provided CompilationData * @param environment - the provided CompilationEnvironment * @param parentIdentifier - the identifier of the script which references the * script being resolved (for detecting circular dependencies) */ export const resolveScriptIdentifier = <TransactionContext, ProgramState>({ data, environment, identifier, }: { identifier: string; data: CompilationData<TransactionContext>; environment: CompilationEnvironment<TransactionContext>; }): CompilationResultSuccess<ProgramState> | string | false => { if ((environment.scripts[identifier] as string | undefined) === undefined) { return false; } const result = compileScriptRaw({ data, environment, scriptId: identifier }); if (result.success) { return result; } return `Compilation error in resolved script "${identifier}": ${stringifyErrors( result.errors )}`; /* * result.errors.reduce( * (all, { error, range }) => * `${ * all === '' ? '' : `${all}; ` * } [${ * range.startLineNumber * }, ${range.startColumn}]: ${error}`, * '' * ); */ }; /** * Return an `IdentifierResolutionFunction` for use in `resolveScriptSegment`. * * @param scriptId - the `id` of the script for which the resulting * `IdentifierResolutionFunction` will be used. * @param environment - a snapshot of the context around `scriptId`. See * `CompilationEnvironment` for details. * @param data - the actual variable values (private keys, shared wallet data, * shared address data, etc.) to use in resolving variables. */ export const createIdentifierResolver = <TransactionContext>({ data, environment, }: { data: CompilationData<TransactionContext>; environment: CompilationEnvironment<TransactionContext>; }): IdentifierResolutionFunction => // eslint-disable-next-line complexity (identifier: string): ReturnType<IdentifierResolutionFunction> => { const opcodeResult: Uint8Array | undefined = environment.opcodes?.[identifier]; if (opcodeResult !== undefined) { return { bytecode: opcodeResult, status: true, type: IdentifierResolutionType.opcode, }; } const variableResult = resolveVariableIdentifier({ data, environment, identifier, }); if (variableResult.status !== 'skip') { return variableResult.status === 'error' ? { ...('debug' in variableResult ? { debug: variableResult.debug } : {}), error: variableResult.error, ...(environment.entityOwnership === undefined ? {} : { entityOwnership: environment.entityOwnership[identifier.split('.')[0]], }), recoverable: 'recoverable' in variableResult, status: false, type: IdentifierResolutionErrorType.variable, } : { ...('debug' in variableResult ? { debug: variableResult.debug } : {}), bytecode: variableResult.bytecode, ...('signature' in variableResult ? { signature: variableResult.signature, } : {}), status: true, type: IdentifierResolutionType.variable, }; } const scriptResult = resolveScriptIdentifier({ data, environment, identifier, }); if (scriptResult !== false) { return typeof scriptResult === 'string' ? { error: scriptResult, scriptId: identifier, status: false, type: IdentifierResolutionErrorType.script, } : { bytecode: scriptResult.bytecode, source: scriptResult.resolve, status: true, type: IdentifierResolutionType.script, }; } return { error: `Unknown identifier "${identifier}".`, status: false, type: IdentifierResolutionErrorType.unknown, }; };
the_stack
import { IllegalStateError, DummyError, CompositeError } from "funfix-core" import * as assert from "./asserts" import { Cancelable, BoolCancelable, AssignCancelable, MultiAssignCancelable, SingleAssignCancelable, SerialCancelable, StackedCancelable, ChainedCancelable } from "../../src/" class TestCancelable extends BoolCancelable { private _isCanceled: boolean constructor() { super() this._isCanceled = false } public isCanceled(): boolean { return this._isCanceled } public cancel(): void { if (this._isCanceled) throw new IllegalStateError("TestCancelable#cancel") this._isCanceled = true } } describe("Cancelable.from", () => { it("converts any callback", () => { let effect = false const c = Cancelable.of(() => { effect = true }) assert.not(effect) c.cancel() assert.ok(effect) }) it("is idempotent", () => { let effect = 0 const c = Cancelable.of(() => { effect += 1 }) c.cancel() assert.equal(effect, 1) c.cancel() assert.equal(effect, 1) }) it("is idempotent even if it throws", () => { const dummy = new DummyError("dummy") const ref = Cancelable.of(() => { throw dummy }) try { ref.cancel() } catch (e) { assert.equal(e, dummy) } // Second time it shouldn't do anything ref.cancel() }) }) describe("Cancelable.empty", () => { it("always returns the same reference", () => { const c = Cancelable.empty() c.cancel() // no-op const c2 = Cancelable.empty() c2.cancel() // no-op assert.equal(c2, c) }) }) describe("Cancelable.collection", () => { it("cancels multiple references", () => { const refs = [new TestCancelable(), new TestCancelable(), new TestCancelable()] const main = Cancelable.collection(...refs) for (const c of refs) assert.not(c.isCanceled()) main.cancel() for (const c of refs) assert.ok(c.isCanceled()) main.cancel() // no-op }) it("throws single error", () => { const dummy = new DummyError("dummy") const refs = [ BoolCancelable.empty(), BoolCancelable.of(() => { throw dummy }), BoolCancelable.empty()] const main = Cancelable.collection(...refs) for (const c of refs) assert.not(c.isCanceled()) try { main.cancel() } catch (e) { assert.equal(e, dummy) for (const ref of refs) assert.ok(ref.isCanceled()) } }) it("throws multiple errors as a composite", () => { const dummy = new DummyError("dummy") function ref() { return Cancelable.of(() => { throw dummy }) } const refs = [ref(), ref(), ref()] const main = Cancelable.collection(...refs) try { main.cancel() } catch (e) { assert.ok(e instanceof CompositeError) const composite = e as CompositeError assert.equal(composite.errors().length, 3) for (const ref of composite.errors()) assert.equal(ref, dummy) } }) it("works with anything being thrown", () => { const dummy = "dummy" const refs = [ Cancelable.of(() => { throw dummy }), Cancelable.of(() => { throw dummy }), Cancelable.of(() => { throw dummy })] const main = Cancelable.collection(...refs) try { main.cancel() } catch (e) { assert.ok(e instanceof CompositeError) const composite = e as CompositeError const errs = composite.errors() assert.equal(errs.length, 3) for (e of errs) assert.equal(e, dummy) } }) it("can be a BoolCancelable", () => { const ref = BoolCancelable.collection( new TestCancelable(), new TestCancelable(), new TestCancelable() ) assert.ok(!ref.isCanceled()) ref.cancel() assert.ok(ref.isCanceled()) ref.cancel() // no-op }) }) describe("BoolCancelable.from", () => { it("converts any callback", () => { let effect = false const c = BoolCancelable.of(() => { effect = true }) assert.not(effect) assert.not(c.isCanceled()) c.cancel() assert.ok(effect) assert.ok(c.isCanceled()) }) it("is idempotent", () => { let effect = 0 const c = BoolCancelable.of(() => { effect += 1 }) assert.not(c.isCanceled()) c.cancel() assert.equal(effect, 1) assert.ok(c.isCanceled()) c.cancel() assert.equal(effect, 1) assert.ok(c.isCanceled()) }) it("is idempotent even if it throws", () => { const dummy = new DummyError("dummy") const ref = BoolCancelable.of(() => { throw dummy }) assert.not(ref.isCanceled()) try { ref.cancel() } catch (e) { assert.equal(e, dummy) assert.ok(ref.isCanceled()) } // Second time it shouldn't do anything ref.cancel() }) }) describe("BoolCancelable.empty", () => { it("returns a reference that can be canceled", () => { const ref = BoolCancelable.empty() assert.ok(!ref.isCanceled()) ref.cancel() assert.ok(ref.isCanceled()) }) }) describe("BoolCancelable.alreadyCanceled", () => { it("is already canceled", () => { const ref = BoolCancelable.alreadyCanceled() assert.ok(ref.isCanceled()) ref.cancel() // no-op assert.ok(ref.isCanceled()) }) it("always returns the same reference", () => { const c = BoolCancelable.alreadyCanceled() const c2 = BoolCancelable.alreadyCanceled() assert.equal(c2, c) }) }) describe("AssignCancelable", () => { it("alreadyCanceled", () => { const ref = AssignCancelable.alreadyCanceled() assert.ok(ref.isCanceled()) const c = BoolCancelable.empty() assert.ok(!c.isCanceled()) ref.update(c) assert.ok(c.isCanceled()) // Should be a no-op ref.cancel() }) it("empty", () => { const ref = AssignCancelable.empty() assert.ok(ref instanceof MultiAssignCancelable) }) it("from", () => { let effect = 0 const ref = AssignCancelable.of(() => { effect += 1 }) assert.ok(ref instanceof MultiAssignCancelable) ref.cancel() assert.ok(ref.isCanceled()) assert.equal(effect, 1) }) }) describe("MultiAssignmentCancelable", () => { it("initialized to given instance", () => { const c = new TestCancelable() const ref = new MultiAssignCancelable(c) ref.cancel() assert.ok(ref.isCanceled()) assert.ok(c.isCanceled()) ref.cancel() // no-op }) it("update multiple times", () => { const ref: MultiAssignCancelable = MultiAssignCancelable.empty() const c1 = new TestCancelable() ref.update(c1) const c2 = new TestCancelable() ref.update(c2) ref.cancel() const c3 = new TestCancelable() ref.update(c3) assert.equal(c1.isCanceled(), false) assert.ok(c2.isCanceled()) assert.ok(c3.isCanceled()) ref.cancel() // no-op }) it("cancel while empty", () => { const ref: MultiAssignCancelable = MultiAssignCancelable.empty() ref.cancel() assert.ok(ref.isCanceled()) const c = new TestCancelable() ref.update(c) assert.ok(c.isCanceled()) }) it("from callback", () => { const ref: MultiAssignCancelable = MultiAssignCancelable.of(() => { effect += 1 }) let effect = 0 ref.cancel() assert.equal(effect, 1) ref.cancel() // no-op assert.equal(effect, 1) }) it("from callback, update", () => { let effect = 0 const ref: MultiAssignCancelable = MultiAssignCancelable.of(() => { effect += 1 }) const c = new TestCancelable() ref.update(c) ref.cancel() assert.ok(c.isCanceled()) assert.equal(effect, 0) ref.cancel() // no-op }) it("collapse on another MultiAssignCancelable", () => { const mc1 = new MultiAssignCancelable() const mc2 = new MultiAssignCancelable() let effect = 0 const c1 = Cancelable.of(() => { effect += 1 }) mc1.update(c1).collapse() mc2.update(mc1).collapse() assert.equal(effect, 0) mc2.cancel() assert.ok(mc2.isCanceled()) assert.equal(effect, 1) assert.ok(!mc1.isCanceled()) mc1.update(mc2).collapse() assert.ok(mc1.isCanceled()) }) it("clear to undefined", () => { const mc = new MultiAssignCancelable() let effect = 0 const c1 = Cancelable.of(() => { effect += 1 }) mc.update(c1) mc.clear() mc.cancel() assert.equal(effect, 0) mc.clear() // no-op }) }) describe("SerialAssignmentCancelable", () => { it("initialized to given instance", () => { const c = new TestCancelable() const ref = new SerialCancelable(c) ref.cancel() assert.ok(ref.isCanceled()) assert.ok(c.isCanceled()) ref.cancel() // no-op }) it("update multiple times", () => { const ref: SerialCancelable = SerialCancelable.empty() const c1 = new TestCancelable() ref.update(c1) const c2 = new TestCancelable() ref.update(c2) ref.cancel() const c3 = new TestCancelable() ref.update(c3) assert.ok(c1.isCanceled()) assert.ok(c2.isCanceled()) assert.ok(c3.isCanceled()) ref.cancel() assert.ok(ref.isCanceled()) ref.cancel() // no-op }) it("cancel while empty", () => { const ref: SerialCancelable = SerialCancelable.empty() ref.cancel() assert.ok(ref.isCanceled()) const c = new TestCancelable() ref.update(c) assert.ok(c.isCanceled()) }) it("from callback", () => { let effect = 0 const ref: SerialCancelable = SerialCancelable.of(() => { effect += 1 }) ref.cancel() assert.equal(effect, 1) ref.cancel() // no-op }) it("from callback, update", () => { let effect = 0 const ref = SerialCancelable.of(() => { effect += 1 }) const c = new TestCancelable() ref.update(c) ref.cancel() assert.ok(c.isCanceled()) assert.equal(effect, 1) ref.cancel() // no-op }) }) describe("SingleAssignmentCancelable", () => { it("update once before cancel", () => { const ref: SingleAssignCancelable = SingleAssignCancelable.empty() const c = new TestCancelable() ref.update(c) assert.ok(!c.isCanceled()) ref.cancel() assert.ok(c.isCanceled()) assert.ok(ref.isCanceled()) ref.cancel() assert.ok(c.isCanceled()) }) it("update after cancel", () => { const ref: SingleAssignCancelable = SingleAssignCancelable.empty() ref.cancel() assert.ok(ref.isCanceled()) const c1 = new TestCancelable() ref.update(c1) assert.ok(c1.isCanceled()) const c2 = new TestCancelable() assert.throws(() => ref.update(c2)) }) it("update multiple times", () => { const ref: SingleAssignCancelable = SingleAssignCancelable.empty() const c1 = new TestCancelable() ref.update(c1) const c2 = new TestCancelable() assert.throws(() => ref.update(c2)) ref.cancel() const c3 = new TestCancelable() assert.throws(() => ref.update(c3)) assert.ok(c1.isCanceled()) assert.ok(!c2.isCanceled()) assert.ok(!c3.isCanceled()) ref.cancel() // no-op }) it("from callback", () => { const ref: SingleAssignCancelable = SingleAssignCancelable.of(() => { effect += 1 }) let effect = 0 ref.cancel() assert.equal(effect, 1) ref.cancel() // no-op assert.equal(effect, 1) }) it("from callback, update", () => { let effect = 0 const ref: SingleAssignCancelable = SingleAssignCancelable.of(() => { effect += 1 }) const c = BoolCancelable.empty() assert.throws(() => ref.update(c)) ref.cancel() assert.ok(!c.isCanceled()) assert.equal(effect, 1) }) }) describe("StackedCancelable", () => { it("cancels underlying tasks", () => { let effect = 0 const c1 = Cancelable.of(() => effect += 1) const c2 = Cancelable.of(() => effect += 2) const c3 = Cancelable.of(() => effect += 3) const all = StackedCancelable.collection(c1, c2, c3) assert.not(all.isCanceled()) assert.equal(effect, 0) all.cancel() assert.ok(all.isCanceled()) assert.equal(effect, 6) all.cancel() // no-op assert.equal(effect, 6) }) it("can .push() and pop() in FIFO order", () => { let effect = 0 const c1 = Cancelable.of(() => effect += 1) const c2 = Cancelable.of(() => effect += 2) const c3 = Cancelable.of(() => effect += 3) const sc = StackedCancelable.collection(c1, c2, c3) assert.equal(sc.pop(), c3) sc.push(Cancelable.of(() => effect += 4)) .push(Cancelable.of(() => effect += 5)) sc.pop() sc.cancel() assert.equal(effect, 1 + 2 + 4) }) it("cancels refs on push() if cancelled", () => { const sc = StackedCancelable.empty() sc.cancel() assert.ok(sc.isCanceled()) const c = BoolCancelable.empty() assert.not(c.isCanceled()) sc.push(c) assert.ok(c.isCanceled()) }) it("returns empty cancelable on pop() if empty or cancelled", () => { const sc = new StackedCancelable() assert.equal(sc.pop(), Cancelable.empty()) sc.cancel() assert.equal(sc.pop(), Cancelable.empty()) }) it("handles once exception", () => { const dummy = new DummyError("dummy") const c1 = BoolCancelable.empty() const c2 = Cancelable.of(() => { throw dummy }) const c3 = BoolCancelable.empty() const sc = StackedCancelable.collection(c1, c2, c3) try { sc.cancel() assert.fail("should have triggered error") } catch (e) { assert.equal(e, dummy) } assert.ok(sc.isCanceled()) assert.ok(c1.isCanceled()) assert.ok(c3.isCanceled()) }) it("handles multiple exceptions", () => { const dummy1 = new DummyError("dummy1") const dummy2 = new DummyError("dummy2") const c1 = BoolCancelable.empty() const c2 = Cancelable.of(() => { throw dummy1 }) const c3 = Cancelable.of(() => { throw dummy2 }) const c4 = BoolCancelable.empty() const sc = StackedCancelable.collection(c1, c2, c3, c4) try { sc.cancel() assert.fail("should have triggered error") } catch (e) { assert.ok(e instanceof CompositeError) const errors = (e as CompositeError).errors() assert.equal(errors.length, 2) assert.equal(errors[0], dummy1) assert.equal(errors[1], dummy2) } assert.ok(sc.isCanceled()) assert.ok(c1.isCanceled()) assert.ok(c4.isCanceled()) }) }) describe("ChainedCancelable", () => { it("cancel()", () => { let effect = 0 const sub = BoolCancelable.of(() => effect += 1) const mSub = new ChainedCancelable(sub) assert.equal(effect, 0) assert.not(sub.isCanceled()) assert.not(mSub.isCanceled()) mSub.cancel() assert.ok(sub.isCanceled() && mSub.isCanceled()) assert.equal(effect, 1) mSub.cancel() assert.ok(sub.isCanceled() && mSub.isCanceled()) assert.equal(effect, 1) }) it("cancel() after second assignment", () => { let effect = 0 const sub = BoolCancelable.of(() => effect += 1) const mSub = new ChainedCancelable(sub) const sub2 = BoolCancelable.of(() => effect += 10) mSub.update(sub2) assert.equal(effect, 0) assert.ok(!sub.isCanceled() && !sub2.isCanceled() && !mSub.isCanceled()) mSub.cancel() assert.ok(sub2.isCanceled() && mSub.isCanceled() && !sub.isCanceled()) assert.equal(effect, 10) }) it("automatically cancel assigned", () => { const mSub = new ChainedCancelable() mSub.cancel() let effect = 0 const sub = BoolCancelable.of(() => effect += 1) assert.equal(effect, 0) assert.ok(!sub.isCanceled() && mSub.isCanceled()) mSub.update(sub) assert.equal(effect, 1) assert.ok(sub.isCanceled()) }) it("update() throws on null", () => { const c = new ChainedCancelable() assert.throws(() => c.update(null as any)) }) it("chain once", () => { const c1 = BoolCancelable.empty() const c2 = BoolCancelable.empty() const source = ChainedCancelable.empty() const child1 = ChainedCancelable.empty() child1.chainTo(source) child1.update(c1) assert.not(c1.isCanceled(), "!c1.isCanceled") source.cancel() assert.ok(c1.isCanceled(), "c1.isCanceled") assert.ok(source.isCanceled(), "source.isCanceled") assert.ok(child1.isCanceled(), "child1.isCanceled") child1.update(c2) assert.ok(c2.isCanceled(), "c2.isCanceled") }) it("chain twice", () => { const c1 = BoolCancelable.empty() const c2 = BoolCancelable.empty() const source = ChainedCancelable.empty() const child1 = ChainedCancelable.empty() const child2 = ChainedCancelable.empty() child1.chainTo(source) child2.chainTo(child1) child2.update(c1) assert.not(c1.isCanceled(), "!c1.isCanceled") source.cancel() assert.ok(c1.isCanceled(), "c1.isCanceled") assert.ok(source.isCanceled(), "source.isCanceled") assert.ok(child1.isCanceled(), "child1.isCanceled") assert.ok(child2.isCanceled(), "child2.isCanceled") child2.update(c2) assert.ok(c2.isCanceled(), "c2.isCanceled") }) it("chain after source cancel", () => { const c1 = BoolCancelable.empty() const c2 = BoolCancelable.empty() const source = new ChainedCancelable(c1) const child1 = ChainedCancelable.empty() source.cancel() assert.ok(c1.isCanceled(), "c1.isCanceled") child1.chainTo(source) assert.ok(child1.isCanceled(), "child1.isCanceled") child1.update(c2) assert.ok(c2.isCanceled(), "c2.isCanceled") }) it("chain after child cancel", () => { const c1 = BoolCancelable.empty() const c2 = BoolCancelable.empty() const source1 = new ChainedCancelable(c1) const source2 = ChainedCancelable.empty() const child = ChainedCancelable.empty() child.cancel() assert.not(c1.isCanceled(), "!c1.isCanceled") child.chainTo(source1) assert.ok(child.isCanceled(), "child1.isCanceled") assert.ok(source1.isCanceled(), "source.isCanceled") assert.ok(c1.isCanceled(), "c1.isCanceled") child.update(c2) assert.ok(c2.isCanceled(), "c2.isCanceled") assert.ok(child.isCanceled(), "child.isCanceled") child.chainTo(source2) assert.ok(child.isCanceled(), "child.isCanceled") assert.ok(source2.isCanceled(), "source2.isCanceled") }) it("chainTo(source) transfers the underlying to `source`", () => { const c = BoolCancelable.empty() const source = ChainedCancelable.empty() const child = new ChainedCancelable(c) child.chainTo(source) child.cancel() assert.ok(c.isCanceled()) }) it("throws exception on chainTo(null)", () => { const c = ChainedCancelable.empty() assert.throws(() => c.chainTo(null as any)) }) it("ref.chainTo(ref) is a no-op", () => { const c = BoolCancelable.empty() const cc = new ChainedCancelable(c) cc.chainTo(cc) cc.cancel() assert.ok(c.isCanceled()) }) it("short-circuits cycles", () => { const c = BoolCancelable.empty() const cc1 = new ChainedCancelable() const cc2 = new ChainedCancelable() const cc3 = new ChainedCancelable() cc1.chainTo(cc2) cc2.chainTo(cc3) cc3.chainTo(cc1) cc1.update(c) cc3.cancel() assert.ok(c.isCanceled()) }) })
the_stack
import tape from 'tape' import Common, { Chain, Hardfork } from '@ethereumjs/common' import { Transaction, AccessListEIP2930Transaction, FeeMarketEIP1559Transaction, N_DIV_2, Capability, } from '../src' import { TxsJsonEntry } from './types' import { BaseTransaction } from '../src/baseTransaction' import { privateToPublic, BN, toBuffer } from 'ethereumjs-util' tape('[BaseTransaction]', function (t) { // EIP-2930 is not enabled in Common by default (2021-03-06) const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London }) const legacyFixtures: TxsJsonEntry[] = require('./json/txs.json') const legacyTxs: BaseTransaction<Transaction>[] = [] legacyFixtures.slice(0, 4).forEach(function (tx: TxsJsonEntry) { legacyTxs.push(Transaction.fromTxData(tx.data, { common })) }) const eip2930Fixtures = require('./json/eip2930txs.json') const eip2930Txs: BaseTransaction<AccessListEIP2930Transaction>[] = [] eip2930Fixtures.forEach(function (tx: any) { eip2930Txs.push(AccessListEIP2930Transaction.fromTxData(tx.data, { common })) }) const eip1559Fixtures = require('./json/eip1559txs.json') const eip1559Txs: BaseTransaction<FeeMarketEIP1559Transaction>[] = [] eip1559Fixtures.forEach(function (tx: any) { eip1559Txs.push(FeeMarketEIP1559Transaction.fromTxData(tx.data, { common })) }) const zero = Buffer.alloc(0) const txTypes = [ { class: Transaction, name: 'Transaction', type: 0, values: Array(6).fill(zero), txs: legacyTxs, fixtures: legacyFixtures, activeCapabilities: [], notActiveCapabilities: [ Capability.EIP1559FeeMarket, Capability.EIP2718TypedTransaction, Capability.EIP2930AccessLists, 9999, ], }, { class: AccessListEIP2930Transaction, name: 'AccessListEIP2930Transaction', type: 1, values: [Buffer.from([1])].concat(Array(7).fill(zero)), txs: eip2930Txs, fixtures: eip2930Fixtures, activeCapabilities: [Capability.EIP2718TypedTransaction, Capability.EIP2930AccessLists], notActiveCapabilities: [Capability.EIP1559FeeMarket, 9999], }, { class: FeeMarketEIP1559Transaction, name: 'FeeMarketEIP1559Transaction', type: 2, values: [Buffer.from([1])].concat(Array(8).fill(zero)), txs: eip1559Txs, fixtures: eip1559Fixtures, activeCapabilities: [ Capability.EIP1559FeeMarket, Capability.EIP2718TypedTransaction, Capability.EIP2930AccessLists, ], notActiveCapabilities: [9999], }, ] t.test('Initialization', function (st) { for (const txType of txTypes) { let tx = txType.class.fromTxData({}, { common }) st.equal( tx.common.hardfork(), 'london', `${txType.name}: should initialize with correct HF provided` ) st.ok(Object.isFrozen(tx), `${txType.name}: tx should be frozen by default`) const initCommon = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London, }) tx = txType.class.fromTxData({}, { common: initCommon }) st.equal( tx.common.hardfork(), 'london', `${txType.name}: should initialize with correct HF provided` ) initCommon.setHardfork(Hardfork.Byzantium) st.equal( tx.common.hardfork(), 'london', `${txType.name}: should stay on correct HF if outer common HF changes` ) tx = txType.class.fromTxData({}, { common, freeze: false }) tx = txType.class.fromTxData({}, { common, freeze: false }) st.ok( !Object.isFrozen(tx), `${txType.name}: tx should not be frozen when freeze deactivated in options` ) // Perform the same test as above, but now using a different construction method. This also implies that passing on the // options object works as expected. tx = txType.class.fromTxData({}, { common, freeze: false }) const rlpData = tx.serialize() tx = txType.class.fromSerializedTx(rlpData, { common }) st.equal( tx.type, txType.type, `${txType.name}: fromSerializedTx() -> should initialize correctly` ) st.ok(Object.isFrozen(tx), `${txType.name}: tx should be frozen by default`) tx = txType.class.fromRlpSerializedTx(rlpData, { common }) st.equal( tx.type, txType.type, `${txType.name}: fromRlpSerializedTx() (deprecated) -> should initialize correctly` ) tx = txType.class.fromSerializedTx(rlpData, { common, freeze: false }) st.ok( !Object.isFrozen(tx), `${txType.name}: tx should not be frozen when freeze deactivated in options` ) tx = txType.class.fromValuesArray(txType.values as any, { common }) st.ok(Object.isFrozen(tx), `${txType.name}: tx should be frozen by default`) tx = txType.class.fromValuesArray(txType.values as any, { common, freeze: false }) st.ok( !Object.isFrozen(tx), `${txType.name}: tx should not be frozen when freeze deactivated in options` ) } st.end() }) t.test('serialize()', function (st) { for (const txType of txTypes) { txType.txs.forEach(function (tx: any) { st.ok( txType.class.fromSerializedTx(tx.serialize(), { common }), `${txType.name}: should do roundtrip serialize() -> fromSerializedTx()` ) st.ok( txType.class.fromSerializedTx(tx.serialize(), { common }), `${txType.name}: should do roundtrip serialize() -> fromSerializedTx()` ) }) } st.end() }) t.test('supports()', function (st) { for (const txType of txTypes) { txType.txs.forEach(function (tx: any) { for (const activeCapability of txType.activeCapabilities) { st.ok( tx.supports(activeCapability), `${txType.name}: should recognize all supported capabilities` ) } for (const notActiveCapability of txType.notActiveCapabilities) { st.notOk( tx.supports(notActiveCapability), `${txType.name}: should reject non-active existing and not existing capabilities` ) } }) } st.end() }) t.test('raw()', function (st) { for (const txType of txTypes) { txType.txs.forEach(function (tx: any) { st.ok( txType.class.fromValuesArray(tx.raw(), { common }), `${txType.name}: should do roundtrip raw() -> fromValuesArray()` ) }) } st.end() }) t.test('verifySignature()', function (st) { for (const txType of txTypes) { txType.txs.forEach(function (tx: any) { st.equals(tx.verifySignature(), true, `${txType.name}: signature should be valid`) }) } st.end() }) t.test('verifySignature() -> invalid', function (st) { for (const txType of txTypes) { txType.fixtures.slice(0, 4).forEach(function (txFixture: any) { // set `s` to zero txFixture.data.s = `0x` + '0'.repeat(16) const tx = txType.class.fromTxData(txFixture.data, { common }) st.equals(tx.verifySignature(), false, `${txType.name}: signature should not be valid`) st.ok( (<string[]>tx.validate(true)).includes('Invalid Signature'), `${txType.name}: should return an error string about not verifying signatures` ) st.notOk(tx.validate(), `${txType.name}: should not validate correctly`) }) } st.end() }) t.test('sign()', function (st) { for (const txType of txTypes) { txType.txs.forEach(function (tx: any, i: number) { const { privateKey } = txType.fixtures[i] if (privateKey) { st.ok(tx.sign(Buffer.from(privateKey, 'hex')), `${txType.name}: should sign tx`) } st.throws( () => tx.sign(Buffer.from('invalid')), `${txType.name}: should fail with invalid PK` ) }) } st.end() }) t.test('getSenderAddress()', function (st) { for (const txType of txTypes) { txType.txs.forEach(function (tx: any, i: number) { const { privateKey, sendersAddress } = txType.fixtures[i] if (privateKey) { const signedTx = tx.sign(Buffer.from(privateKey, 'hex')) st.equals( signedTx.getSenderAddress().toString(), `0x${sendersAddress}`, `${txType.name}: should get sender's address after signing it` ) } }) } st.end() }) t.test('getSenderPublicKey()', function (st) { for (const txType of txTypes) { txType.txs.forEach(function (tx: any, i: number) { const { privateKey } = txType.fixtures[i] if (privateKey) { const signedTx = tx.sign(Buffer.from(privateKey, 'hex')) const txPubKey = signedTx.getSenderPublicKey() const pubKeyFromPriv = privateToPublic(Buffer.from(privateKey, 'hex')) st.ok( txPubKey.equals(pubKeyFromPriv), `${txType.name}: should get sender's public key after signing it` ) } }) } st.end() }) t.test( 'getSenderPublicKey() -> should throw if s-value is greater than secp256k1n/2', function (st) { // EIP-2: All transaction signatures whose s-value is greater than secp256k1n/2 are considered invalid. // Reasoning: https://ethereum.stackexchange.com/a/55728 for (const txType of txTypes) { txType.txs.forEach(function (tx: any, i: number) { const { privateKey } = txType.fixtures[i] if (privateKey) { let signedTx = tx.sign(Buffer.from(privateKey, 'hex')) signedTx = JSON.parse(JSON.stringify(signedTx)) // deep clone ;(signedTx as any).s = N_DIV_2.addn(1) st.throws(() => { signedTx.getSenderPublicKey() }, 'should throw when s-value is greater than secp256k1n/2') } }) } st.end() } ) t.test('verifySignature()', function (st) { for (const txType of txTypes) { txType.txs.forEach(function (tx: any, i: number) { const { privateKey } = txType.fixtures[i] if (privateKey) { const signedTx = tx.sign(Buffer.from(privateKey, 'hex')) st.ok(signedTx.verifySignature(), `${txType.name}: should verify signing it`) } }) } st.end() }) t.test('initialization with defaults', function (st) { const bufferZero = toBuffer('0x') const tx = Transaction.fromTxData({ nonce: '', gasLimit: '', gasPrice: '', to: '', value: '', data: '', v: '', r: '', s: '', }) st.equal(tx.v, undefined) st.equal(tx.r, undefined) st.equal(tx.s, undefined) st.isEquivalent(tx.to, undefined) st.isEquivalent(tx.value, new BN(bufferZero)) st.isEquivalent(tx.data, bufferZero) st.isEquivalent(tx.gasPrice, new BN(bufferZero)) st.isEquivalent(tx.gasLimit, new BN(bufferZero)) st.isEquivalent(tx.nonce, new BN(bufferZero)) st.end() }) })
the_stack
import { Value } from '../lib/value' import { Schema } from '../lib/schema' import { AnyType } from '../lib/util'; import * as JoiLib from "../lib/joi"; import { AlternativesSchema } from './alternative'; import { AnySchema } from './any'; import { ArraySchema } from './array'; import { BinarySchema } from './binary'; import { BooleanSchema } from './boolean'; import { DateSchema } from './date'; import { FunctionSchema } from './function'; import { LazySchema } from './lazy'; import { NumberSchema } from './number'; import { ObjectSchema } from './object'; import { StringSchema } from './string'; import { SymbolSchema } from './symbol'; /** The collection of all available schemas */ export interface SchemaCollection<TValue extends Value.AnyValue> { alternatives: AlternativesSchema<TValue>, any: AnySchema<TValue>, array: ArraySchema<TValue>, binary: BinarySchema<TValue>, boolean: BooleanSchema<TValue>, date: DateSchema<TValue>, function: FunctionSchema<TValue>, lazy: LazySchema<TValue>, number: NumberSchema<TValue>, object: ObjectSchema<TValue>, string: StringSchema<TValue>, symbol: SymbolSchema<TValue> } /** * Assemble a schema type (e.g. `string`, `any`) and a value type into a schema. * This is basically a lookup in `SchemaCollection`. */ export type SchemaType<TSchemaType extends string, TValue extends Value.AnyValue> = ( TSchemaType extends keyof SchemaCollection<any> ? SchemaCollection<TValue>[TSchemaType] : never ) /** * `Schema` with a `schemaType` tag. * * @description * There is no functions defined in `AbstractSchema` because these functions may make trouble to type matching. * `AbstractSchema` is being used to let TypeScript know what is the kind of a `Schema`. */ export interface AbstractSchema<TSchemaType extends string, TValue extends Value.AnyValue> extends Schema<TValue> { schemaType: TSchemaType } /** * The schema type with all the instance methods of `AnySchema` of joi. * * @description * Notice: do not use `BaseSchema` as the constraint pf a type variable. * The functions of `BaseSchema` will make all specific schema types fail. */ export interface BaseSchema<TSchemaType extends string, TValue extends Value.AnyValue> extends AbstractSchema<TSchemaType, TValue>, JoiLib.JoiObject { /** Validates a value using the schema and options. */ validate (value: any, options?: JoiLib.ValidationOptions): JoiLib.ValidationResult<Value.literal<TValue>> validate (value: any, callback: JoiLib.ValidationCallback<Value.literal<TValue>>): void validate (value: any, options: JoiLib.ValidationOptions, callback: JoiLib.ValidationCallback<Value.literal<TValue>>): void /** Whitelists a value */ allow<T extends AnyType[]> (values: T): SchemaType<TSchemaType, Value.allow<TValue, T[number]>> allow<T extends AnyType[]> (...values: T): SchemaType<TSchemaType, Value.allow<TValue, T[number]>> /** Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. */ valid<T extends AnyType[]> (values: T): SchemaType<TSchemaType, Value.allowOnly<TValue, T[number]>> valid<T extends AnyType[]> (...values: T): SchemaType<TSchemaType, Value.allowOnly<TValue, T[number]>> /** Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. */ only<T extends AnyType[]> (values: T): SchemaType<TSchemaType, Value.allowOnly<TValue, T[number]>> only<T extends AnyType[]> (...values: T): SchemaType<TSchemaType, Value.allowOnly<TValue, T[number]>> /** Adds the provided values into the allowed whitelist and marks them as the only valid values allowed. */ equal<T extends AnyType[]> (values: T): SchemaType<TSchemaType, Value.allowOnly<TValue, T[number]>> equal<T extends AnyType[]> (...values: T): SchemaType<TSchemaType, Value.allowOnly<TValue, T[number]>> /** Blacklists a value */ invalid<T extends AnyType[]> (values: T): SchemaType<TSchemaType, Value.disallow<TValue, T[number]>> invalid<T extends AnyType[]> (...values: T): SchemaType<TSchemaType, Value.disallow<TValue, T[number]>> /** Blacklists a value */ disallow<T extends AnyType[]> (values: T): SchemaType<TSchemaType, Value.disallow<TValue, T[number]>> disallow<T extends AnyType[]> (...values: T): SchemaType<TSchemaType, Value.disallow<TValue, T[number]>> /** Blacklists a value */ not<T extends AnyType[]> (values: T): SchemaType<TSchemaType, Value.disallow<TValue, T[number]>> not<T extends AnyType[]> (...values: T): SchemaType<TSchemaType, Value.disallow<TValue, T[number]>> /** * By default, some Joi methods to function properly need to rely on the Joi instance they are attached to because * they use `this` internally. * So `Joi.string()` works but if you extract the function from it and call `string()` it won't. * `bind()` creates a new Joi instance where all the functions relying on `this` are bound to the Joi instance. */ bind (): this /** Returns a new type that is the result of adding the rules of one type to another. */ concat<TSchema extends AbstractSchema<string, Value.AnyValue>> (schema: TSchema): Schema.concat<this, TSchema> /** Marks a key as required which will not allow undefined as value. All keys are optional by default. */ required (): SchemaType<TSchemaType, Value.required<TValue>> /** Marks a key as required which will not allow undefined as value. All keys are optional by default. */ exist (): SchemaType<TSchemaType, Value.required<TValue>> /** Marks a key as optional which will allow undefined as values. Used to annotate the schema for readability as all keys are optional by default. */ optional (): SchemaType<TSchemaType, Value.optional<TValue>> /** Marks a key as forbidden which will not allow any value except undefined. Used to explicitly forbid keys. */ forbidden (): SchemaType<TSchemaType, Value.forbidden<TValue>> /** Marks a key to be removed from a resulting object or array after validation. Used to sanitize output. */ strip (): SchemaType<TSchemaType, Value.forbidden<TValue>> /** Annotates the key. */ description (desc: string): this /** Annotates the key. */ notes (notes: string | string[]): this /** Annotates the key. */ tags (notes: string | string[]): this /** Attaches metadata to the key. */ meta (meta: Record<any, any>): this /** Annotates the key with an example value, must be valid. */ example (...value: any[]): this /** Annotates the key with an unit name. */ unit (name: string): this /** Overrides the global validate() options for the current key and any sub-key. */ options (options: JoiLib.ValidationOptions): this /** Sets the options.convert options to false which prevent type casting for the current key and any child keys. */ strict (isStrict?: boolean): this /** * Sets a default value if the original value is undefined. * @param value - the value. * value supports references. * value may also be a function which returns the default value. * If value is specified as a function that accepts a single parameter, that parameter will be a context * object that can be used to derive the resulting value. This clones the object however, which incurs some * overhead so if you don't need access to the context define your method so that it does not accept any * parameters. * Without any value, default has no effect, except for object that will then create nested defaults * (applying inner defaults of that object). * * Note that if value is an object, any changes to the object after default() is called will change the * reference and any future assignment. * * Additionally, when specifying a method you must either have a description property on your method or the * second parameter is required. */ default (): this default<T = never> (value: JoiLib.Reference, description?: string): SchemaType<TSchemaType, Value.setDefault<TValue, T>> default<TDefault extends AnyType> (value: JoiLib.DefaultFunction<TDefault>, description: string): SchemaType<TSchemaType, Value.setDefault<TValue, TDefault>> default<TDefault extends AnyType> (value: JoiLib.DefaultFunctionWithDescription<TDefault>, description?: string): SchemaType<TSchemaType, Value.setDefault<TValue, TDefault>> default<TDefault extends AnyType> (value: TDefault, description?: string): SchemaType<TSchemaType, Value.setDefault<TValue, TDefault>> /** Converts the type into an alternatives type where the conditions are merged into the type definition. */ when<T extends JoiLib.WhenIs> (ref: string | JoiLib.Reference, options: T): AlternativesSchema<Schema.valueType<Schema.when<this, T>>> when<T extends JoiLib.When> (ref: Schema.SchemaLike, options: T): AlternativesSchema<Schema.valueType<Schema.when<this, T>>> /** Overrides the key name in error messages. */ label (name: string): this /** Outputs the original untouched value instead of the casted value. */ raw (isRaw?: boolean): this /** * Considers anything that matches the schema to be empty (undefined). * @param schema - any object or joi schema to match. An undefined schema unsets that rule. */ empty (schema?: Schema.SchemaLike): this /** * Overrides the default joi error with a custom error if the rule fails where: * @param err - can be: * an instance of `Error` - the override error. * a `function(errors)`, taking an array of errors as argument, where it must either: * return a `string` - substitutes the error message with this text * return a single ` object` or an `Array` of it, where: * `type` - optional parameter providing the type of the error (eg. `number.min`). * `message` - optional parameter if `template` is provided, containing the text of the error. * `template` - optional parameter if `message` is provided, containing a template string, using the same format as usual joi language errors. * `context` - optional parameter, to provide context to your error if you are using the `template`. * return an `Error` - same as when you directly provide an `Error`, but you can customize the error message based on the errors. * * Note that if you provide an `Error`, it will be returned as-is, unmodified and undecorated with any of the * normal joi error properties. If validation fails and another error is found before the error * override, that error will be returned and the override will be ignored (unless the `abortEarly` * option has been set to `false`). */ error (err: Error | JoiLib.ValidationErrorFunction, options?: JoiLib.ErrorOptions): this /** Returns a plain object representing the schema's rules and properties. */ describe (): JoiLib.Description } export { AlternativesSchema, AnySchema, ArraySchema, BinarySchema, BooleanSchema, DateSchema, FunctionSchema, LazySchema, NumberSchema, ObjectSchema, StringSchema, SymbolSchema }
the_stack
import * as React from 'react'; import { useTranslation } from 'react-i18next'; import { Label, CommandBar, ICommandBarItemProps, DetailsList, IColumn, SelectionMode, MessageBar, MessageBarType, Announced, Pivot, PivotItem, Link } from '@fluentui/react'; import { NavLink, useLocation, useRouteMatch } from 'react-router-dom'; import { ROUTE_PARTS, ROUTE_PARAMS } from '../../../constants/routes'; import { getDeviceIdFromQueryString, getModuleIdentityIdFromQueryString } from '../../../shared/utils/queryStringHelper'; import { ResourceKeys } from '../../../../localization/resourceKeys'; import { SynchronizationStatus } from '../../../api/models/synchronizationStatus'; import { REFRESH } from '../../../constants/iconNames'; import { LARGE_COLUMN_WIDTH } from '../../../constants/columnWidth'; import { InterfaceNotFoundMessageBar } from '../../shared/components/interfaceNotFoundMessageBar'; import { ModelDefinitionSourceView } from '../../shared/components/modelDefinitionSource'; import { MaskedCopyableTextField } from '../../../shared/components/maskedCopyableTextField'; import { JSONEditor } from '../../../shared/components/jsonEditor'; import { HeaderView } from '../../../shared/components/headerView'; import { MultiLineShimmer } from '../../../shared/components/multiLineShimmer'; import { usePnpStateContext } from '../../../shared/contexts/pnpStateContext'; import { ModelDefinition } from '../../../api/models/modelDefinition'; import { ComponentAndInterfaceId, JsonSchemaAdaptor } from '../../../shared/utils/jsonSchemaAdaptor'; import { DEFAULT_COMPONENT_FOR_DIGITAL_TWIN } from '../../../constants/devices'; import { ErrorBoundary } from '../../shared/components/errorBoundary'; import '../../../css/_digitalTwinInterfaces.scss'; import { dispatchGetTwinAction } from '../utils'; interface ModelContent { link: string; componentName: string; interfaceId: string; } const getComponentNameAndInterfaceIdArray = (modelDefinition: ModelDefinition): ComponentAndInterfaceId[] => { if (!modelDefinition) { return []; } const jsonSchemaAdaptor = new JsonSchemaAdaptor(modelDefinition); const components = jsonSchemaAdaptor.getComponentNameAndInterfaceIdArray(); // check if model contains no-component items if (jsonSchemaAdaptor.getNonWritableProperties().length + jsonSchemaAdaptor.getWritableProperties().length + jsonSchemaAdaptor.getCommands().length + jsonSchemaAdaptor.getTelemetry().length > 0) { components.unshift({ componentName: DEFAULT_COMPONENT_FOR_DIGITAL_TWIN, interfaceId: modelDefinition['@id'] }); } return components; }; // tslint:disable-next-line: cyclomatic-complexity export const DigitalTwinInterfacesList: React.FC = () => { const { search } = useLocation(); const { url } = useRouteMatch(); const deviceId = getDeviceIdFromQueryString(search); const moduleId = getModuleIdentityIdFromQueryString(search); const { t } = useTranslation(); const { pnpState, dispatch, } = usePnpStateContext(); const modelDefinitionWithSource = pnpState.modelDefinitionWithSource.payload; const modelDefinition = modelDefinitionWithSource && modelDefinitionWithSource.modelDefinition; const twin = pnpState.twin.payload; const twinSynchronizationStatus = pnpState.twin.synchronizationStatus; const modelDefinitionSynchronizationStatus = pnpState.modelDefinitionWithSource.synchronizationStatus; const isModelDefinitionLoading = modelDefinitionSynchronizationStatus === SynchronizationStatus.working; const isTwinLoading = twinSynchronizationStatus === SynchronizationStatus.working; const modelId = twin?.modelId; const componentNameToIds = getComponentNameAndInterfaceIdArray(modelDefinition); const onRefresh = (ev?: React.MouseEvent<HTMLElement, MouseEvent> | React.KeyboardEvent<HTMLElement>) => { dispatchGetTwinAction(search, dispatch); }; const modelContents: ModelContent[] = componentNameToIds && componentNameToIds.map(nameToId => { let link = `${url}${ROUTE_PARTS.DIGITAL_TWINS_DETAIL}/${ROUTE_PARTS.INTERFACES}/` + `?${ROUTE_PARAMS.DEVICE_ID}=${encodeURIComponent(deviceId)}` + `&${ROUTE_PARAMS.COMPONENT_NAME}=${nameToId.componentName}` + `&${ROUTE_PARAMS.INTERFACE_ID}=${nameToId.interfaceId}`; if (moduleId) { link += `&${ROUTE_PARAMS.MODULE_ID}=${moduleId}`; } if (nameToId.componentName === DEFAULT_COMPONENT_FOR_DIGITAL_TWIN && nameToId.interfaceId === modelId) { return{ componentName: t(ResourceKeys.digitalTwin.pivot.defaultComponent), interfaceId: nameToId.interfaceId, link }; } else { return { ...nameToId, link }; } }); const createCommandBarItems = (): ICommandBarItemProps[] => { return [ { ariaLabel: t(ResourceKeys.deviceEvents.command.refresh), disabled: isTwinLoading, iconProps: {iconName: REFRESH}, key: REFRESH, name: t(ResourceKeys.deviceEvents.command.refresh), onClick: onRefresh } ]; }; const getColumns = (): IColumn[] => { return [ { fieldName: 'componentName', isMultiline: true, isResizable: true, key: 'name', maxWidth: LARGE_COLUMN_WIDTH, minWidth: 100, name: t(ResourceKeys.digitalTwin.componentName) }, { fieldName: 'interfaceId', isMultiline: true, isResizable: true, key: 'id', maxWidth: LARGE_COLUMN_WIDTH, minWidth: 100, name: t(ResourceKeys.digitalTwin.interfaceId)} ]; }; const renderItemColumn = () => (item: ModelContent, index: number, column: IColumn) => { switch (column.key) { case 'name': return ( <NavLink key={column.key} to={item.link}> {item.componentName} </NavLink> ); case 'id': return ( <Label key={column.key} > {item.interfaceId} </Label> ); default: return; } }; const renderComponentList = () => { const listView = ( <> { modelContents.length !== 0 ? <div className="list-detail"> <DetailsList onRenderItemColumn={renderItemColumn()} className="component-list" items={modelContents} columns={getColumns()} selectionMode={SelectionMode.none} /> </div> : <> <Label className="no-component">{t(ResourceKeys.digitalTwin.modelContainsNoComponents, {modelId })}</Label> <Announced message={t(ResourceKeys.digitalTwin.modelContainsNoComponents, { modelId })} /> </> } </>); return ( <> <h4>{t(ResourceKeys.digitalTwin.steps.third)}</h4> <h5>{t(ResourceKeys.digitalTwin.steps.explanation, {modelId})}</h5> <Pivot aria-label={t(ResourceKeys.digitalTwin.pivot.ariaLabel)}> <PivotItem headerText={t(ResourceKeys.digitalTwin.pivot.components)}> <ErrorBoundary error={t(ResourceKeys.deviceInterfaces.interfaceListFailedToRender)}> {listView} </ErrorBoundary> </PivotItem> <PivotItem headerText={t(ResourceKeys.digitalTwin.pivot.content)}> <JSONEditor className="interface-definition-json-editor" content={JSON.stringify(modelDefinitionWithSource.modelDefinition, null, '\t')} /> </PivotItem> </Pivot> </> ); }; const renderModelDefinition = () => { if (isModelDefinitionLoading) { return <MultiLineShimmer/>; } if (!modelDefinitionWithSource) { return ( <> <h4>{t(ResourceKeys.digitalTwin.steps.secondFailure, {modelId})}</h4> <InterfaceNotFoundMessageBar/> </>); } return ( <> <h4>{t(ResourceKeys.digitalTwin.steps.secondSuccess)}</h4> <ModelDefinitionSourceView source={modelDefinitionWithSource.source} /> {modelDefinitionWithSource.isModelValid ? renderComponentList() : <> <MessageBar messageBarType={MessageBarType.error}> {t(ResourceKeys.deviceInterfaces.interfaceNotValid)} </MessageBar> <JSONEditor className="interface-definition-json-editor" content={JSON.stringify(modelDefinitionWithSource.modelDefinition, null, '\t')} /> </> } </> ); }; return ( <> <CommandBar className="command" items={createCommandBarItems()} /> <HeaderView headerText={ResourceKeys.digitalTwin.headerText} link={ResourceKeys.settings.questions.questions.documentation.link} tooltip={ResourceKeys.settings.questions.questions.documentation.text} /> {isTwinLoading ? <MultiLineShimmer/> : <section className="device-detail"> {modelId ? <> <h4>{moduleId ? t(ResourceKeys.digitalTwin.steps.firstModule) : t(ResourceKeys.digitalTwin.steps.first)}</h4> <MaskedCopyableTextField ariaLabel={t(ResourceKeys.digitalTwin.modelId)} label={t(ResourceKeys.digitalTwin.modelId)} value={modelId} allowMask={false} readOnly={true} /> {renderModelDefinition()} </> : <> <span>{moduleId ? t(ResourceKeys.digitalTwin.steps.zeroModule) : t(ResourceKeys.digitalTwin.steps.zero)}</span> <Link href={t(ResourceKeys.settings.questions.questions.documentation.link)} target="_blank" > {t(ResourceKeys.settings.questions.questions.documentation.text)} </Link> </> } </section> } </> ); };
the_stack
import {isFunction, Symbol, SymbolKind} from "../../compiler/core/symbol"; import {ByteArray, ByteArray_set32, ByteArray_setString} from "../../utils/bytearray"; import {CheckContext} from "../../compiler/analyzer/type-checker"; import {alignToNextMultipleOf, toHex} from "../../utils/utils"; import {isExpression, isUnary, isUnaryPostfix, Node, NODE_FLAG_IMPORT, NodeKind} from "../../compiler/core/node"; import {Type} from "../../compiler/core/type"; import {Compiler} from "../../compiler/compiler"; import {WasmOpcode} from "./opcode"; import {getBuiltinOpcode, isBuiltin} from "./builtins-helper"; import {assert} from "../../utils/assert"; import {WasmType, WasmTypeToString} from "./core/wasm-type"; import {log, logData} from "./utils/logger"; import {Bitness} from "../bitness"; import {WasmSection} from "./core/wasm-section"; import {WasmExternalKind} from "./core/wasm-external-kind"; import {WasmGlobal} from "./core/wasm-global"; import {WasmFunction} from "./core/wasm-function"; import {WasmLocal} from "./core/wasm-local"; import {WasmSharedOffset} from "./core/wasm-shared-offset"; import {WasmAssembler} from "./assembler/wasm-assembler"; import {Terminal} from "../../utils/terminal"; import {getTypedArrayElementSize, getWasmFunctionName, symbolToWasmType, typeToDataType} from "./utils"; import {WasmOptimizer} from "./optimizer/wasm-optimizer"; import {SignatureSection} from "./wasm/sections/signature-section"; import {ImportSection} from "./wasm/sections/import-section"; import {FunctionSection} from "./wasm/sections/function-section"; import {MemorySection} from "./wasm/sections/memory-section"; import {WasmBinary} from "./wasm/wasm-binary"; import {GlobalSection} from "./wasm/sections/global-section"; import {StartSection} from "./wasm/sections/start-section"; import {CodeSection} from "./wasm/sections/code-section"; import {ExportSection} from "./wasm/sections/export-section"; import {BinaryImporter, getMergedCallIndex, isBinaryImport} from "../../importer/binary-importer"; class WasmModuleEmitter { memoryInitializer: ByteArray; private HEAP_BASE_INDEX: int32 = -1; mallocFunctionIndex: int32 = -1; freeFunctionIndex: int32 = -1; startFunctionIndex: int32 = -1; context: CheckContext; startFunction: WasmFunction; currentFunction: WasmFunction; assembler: WasmAssembler; constructor(public bitness: Bitness) { this.assembler = new WasmAssembler(); } growMemoryInitializer(): void { let array = this.memoryInitializer; let current = array.length; let length = this.context.nextGlobalVariableOffset; while (current < length) { array.append(0); current = current + 1; } } emitModule(): void { this.emitTypes(); this.emitImportTable(); this.emitFunctionDeclarations(); // this.emitTables(); this.emitMemory(); this.emitGlobalDeclarations(); this.emitExportTable(); this.emitStart(); this.emitElements(); this.emitFunctionBodies(); this.emitDataSegments(); this.emitNames(); this.assembler.finish(); } emitTypes(): void { let section = this.assembler.startSection(WasmSection.Signature) as SignatureSection; let signatures = section.signatures; let offset = 0; this.assembler.writeUnsignedLEB128(signatures.length); signatures.forEach((signature, index) => { // Emit signature this.assembler.activeCode.append(`(type (;${index};) (func`); log(section.payload, offset, WasmType.func, "func sig " + index); this.assembler.writeUnsignedLEB128(WasmType.func); //form, the value for the func type constructor log(section.payload, offset, signature.argumentTypes.length, "num params"); this.assembler.writeUnsignedLEB128(signature.argumentTypes.length); //param_count, the number of parameters to the function if (signature.argumentTypes.length > 0) { this.assembler.activeCode.append(` (param`); } signature.argumentTypes.forEach(type => { log(section.payload, offset, type, WasmType[type]); this.assembler.writeUnsignedLEB128(type); //value_type, the parameter types of the function this.assembler.activeCode.append(` ${WasmTypeToString[type]}`); }); if (signature.argumentTypes.length > 0) { this.assembler.activeCode.append(`)`); } if (signature.returnType !== WasmType.VOID) { log(section.payload, offset, 1, "num results"); this.assembler.writeUnsignedLEB128(1); //return_count, the number of results from the function log(section.payload, offset, signature.returnType, WasmType[signature.returnType]); this.assembler.writeUnsignedLEB128(signature.returnType); this.assembler.activeCode.append(` (result ${WasmTypeToString[signature.returnType]})`); } else { this.assembler.writeUnsignedLEB128(0); } this.assembler.activeCode.append("))\n"); }); this.assembler.endSection(section); } emitImportTable(): void { if (this.assembler.module.importCount == 0) { return; } let section = this.assembler.startSection(WasmSection.Import) as ImportSection; let imports = section.imports; let offset = 0; log(section.payload, offset, imports.length, "num imports"); this.assembler.writeUnsignedLEB128(imports.length); imports.forEach((_import, index) => { log(section.payload, offset, null, `import func (${index}) ${_import.namespace} ${_import.name}`); this.assembler.activeCode.append(`(import "${_import.namespace}" "${_import.name}" (func (;${index};) (type ${_import.signatureIndex})))\n`); this.assembler.writeWasmString(_import.namespace); this.assembler.writeWasmString(_import.name); this.assembler.writeUnsignedLEB128(WasmExternalKind.Function); this.assembler.writeUnsignedLEB128(_import.signatureIndex); }); this.assembler.endSection(section); } emitFunctionDeclarations(): void { if (this.assembler.module.functionCount === 0) { return; } let section = this.assembler.startSection(WasmSection.Function) as FunctionSection; let functions = section.functions; let offset = 0; log(section.payload, offset, functions.length, "num functions"); this.assembler.writeUnsignedLEB128(functions.length); let importCount = this.assembler.module.importCount; functions.forEach((fn, index) => { log(section.payload, offset, fn.signatureIndex, `func ${importCount + index} sig ${getWasmFunctionName(fn.symbol)}`); this.assembler.writeUnsignedLEB128(fn.signatureIndex); }); this.assembler.endSection(section); } emitTables(): void { //TODO } emitMemory(): void { let section = this.assembler.startSection(WasmSection.Memory) as MemorySection; let memory = section.memory; if (memory.length > 1) { Terminal.warn("More than 1 memory found, In the MVP, the number of memories must be no more than 1.") } this.assembler.module.allocateExport("memory", WasmExternalKind.Memory, 0); let offset = 0; log(section.payload, offset, memory.length, "num memories"); this.assembler.writeUnsignedLEB128(1); //indicating the number of memories defined by the namespace, In the MVP, the number of memories must be no more than 1. //resizable_limits log(section.payload, offset, 0, "memory flags"); this.assembler.writeUnsignedLEB128(WasmBinary.SET_MAX_MEMORY ? 0x1 : 0); //flags, bit 0x1 is set if the maximum field is present log(section.payload, offset, WasmBinary.SIZE_IN_PAGES, "memory initial pages"); this.assembler.writeUnsignedLEB128(WasmBinary.SIZE_IN_PAGES); //initial length (in units of table elements or wasm pages) if (WasmBinary.SET_MAX_MEMORY) { log(section.payload, offset, WasmBinary.MAX_MEMORY, "maximum memory"); this.assembler.writeUnsignedLEB128(WasmBinary.MAX_MEMORY);// maximum, only present if specified by flags } this.assembler.activeCode.append("(memory $0 1)\n"); this.assembler.endSection(section); } emitGlobalDeclarations(): void { if (this.assembler.module.globals.length === 0) { return; } let section = this.assembler.startSection(WasmSection.Global) as GlobalSection; let globals = section.globals; let offset = 0; this.assembler.writeUnsignedLEB128(globals.length); this.assembler.stackTracer.setGlobals(globals); // Initialize mspace before initializing globals if (Compiler.mallocRequired) { // write mspace_init let mspace_init_index = getMergedCallIndex("mspace_init"); this.assembler.startFunctionChunk(this.startFunction, this.startFunctionIndex); this.assembler.appendOpcode(0, WasmOpcode.I32_CONST); this.assembler.writeUnsignedLEB128(40); this.assembler.appendOpcode(0, WasmOpcode.CALL); this.assembler.writeUnsignedLEB128(mspace_init_index); this.assembler.appendOpcode(0, WasmOpcode.SET_GLOBAL); this.assembler.writeUnsignedLEB128(this.HEAP_BASE_INDEX); this.assembler.endFunctionChunk(); } globals.forEach((global, index) => { let wasmType: WasmType = symbolToWasmType(global.symbol, this.bitness); let value = global.symbol.node.variableValue(); section.payload.append(wasmType); //content_type this.assembler.writeUnsignedLEB128(global.mutable ? 1 : 0); //mutability, 0 if immutable, 1 if mutable. let rawValue = 0; if (value) { if (value.kind === NodeKind.NULL || value.kind === NodeKind.UNDEFINED) { rawValue = 0; } else if (value.rawValue !== undefined) { rawValue = value.rawValue; } else { // Emit evaluation to start function this.addGlobalToStartFunction(global); } } this.assembler.appendOpcode(offset, WasmOpcode[`${WasmType[wasmType]}_CONST`], rawValue); switch (wasmType) { case WasmType.I32: this.assembler.writeUnsignedLEB128(rawValue); break; case WasmType.I64: this.assembler.writeUnsignedLEB128(rawValue); break; case WasmType.F32: this.assembler.writeFloat(rawValue); break; case WasmType.F64: this.assembler.writeDouble(rawValue); break; } let wasmTypeStr = WasmTypeToString[wasmType]; this.assembler.activeCode.append(`(global (;${index};) (mut ${wasmTypeStr}) (${wasmTypeStr}.const ${rawValue}))\n`); this.assembler.appendOpcode(offset, WasmOpcode.END); }); this.assembler.endSection(section); } addGlobalToStartFunction(global: WasmGlobal): void { let value = global.symbol.node.variableValue(); this.assembler.startFunctionChunk(this.startFunction, this.startFunctionIndex); this.emitNode(0, value); this.assembler.appendOpcode(0, WasmOpcode.SET_GLOBAL); this.assembler.writeUnsignedLEB128(global.symbol.offset); this.assembler.endFunctionChunk(); } emitExportTable(): void { if (this.assembler.module.exportCount === 0) { return; } let offset = 0; let section = this.assembler.startSection(WasmSection.Export) as ExportSection; let importCount = this.assembler.module.importCount; let exports = section.exports; log(section.payload, offset, exports.length, "num exports"); this.assembler.writeUnsignedLEB128(exports.length); //Export main memory // let memoryName: string = "memory"; // log(section.payload, offset, memoryName.length, "export name length"); // log(section.payload, null, null, `${toHex(section.payload.position + offset + 4)}: ${memoryName} // export name`); // this.assembler.writeWasmString(memoryName); // log(section.payload, offset, WasmExternalKind.Memory, "export kind"); // this.assembler.activePayload.writeUnsignedByte(WasmExternalKind.Memory); // log(section.payload, offset, 0, "export memory index"); // this.assembler.writeUnsignedLEB128(0); // this.assembler.activeCode.append(`(export "memory" (memory $0))\n`); exports.forEach((_export) => { let isFunctionExport = _export.kind === WasmExternalKind.Function; let exportIndex = isFunctionExport ? importCount + _export.index : _export.index; log(section.payload, offset, _export.as.length, "export name length"); log(section.payload, null, null, `${toHex(section.payload.position + offset + 4)}: ${_export.as} // export name`); this.assembler.writeWasmString(_export.as); log(section.payload, offset, _export.kind, "export kind"); this.assembler.writeUnsignedLEB128(_export.kind); log(section.payload, offset, exportIndex, "export index"); this.assembler.writeUnsignedLEB128(exportIndex); if (isFunctionExport) { this.assembler.activeCode.append(`(export "${_export.as}" (func $${_export.name}))\n`); } else if (_export.kind === WasmExternalKind.Memory) { this.assembler.activeCode.append(`(export "${_export.as}" (memory $${_export.index}))\n`); } }); this.assembler.endSection(section); } emitStart(): void { if (this.startFunctionIndex != -1) { let section = this.assembler.startSection(WasmSection.Start) as StartSection; let offset = 0; let importCount = this.assembler.module.importCount; log(section.payload, offset, this.startFunctionIndex, "start function index"); this.assembler.activeCode.append(`(start ${importCount + this.startFunctionIndex})\n`); this.assembler.writeUnsignedLEB128(importCount + this.startFunctionIndex); this.assembler.endSection(section); } } emitElements(): void { //TODO } emitFunctionBodies(): void { if (this.assembler.module.functionCount === 0) { return; } let offset = 0; let signatures = (this.assembler.module.binary.getSection(WasmSection.Signature) as SignatureSection).signatures; let functions = (this.assembler.module.binary.getSection(WasmSection.Function) as FunctionSection).functions; let section = this.assembler.startSection(WasmSection.Code) as CodeSection; // FIXME: functions might overwrite section.functions = functions; log(section.payload, offset, this.assembler.module.functionCount, "num functions"); this.assembler.writeUnsignedLEB128(this.assembler.module.functionCount); functions.forEach((fn, index) => { this.currentFunction = fn; let sectionOffset = offset + section.payload.position; let wasmFunctionName = getWasmFunctionName(fn.symbol); if (!fn.isExternal) { let bodyData = new ByteArray(); fn.body = bodyData; log(bodyData, sectionOffset, fn.locals.length, "local var count"); this.assembler.startFunction(fn, index); /* wasm text format */ this.assembler.activeCode.emitIndent(); this.assembler.activeCode.append(`(func $${wasmFunctionName} (type ${fn.signatureIndex}) `); fn.argumentVariables.forEach((argumentEntry) => { this.assembler.activeCode.append(`(param $${argumentEntry.name} ${WasmTypeToString[argumentEntry.type]}) `); }); let signature = signatures[fn.signatureIndex]; if (signature.returnType !== WasmType.VOID) { this.assembler.activeCode.append(`(result ${WasmTypeToString[signature.returnType]})`); } this.assembler.activeCode.append("\n", 2); if (fn.localVariables.length > 0) { bodyData.writeUnsignedLEB128(fn.localVariables.length); //local_count // TODO: Optimize local declarations fn.localVariables.forEach((localVariableEntry) => { log(bodyData, sectionOffset, 1, "local index"); bodyData.writeUnsignedLEB128(1); //count log(bodyData, sectionOffset, localVariableEntry.type, WasmType[localVariableEntry.type]); bodyData.append(localVariableEntry.type); //value_type this.assembler.activeCode.append(`(local $${localVariableEntry.name} ${WasmTypeToString[localVariableEntry.type]}) `); }); this.assembler.activeCode.append("\n"); } else { bodyData.writeUnsignedLEB128(0); } let lastChild; if (fn.isConstructor) { // this is <CLASS>__ctr function this.emitConstructor(sectionOffset, fn) } let child = fn.symbol.node.functionBody().firstChild; while (child != null) { lastChild = child; this.emitNode(sectionOffset, child); child = child.nextSibling; } if (fn.chunks.length > 0) { this.assembler.activeCode.clearIndent(2); fn.chunks.forEach((chunk, index) => { bodyData.copy(chunk.payload); bodyData.log += chunk.payload.log; chunk.code.removeLastLinebreak(); this.assembler.activeCode.appendRaw(chunk.code.finish()); }); } else { if (lastChild && lastChild.kind !== NodeKind.RETURN && fn.returnType != WasmType.VOID) { this.assembler.appendOpcode(sectionOffset, WasmOpcode.RETURN); } } if (fn.returnType === WasmType.VOID) { // Drop stack if not empty this.assembler.dropStack(); } this.assembler.appendOpcode(sectionOffset, WasmOpcode.END, null, true); //end, 0x0b, indicating the end of the body this.assembler.endFunction(); this.assembler.activeCode.removeLastLinebreak(); this.assembler.activeCode.append(`)\n`); } else { console.log("External function " + fn.name); } section.payload.writeUnsignedLEB128(fn.body.length); log(section.payload, offset, null, ` - func body ${this.assembler.module.importCount + (index)} (${wasmFunctionName})`); log(section.payload, offset, fn.body.length, "func body size"); section.payload.log += fn.body.log; section.payload.copy(fn.body); }); this.assembler.endSection(section); } emitDataSegments(): void { this.growMemoryInitializer(); let memoryInitializer = this.memoryInitializer; let initializerLength = memoryInitializer.length; let initialHeapPointer = alignToNextMultipleOf(WasmBinary.MEMORY_INITIALIZER_BASE + initializerLength, 8); // Store initial heap base pointer // memoryInitializer.writeUnsignedInt(initialHeapPointer, this.mspaceBasePointer); let section = this.assembler.startSection(WasmSection.Data); let offset = 0; // This only writes one single section containing everything log(section.payload, offset, 1, "num data segments"); this.assembler.writeUnsignedLEB128(1); //data_segment log(section.payload, offset, null, " - data segment header 0"); log(section.payload, offset, 0, "memory index"); this.assembler.writeUnsignedLEB128(0); //index, the linear memory index (0 in the MVP) //offset, an i32 initializer expression that computes the offset at which to place the data this.assembler.appendOpcode(offset, WasmOpcode.I32_CONST); log(section.payload, offset, WasmBinary.MEMORY_INITIALIZER_BASE, "i32 literal"); this.assembler.writeUnsignedLEB128(WasmBinary.MEMORY_INITIALIZER_BASE); //const value this.assembler.appendOpcode(offset, WasmOpcode.END); log(section.payload, offset, initializerLength, "data segment size"); this.assembler.writeUnsignedLEB128(initializerLength); //size, size of data (in bytes) log(section.payload, offset, null, " - data segment data 0"); //data, sequence of size bytes // Copy the entire memory initializer (also includes zero-initialized data for now) this.assembler.activeCode.append(`(data (i32.const ${WasmBinary.MEMORY_INITIALIZER_BASE}) " `); let i = 0; let value; while (i < initializerLength) { for (let j = 0; j < 16; j++) { if (i + j < initializerLength) { value = memoryInitializer.get(i + j); section.payload.append(value); this.assembler.activeCode.append("\\" + toHex(value, 2)); logData(section.payload, offset, value, j == 0); } } section.payload.log += "\n"; i = i + 16; } this.assembler.activeCode.append('")\n'); // section.payload.copy(memoryInitializer, initializerLength); this.assembler.endSection(section); } // Custom section for debug names // emitNames(): void { let section = this.assembler.startSection(WasmSection.Custom, "name"); let functions = (this.assembler.module.binary.getSection(WasmSection.Function) as FunctionSection).functions; let subsectionFunc: ByteArray = new ByteArray(); let subsectionLocal: ByteArray = new ByteArray(); subsectionFunc.writeUnsignedLEB128(this.assembler.module.functionCount); subsectionLocal.writeUnsignedLEB128(this.assembler.module.functionCount); functions.forEach((fn, index) => { let fnIndex = this.assembler.module.importCount + index; subsectionFunc.writeUnsignedLEB128(fnIndex); subsectionFunc.writeWasmString(fn.name); subsectionLocal.writeUnsignedLEB128(fnIndex); if (fn.locals !== undefined) { subsectionLocal.writeUnsignedLEB128(fn.locals.length); fn.locals.forEach((local, index) => { subsectionLocal.writeUnsignedLEB128(index); subsectionLocal.writeWasmString(local.name); }); } }); //subsection for function names this.assembler.writeUnsignedLEB128(1); // name_type this.assembler.writeUnsignedLEB128(subsectionFunc.length); // name_payload_len section.payload.copy(subsectionFunc); // name_payload_data //subsection for local names this.assembler.writeUnsignedLEB128(2); // name_type this.assembler.writeUnsignedLEB128(subsectionLocal.length); // name_payload_len section.payload.copy(subsectionLocal); // name_payload_data this.assembler.endSection(section); } mergeBinaryImports(): void { // TODO: Merge only imported functions and it's dependencies this.assembler.mergeBinaries(BinaryImporter.binaries); } prepareToEmit(node: Node): void { if (node.kind == NodeKind.STRING) { let text = node.stringValue; let length = text.length; let offset = this.context.allocateGlobalVariableOffset(length * 2 + 4, 4); node.intValue = offset; this.growMemoryInitializer(); let memoryInitializer = this.memoryInitializer; // Emit a length-prefixed string ByteArray_set32(memoryInitializer, offset, length); ByteArray_setString(memoryInitializer, offset + 4, text); } else if (node.kind == NodeKind.VARIABLE) { let symbol = node.symbol; /*if (symbol.kind == SymbolKind.VARIABLE_GLOBAL) { let sizeOf = symbol.resolvedType.variableSizeOf(this.context); let value = symbol.node.variableValue(); let memoryInitializer = this.memoryInitializer; // Copy the initial value into the memory initializer this.growMemoryInitializer(); let offset = symbol.offset; if (sizeOf == 1) { if (symbol.resolvedType.isUnsigned()) { memoryInitializer.writeUnsignedByte(value.intValue, offset); } else { memoryInitializer.writeByte(value.intValue, offset); } } else if (sizeOf == 2) { if (symbol.resolvedType.isUnsigned()) { memoryInitializer.writeUnsignedShort(value.intValue, offset); } else { memoryInitializer.writeShort(value.intValue, offset); } } else if (sizeOf == 4) { if (symbol.resolvedType.isFloat()) { memoryInitializer.writeFloat(value.floatValue, offset); } else { if (symbol.resolvedType.isUnsigned()) { memoryInitializer.writeUnsignedInt(value.intValue, offset); } else { memoryInitializer.writeInt(value.intValue, offset); } } } else if (sizeOf == 8) { if (symbol.resolvedType.isDouble()) { memoryInitializer.writeDouble(value.rawValue, offset); } else { //TODO Implement Int64 write if (symbol.resolvedType.isUnsigned()) { //memoryInitializer.writeUnsignedInt64(value.rawValue, offset); } else { //memoryInitializer.writeInt64(value.rawValue, offset); } } } else assert(false);*/ if (symbol.kind == SymbolKind.VARIABLE_GLOBAL) { let global = this.assembler.module.allocateGlobal(symbol, this.bitness); // Make sure the heap offset is tracked if (symbol.name == "HEAP_BASE") { assert(this.HEAP_BASE_INDEX == -1); this.HEAP_BASE_INDEX = symbol.offset; } } } else if (node.kind == NodeKind.FUNCTION && (node.symbol.kind != SymbolKind.FUNCTION_INSTANCE || node.symbol.kind == SymbolKind.FUNCTION_INSTANCE && !node.parent.isTemplate())) { let symbol = node.symbol; let wasmFunctionName: string = getWasmFunctionName(symbol); // if (isBinaryImport(wasmFunctionName)) { // node = node.nextSibling; // return; // } let returnType: Node = node.functionReturnType(); let wasmReturnType = this.getWasmType(returnType.resolvedType); let shared = new WasmSharedOffset(); let isConstructor: boolean = symbol.name == "constructor"; // Make sure to include the implicit "this" variable as a normal argument let argument = node.isExternalImport() ? node.functionFirstArgumentIgnoringThis() : node.functionFirstArgument(); let argumentVariables: WasmLocal[] = []; let argumentTypes: WasmType[] = []; while (argument != returnType) { let wasmType = this.getWasmType(argument.variableType().resolvedType); argumentVariables.push(new WasmLocal(wasmType, argument.symbol.name, argument.symbol, true)); argumentTypes.push(wasmType); shared.nextLocalOffset = shared.nextLocalOffset + 1; argument = argument.nextSibling; } let [signatureIndex, signature] = this.assembler.module.allocateSignature(argumentTypes, wasmReturnType); let body = node.functionBody(); // Functions without bodies are imports if (body == null) { if (!isBuiltin(wasmFunctionName)) { let moduleName = symbol.kind == SymbolKind.FUNCTION_INSTANCE ? symbol.parent().name : "global"; symbol.offset = this.assembler.module.importCount; if (isBinaryImport(wasmFunctionName)) { // this.assembler.module.allocateImport(signature, signatureIndex, "internal", symbol.name); symbol.node.flags |= NODE_FLAG_IMPORT; } else { this.assembler.module.allocateImport(signature, signatureIndex, moduleName, symbol.name); } } node = node.nextSibling; return; } else { symbol.offset = this.assembler.module.functionCount; } let fn = this.assembler.module.allocateFunction(wasmFunctionName, signature, signatureIndex, symbol, node.isExport()); fn.argumentVariables = argumentVariables; fn.isConstructor = isConstructor; fn.returnType = wasmReturnType; // Make sure "malloc" is tracked if (symbol.kind == SymbolKind.FUNCTION_GLOBAL && symbol.name == "malloc") { assert(this.mallocFunctionIndex == -1); this.mallocFunctionIndex = symbol.offset; } if (symbol.kind == SymbolKind.FUNCTION_GLOBAL && symbol.name == "free") { assert(this.freeFunctionIndex == -1); this.freeFunctionIndex = symbol.offset; } // Make "__WASM_INITIALIZER" as start function if (symbol.kind == SymbolKind.FUNCTION_GLOBAL && symbol.name == "__WASM_INITIALIZER") { assert(this.startFunctionIndex == -1); this.startFunctionIndex = symbol.offset; this.startFunction = fn; this.startFunction.body = new ByteArray(); } wasmAssignLocalVariableOffsets(fn, body, shared, this.bitness); fn.locals = argumentVariables.concat(fn.localVariables); } let child = node.firstChild; while (child != null) { this.prepareToEmit(child); child = child.nextSibling; } } emitBinaryExpression(byteOffset: int32, node: Node, opcode: uint8): void { this.emitNode(byteOffset, node.binaryLeft()); this.emitNode(byteOffset, node.binaryRight()); this.assembler.appendOpcode(byteOffset, opcode); } emitLoadFromMemory(byteOffset: int32, type: Type, relativeBase: Node, offset: int32): void { let opcode; // Relative address if (relativeBase != null) { this.emitNode(byteOffset, relativeBase); } // Absolute address else { opcode = WasmOpcode.I32_CONST; this.assembler.appendOpcode(byteOffset, opcode); log(this.assembler.activePayload, byteOffset, 0, "i32 literal"); this.assembler.writeUnsignedLEB128(0); } let sizeOf = type.variableSizeOf(this.context); if (sizeOf == 1) { opcode = type.isUnsigned() ? WasmOpcode.I32_LOAD8_U : WasmOpcode.I32_LOAD8_S; this.assembler.appendOpcode(byteOffset, opcode); log(this.assembler.activePayload, byteOffset, 0, "alignment"); this.assembler.writeUnsignedLEB128(0); } else if (sizeOf == 2) { opcode = type.isUnsigned() ? WasmOpcode.I32_LOAD16_U : WasmOpcode.I32_LOAD16_S; this.assembler.appendOpcode(byteOffset, opcode); log(this.assembler.activePayload, byteOffset, 1, "alignment"); this.assembler.writeUnsignedLEB128(1); } else if (sizeOf == 4 || type.isClass()) { if (type.isFloat()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_LOAD); } else { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_LOAD); } log(this.assembler.activePayload, byteOffset, 2, "alignment"); this.assembler.writeUnsignedLEB128(2); } else if (sizeOf == 8) { if (type.isDouble()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_LOAD); } else { this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_LOAD); } log(this.assembler.activePayload, byteOffset, 3, "alignment"); this.assembler.writeUnsignedLEB128(3); } else { assert(false); } log(this.assembler.activePayload, byteOffset, offset, "load offset"); this.assembler.writeUnsignedLEB128(offset); } emitStoreToMemory(byteOffset: int32, type: Type, relativeBase: Node, offset: int32, value: Node): void { // Relative address if (relativeBase != null ) { this.emitNode(byteOffset, relativeBase); } // Absolute address else { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST); log(this.assembler.activePayload, byteOffset, 0, "i32 literal"); this.assembler.writeUnsignedLEB128(0); } this.emitNode(byteOffset, value); let sizeOf = type.variableSizeOf(this.context); if (sizeOf == 1) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_STORE8); log(this.assembler.activePayload, byteOffset, 0, "alignment"); this.assembler.writeUnsignedLEB128(0); } else if (sizeOf == 2) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_STORE16); log(this.assembler.activePayload, byteOffset, 1, "alignment"); this.assembler.writeUnsignedLEB128(1); } else if (sizeOf == 4 || type.isClass()) { if (type.isFloat()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_STORE); } else { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_STORE); } log(this.assembler.activePayload, byteOffset, 2, "alignment"); this.assembler.writeUnsignedLEB128(2); } else if (sizeOf == 8) { if (type.isDouble()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_STORE); } else if (type.isLong()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_STORE); } log(this.assembler.activePayload, byteOffset, 3, "alignment"); this.assembler.writeUnsignedLEB128(3); } else { assert(false); } log(this.assembler.activePayload, byteOffset, offset, "load offset"); this.assembler.writeUnsignedLEB128(offset); } /** * Emit instance * @param array * @param byteOffset * @param node */ emitInstance(byteOffset: int32, node: Node): void { let constructorNode = node.constructorNode(); if (constructorNode !== undefined) { let callSymbol = constructorNode.symbol; let type = node.newType(); let size; if (type.resolvedType.isArray()) { /** * If the new type if an array append total byte length and element size **/ let elementNode = type.firstGenericType(); let elementType = elementNode.resolvedType; let isClassElement = elementType.isClass(); //ignore 64 bit pointer size = isClassElement ? 4 : elementType.allocationSizeOf(this.context); assert(size > 0); let lengthNode = node.arrayLength(); if (lengthNode.kind == NodeKind.INT32) { let length = size * lengthNode.intValue; this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, length); this.assembler.writeLEB128(length); //array byteLength } else { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, size); this.assembler.writeLEB128(size); this.emitNode(byteOffset, lengthNode); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_MUL); //array byteLength } this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, size); this.assembler.writeLEB128(size); // array element size let callIndex: int32 = this.getWasmFunctionCallIndex(callSymbol); this.assembler.appendOpcode(byteOffset, WasmOpcode.CALL); log(this.assembler.activePayload, byteOffset, callIndex, `call func index (${callIndex})`); this.assembler.writeUnsignedLEB128(callIndex); } else if (type.resolvedType.isTypedArray()) { // let elementSize = getTypedArrayElementSize(type.resolvedType.symbol.name); // this.assembler.appendOpcode(byteOffset, WasmOpcode.GET_LOCAL); // this.assembler.writeLEB128(0); // this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST); // this.assembler.writeLEB128(elementSize); // this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_SHL); // this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST); // this.assembler.writeLEB128(size); // this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_ADD); } else { // Emit constructor argumentVariables let child = node.firstChild.nextSibling; while (child != null) { this.emitNode(byteOffset, child); child = child.nextSibling; } let callIndex: int32 = this.getWasmFunctionCallIndex(callSymbol); this.assembler.appendOpcode(byteOffset, WasmOpcode.CALL, callIndex); this.assembler.writeUnsignedLEB128(callIndex); } } } /** * Emit constructor function where malloc happens * @param array * @param byteOffset * @param fn */ emitConstructor(byteOffset: int32, fn: WasmFunction): void { let constructorNode: Node = fn.symbol.node; let type = constructorNode.parent.symbol; let size = type.resolvedType.allocationSizeOf(this.context); assert(size > 0); if (type.resolvedType.isArray()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.GET_LOCAL, 0); this.assembler.writeUnsignedLEB128(0); // array parameter byteLength this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, size); this.assembler.writeLEB128(size); // size of array class, default is 8 bytes this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_ADD); } else if (type.resolvedType.isTypedArray()) { let elementSize = getTypedArrayElementSize(type.resolvedType.symbol.name); this.assembler.appendOpcode(byteOffset, WasmOpcode.GET_LOCAL, 0); this.assembler.writeUnsignedLEB128(0); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, elementSize); this.assembler.writeLEB128(elementSize); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_SHL); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, size); this.assembler.writeLEB128(size); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_ADD); } else { // Pass the object size as the first argument this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, size); this.assembler.writeLEB128(size); } // Allocate memory let mallocIndex = this.calculateWasmFunctionIndex(this.mallocFunctionIndex); this.assembler.appendOpcode(byteOffset, WasmOpcode.CALL, mallocIndex); this.assembler.writeUnsignedLEB128(mallocIndex); this.assembler.appendOpcode(byteOffset, WasmOpcode.SET_LOCAL, fn.signature.argumentTypes.length); this.assembler.writeUnsignedLEB128(fn.signature.argumentTypes.length); // Set self pointer to first local variable which is immediate after the argument variable } emitNode(byteOffset: int32, node: Node): int32 { // Assert assert(!isExpression(node) || node.resolvedType != null); if (node.kind == NodeKind.BLOCK) { /** * Skip emitting block if parent is 'if' or 'loop' since it is already a block */ let skipBlock = node.parent.kind === NodeKind.IF; if (!skipBlock) { this.assembler.appendOpcode(byteOffset, WasmOpcode.BLOCK); if (node.returnNode !== undefined) { // log(this.assembler.activePayload, byteOffset, this.currentFunction.returnType, WasmType[this.currentFunction.returnType]); this.assembler.append(byteOffset, this.currentFunction.returnType); this.assembler.activeCode.removeLastLinebreak(); this.assembler.activeCode.append(" (result " + WasmTypeToString[this.currentFunction.returnType] + ")\n", 1); } else { // log(this.assembler.activePayload, byteOffset, WasmType.block_type); this.assembler.append(byteOffset, WasmType.block_type); } } let child = node.firstChild; while (child != null) { this.emitNode(byteOffset, child); child = child.nextSibling; } if (!skipBlock) { this.assembler.activeCode.clearIndent(1); this.assembler.activeCode.indent -= 1; this.assembler.appendOpcode(byteOffset, WasmOpcode.END); } } else if (node.kind == NodeKind.WHILE) { let value = node.whileValue(); let body = node.whileBody(); // Ignore "while (false) { ... }" if (value.kind == NodeKind.BOOLEAN && value.intValue == 0) { return 0; } this.assembler.appendOpcode(byteOffset, WasmOpcode.BLOCK); //log(this.assembler.activePayload, WasmType.block_type); this.assembler.append(byteOffset, WasmType.block_type); this.assembler.appendOpcode(byteOffset, WasmOpcode.LOOP); //log(this.assembler.activePayload, 0, WasmType.block_type, WasmType[WasmType.block_type]); this.assembler.append(byteOffset, WasmType.block_type); if (value.kind != NodeKind.BOOLEAN) { this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_EQZ); this.assembler.appendOpcode(byteOffset, WasmOpcode.BR_IF); this.assembler.writeUnsignedLEB128(1); // Break out of the immediately enclosing loop } let child = body.firstChild; while (child != null) { this.emitNode(byteOffset, child); child = child.nextSibling; } // Jump back to the top (this doesn't happen automatically) this.assembler.appendOpcode(byteOffset, WasmOpcode.BR); this.assembler.writeUnsignedLEB128(0); // Continue back to the immediately enclosing loop this.assembler.appendOpcode(byteOffset, WasmOpcode.END); // end inner block this.assembler.appendOpcode(byteOffset, WasmOpcode.END); // end outer block } else if (node.kind == NodeKind.FOR) { let initializationStmt = node.forInitializationStatement(); let terminationStmt = node.forTerminationStatement(); let updateStmt = node.forUpdateStatements(); let body = node.forBody(); this.assembler.appendOpcode(byteOffset, WasmOpcode.BLOCK); //log(this.assembler.activePayload, WasmType.block_type); this.assembler.append(byteOffset, WasmType.block_type); this.emitNode(byteOffset, initializationStmt); this.assembler.appendOpcode(byteOffset, WasmOpcode.LOOP); //log(this.assembler.activePayload, 0, WasmType.block_type, WasmType[WasmType.block_type]); this.assembler.append(byteOffset, WasmType.block_type); if (terminationStmt.kind != NodeKind.BOOLEAN) { this.emitNode(byteOffset, terminationStmt); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_EQZ); this.assembler.appendOpcode(byteOffset, WasmOpcode.BR_IF); this.assembler.writeUnsignedLEB128(1); // Break out of the immediately enclosing loop } let child = body.firstChild; while (child != null) { this.emitNode(byteOffset, child); child = child.nextSibling; } this.emitNode(byteOffset, updateStmt); // Jump back to the top (this doesn't happen automatically) this.assembler.appendOpcode(byteOffset, WasmOpcode.BR); this.assembler.writeUnsignedLEB128(0); // Continue back to the immediately enclosing loop this.assembler.appendOpcode(byteOffset, WasmOpcode.END); // end inner block this.assembler.appendOpcode(byteOffset, WasmOpcode.END); // end outer block } else if (node.kind == NodeKind.BREAK || node.kind == NodeKind.CONTINUE) { let label = 0; let parent = node.parent; while (parent != null && parent.kind != NodeKind.WHILE) { if (parent.kind == NodeKind.BLOCK) { label = label + 1; } parent = parent.parent; } assert(label > 0); this.assembler.appendOpcode(byteOffset, WasmOpcode.BR); this.assembler.writeUnsignedLEB128(label - (node.kind == NodeKind.BREAK ? 0 : 1)); } else if (node.kind == NodeKind.EMPTY) { return 0; } else if (node.kind == NodeKind.EXPRESSIONS) { let child = node.firstChild; while (child) { this.emitNode(byteOffset, child.expressionValue()); child = child.nextSibling; } } else if (node.kind == NodeKind.EXPRESSION) { this.emitNode(byteOffset, node.expressionValue()); } else if (node.kind == NodeKind.RETURN) { let value = node.returnValue(); if (value != null) { this.emitNode(byteOffset, value); } this.assembler.appendOpcode(byteOffset, WasmOpcode.RETURN); } else if (node.kind == NodeKind.VARIABLES) { let count = 0; let child = node.firstChild; while (child != null) { assert(child.kind == NodeKind.VARIABLE); count = count + this.emitNode(byteOffset, child); child = child.nextSibling; } return count; } else if (node.kind == NodeKind.IF) { let branch = node.ifFalse(); this.emitNode(byteOffset, node.ifValue()); this.assembler.appendOpcode(byteOffset, WasmOpcode.IF); let returnNode = node.ifReturnNode(); let needEmptyElse = false; if (returnNode == null && branch === null) { this.assembler.append(0, WasmType.block_type, WasmType[WasmType.block_type]); } else { if (returnNode !== null) { let returnType: WasmType = symbolToWasmType(returnNode.resolvedType.symbol); this.assembler.append(0, returnType, WasmType[returnType]); this.assembler.activeCode.removeLastLinebreak(); this.assembler.activeCode.append(` (result ${WasmTypeToString[returnType]})\n`); if (branch == null) { needEmptyElse = true; } } else { this.assembler.append(0, WasmType.block_type, WasmType[WasmType.block_type]); } } this.emitNode(byteOffset, node.ifTrue()); if (branch != null) { this.assembler.activeCode.indent -= 1; this.assembler.activeCode.clearIndent(1); this.assembler.appendOpcode(byteOffset, WasmOpcode.IF_ELSE); this.emitNode(byteOffset, branch); } else if (needEmptyElse) { this.assembler.activeCode.indent -= 1; this.assembler.activeCode.clearIndent(1); this.assembler.appendOpcode(byteOffset, WasmOpcode.IF_ELSE); let dataType: string = typeToDataType(returnNode.resolvedType, this.bitness); this.assembler.appendOpcode(byteOffset, WasmOpcode[`${dataType}_CONST`]); if (dataType === "I32" || dataType === "I64") { this.assembler.writeUnsignedLEB128(0); } else if (dataType === "F32") { this.assembler.writeFloat(0); } else if (dataType === "F64") { this.assembler.writeDouble(0); } } this.assembler.appendOpcode(byteOffset, WasmOpcode.END); } else if (node.kind == NodeKind.HOOK) { this.emitNode(byteOffset, node.hookValue()); this.assembler.appendOpcode(byteOffset, WasmOpcode.IF); let trueValue = node.hookTrue(); let trueValueType = symbolToWasmType(trueValue.resolvedType.symbol); this.assembler.append(0, trueValueType, WasmType[trueValueType]); this.emitNode(byteOffset, trueValue); this.assembler.appendOpcode(byteOffset, WasmOpcode.IF_ELSE); this.emitNode(byteOffset, node.hookFalse()); this.assembler.appendOpcode(byteOffset, WasmOpcode.END); } else if (node.kind == NodeKind.VARIABLE) { let value = node.variableValue(); if (node.symbol.name == "this" && this.currentFunction.symbol.name == "constructor") { // skip this } else if (node.symbol.kind == SymbolKind.VARIABLE_LOCAL) { if (value && value.kind != NodeKind.NAME && value.kind != NodeKind.CALL && value.kind != NodeKind.NEW && value.kind != NodeKind.DOT && value.rawValue) { if (node.symbol.resolvedType.isFloat()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_CONST, value.floatValue); this.assembler.writeFloat(value.floatValue); } else if (node.symbol.resolvedType.isDouble()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_CONST, value.doubleValue); this.assembler.writeDouble(value.doubleValue); } else if (node.symbol.resolvedType.isLong()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, value.longValue); this.assembler.writeLEB128(value.longValue); } else { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, value.intValue); this.assembler.writeLEB128(value.intValue); } } else { if (value != null) { this.emitNode(byteOffset, value); } else { // Default value if (node.symbol.resolvedType.isFloat()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_CONST, 0); this.assembler.writeFloat(0); } else if (node.symbol.resolvedType.isDouble()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_CONST, 0); this.assembler.writeDouble(0); } else if (node.symbol.resolvedType.isLong()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, 0); this.assembler.writeLEB128(0); } else { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, 0); this.assembler.writeLEB128(0); } } } let skipSetLocal = value && isUnaryPostfix(value.kind); if (skipSetLocal == false) { this.assembler.appendOpcode(byteOffset, WasmOpcode.SET_LOCAL, node.symbol.offset); this.assembler.writeUnsignedLEB128(node.symbol.offset); } } else { assert(false); } } else if (node.kind == NodeKind.NAME) { let symbol = node.symbol; if (symbol.kind == SymbolKind.VARIABLE_ARGUMENT || symbol.kind == SymbolKind.VARIABLE_LOCAL) { // FIXME This should handle in checker. if (symbol.name === "this" && this.currentFunction.symbol.name === "constructor") { this.assembler.appendOpcode(byteOffset, WasmOpcode.GET_LOCAL, this.currentFunction.signature.argumentTypes.length); this.assembler.writeUnsignedLEB128(this.currentFunction.signature.argumentTypes.length); } else { this.assembler.appendOpcode(byteOffset, WasmOpcode.GET_LOCAL, symbol.offset); this.assembler.writeUnsignedLEB128(symbol.offset); } } else if (symbol.kind == SymbolKind.VARIABLE_GLOBAL) { // FIXME: Final spec allow immutable global variables this.assembler.appendOpcode(byteOffset, WasmOpcode.GET_GLOBAL, symbol.offset); this.assembler.writeUnsignedLEB128(symbol.offset); // this.emitLoadFromMemory(byteOffset, symbol.resolvedType, null, MEMORY_INITIALIZER_BASE + symbol.offset); } else { assert(false); } } else if (node.kind == NodeKind.DEREFERENCE) { this.emitLoadFromMemory(byteOffset, node.resolvedType.underlyingType(this.context), node.unaryValue(), 0); } else if (node.kind == NodeKind.POINTER_INDEX) { this.emitLoadFromMemory(byteOffset, node.resolvedType.underlyingType(this.context), node.pointer(), node.pointerOffset()); } else if (node.kind == NodeKind.NULL) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, 0); this.assembler.writeLEB128(0); } else if (node.kind == NodeKind.INT32 || node.kind == NodeKind.BOOLEAN) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, node.intValue); this.assembler.writeLEB128(node.intValue || 0); } else if (node.kind == NodeKind.INT64) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, node.longValue); this.assembler.writeLEB128(node.longValue); } else if (node.kind == NodeKind.FLOAT32) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_CONST, node.floatValue); this.assembler.writeFloat(node.floatValue); } else if (node.kind == NodeKind.FLOAT64) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_CONST, node.doubleValue); this.assembler.writeDouble(node.doubleValue); } else if (node.kind == NodeKind.STRING) { let value = WasmBinary.MEMORY_INITIALIZER_BASE + node.intValue; this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, value); this.assembler.writeLEB128(value); } else if (node.kind == NodeKind.CALL) { let value = node.callValue(); let symbol = value.symbol; assert(isFunction(symbol.kind)); // Write out the implicit "this" argument if (!symbol.node.isExternalImport() && symbol.kind == SymbolKind.FUNCTION_INSTANCE) { let dotTarget = value.dotTarget(); this.emitNode(byteOffset, dotTarget); if (dotTarget.kind == NodeKind.NEW) { this.emitInstance(byteOffset, dotTarget); } } let child = value.nextSibling; while (child != null) { this.emitNode(byteOffset, child); child = child.nextSibling; } let wasmFunctionName: string = getWasmFunctionName(symbol); if (isBuiltin(wasmFunctionName)) { this.assembler.appendOpcode(byteOffset, getBuiltinOpcode(symbol.name)); } else { let callIndex: int32; if (isBinaryImport(wasmFunctionName)) { callIndex = getMergedCallIndex(wasmFunctionName); } else { callIndex = this.getWasmFunctionCallIndex(symbol); } this.assembler.appendOpcode(byteOffset, WasmOpcode.CALL, callIndex); this.assembler.writeUnsignedLEB128(callIndex); } } else if (node.kind == NodeKind.NEW) { this.emitInstance(byteOffset, node); } else if (node.kind == NodeKind.DELETE) { let value = node.deleteValue(); this.emitNode(byteOffset, value); let freeIndex = this.calculateWasmFunctionIndex(this.freeFunctionIndex); this.assembler.appendOpcode(byteOffset, WasmOpcode.CALL, freeIndex); this.assembler.writeUnsignedLEB128(freeIndex); } else if (node.kind == NodeKind.POSITIVE) { this.emitNode(byteOffset, node.unaryValue()); } else if (node.kind == NodeKind.NEGATIVE) { let resolvedType = node.unaryValue().resolvedType; if (resolvedType.isFloat()) { this.emitNode(byteOffset, node.unaryValue()); this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_NEG); } else if (resolvedType.isDouble()) { this.emitNode(byteOffset, node.unaryValue()); this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_NEG); } else if (resolvedType.isInteger()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, 0); this.assembler.writeLEB128(0); this.emitNode(byteOffset, node.unaryValue()); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_SUB); } else if (resolvedType.isLong()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, 0); this.assembler.writeLEB128(0); this.emitNode(byteOffset, node.unaryValue()); this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_SUB); } } else if (node.kind == NodeKind.COMPLEMENT) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, ~0); this.assembler.writeLEB128(~0); this.emitNode(byteOffset, node.unaryValue()); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_XOR); } else if (node.kind == NodeKind.NOT) { this.emitNode(byteOffset, node.unaryValue()); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_EQZ); } else if (node.kind == NodeKind.CAST) { let value = node.castValue(); let context = this.context; let from = value.resolvedType.underlyingType(context); let type = node.resolvedType.underlyingType(context); let fromSize = from.variableSizeOf(context); let typeSize = type.variableSizeOf(context); //FIXME: Handle 8,16 bit integer to float casting // Sign-extend // if ( // from == context.int32Type && // type == context.int8Type || type == context.int16Type // ) { // let shift = 32 - typeSize * 8; // this.emitNode(byteOffset, value); // this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST); // log(byteOffset, shift, "i32 literal"); // this.assembler.writeLEB128(shift); // this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_SHR_S); // this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST); // log(byteOffset, shift, "i32 literal"); // this.assembler.writeLEB128(shift); // this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_SHL); // } // // // Mask // else if ( // from == context.int32Type || from == context.uint32Type && // type == context.uint8Type || type == context.uint16Type // ) { // this.emitNode(byteOffset, value); // this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST); // let _value = type.integerBitMask(this.context); // log(byteOffset, _value, "i32 literal"); // this.assembler.writeLEB128(_value); // this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_AND); // } // --- 32 bit Integer casting --- // i32 > i64 if ( (from == context.nullType || from == context.booleanType || from == context.int32Type || from == context.uint32Type) && (type == context.int64Type || type == context.uint64Type) ) { if (value.kind == NodeKind.NULL) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, 0); this.assembler.writeLEB128(0); } else if (value.kind == NodeKind.BOOLEAN) { let intValue = value.intValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, intValue); this.assembler.writeLEB128(intValue); } else if (value.kind == NodeKind.INT32) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, value.longValue); this.assembler.writeLEB128(value.longValue); } else { let isUnsigned = value.resolvedType.isUnsigned(); this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, isUnsigned ? WasmOpcode.I64_EXTEND_U_I32 : WasmOpcode.I64_EXTEND_S_I32); } } // i32 > f32 else if ( (from == context.nullType || from == context.booleanType || from == context.int32Type || from == context.uint32Type) && type == context.float32Type ) { if (value.kind == NodeKind.NULL) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_CONST, 0); this.assembler.writeFloat(0); } else if (value.kind == NodeKind.BOOLEAN) { let floatValue = value.intValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_CONST, floatValue); this.assembler.writeFloat(floatValue); } else if (value.kind == NodeKind.INT32) { let floatValue = value.floatValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_CONST, floatValue); this.assembler.writeFloat(floatValue); } else { let isUnsigned = value.resolvedType.isUnsigned(); this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, isUnsigned ? WasmOpcode.F32_CONVERT_U_I32 : WasmOpcode.F32_CONVERT_S_I32); } } // i32 > f64 else if ( (from == context.nullType || from == context.int32Type || from == context.uint32Type) && type == context.float64Type ) { if (value.kind == NodeKind.NULL) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_CONST, 0); this.assembler.writeDouble(0); } else if (value.kind == NodeKind.BOOLEAN) { let doubleValue = value.doubleValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_CONST, doubleValue); this.assembler.writeDouble(doubleValue); } else if (value.kind == NodeKind.INT32) { let doubleValue = value.doubleValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_CONST, doubleValue); this.assembler.writeDouble(doubleValue); } else { let isUnsigned = value.resolvedType.isUnsigned(); this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, isUnsigned ? WasmOpcode.F64_CONVERT_U_I32 : WasmOpcode.F64_CONVERT_S_I32); } } //----- // --- 64 bit Integer casting --- // i64 > i32 else if ( (from == context.int64Type || from == context.uint64Type) && (type == context.int32Type || type == context.uint32Type) ) { if (value.kind == NodeKind.INT64) { let intValue = value.intValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, intValue); this.assembler.writeLEB128(intValue); } else { this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_WRAP_I64); } } // i64 > f32 else if ( (from == context.int64Type || from == context.uint64Type) && type == context.float32Type ) { if (value.kind == NodeKind.INT32) { let floatValue = value.floatValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_CONST, floatValue); this.assembler.writeFloat(floatValue); } else { let isUnsigned = value.resolvedType.isUnsigned(); this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, isUnsigned ? WasmOpcode.F32_CONVERT_U_I64 : WasmOpcode.F32_CONVERT_S_I64); } } // i64 > f64 else if ( (from == context.int64Type || from == context.uint64Type) && type == context.float64Type) { if (value.kind == NodeKind.INT64) { let doubleValue = value.doubleValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_CONST, doubleValue); this.assembler.writeDouble(doubleValue); } else { let isUnsigned = value.resolvedType.isUnsigned(); this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, isUnsigned ? WasmOpcode.F64_CONVERT_U_I64 : WasmOpcode.F64_CONVERT_S_I64); } } //------ // --- 32 bit float casting --- // f32 > i32 else if ( from == context.float32Type && (type == context.uint8Type || type == context.int8Type || type == context.uint16Type || type == context.int16Type || type == context.uint32Type || type == context.int32Type) ) { if (value.kind == NodeKind.FLOAT32) { let intValue = value.intValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, intValue); this.assembler.writeLEB128(intValue); } else { let isUnsigned = type.isUnsigned(); this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, isUnsigned ? WasmOpcode.I32_TRUNC_U_F32 : WasmOpcode.I32_TRUNC_S_F32); } } // f32 > i64 else if ( from == context.float32Type && (type == context.int64Type || type == context.uint64Type) ) { if (value.kind == NodeKind.FLOAT32) { let longValue = value.longValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, longValue); this.assembler.writeLEB128(longValue); } else { let isUnsigned = type.isUnsigned(); this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, isUnsigned ? WasmOpcode.I64_TRUNC_U_F32 : WasmOpcode.I64_TRUNC_S_F32); } } // f32 > f64 else if (from == context.float32Type && type == context.float64Type) { if (value.kind == NodeKind.FLOAT32) { let doubleValue = value.doubleValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_CONST, doubleValue); this.assembler.writeDouble(doubleValue); } else { this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_PROMOTE_F32); } } //---- // --- 64 bit float casting --- // f64 > i32 else if ( from == context.float64Type && (type == context.uint8Type || type == context.int8Type || type == context.uint16Type || type == context.int16Type || type == context.uint32Type || type == context.int32Type) ) { if (value.kind == NodeKind.FLOAT64) { let intValue = value.intValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, intValue); this.assembler.writeLEB128(intValue); } else { let isUnsigned = type.isUnsigned(); this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, isUnsigned ? WasmOpcode.I32_TRUNC_U_F64 : WasmOpcode.I32_TRUNC_S_F64); } } // f64 > i64 else if ( from == context.float64Type && (type == context.int64Type || type == context.uint64Type) ) { if (value.kind == NodeKind.FLOAT64) { let longValue = value.longValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, longValue); this.assembler.writeLEB128(longValue); } else { let isUnsigned = type.isUnsigned(); this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, isUnsigned ? WasmOpcode.I64_TRUNC_U_F64 : WasmOpcode.I64_TRUNC_S_F64); } } // f64 > f32 else if (from == context.float64Type && type == context.float32Type) { if (value.kind == NodeKind.FLOAT64) { let floatValue = value.floatValue || 0; this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_CONST, floatValue); this.assembler.writeFloat(floatValue); } else { this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_DEMOTE_F64); } } // No cast needed else { this.emitNode(byteOffset, value); } } else if (node.kind == NodeKind.DOT) { let symbol = node.symbol; if (symbol.kind == SymbolKind.VARIABLE_INSTANCE) { this.emitLoadFromMemory(byteOffset, symbol.resolvedType, node.dotTarget(), symbol.offset); } else { assert(false); } } else if (node.kind == NodeKind.ASSIGN) { let left = node.binaryLeft(); let right = node.binaryRight(); let symbol = left.symbol; if (left.kind == NodeKind.DEREFERENCE) { this.emitStoreToMemory(byteOffset, left.resolvedType.underlyingType(this.context), left.unaryValue(), 0, right); } else if (left.kind == NodeKind.POINTER_INDEX) { this.emitStoreToMemory(byteOffset, left.resolvedType.underlyingType(this.context), left.pointer(), left.pointerOffset(), right); } else if (symbol.kind == SymbolKind.VARIABLE_INSTANCE) { this.emitStoreToMemory(byteOffset, symbol.resolvedType, left.dotTarget(), symbol.offset, right); } else if (symbol.kind == SymbolKind.VARIABLE_GLOBAL) { this.emitNode(byteOffset, right); this.assembler.appendOpcode(byteOffset, WasmOpcode.SET_GLOBAL); this.assembler.writeUnsignedLEB128(symbol.offset); // this.emitStoreToMemory(byteOffset, symbol.resolvedType, null, MEMORY_INITIALIZER_BASE + symbol.offset, right); } else if (symbol.kind == SymbolKind.VARIABLE_ARGUMENT || symbol.kind == SymbolKind.VARIABLE_LOCAL) { this.emitNode(byteOffset, right); if (!isUnaryPostfix(right.kind)) { this.assembler.appendOpcode(byteOffset, WasmOpcode.SET_LOCAL, symbol.offset); this.assembler.writeUnsignedLEB128(symbol.offset); } } else { assert(false); } } else if (node.kind == NodeKind.LOGICAL_AND) { this.emitNode(byteOffset, node.binaryLeft()); this.emitNode(byteOffset, node.binaryRight()); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_AND); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, 1); this.assembler.writeLEB128(1); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_EQ); } else if (node.kind == NodeKind.LOGICAL_OR) { this.emitNode(byteOffset, node.binaryLeft()); this.emitNode(byteOffset, node.binaryRight()); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_OR); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST); log(this.assembler.activePayload, byteOffset, 1, "i32 literal"); this.assembler.writeLEB128(1); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_EQ); } else if (isUnary(node.kind)) { let kind = node.kind; if (kind == NodeKind.POSTFIX_INCREMENT || kind == NodeKind.POSTFIX_DECREMENT) { let value = node.unaryValue(); let dataType: string = typeToDataType(value.resolvedType, this.bitness); //TODO handle instance variable if (node.parent.kind == NodeKind.VARIABLE) { this.emitNode(byteOffset, value); this.assembler.appendOpcode(byteOffset, WasmOpcode.SET_LOCAL, node.parent.symbol.offset); this.assembler.writeUnsignedLEB128(node.parent.symbol.offset); } else if (node.parent.kind == NodeKind.ASSIGN) { this.emitNode(byteOffset, value); let left = node.parent.binaryLeft(); this.assembler.appendOpcode(byteOffset, WasmOpcode.SET_LOCAL, left.symbol.offset); this.assembler.writeUnsignedLEB128(left.symbol.offset); } this.emitNode(byteOffset, value); if (node.parent.kind != NodeKind.RETURN) { assert( value.resolvedType.isInteger() || value.resolvedType.isLong() || value.resolvedType.isFloat() || value.resolvedType.isDouble() ); let size = value.resolvedType.pointerTo ? value.resolvedType.pointerTo.allocationSizeOf(this.context) : value.resolvedType.allocationSizeOf(this.context); if (size == 1 || size == 2) { if (value.kind == NodeKind.INT32 || value.resolvedType.isInteger()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, 1); this.assembler.writeLEB128(1); } else { Terminal.error("Wrong type"); } } else if (size == 4) { if (value.kind == NodeKind.INT32 || value.resolvedType.isInteger()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, 1); this.assembler.writeLEB128(1); } else if (value.kind == NodeKind.FLOAT32 || value.resolvedType.isFloat()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_CONST, 1.0); this.assembler.writeFloat(1); } else { Terminal.error("Wrong type"); } } else if (size == 8) { if (value.kind == NodeKind.INT64 || value.resolvedType.isLong()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, 1); this.assembler.writeLEB128(1); } else if (value.kind == NodeKind.FLOAT64 || value.resolvedType.isDouble()) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_CONST, 1.0); this.assembler.writeDouble(1); } else { Terminal.error("Wrong type"); } } //TODO extend to other operations let operation = kind == NodeKind.POSTFIX_INCREMENT ? "ADD" : "SUB"; this.assembler.appendOpcode(byteOffset, WasmOpcode[`${dataType}_${operation}`]); if (value.symbol.kind == SymbolKind.VARIABLE_GLOBAL) { this.assembler.appendOpcode(byteOffset, WasmOpcode.SET_GLOBAL, value.symbol.offset); this.assembler.writeLEB128(value.symbol.offset); } else if (value.symbol.kind == SymbolKind.VARIABLE_LOCAL || value.symbol.kind == SymbolKind.VARIABLE_ARGUMENT) { this.assembler.appendOpcode(byteOffset, WasmOpcode.SET_LOCAL, value.symbol.offset); this.assembler.writeLEB128(value.symbol.offset); } else if (value.symbol.kind == SymbolKind.VARIABLE_INSTANCE) { //FIXME //this.emitStoreToMemory(byteOffset, value.symbol.resolvedType, value.dotTarget(), value.symbol.offset, node); } } } } else { let isUnsigned = node.isUnsignedOperator(); let left = node.binaryLeft(); let right = node.binaryRight(); let isFloat: boolean = left.resolvedType.isFloat() || right.resolvedType.isFloat(); let isDouble: boolean = left.resolvedType.isDouble() || right.resolvedType.isDouble(); let dataTypeLeft: string = typeToDataType(left.resolvedType, this.bitness); let dataTypeRight: string = typeToDataType(right.resolvedType, this.bitness); if (node.kind == NodeKind.ADD) { this.emitNode(byteOffset, left); if (left.resolvedType.pointerTo == null) { this.emitNode(byteOffset, right); } // Need to multiply the right by the size of the pointer target else { assert( right.resolvedType.isInteger() || right.resolvedType.isLong() || right.resolvedType.isFloat() || right.resolvedType.isDouble() ); let size = left.resolvedType.pointerTo.allocationSizeOf(this.context); if (size == 2) { if (right.kind == NodeKind.INT32) { let _value = right.intValue << 1; this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, _value); this.assembler.writeLEB128(_value); } else { this.emitNode(byteOffset, right); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, 1); this.assembler.writeLEB128(1); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_SHL); } } else if (size == 4) { if (right.kind == NodeKind.INT32) { let _value = right.intValue << 2; this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, _value); this.assembler.writeLEB128(_value); } else if (right.kind == NodeKind.FLOAT32) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F32_CONST, right.floatValue); this.assembler.writeFloat(right.floatValue); } else { this.emitNode(byteOffset, right); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_CONST, 2); this.assembler.writeLEB128(2); this.assembler.appendOpcode(byteOffset, WasmOpcode.I32_SHL); } } else if (size == 8) { if (right.kind == NodeKind.INT64) { this.assembler.appendOpcode(byteOffset, WasmOpcode.I64_CONST, right.longValue); this.assembler.writeLEB128(right.longValue); } else if (right.kind == NodeKind.FLOAT64) { this.assembler.appendOpcode(byteOffset, WasmOpcode.F64_CONST, right.doubleValue); this.assembler.writeDouble(right.doubleValue); } } else { this.emitNode(byteOffset, right); } } this.assembler.appendOpcode(byteOffset, WasmOpcode[`${dataTypeLeft}_ADD`]); } else if (node.kind == NodeKind.BITWISE_AND) { if (isFloat || isDouble) { let error = "Cannot do bitwise operations on floating point number" Terminal.error(error); throw error; } this.emitBinaryExpression(byteOffset, node, WasmOpcode[`${dataTypeLeft}_AND`]); } else if (node.kind == NodeKind.BITWISE_OR) { if (isFloat || isDouble) { let error = "Cannot do bitwise operations on floating point number"; Terminal.error(error); throw error; } this.emitBinaryExpression(byteOffset, node, WasmOpcode[`${dataTypeLeft}_OR`]); } else if (node.kind == NodeKind.BITWISE_XOR) { this.emitBinaryExpression(byteOffset, node, WasmOpcode[`${dataTypeLeft}_XOR`]); } else if (node.kind == NodeKind.EQUAL) { this.emitBinaryExpression(byteOffset, node, WasmOpcode[`${dataTypeLeft}_EQ`]); } else if (node.kind == NodeKind.MULTIPLY) { this.emitBinaryExpression(byteOffset, node, WasmOpcode[`${dataTypeLeft}_MUL`]); } else if (node.kind == NodeKind.NOT_EQUAL) { this.emitBinaryExpression(byteOffset, node, WasmOpcode[`${dataTypeLeft}_NE`]); } else if (node.kind == NodeKind.SHIFT_LEFT) { if (isFloat || isDouble) { let error = "Cannot do bitwise operations on floating point number"; Terminal.error(error); throw error; } this.emitBinaryExpression(byteOffset, node, WasmOpcode[`${dataTypeLeft}_SHL`]); } else if (node.kind == NodeKind.SUBTRACT) { this.emitBinaryExpression(byteOffset, node, WasmOpcode[`${dataTypeLeft}_SUB`]); } else if (node.kind == NodeKind.DIVIDE) { let opcode = (isFloat || isDouble) ? WasmOpcode[`${dataTypeLeft}_DIV`] : (isUnsigned ? WasmOpcode[`${dataTypeLeft}_DIV_U`] : WasmOpcode[`${dataTypeLeft}_DIV_S`]); this.emitBinaryExpression(byteOffset, node, opcode); } else if (node.kind == NodeKind.GREATER_THAN) { let opcode = (isFloat || isDouble) ? WasmOpcode[`${dataTypeLeft}_GT`] : (isUnsigned ? WasmOpcode[`${dataTypeLeft}_GT_U`] : WasmOpcode[`${dataTypeLeft}_GT_S`]); this.emitBinaryExpression(byteOffset, node, opcode); } else if (node.kind == NodeKind.GREATER_THAN_EQUAL) { let opcode = (isFloat || isDouble) ? WasmOpcode[`${dataTypeLeft}_GE`] : (isUnsigned ? WasmOpcode[`${dataTypeLeft}_GE_U`] : WasmOpcode[`${dataTypeLeft}_GE_S`]); this.emitBinaryExpression(byteOffset, node, opcode); } else if (node.kind == NodeKind.LESS_THAN) { let opcode = (isFloat || isDouble) ? WasmOpcode[`${dataTypeLeft}_LT`] : (isUnsigned ? WasmOpcode[`${dataTypeLeft}_LT_U`] : WasmOpcode[`${dataTypeLeft}_LT_S`]); this.emitBinaryExpression(byteOffset, node, opcode); } else if (node.kind == NodeKind.LESS_THAN_EQUAL) { let opcode = (isFloat || isDouble) ? WasmOpcode[`${dataTypeLeft}_LE`] : (isUnsigned ? WasmOpcode[`${dataTypeLeft}_LE_U`] : WasmOpcode[`${dataTypeLeft}_LE_S`]); this.emitBinaryExpression(byteOffset, node, opcode); } else if (node.kind == NodeKind.REMAINDER) { if (isFloat || isDouble) { let error = "Floating point remainder is not yet supported in WebAssembly. Please import javascript function to handle this"; Terminal.error(error); throw error; } this.emitBinaryExpression(byteOffset, node, isUnsigned ? WasmOpcode[`${dataTypeLeft}_REM_U`] : WasmOpcode[`${dataTypeLeft}_REM_S`]); } else if (node.kind == NodeKind.SHIFT_RIGHT) { if (isFloat || isDouble) { let error = "Cannot do bitwise operations on floating point number"; Terminal.error(error); throw error; } this.emitBinaryExpression(byteOffset, node, isUnsigned ? WasmOpcode[`${dataTypeLeft}_SHR_U`] : WasmOpcode[`${dataTypeLeft}_SHR_S`]); } else { assert(false); } } return 1; } calculateWasmFunctionIndex(index: int32): int32 { return this.assembler.module.importCount + index; } getWasmFunctionCallIndex(symbol: Symbol): int32 { return (symbol.node.isImport() || symbol.node.isExternalImport()) ? symbol.offset : this.assembler.module.importCount + symbol.offset; } getWasmType(type: Type): WasmType { let context = this.context; if (type == context.booleanType || type.isClass() || type.isInteger() || (this.bitness == Bitness.x32 && type.isReference())) { return WasmType.I32; } else if (type.isLong() || (this.bitness == Bitness.x64 && type.isReference())) { return WasmType.I64; } else if (type.isDouble()) { return WasmType.F64; } else if (type.isFloat()) { return WasmType.F32; } if (type == context.voidType) { return WasmType.VOID; } assert(false); return WasmType.VOID; } } function wasmAssignLocalVariableOffsets(fn: WasmFunction, node: Node, shared: WasmSharedOffset, bitness: Bitness): void { if (node.kind == NodeKind.VARIABLE) { assert(node.symbol.kind == SymbolKind.VARIABLE_LOCAL); // node.symbol.offset = shared.nextLocalOffset; shared.nextLocalOffset = shared.nextLocalOffset + 1; shared.localCount = shared.localCount + 1; let local = new WasmLocal( symbolToWasmType(node.symbol, bitness), node.symbol.internalName, node.symbol, false ); node.symbol.offset = fn.argumentVariables.length + fn.localVariables.length; fn.localVariables.push(new WasmLocal(local.type, local.symbol.name)); } let child = node.firstChild; while (child != null) { wasmAssignLocalVariableOffsets(fn, child, shared, bitness); child = child.nextSibling; } } export function wasmEmit(compiler: Compiler, bitness: Bitness = Bitness.x32, optimize: boolean = true): void { let wasmEmitter = new WasmModuleEmitter(bitness); wasmEmitter.context = compiler.context; wasmEmitter.memoryInitializer = new ByteArray(); if (Compiler.mallocRequired) { // Merge imported malloc.wasm binaries wasmEmitter.mergeBinaryImports(); } // Emission requires two passes wasmEmitter.prepareToEmit(compiler.global); wasmEmitter.assembler.sealFunctions(); compiler.outputWASM = wasmEmitter.assembler.module.binary.data; wasmEmitter.emitModule(); if (optimize) { WasmOptimizer.optimize(compiler.outputWASM) } compiler.outputWAST = wasmEmitter.assembler.module.text; }
the_stack
import * as async from 'async'; import * as common from './common'; // // ### function Provider (options) // #### @options {Object} Options for this instance. // Constructor function for the Provider object responsible // for exposing the pluggable storage features of `nconf`. // export const Provider = function(this: any, options = {}) { // // Setup default options for working with `stores`, // `overrides`, `process.env` and `process.argv`. // options = options || {}; this.stores = {}; this.sources = []; this.init(options); }; // // Define wrapper functions for using basic stores // in this instance // ['argv', 'env'].forEach(function(type) { Provider.prototype[type] = function() { const args = [type].concat(Array.prototype.slice.call(arguments)); return this.add.apply(this, args); }; }); // // ### function file (key, options) // #### @key {string|Object} Fully qualified options, name of file store, or path. // #### @path {string|Object} **Optional** Full qualified options, or path. // Adds a new `File` store to this instance. Accepts the following options // // nconf.file({ file: '.jitsuconf', dir: process.env.HOME, search: true }); // nconf.file('path/to/config/file'); // nconf.file('userconfig', 'path/to/config/file'); // nconf.file('userconfig', { file: '.jitsuconf', search: true }); // Provider.prototype.file = function(key, options) { if (arguments.length == 1) { options = typeof key === 'string' ? { file: key } : key; key = 'file'; } else { options = typeof options === 'string' ? { file: options } : options; } options.type = 'file'; return this.add(key, options); }; // // Define wrapper functions for using // overrides and defaults // ['defaults', 'overrides'].forEach(function(type) { Provider.prototype[type] = function(options) { options = options || {}; if (!options.type) { options.type = 'literal'; } return this.add(type, options); }; }); // // ### function use (name, options) // #### @type {string} Type of the nconf store to use. // #### @options {Object} Options for the store instance. // Adds (or replaces) a new store with the specified `name` // and `options`. If `options.type` is not set, then `name` // will be used instead: // // provider.use('file'); // provider.use('file', { type: 'file', filename: '/path/to/userconf' }) // Provider.prototype.use = function(name, options) { options = options || {}; function sameOptions(store) { return Object.keys(options).every(function(key) { return options[key] === store[key]; }); } const store = this.stores[name], update = store && !sameOptions(store); if (!store || update) { if (update) { this.remove(name); } this.add(name, options); } return this; }; // // ### function add (name, options) // #### @name {string} Name of the store to add to this instance // #### @options {Object} Options for the store to create // Adds a new store with the specified `name` and `options`. If `options.type` // is not set, then `name` will be used instead: // // provider.add('memory'); // provider.add('userconf', { type: 'file', filename: '/path/to/userconf' }) // Provider.prototype.add = function(name, options, usage) { options = options || {}; const type = options.type || name; if (!require('../nconf').default[common.capitalize(type)]) { throw new Error('Cannot add store with unknown type: ' + type); } this.stores[name] = this.create(type, options, usage); if (this.stores[name].loadSync) { this.stores[name].loadSync(); } return this; }; // // ### function remove (name) // #### @name {string} Name of the store to remove from this instance // Removes a store with the specified `name` from this instance. Users // are allowed to pass in a type argument (e.g. `memory`) as name if // this was used in the call to `.add()`. // Provider.prototype.remove = function(name) { delete this.stores[name]; return this; }; // // ### function create (type, options) // #### @type {string} Type of the nconf store to use. // #### @options {Object} Options for the store instance. // Creates a store of the specified `type` using the // specified `options`. // Provider.prototype.create = function(type, options, usage) { return new (require('../nconf').default[ common.capitalize(type.toLowerCase()) ])(options, usage); }; // // ### function init (options) // #### @options {Object} Options to initialize this instance with. // Initializes this instance with additional `stores` or `sources` in the // `options` supplied. // Provider.prototype.init = function(options) { const self = this; // // Add any stores passed in through the options // to this instance. // if (options.type) { this.add(options.type, options); } else if (options.store) { this.add(options.store.name || options.store.type, options.store); } else if (options.stores) { Object.keys(options.stores).forEach(function(name) { const store = options.stores[name]; self.add(store.name || name || store.type, store); }); } // // Add any read-only sources to this instance // if (options.source) { this.sources.push( this.create(options.source.type || options.source.name, options.source), ); } else if (options.sources) { Object.keys(options.sources).forEach(function(name) { const source = options.sources[name]; self.sources.push( self.create(source.type || source.name || name, source), ); }); } }; // // ### function get (key, callback) // #### @key {string} Key to retrieve for this instance. // #### @callback {function} **Optional** Continuation to respond to when complete. // Retrieves the value for the specified key (if any). // Provider.prototype.get = function(key, callback) { if (typeof key === 'function') { // Allow a * key call to be made callback = key; key = null; } // // If there is no callback we can short-circuit into the default // logic for traversing stores. // if (!callback) { return this._execute('get', 1, key, callback); } // // Otherwise the asynchronous, hierarchical `get` is // slightly more complicated because we do not need to traverse // the entire set of stores, but up until there is a defined value. // let current = 0, names = Object.keys(this.stores), self = this, response, mergeObjs: any[] = []; async.whilst( function() { return typeof response === 'undefined' && current < names.length; }, function(next) { const store = self.stores[names[current]]; current++; if (store.get.length >= 2) { return store.get(key, function(err, value) { if (err) { return next(err); } response = value; // Merge objects if necessary if ( response && typeof response === 'object' && !Array.isArray(response) ) { mergeObjs.push(response); response = undefined; } next(); }); } response = store.get(key); // Merge objects if necessary if ( response && typeof response === 'object' && !Array.isArray(response) ) { mergeObjs.push(response); response = undefined; } next(); }, function(err) { if (!err && mergeObjs.length) { response = common.merge(mergeObjs.reverse()); } return err ? callback(err) : callback(null, response); }, ); }; // // ### function any (keys, callback) // #### @keys {array|string...} Array of keys to query, or a variable list of strings // #### @callback {function} **Optional** Continuation to respond to when complete. // Retrieves the first truthy value (if any) for the specified list of keys. // Provider.prototype.any = function(keys, callback) { if (!Array.isArray(keys)) { keys = Array.prototype.slice.call(arguments); if (keys.length > 0 && typeof keys[keys.length - 1] === 'function') { callback = keys.pop(); } else { callback = null; } } // // If there is no callback, use the short-circuited "get" // on each key in turn. // if (!callback) { let val; for (let i = 0; i < keys.length; ++i) { val = this._execute('get', 1, keys[i], callback); if (val) { return val; } } return null; } let keyIndex = 0, result, self = this; async.whilst( function() { return !result && keyIndex < keys.length; }, function(next) { const key = keys[keyIndex]; keyIndex++; self.get(key, function(err, v) { if (err) { next(err); } else { result = v; next(); } }); }, function(err) { return err ? callback(err) : callback(null, result); }, ); }; // // ### function set (key, value, callback) // #### @key {string} Key to set in this instance // #### @value {literal|Object} Value for the specified key // #### @callback {function} **Optional** Continuation to respond to when complete. // Sets the `value` for the specified `key` in this instance. // Provider.prototype.set = function(key, value, callback) { return this._execute('set', 2, key, value, callback); }; // // ### function required (keys) // #### @keys {array} List of keys // Throws an error if any of `keys` has no value, otherwise returns `true` Provider.prototype.required = function(keys) { if (!Array.isArray(keys)) { throw new Error('Incorrect parameter, array expected'); } const missing: any[] = []; keys.forEach(function(this: any, key) { if (typeof this.get(key) === 'undefined') { missing.push(key); } }, this); if (missing.length) { throw new Error('Missing required keys: ' + missing.join(', ')); } else { return this; } }; // // ### function reset (callback) // #### @callback {function} **Optional** Continuation to respond to when complete. // Clears all keys associated with this instance. // Provider.prototype.reset = function(callback) { return this._execute('reset', 0, callback); }; // // ### function clear (key, callback) // #### @key {string} Key to remove from this instance // #### @callback {function} **Optional** Continuation to respond to when complete. // Removes the value for the specified `key` from this instance. // Provider.prototype.clear = function(key, callback) { return this._execute('clear', 1, key, callback); }; // // ### function merge ([key,] value [, callback]) // #### @key {string} Key to merge the value into // #### @value {literal|Object} Value to merge into the key // #### @callback {function} **Optional** Continuation to respond to when complete. // Merges the properties in `value` into the existing object value at `key`. // // 1. If the existing value `key` is not an Object, it will be completely overwritten. // 2. If `key` is not supplied, then the `value` will be merged into the root. // Provider.prototype.merge = function() { const self = this, args = Array.prototype.slice.call(arguments), callback = typeof args[args.length - 1] === 'function' && args.pop(), value = args.pop(), key = args.pop(); function mergeProperty(prop, next) { return self._execute('merge', 2, prop, value[prop], next); } if (!key) { if (Array.isArray(value) || typeof value !== 'object') { return onError( new Error('Cannot merge non-Object into top-level.'), callback, ); } return async.forEach( Object.keys(value), mergeProperty, callback || function() {}, ); } return this._execute('merge', 2, key, value, callback); }; // // ### function load (callback) // #### @callback {function} Continuation to respond to when complete. // Responds with an Object representing all keys associated in this instance. // Provider.prototype.load = function(callback) { const self = this; function getStores() { const stores = Object.keys(self.stores); stores.reverse(); return stores.map(function(name) { return self.stores[name]; }); } function loadStoreSync(store) { if (!store.loadSync) { throw new Error( 'nconf store ' + store.type + ' has no loadSync() method', ); } return store.loadSync(); } function loadStore(store, next) { if (!store.load && !store.loadSync) { return next( new Error('nconf store ' + store.type + ' has no load() method'), ); } return store.loadSync ? next(null, store.loadSync()) : store.load(next); } function loadBatch(targets, done?) { if (!done) { return common.merge(targets.map(loadStoreSync)); } async.map(targets, loadStore, function(err, objs) { return err ? done(err) : done(null, common.merge(objs)); }); } function mergeSources(data) { // // If `data` was returned then merge it into // the system store. // if (data && typeof data === 'object') { self.use('sources', { type: 'literal', store: data, }); } } function loadSources() { const sourceHierarchy = self.sources.splice(0); sourceHierarchy.reverse(); // // If we don't have a callback and the current // store is capable of loading synchronously // then do so. // if (!callback) { mergeSources(loadBatch(sourceHierarchy)); return loadBatch(getStores()); } loadBatch(sourceHierarchy, function(err, data) { if (err) { return callback(err); } mergeSources(data); return loadBatch(getStores(), callback); }); } return self.sources.length ? loadSources() : loadBatch(getStores(), callback); }; // // ### function save (callback) // #### @callback {function} **optional** Continuation to respond to when // complete. // Instructs each provider to save. If a callback is provided, we will attempt // asynchronous saves on the providers, falling back to synchronous saves if // this isn't possible. If a provider does not know how to save, it will be // ignored. Returns an object consisting of all of the data which was // actually saved. // Provider.prototype.save = function(value, callback) { if (!callback && typeof value === 'function') { callback = value; value = null; } const self = this, names = Object.keys(this.stores); function saveStoreSync(memo, name) { const store = self.stores[name]; // // If the `store` doesn't have a `saveSync` method, // just ignore it and continue. // if (store.saveSync) { const ret = store.saveSync(); if (typeof ret == 'object' && ret !== null) { memo.push(ret); } } return memo; } function saveStore(memo, name, next) { const store = self.stores[name]; // // If the `store` doesn't have a `save` or saveSync` // method(s), just ignore it and continue. // if (store.save) { return store.save(value, function(err, data) { if (err) { return next(err); } if (typeof data == 'object' && data !== null) { memo.push(data); } next(null, memo); }); } else if (store.saveSync) { memo.push(store.saveSync()); } next(null, memo); } // // If we don't have a callback and the current // store is capable of saving synchronously // then do so. // if (!callback) { return common.merge(names.reduce(saveStoreSync, [])); } async.reduce(names, [], saveStore, function(err, objs) { return err ? callback(err) : callback(null, common.merge(objs)); }); }; // // ### @private function _execute (action, syncLength, [arguments]) // #### @action {string} Action to execute on `this.store`. // #### @syncLength {number} Function length of the sync version. // #### @arguments {Array} Arguments array to apply to the action // Executes the specified `action` on all stores for this instance, ensuring a callback supplied // to a synchronous store function is still invoked. // Provider.prototype._execute = function(action, syncLength /* [arguments] */) { let args = Array.prototype.slice.call(arguments, 2), callback = typeof args[args.length - 1] === 'function' && args.pop(), destructive = ['set', 'clear', 'merge', 'reset'].indexOf(action) !== -1, self = this, response, mergeObjs: any[] = [], keys = Object.keys(this.stores); function runAction(name, next) { const store = self.stores[name]; if (destructive && store.readOnly) { return next(); } return store[action].length > syncLength ? store[action].apply(store, args.concat(next)) : next(null, store[action].apply(store, args)); } if (callback) { return async.forEach(keys, runAction, function(err) { return err ? callback(err) : callback(); }); } keys.forEach(function(name) { if (typeof response === 'undefined') { const store = self.stores[name]; if (destructive && store.readOnly) { return; } response = store[action].apply(store, args); // Merge objects if necessary if ( response && action === 'get' && typeof response === 'object' && !Array.isArray(response) ) { mergeObjs.push(response); response = undefined; } } }); if (mergeObjs.length) { response = common.merge(mergeObjs.reverse()); } return response; }; // // Throw the `err` if a callback is not supplied // function onError(err, callback) { if (callback) { return callback(err); } throw err; }
the_stack
import * as cdk from '@aws-cdk/core'; import * as ssm from '@aws-cdk/aws-ssm'; import * as fs from 'fs'; import * as yaml from 'js-yaml'; import * as sfn from '@aws-cdk/aws-stepfunctions'; import * as events from '@aws-cdk/aws-events'; import { Effect, PolicyStatement, ServicePrincipal, Policy, Role, CfnRole, ArnPrincipal, CompositePrincipal } from '@aws-cdk/aws-iam'; import { StateMachine } from '@aws-cdk/aws-stepfunctions'; import { IRuleTarget, EventPattern, Rule } from '@aws-cdk/aws-events'; import { MemberRoleStack } from '../solution_deploy/lib/remediation_runbook-stack'; /* * @author AWS Solutions Development * @description SSM-based remediation parameters * @type {playbookConstruct} */ export interface IssmPlaybookProps { securityStandard: string; // ex. AFSBP securityStandardVersion: string; controlId: string; ssmDocPath: string; ssmDocFileName: string; solutionVersion: string; solutionDistBucket: string; adminRoleName?: string; remediationPolicy?: Policy; adminAccountNumber?: string; solutionId?: string; scriptPath?: string; } export class SsmPlaybook extends cdk.Construct { constructor(scope: cdk.Construct, id: string, props: IssmPlaybookProps) { super(scope, id); let scriptPath = '' if (props.scriptPath == undefined ) { scriptPath = `${props.ssmDocPath}/scripts` } else { scriptPath = props.scriptPath } let illegalChars = /[\.]/g; const enableParam = new cdk.CfnParameter(this, 'Enable ' + props.controlId, { type: "String", description: `Enable/disable availability of remediation for ${props.securityStandard} version ${props.securityStandardVersion} Control ${props.controlId} in Security Hub Console Custom Actions. If NOT Available the remediation cannot be triggered from the Security Hub console in the Security Hub Admin account.`, default: "Available", allowedValues: ["Available", "NOT Available"] }) enableParam.overrideLogicalId(`${props.securityStandard}${props.controlId.replace(illegalChars, '')}Active`) const installSsmDoc = new cdk.CfnCondition(this, 'Enable ' + props.controlId + ' Condition', { expression: cdk.Fn.conditionEquals(enableParam, "Available") }) let ssmDocName = `SHARR-${props.securityStandard}_${props.securityStandardVersion}_${props.controlId}` let ssmDocFQFileName = `${props.ssmDocPath}/${props.ssmDocFileName}` let ssmDocType = props.ssmDocFileName.substr(props.ssmDocFileName.length - 4).toLowerCase() let ssmDocIn = fs.readFileSync(ssmDocFQFileName, 'utf8') let ssmDocOut: string = '' const re = /^(?<padding>\s+)%%SCRIPT=(?<script>.*)%%/ for (let line of ssmDocIn.split('\n')) { let foundMatch = re.exec(line) if (foundMatch && foundMatch.groups && foundMatch.groups.script) { let scriptIn = fs.readFileSync(`${scriptPath}/${foundMatch.groups.script}`, 'utf8') for (let scriptLine of scriptIn.split('\n')) { ssmDocOut += foundMatch.groups.padding + scriptLine + '\n' } } else { ssmDocOut += line + '\n' } } let ssmDocSource = undefined if (ssmDocType == 'json') { ssmDocSource = JSON.parse(ssmDocOut) } else if (ssmDocType == 'yaml') { ssmDocSource = yaml.load(ssmDocOut) } const AutoDoc = new ssm.CfnDocument(this, 'Automation Document', { content: ssmDocSource, documentType: 'Automation', name: ssmDocName }) AutoDoc.cfnOptions.condition = installSsmDoc } } /* * @author AWS Solutions Development * @description SSM-based remediation trigger * @type {trigger} */ export interface ITriggerProps { description?: string, securityStandard: string; // ex. AFSBP generatorId: string; // ex. "arn:aws-cn:securityhub:::ruleset/cis-aws-foundations-benchmark/v/1.2.0" controlId: string; targetArn: string; } export class Trigger extends cdk.Construct { constructor(scope: cdk.Construct, id: string, props: ITriggerProps) { super(scope, id); let illegalChars = /[\.]/g; // Event to Step Function // ---------------------- // Create CWE rule // Create custom action let description = `Remediate ${props.securityStandard} ${props.controlId}` if (props.description) { description = props.description } let workflowStatusFilter = { "Status": [ "NEW" ] } let complianceStatusFilter = { "Status": [ "FAILED", "WARNING" ] } const stateMachine = sfn.StateMachine.fromStateMachineArn(this, 'orchestrator', props.targetArn); // Create an IAM role for Events to start the State Machine const eventsRole = new Role(this, 'EventsRuleRole', { assumedBy: new ServicePrincipal('events.amazonaws.com') }); // Grant the start execution permission to the Events service stateMachine.grantStartExecution(eventsRole); // Create an event rule to trigger the step function const stateMachineTarget: events.IRuleTarget = { bind: () => ({ id: '', arn: props.targetArn, role: eventsRole }) }; const enable_auto_remediation_param = new cdk.CfnParameter(this, 'AutoEnable', { description: "This will fully enable automated remediation for "+ props.securityStandard + ' ' + props.controlId, type: "String", allowedValues: ["ENABLED", "DISABLED"], default: "DISABLED" }); enable_auto_remediation_param.overrideLogicalId(`${props.securityStandard}${props.controlId.replace(illegalChars, '')}AutoTrigger`) interface IPattern { source: any, detailType: any detail: any } let eventPattern: IPattern = { source: ["aws.securityhub"], detailType: ["Security Hub Findings - Imported"], detail: { findings: { GeneratorId: [props.generatorId], ProductFields: { ControlId: [props.controlId] }, Workflow: workflowStatusFilter, Compliance: complianceStatusFilter } } } let triggerPattern: events.EventPattern = eventPattern // Adding an automated even rule for the playbook const eventRule_auto = new events.Rule(this, 'AutoEventRule', { description: description + ' automatic remediation trigger event rule.', ruleName: `${props.securityStandard}_${props.controlId}_AutoTrigger`, targets: [stateMachineTarget], eventPattern: triggerPattern }); const cfnEventRule_auto = eventRule_auto.node.defaultChild as events.CfnRule; cfnEventRule_auto.addPropertyOverride('State', enable_auto_remediation_param.valueAsString); } } export interface IOneTriggerProps { description?: string, targetArn: string; serviceToken: string; prereq: cdk.CfnResource[]; } export class OneTrigger extends cdk.Construct { // used in place of Trigger. Sends all finding events for which the // SHARR custom action is initiated to the Step Function constructor(scope: cdk.Construct, id: string, props: IOneTriggerProps) { super(scope, id); const stack = cdk.Stack.of(this) // Event to Step Function // ---------------------- // Create CWE rule // Create custom action let description = `Remediate with SHARR` if (props.description) { description = props.description } let complianceStatusFilter = { "Status": [ "FAILED", "WARNING" ] } const stateMachine = StateMachine.fromStateMachineArn(this, 'orchestrator', props.targetArn); // Note: Id is max 20 characters const customAction = new cdk.CustomResource(this, 'Custom Action', { serviceToken: props.serviceToken, resourceType: 'Custom::ActionTarget', properties: { Name: 'Remediate with SHARR', Description: 'Submit the finding to AWS Security Hub Automated Response and Remediation', Id: 'SHARRRemediation' } }); { let child = customAction.node.defaultChild as cdk.CfnCustomResource for (var prereq of props.prereq) { child.addDependsOn(prereq) } } // Create an IAM role for Events to start the State Machine const eventsRole = new Role(this, 'EventsRuleRole', { assumedBy: new ServicePrincipal('events.amazonaws.com') }); // Grant the start execution permission to the Events service stateMachine.grantStartExecution(eventsRole); // Create an event rule to trigger the step function const stateMachineTarget: IRuleTarget = { bind: () => ({ id: '', arn: props.targetArn, role: eventsRole }) }; let eventPattern: EventPattern = { source: ["aws.securityhub"], detailType: ["Security Hub Findings - Custom Action"], resources: [ customAction.getAttString('Arn') ], detail: { findings: { Compliance: complianceStatusFilter } } } new Rule(this, 'Remediate Custom Action', { description: description, enabled: true, eventPattern: eventPattern, ruleName: `Remediate_with_SHARR_CustomAction`, targets: [stateMachineTarget] }) } } export interface RoleProps { readonly solutionId: string; readonly ssmDocName: string; readonly remediationPolicy: Policy; readonly remediationRoleName: string; } export class SsmRole extends cdk.Construct { constructor(scope: cdk.Construct, id: string, props: RoleProps) { super(scope, id); const stack = cdk.Stack.of(this) const roleStack = MemberRoleStack.of(this) const RESOURCE_PREFIX = props.solutionId.replace(/^DEV-/,''); // prefix on every resource name const adminRoleName = `${RESOURCE_PREFIX}-SHARR-Orchestrator-Admin` const basePolicy = new Policy(this, 'SHARR-Member-Base-Policy') const adminAccount = roleStack.node.findChild('AdminAccountParameter').node.findChild('Admin Account Number') as cdk.CfnParameter; const ssmParmPerms = new PolicyStatement(); ssmParmPerms.addActions( "ssm:GetParameters", "ssm:GetParameter", "ssm:PutParameter" ) ssmParmPerms.effect = Effect.ALLOW ssmParmPerms.addResources( `arn:${stack.partition}:ssm:*:${stack.account}:parameter/Solutions/SO0111/*` ); basePolicy.addStatements(ssmParmPerms) // AssumeRole Policy let principalPolicyStatement = new PolicyStatement(); principalPolicyStatement.addActions("sts:AssumeRole"); principalPolicyStatement.effect = Effect.ALLOW; let roleprincipal = new ArnPrincipal( 'arn:' + stack.partition + ':iam::' + adminAccount.valueAsString + ':role/' + adminRoleName ); let principals = new CompositePrincipal(roleprincipal); principals.addToPolicy(principalPolicyStatement); let serviceprincipal = new ServicePrincipal('ssm.amazonaws.com') principals.addPrincipals(serviceprincipal); let memberRole = new Role(this, 'MemberAccountRole', { assumedBy: principals, roleName: props.remediationRoleName }); memberRole.attachInlinePolicy(basePolicy) memberRole.attachInlinePolicy(props.remediationPolicy) memberRole.applyRemovalPolicy(cdk.RemovalPolicy.RETAIN) const memberRoleResource = memberRole.node.findChild('Resource') as CfnRole; memberRoleResource.cfnOptions.metadata = { cfn_nag: { rules_to_suppress: [{ id: 'W11', reason: 'Resource * is required due to the administrative nature of the solution.' },{ id: 'W28', reason: 'Static names chosen intentionally to provide integration in cross-account permissions' }] } }; } } export interface RemediationRunbookProps { ssmDocName: string; ssmDocPath: string; ssmDocFileName: string; solutionVersion: string; solutionDistBucket: string; remediationPolicy?: Policy; solutionId?: string; scriptPath?: string; } export class SsmRemediationRunbook extends cdk.Construct { constructor(scope: cdk.Construct, id: string, props: RemediationRunbookProps) { super(scope, id); // Add prefix to ssmDocName let ssmDocName = `SHARR-${props.ssmDocName}` let scriptPath = '' if (props.scriptPath == undefined) { scriptPath = 'ssmdocs/scripts' } else { scriptPath = props.scriptPath } let ssmDocFQFileName = `${props.ssmDocPath}/${props.ssmDocFileName}` let ssmDocType = props.ssmDocFileName.substr(props.ssmDocFileName.length - 4).toLowerCase() let ssmDocIn = fs.readFileSync(ssmDocFQFileName, 'utf8') let ssmDocOut: string = '' const re = /^(?<padding>\s+)%%SCRIPT=(?<script>.*)%%/ for (let line of ssmDocIn.split('\n')) { let foundMatch = re.exec(line) if (foundMatch && foundMatch.groups && foundMatch.groups.script) { let scriptIn = fs.readFileSync(`${scriptPath}/${foundMatch.groups.script}`, 'utf8') for (let scriptLine of scriptIn.split('\n')) { ssmDocOut += foundMatch.groups.padding + scriptLine + '\n' } } else { ssmDocOut += line + '\n' } } let ssmDocSource = undefined if (ssmDocType == 'json') { ssmDocSource = JSON.parse(ssmDocOut) } else if (ssmDocType == 'yaml') { ssmDocSource = yaml.load(ssmDocOut) } new ssm.CfnDocument(this, 'Automation Document', { content: ssmDocSource, documentType: 'Automation', name: ssmDocName }) } }
the_stack
import {CallTreeProfileBuilder, Frame, FrameInfo, Profile, ProfileGroup} from '../lib/profile' import {getOrElse, getOrInsert, KeyedSet} from '../lib/utils' import {ByteFormatter, TimeFormatter} from '../lib/value-formatters' class CallGraph { private frameSet = new KeyedSet<Frame>() private totalWeights = new Map<Frame, number>() private childrenTotalWeights = new Map<Frame, Map<Frame, number>>() constructor(private fileName: string, private fieldName: string) {} private getOrInsertFrame(info: FrameInfo): Frame { return Frame.getOrInsert(this.frameSet, info) } private addToTotalWeight(frame: Frame, weight: number) { if (!this.totalWeights.has(frame)) { this.totalWeights.set(frame, weight) } else { this.totalWeights.set(frame, this.totalWeights.get(frame)! + weight) } } addSelfWeight(frameInfo: FrameInfo, weight: number) { this.addToTotalWeight(this.getOrInsertFrame(frameInfo), weight) } addChildWithTotalWeight(parentInfo: FrameInfo, childInfo: FrameInfo, weight: number) { const parent = this.getOrInsertFrame(parentInfo) const child = this.getOrInsertFrame(childInfo) const childMap = getOrInsert(this.childrenTotalWeights, parent, k => new Map()) if (!childMap.has(child)) { childMap.set(child, weight) } else { childMap.set(child, childMap.get(child) + weight) } this.addToTotalWeight(parent, weight) } toProfile(): Profile { // To convert a call graph into a profile, we first need to identify what // the "root weights" are. "root weights" are the total weight of each frame // while at the bottom of the call-stack. The majority of functions will have // zero weight while at the bottom of the call-stack, since most functions // are never at the bottom of the call-stack. const rootWeights = new Map<Frame, number>() for (let [frame, totalWeight] of this.totalWeights) { rootWeights.set(frame, totalWeight) } for (let [_, childMap] of this.childrenTotalWeights) { for (let [child, weight] of childMap) { rootWeights.set(child, getOrElse(rootWeights, child, () => weight) - weight) } } let totalProfileWeight = 0 for (let [_, rootWeight] of rootWeights) { totalProfileWeight += rootWeight } const profile = new CallTreeProfileBuilder() let unitMultiplier = 1 // These are common field names used by Xdebug. Let's give them special // treatment to more helpfully display units. if (this.fieldName === 'Time_(10ns)') { profile.setName(`${this.fileName} -- Time`) unitMultiplier = 10 profile.setValueFormatter(new TimeFormatter('nanoseconds')) } else if (this.fieldName == 'Memory_(bytes)') { profile.setName(`${this.fileName} -- Memory`) profile.setValueFormatter(new ByteFormatter()) } else { profile.setName(`${this.fileName} -- ${this.fieldName}`) } let totalCumulative = 0 const currentStack = new Set<Frame>() const visit = (frame: Frame, callTreeWeight: number) => { if (currentStack.has(frame)) { // Call-graphs are allowed to have cycles. Call-trees are not. In case // we run into a cycle, we'll just avoid recursing into the same subtree // more than once in a call stack. The result will be that the time // spent in the recursive call will instead be attributed as self time // in the parent. return } // We need to calculate how much weight to give to a particular node in // the call-tree based on information from the call-graph. A given node // from the call-graph might correspond to several nodes in the call-tree, // so we need to decide how to distribute the weight of the call-graph // node to the various call-tree nodes. // // We assume that the weighting is evenly distributed. If a call-tree node // X occurs with weights x1 and x2, and we know from the call-graph that // child Y of X has a total weight y, then we assume the child Y of X has // weight y*x1/(x1 + x2) for the first occurrence, and y*x2(y1 + x2) for // the second occurrence. // // This assumption is incorrectly (sometimes wildly so), but we need to // make *some* assumption, and this seems to me the sanest option. // // See the comment at the top of the file for an example where this // assumption can yield especially misleading results. if (callTreeWeight < 1e-4 * totalProfileWeight) { // This assumption about even distribution can cause us to generate a // call tree with dramatically more nodes than the call graph. // // Consider a function which is called 1000 times, where the result is // cached. The first invocation has a complex call tree and may take // 100ms. Let's say that this complex call tree has 250 nodes. // // Subsequent calls use the cached result, so take only 1ms, and have no // children in their call trees. So we have, in total, (1 + 250) + 999 // nodes in the call-tree for a total of 1250 nodes. // // The information specific to each invocation is, however, lost in the // call-graph representation. // // Because of the even distribution assumption we make, this means that // the call-trees of each invocation will have the same shape. Each 1ms // call-tree will look identical to the 100ms call-tree, just // horizontally compacted. So instead of 1251 nodes, we have // 1000*250=250,000 nodes in the resulting call graph. // // To mitigate this explosion of the # of nodes, we ignore subtrees // whose weights are less than 0.01% of the total weight of the profile. return } // totalWeightForFrame is the total weight for the given frame in the // entire call graph. const callGraphWeightForFrame = getOrElse(this.totalWeights, frame, () => 0) if (callGraphWeightForFrame === 0) { return } // This is the portion of the total time the given child spends within the // given parent that we'll attribute to this specific path in the call // tree. const ratio = callTreeWeight / callGraphWeightForFrame let selfWeightForFrame = callGraphWeightForFrame profile.enterFrame(frame, totalCumulative * unitMultiplier) currentStack.add(frame) for (let [child, callGraphEdgeWeight] of this.childrenTotalWeights.get(frame) || []) { selfWeightForFrame -= callGraphEdgeWeight const childCallTreeWeight = callGraphEdgeWeight * ratio visit(child, childCallTreeWeight) } currentStack.delete(frame) totalCumulative += selfWeightForFrame * ratio profile.leaveFrame(frame, totalCumulative * unitMultiplier) } for (let [rootFrame, rootWeight] of rootWeights) { if (rootWeight <= 0) { continue } // If we've reached here, it means that the given root frame has some // weight while at the top of the call-stack. visit(rootFrame, rootWeight) } return profile.build() } } // In writing this, I initially tried to use the formal grammar described in // section 3.2 of https://www.valgrind.org/docs/manual/cl-format.html, but // stopped because most of the information isn't relevant for visualization, and // because there's inconsistency between the grammar and subsequence // descriptions. // // For example, the grammar for headers specifies all the valid header names, // but then the writing below that mentions there may be a "totals" or "summary" // header, which should be disallowed by the formal grammar. // // So, instead, I'm not going to bother with a formal parse. Since there are no // real recursive structures in this file format, that should be okay. class CallgrindParser { private lines: string[] private lineNum: number private callGraphs: CallGraph[] | null = null private eventsLine: string | null = null private filename: string | null = null private functionName: string | null = null private calleeFilename: string | null = null private calleeFunctionName: string | null = null private savedFileNames: {[id: string]: string} = {} private savedFunctionNames: {[id: string]: string} = {} constructor(contents: string, private importedFileName: string) { this.lines = contents.split('\n') this.lineNum = 0 } parse(): ProfileGroup | null { while (this.lineNum < this.lines.length) { const line = this.lines[this.lineNum++] if (/^\s*#/.exec(line)) { // Line is a comment. Ignore it. continue } if (/^\s*$/.exec(line)) { // Line is empty. Ignore it. continue } if (this.parseHeaderLine(line)) { continue } if (this.parseAssignmentLine(line)) { continue } if (this.parseCostLine(line, 'self')) { continue } throw new Error(`Unrecognized line "${line}" on line ${this.lineNum}`) } if (!this.callGraphs) { return null } return { name: this.importedFileName, indexToView: 0, profiles: this.callGraphs.map(cg => cg.toProfile()), } } private frameInfo(): FrameInfo { const file = this.filename || '(unknown)' const name = this.functionName || '(unknown)' const key = `${file}:${name}` return {key, name, file} } private calleeFrameInfo(): FrameInfo { const file = this.calleeFilename || '(unknown)' const name = this.calleeFunctionName || '(unknown)' const key = `${file}:${name}` return {key, name, file} } private parseHeaderLine(line: string): boolean { const headerMatch = /^\s*(\w+):\s*(.*)+$/.exec(line) if (!headerMatch) return false if (headerMatch[1] !== 'events') { // We don't care about other headers. Ignore this line. return true } // Line specifies the formatting of subsequent cost lines. const fields = headerMatch[2].split(' ') if (this.callGraphs != null) { throw new Error( `Duplicate "events: " lines specified. First was "${this.eventsLine}", now received "${line}" on ${this.lineNum}.`, ) } this.callGraphs = fields.map(fieldName => { return new CallGraph(this.importedFileName, fieldName) }) return true } private parseAssignmentLine(line: string): boolean { const assignmentMatch = /^(\w+)=\s*(.*)$/.exec(line) if (!assignmentMatch) return false const key = assignmentMatch[1] const value = assignmentMatch[2] switch (key) { case 'fe': case 'fi': case 'fl': { this.filename = this.parseNameWithCompression(value, this.savedFileNames) this.calleeFilename = this.filename break } case 'fn': { this.functionName = this.parseNameWithCompression(value, this.savedFunctionNames) break } case 'cfi': case 'cfl': { this.calleeFilename = this.parseNameWithCompression(value, this.savedFileNames) break } case 'cfn': { this.calleeFunctionName = this.parseNameWithCompression(value, this.savedFunctionNames) break } case 'calls': { // TODO(jlfwong): This is currently ignoring the number of calls being // made. Accounting for the number of calls might be unhelpful anyway, // since it'll just be copying the exact same frame over-and-over again, // but that might be better than ignoring it. this.parseCostLine(this.lines[this.lineNum++], 'child') break } default: { console.log(`Ignoring assignment to unrecognized key "${line}" on line ${this.lineNum}`) } } return true } private parseNameWithCompression(name: string, saved: {[id: string]: string}): string { { const nameDefinitionMatch = /^\((\d+)\)\s*(.+)$/.exec(name) if (nameDefinitionMatch) { const id = nameDefinitionMatch[1] const name = nameDefinitionMatch[2] if (id in saved) { throw new Error( `Redefinition of name with id: ${id}. Original value was "${saved[id]}". Tried to redefine as "${name}" on line ${this.lineNum}.`, ) } saved[id] = name return name } } { const nameUseMatch = /^\((\d+)\)$/.exec(name) if (nameUseMatch) { const id = nameUseMatch[1] if (!(id in saved)) { throw new Error( `Tried to use name with id ${id} on line ${this.lineNum} before it was defined.`, ) } return saved[id] } } return name } private parseCostLine(line: string, costType: 'self' | 'child'): boolean { // TODO(jlfwong): Handle "Subposition compression" // TODO(jlfwong): Allow hexadecimal encoding const parts = line.split(/\s+/) const nums: number[] = [] for (let part of parts) { // As far as I can tell from the specification, the callgrind format does // not accept floating point numbers. const asNum = parseInt(part) if (isNaN(asNum)) { return false } nums.push(asNum) } if (nums.length == 0) { return false } // TODO(jlfwong): Handle custom positions format w/ multiple parts const numPositionFields = 1 // NOTE: We intentionally do not include the line number here because // callgrind uses the line number of the function invocation, not the // line number of the function definition, which conflicts with how // speedscope uses line numbers. // // const lineNum = nums[0] if (!this.callGraphs) { throw new Error( `Encountered a cost line on line ${this.lineNum} before event specification was provided.`, ) } for (let i = 0; i < this.callGraphs.length; i++) { if (costType === 'self') { this.callGraphs[i].addSelfWeight(this.frameInfo(), nums[numPositionFields + i]) } else if (costType === 'child') { this.callGraphs[i].addChildWithTotalWeight( this.frameInfo(), this.calleeFrameInfo(), nums[numPositionFields + i] || 0, ) } } return true } } export function importFromCallgrind( contents: string, importedFileName: string, ): ProfileGroup | null { return new CallgrindParser(contents, importedFileName).parse() }
the_stack