text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
namespace ts { // eslint-disable-line one-namespace-per-file // should be used as tracing?.___ export let tracing: typeof tracingEnabled | undefined; // enable the above using startTracing() // `tracingEnabled` should never be used directly, only through the above namespace tracingEnabled { // eslint-disable-line one-namespace-per-file type Mode = "project" | "build" | "server"; let fs: typeof import("fs"); let traceCount = 0; let traceFd = 0; let mode: Mode; const typeCatalog: Type[] = []; // NB: id is index + 1 let legendPath: string | undefined; const legend: TraceRecord[] = []; // The actual constraint is that JSON.stringify be able to serialize it without throwing. interface Args { [key: string]: string | number | boolean | null | undefined | Args | readonly (string | number | boolean | null | undefined | Args)[]; }; /** Starts tracing for the given project. */ export function startTracing(tracingMode: Mode, traceDir: string, configFilePath?: string) { Debug.assert(!tracing, "Tracing already started"); if (fs === undefined) { try { fs = require("fs"); } catch (e) { throw new Error(`tracing requires having fs\n(original error: ${e.message || e})`); } } mode = tracingMode; typeCatalog.length = 0; if (legendPath === undefined) { legendPath = combinePaths(traceDir, "legend.json"); } // Note that writing will fail later on if it exists and is not a directory if (!fs.existsSync(traceDir)) { fs.mkdirSync(traceDir, { recursive: true }); } const countPart = mode === "build" ? `.${process.pid}-${++traceCount}` : mode === "server" ? `.${process.pid}` : ``; const tracePath = combinePaths(traceDir, `trace${countPart}.json`); const typesPath = combinePaths(traceDir, `types${countPart}.json`); legend.push({ configFilePath, tracePath, typesPath, }); traceFd = fs.openSync(tracePath, "w"); tracing = tracingEnabled; // only when traceFd is properly set // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import) const meta = { cat: "__metadata", ph: "M", ts: 1000 * timestamp(), pid: 1, tid: 1 }; fs.writeSync(traceFd, "[\n" + [{ name: "process_name", args: { name: "tsc" }, ...meta }, { name: "thread_name", args: { name: "Main" }, ...meta }, { name: "TracingStartedInBrowser", ...meta, cat: "disabled-by-default-devtools.timeline" }] .map(v => JSON.stringify(v)).join(",\n")); } /** Stops tracing for the in-progress project and dumps the type catalog. */ export function stopTracing() { Debug.assert(tracing, "Tracing is not in progress"); Debug.assert(!!typeCatalog.length === (mode !== "server")); // Have a type catalog iff not in server mode fs.writeSync(traceFd, `\n]\n`); fs.closeSync(traceFd); tracing = undefined; if (typeCatalog.length) { dumpTypes(typeCatalog); } else { // We pre-computed this path for convenience, but clear it // now that the file won't be created. legend[legend.length - 1].typesPath = undefined; } } export function recordType(type: Type): void { if (mode !== "server") { typeCatalog.push(type); } } export const enum Phase { Parse = "parse", Program = "program", Bind = "bind", Check = "check", // Before we get into checking types (e.g. checkSourceFile) CheckTypes = "checkTypes", Emit = "emit", Session = "session", } export function instant(phase: Phase, name: string, args?: Args) { writeEvent("I", phase, name, args, `"s":"g"`); } const eventStack: { phase: Phase, name: string, args?: Args, time: number, separateBeginAndEnd: boolean }[] = []; /** * @param separateBeginAndEnd - used for special cases where we need the trace point even if the event * never terminates (typically for reducing a scenario too big to trace to one that can be completed). * In the future we might implement an exit handler to dump unfinished events which would deprecate * these operations. */ export function push(phase: Phase, name: string, args?: Args, separateBeginAndEnd = false) { if (separateBeginAndEnd) { writeEvent("B", phase, name, args); } eventStack.push({ phase, name, args, time: 1000 * timestamp(), separateBeginAndEnd }); } export function pop() { Debug.assert(eventStack.length > 0); writeStackEvent(eventStack.length - 1, 1000 * timestamp()); eventStack.length--; } export function popAll() { const endTime = 1000 * timestamp(); for (let i = eventStack.length - 1; i >= 0; i--) { writeStackEvent(i, endTime); } eventStack.length = 0; } // sample every 10ms const sampleInterval = 1000 * 10; function writeStackEvent(index: number, endTime: number) { const { phase, name, args, time, separateBeginAndEnd } = eventStack[index]; if (separateBeginAndEnd) { writeEvent("E", phase, name, args, /*extras*/ undefined, endTime); } // test if [time,endTime) straddles a sampling point else if (sampleInterval - (time % sampleInterval) <= endTime - time) { writeEvent("X", phase, name, args, `"dur":${endTime - time}`, time); } } function writeEvent(eventType: string, phase: Phase, name: string, args: Args | undefined, extras?: string, time: number = 1000 * timestamp()) { // In server mode, there's no easy way to dump type information, so we drop events that would require it. if (mode === "server" && phase === Phase.CheckTypes) return; performance.mark("beginTracing"); fs.writeSync(traceFd, `,\n{"pid":1,"tid":1,"ph":"${eventType}","cat":"${phase}","ts":${time},"name":"${name}"`); if (extras) fs.writeSync(traceFd, `,${extras}`); if (args) fs.writeSync(traceFd, `,"args":${JSON.stringify(args)}`); fs.writeSync(traceFd, `}`); performance.mark("endTracing"); performance.measure("Tracing", "beginTracing", "endTracing"); } function getLocation(node: Node | undefined) { const file = getSourceFileOfNode(node); return !file ? undefined : { path: file.path, start: indexFromOne(getLineAndCharacterOfPosition(file, node!.pos)), end: indexFromOne(getLineAndCharacterOfPosition(file, node!.end)), }; function indexFromOne(lc: LineAndCharacter): LineAndCharacter { return { line: lc.line + 1, character: lc.character + 1, }; } } function dumpTypes(types: readonly Type[]) { performance.mark("beginDumpTypes"); const typesPath = legend[legend.length - 1].typesPath!; const typesFd = fs.openSync(typesPath, "w"); const recursionIdentityMap = new Map<object, number>(); // Cleverness: no line break here so that the type ID will match the line number fs.writeSync(typesFd, "["); const numTypes = types.length; for (let i = 0; i < numTypes; i++) { const type = types[i]; const objectFlags = (type as any).objectFlags; const symbol = type.aliasSymbol ?? type.symbol; // It's slow to compute the display text, so skip it unless it's really valuable (or cheap) let display: string | undefined; if ((objectFlags & ObjectFlags.Anonymous) | (type.flags & TypeFlags.Literal)) { try { display = type.checker?.typeToString(type); } catch { display = undefined; } } let indexedAccessProperties: object = {}; if (type.flags & TypeFlags.IndexedAccess) { const indexedAccessType = type as IndexedAccessType; indexedAccessProperties = { indexedAccessObjectType: indexedAccessType.objectType?.id, indexedAccessIndexType: indexedAccessType.indexType?.id, }; } let referenceProperties: object = {}; if (objectFlags & ObjectFlags.Reference) { const referenceType = type as TypeReference; referenceProperties = { instantiatedType: referenceType.target?.id, typeArguments: referenceType.resolvedTypeArguments?.map(t => t.id), referenceLocation: getLocation(referenceType.node), }; } let conditionalProperties: object = {}; if (type.flags & TypeFlags.Conditional) { const conditionalType = type as ConditionalType; conditionalProperties = { conditionalCheckType: conditionalType.checkType?.id, conditionalExtendsType: conditionalType.extendsType?.id, conditionalTrueType: conditionalType.resolvedTrueType?.id ?? -1, conditionalFalseType: conditionalType.resolvedFalseType?.id ?? -1, }; } let substitutionProperties: object = {}; if (type.flags & TypeFlags.Substitution) { const substitutionType = type as SubstitutionType; substitutionProperties = { substitutionBaseType: substitutionType.baseType?.id, substituteType: substitutionType.substitute?.id, }; } let reverseMappedProperties: object = {}; if (objectFlags & ObjectFlags.ReverseMapped) { const reverseMappedType = type as ReverseMappedType; reverseMappedProperties = { reverseMappedSourceType: reverseMappedType.source?.id, reverseMappedMappedType: reverseMappedType.mappedType?.id, reverseMappedConstraintType: reverseMappedType.constraintType?.id, }; } let evolvingArrayProperties: object = {}; if (objectFlags & ObjectFlags.EvolvingArray) { const evolvingArrayType = type as EvolvingArrayType; evolvingArrayProperties = { evolvingArrayElementType: evolvingArrayType.elementType.id, evolvingArrayFinalType: evolvingArrayType.finalArrayType?.id, }; } // We can't print out an arbitrary object, so just assign each one a unique number. // Don't call it an "id" so people don't treat it as a type id. let recursionToken: number | undefined; const recursionIdentity = type.checker.getRecursionIdentity(type); if (recursionIdentity) { recursionToken = recursionIdentityMap.get(recursionIdentity); if (!recursionToken) { recursionToken = recursionIdentityMap.size; recursionIdentityMap.set(recursionIdentity, recursionToken); } } const descriptor = { id: type.id, intrinsicName: (type as any).intrinsicName, symbolName: symbol?.escapedName && unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, isTuple: objectFlags & ObjectFlags.Tuple ? true : undefined, unionTypes: (type.flags & TypeFlags.Union) ? (type as UnionType).types?.map(t => t.id) : undefined, intersectionTypes: (type.flags & TypeFlags.Intersection) ? (type as IntersectionType).types.map(t => t.id) : undefined, aliasTypeArguments: type.aliasTypeArguments?.map(t => t.id), keyofType: (type.flags & TypeFlags.Index) ? (type as IndexType).type?.id : undefined, ...indexedAccessProperties, ...referenceProperties, ...conditionalProperties, ...substitutionProperties, ...reverseMappedProperties, ...evolvingArrayProperties, destructuringPattern: getLocation(type.pattern), firstDeclaration: getLocation(symbol?.declarations?.[0]), flags: Debug.formatTypeFlags(type.flags).split("|"), display, }; fs.writeSync(typesFd, JSON.stringify(descriptor)); if (i < numTypes - 1) { fs.writeSync(typesFd, ",\n"); } } fs.writeSync(typesFd, "]\n"); fs.closeSync(typesFd); performance.mark("endDumpTypes"); performance.measure("Dump types", "beginDumpTypes", "endDumpTypes"); } export function dumpLegend() { if (!legendPath) { return; } fs.writeFileSync(legendPath, JSON.stringify(legend)); } interface TraceRecord { configFilePath?: string; tracePath: string; typesPath?: string; } } // define after tracingEnabled is initialized export const startTracing = tracingEnabled.startTracing; export const dumpTracingLegend = tracingEnabled.dumpLegend; export interface TracingNode { tracingPath?: Path; } }
the_stack
* @packageDocumentation * @module csvviewer-extension */ import { ILayoutRestorer, JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application'; import { createToolbarFactory, InputDialog, IThemeManager, IToolbarWidgetRegistry, WidgetTracker } from '@jupyterlab/apputils'; import { CSVDelimiter, CSVViewer, CSVViewerFactory, TextRenderConfig, TSVViewerFactory } from '@jupyterlab/csvviewer'; import { DocumentRegistry, IDocumentWidget } from '@jupyterlab/docregistry'; import { ISearchProviderRegistry } from '@jupyterlab/documentsearch'; import { IEditMenu, IMainMenu } from '@jupyterlab/mainmenu'; import { ISettingRegistry } from '@jupyterlab/settingregistry'; import { ITranslator } from '@jupyterlab/translation'; import { DataGrid } from '@lumino/datagrid'; import { CSVSearchProvider } from './searchprovider'; /** * The name of the factories that creates widgets. */ const FACTORY_CSV = 'CSVTable'; const FACTORY_TSV = 'TSVTable'; /** * The CSV file handler extension. */ const csv: JupyterFrontEndPlugin<void> = { activate: activateCsv, id: '@jupyterlab/csvviewer-extension:csv', requires: [ITranslator], optional: [ ILayoutRestorer, IThemeManager, IMainMenu, ISearchProviderRegistry, ISettingRegistry, IToolbarWidgetRegistry ], autoStart: true }; /** * The TSV file handler extension. */ const tsv: JupyterFrontEndPlugin<void> = { activate: activateTsv, id: '@jupyterlab/csvviewer-extension:tsv', requires: [ITranslator], optional: [ ILayoutRestorer, IThemeManager, IMainMenu, ISearchProviderRegistry, ISettingRegistry, IToolbarWidgetRegistry ], autoStart: true }; /** * Connect menu entries for find and go to line. */ function addMenuEntries( mainMenu: IMainMenu, tracker: WidgetTracker<IDocumentWidget<CSVViewer>>, translator: ITranslator ) { const trans = translator.load('jupyterlab'); // Add go to line capability to the edit menu. mainMenu.editMenu.goToLiners.add({ tracker, goToLine: (widget: IDocumentWidget<CSVViewer>) => { return InputDialog.getNumber({ title: trans.__('Go to Line'), value: 0 }).then(value => { if (value.button.accept && value.value !== null) { widget.content.goToLine(value.value); } }); } } as IEditMenu.IGoToLiner<IDocumentWidget<CSVViewer>>); } /** * Activate cssviewer extension for CSV files */ function activateCsv( app: JupyterFrontEnd, translator: ITranslator, restorer: ILayoutRestorer | null, themeManager: IThemeManager | null, mainMenu: IMainMenu | null, searchregistry: ISearchProviderRegistry | null, settingRegistry: ISettingRegistry | null, toolbarRegistry: IToolbarWidgetRegistry | null ): void { let toolbarFactory: | ((widget: IDocumentWidget<CSVViewer>) => DocumentRegistry.IToolbarItem[]) | undefined; if (toolbarRegistry) { toolbarRegistry.registerFactory<IDocumentWidget<CSVViewer>>( FACTORY_CSV, 'delimiter', widget => new CSVDelimiter({ widget: widget.content, translator }) ); if (settingRegistry) { toolbarFactory = createToolbarFactory( toolbarRegistry, settingRegistry, FACTORY_CSV, csv.id, translator ); } } const trans = translator.load('jupyterlab'); const factory = new CSVViewerFactory({ name: FACTORY_CSV, label: trans.__('CSV Viewer'), fileTypes: ['csv'], defaultFor: ['csv'], readOnly: true, toolbarFactory, translator }); const tracker = new WidgetTracker<IDocumentWidget<CSVViewer>>({ namespace: 'csvviewer' }); // The current styles for the data grids. let style: DataGrid.Style = Private.LIGHT_STYLE; let rendererConfig: TextRenderConfig = Private.LIGHT_TEXT_CONFIG; if (restorer) { // Handle state restoration. void restorer.restore(tracker, { command: 'docmanager:open', args: widget => ({ path: widget.context.path, factory: FACTORY_CSV }), name: widget => widget.context.path }); } app.docRegistry.addWidgetFactory(factory); const ft = app.docRegistry.getFileType('csv'); factory.widgetCreated.connect((sender, widget) => { // Track the widget. void tracker.add(widget); // Notify the widget tracker if restore data needs to update. widget.context.pathChanged.connect(() => { void tracker.save(widget); }); if (ft) { widget.title.icon = ft.icon!; widget.title.iconClass = ft.iconClass!; widget.title.iconLabel = ft.iconLabel!; } // Set the theme for the new widget. widget.content.style = style; widget.content.rendererConfig = rendererConfig; }); // Keep the themes up-to-date. const updateThemes = () => { const isLight = themeManager && themeManager.theme ? themeManager.isLight(themeManager.theme) : true; style = isLight ? Private.LIGHT_STYLE : Private.DARK_STYLE; rendererConfig = isLight ? Private.LIGHT_TEXT_CONFIG : Private.DARK_TEXT_CONFIG; tracker.forEach(grid => { grid.content.style = style; grid.content.rendererConfig = rendererConfig; }); }; if (themeManager) { themeManager.themeChanged.connect(updateThemes); } if (mainMenu) { addMenuEntries(mainMenu, tracker, translator); } if (searchregistry) { searchregistry.register('csv', CSVSearchProvider); } } /** * Activate cssviewer extension for TSV files */ function activateTsv( app: JupyterFrontEnd, translator: ITranslator, restorer: ILayoutRestorer | null, themeManager: IThemeManager | null, mainMenu: IMainMenu | null, searchregistry: ISearchProviderRegistry | null, settingRegistry: ISettingRegistry | null, toolbarRegistry: IToolbarWidgetRegistry | null ): void { let toolbarFactory: | ((widget: IDocumentWidget<CSVViewer>) => DocumentRegistry.IToolbarItem[]) | undefined; if (toolbarRegistry) { toolbarRegistry.registerFactory<IDocumentWidget<CSVViewer>>( FACTORY_TSV, 'delimiter', widget => new CSVDelimiter({ widget: widget.content, translator }) ); if (settingRegistry) { toolbarFactory = createToolbarFactory( toolbarRegistry, settingRegistry, FACTORY_TSV, tsv.id, translator ); } } const trans = translator.load('jupyterlab'); const factory = new TSVViewerFactory({ name: FACTORY_TSV, label: trans.__('TSV Viewer'), fileTypes: ['tsv'], defaultFor: ['tsv'], readOnly: true, toolbarFactory, translator }); const tracker = new WidgetTracker<IDocumentWidget<CSVViewer>>({ namespace: 'tsvviewer' }); // The current styles for the data grids. let style: DataGrid.Style = Private.LIGHT_STYLE; let rendererConfig: TextRenderConfig = Private.LIGHT_TEXT_CONFIG; if (restorer) { // Handle state restoration. void restorer.restore(tracker, { command: 'docmanager:open', args: widget => ({ path: widget.context.path, factory: FACTORY_TSV }), name: widget => widget.context.path }); } app.docRegistry.addWidgetFactory(factory); const ft = app.docRegistry.getFileType('tsv'); factory.widgetCreated.connect((sender, widget) => { // Track the widget. void tracker.add(widget); // Notify the widget tracker if restore data needs to update. widget.context.pathChanged.connect(() => { void tracker.save(widget); }); if (ft) { widget.title.icon = ft.icon!; widget.title.iconClass = ft.iconClass!; widget.title.iconLabel = ft.iconLabel!; } // Set the theme for the new widget. widget.content.style = style; widget.content.rendererConfig = rendererConfig; }); // Keep the themes up-to-date. const updateThemes = () => { const isLight = themeManager && themeManager.theme ? themeManager.isLight(themeManager.theme) : true; style = isLight ? Private.LIGHT_STYLE : Private.DARK_STYLE; rendererConfig = isLight ? Private.LIGHT_TEXT_CONFIG : Private.DARK_TEXT_CONFIG; tracker.forEach(grid => { grid.content.style = style; grid.content.rendererConfig = rendererConfig; }); }; if (themeManager) { themeManager.themeChanged.connect(updateThemes); } if (mainMenu) { addMenuEntries(mainMenu, tracker, translator); } if (searchregistry) { searchregistry.register('tsv', CSVSearchProvider); } } /** * Export the plugins as default. */ const plugins: JupyterFrontEndPlugin<any>[] = [csv, tsv]; export default plugins; /** * A namespace for private data. */ namespace Private { /** * The light theme for the data grid. */ export const LIGHT_STYLE: DataGrid.Style = { ...DataGrid.defaultStyle, voidColor: '#F3F3F3', backgroundColor: 'white', headerBackgroundColor: '#EEEEEE', gridLineColor: 'rgba(20, 20, 20, 0.15)', headerGridLineColor: 'rgba(20, 20, 20, 0.25)', rowBackgroundColor: i => (i % 2 === 0 ? '#F5F5F5' : 'white') }; /** * The dark theme for the data grid. */ export const DARK_STYLE: DataGrid.Style = { ...DataGrid.defaultStyle, voidColor: 'black', backgroundColor: '#111111', headerBackgroundColor: '#424242', gridLineColor: 'rgba(235, 235, 235, 0.15)', headerGridLineColor: 'rgba(235, 235, 235, 0.25)', rowBackgroundColor: i => (i % 2 === 0 ? '#212121' : '#111111') }; /** * The light config for the data grid renderer. */ export const LIGHT_TEXT_CONFIG: TextRenderConfig = { textColor: '#111111', matchBackgroundColor: '#FFFFE0', currentMatchBackgroundColor: '#FFFF00', horizontalAlignment: 'right' }; /** * The dark config for the data grid renderer. */ export const DARK_TEXT_CONFIG: TextRenderConfig = { textColor: '#F5F5F5', matchBackgroundColor: '#838423', currentMatchBackgroundColor: '#A3807A', horizontalAlignment: 'right' }; }
the_stack
import { Component, OnInit, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { ViewModel, TechniqueVM } from "../viewmodels.service"; import { ConfigService } from "../config.service"; import { Technique, DataService, Tactic, Matrix } from '../data.service'; import * as is from 'is_js'; declare var d3: any; //d3js declare var tinycolor: any; //use tinycolor2 import { ColorPickerModule } from 'ngx-color-picker'; @Component({ selector: 'exporter', templateUrl: './exporter.component.html', styleUrls: ['./exporter.component.scss'] }) export class ExporterComponent implements OnInit { public currentDropdown: string = null; viewModel: ViewModel; public config: any = {} public isIE() { return is.ie(); } private svgDivName = "svgInsert_tmp" unitEnum = 0; //counter for unit change ui element constructor(private dialogRef: MatDialogRef<ExporterComponent>, private configService: ConfigService, private dataService: DataService, @Inject(MAT_DIALOG_DATA) public data) { this.config = { "width": 11, "height": 8.5, "headerHeight": 1, "unit": "in", "showSubtechniques": "expanded", "font": 'sans-serif', "tableBorderColor": "#6B7279", "showHeader": true, "legendDocked": true, "legendX": 0, "legendY": 0, "legendWidth": 2, "legendHeight": 1, "showLegend": true, "showGradient": true, "showFilters": true, "showAbout": true, "showDomain": true, "showAggregate": false, } } ngOnInit() { this.viewModel = this.data.vm; this.svgDivName = "svgInsert" + this.viewModel.uid; let self = this; //determine if the layer has any scores for (let matrix of this.dataService.getDomain(this.viewModel.domainVersionID).matrices) { for (let tactic of this.viewModel.filterTactics(matrix.tactics, matrix)) { for (let technique of this.viewModel.filterTechniques(tactic.techniques, tactic, matrix)) { if (technique.subtechniques.length > 0) { for (let subtechnique of this.viewModel.filterTechniques(technique.subtechniques, tactic, matrix)) { if (self.viewModel.hasTechniqueVM(subtechnique, tactic)) { if (self.viewModel.getTechniqueVM(subtechnique, tactic).score != "") self.hasScores = true; } } } if (self.viewModel.hasTechniqueVM(technique, tactic)) { if (self.viewModel.getTechniqueVM(technique, tactic).score != "") self.hasScores = true; } } } } // dynamic legend height according to content; let legendSectionCount = 0; if (self.hasScores) legendSectionCount++; if (self.hasLegendItems()) legendSectionCount++; self.config.legendHeight = 0.5 * legendSectionCount; //initial legend position for undocked legend this.config.legendX = this.config.width - this.config.legendWidth - 0.1; this.config.legendY = this.config.height - this.config.legendHeight - 0.1; if (this.config.showHeader) this.config.legendY -= this.config.headerHeight; //put at the end of the function queue so that the page can render before building the svg window.setTimeout(function() {self.buildSVG(self)}, 0) } //visibility of SVG parts //assess data in viewModel hasName(): boolean {return this.viewModel.name.length > 0} hasDomain(): boolean {return this.viewModel.domainVersionID.length > 0} hasDescription(): boolean {return this.viewModel.description.length > 0} hasScores: boolean; //does the viewmodel have scores? built in ngAfterViewInit hasLegendItems(): boolean {return this.viewModel.legendItems.length > 0;} //above && user preferences showName(): boolean {return this.config.showAbout && this.hasName() && this.config.showHeader} showDomain(): boolean {return this.config.showDomain && this.hasDomain() && this.config.showHeader} showAggregate(): boolean {return this.viewModel.layout.showAggregateScores && this.config.showHeader} showDescription(): boolean {return this.config.showAbout && this.hasDescription() && this.config.showHeader} showLayerInfo(): boolean {return (this.showName() || this.showDescription()) && this.config.showHeader} showFilters(): boolean {return this.config.showFilters && this.config.showHeader}; showGradient(): boolean {return this.config.showGradient && this.hasScores && this.config.showHeader} showLegend(): boolean {return this.config.showLegend && this.hasLegendItems()} showLegendContainer(): boolean{return this.showLegend() || this.showGradient()} showLegendInHeader(): boolean {return this.config.legendDocked} // showItemCount(): boolean {return this.config.showTechniqueCount} buildSVGDebounce = false; buildSVG(self?, bypassDebounce=false): void { if (!self) self = this; //in case we were called from somewhere other than ngViewInit console.log("settings changed") if (self.buildSVGDebounce && !bypassDebounce) { // console.log("skipping debounce...") return; } if (!bypassDebounce) { // console.log("debouncing..."); self.buildSVGDebounce = true; window.setTimeout(function() {self.buildSVG(self, true)}, 500) return; } self.buildSVGDebounce = false; console.log("building SVG"); //check preconditions, make sure they're in the right range let margin = {top: 5, right: 5, bottom: 5, left: 5}; let width = Math.max(self.convertToPx(self.config.width, self.config.unit) - (margin.right + margin.left), 10); console.log("width", width); let height = Math.max(self.convertToPx(self.config.height, self.config.unit) - (margin.top + margin.bottom), 10); console.log("height", height) let headerHeight = Math.max(self.convertToPx(self.config.headerHeight, self.config.unit), 1); console.log("headerHeight", headerHeight); let legendX = Math.max(self.convertToPx(self.config.legendX, self.config.unit), 0); let legendY = Math.max(self.convertToPx(self.config.legendY, self.config.unit), 0); let legendWidth = Math.max(self.convertToPx(self.config.legendWidth, self.config.unit), 10); let legendHeight = Math.max(self.convertToPx(self.config.legendHeight, self.config.unit), 10); //remove previous graphic let element = <HTMLElement>document.getElementById(self.svgDivName); element.innerHTML = ""; let svg = d3.select("#" + self.svgDivName).append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .attr("xmlns", "http://www.w3.org/2000/svg") .attr("id", "svg" + self.viewModel.uid) //Tag for downloadSVG .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")") .style("font-family", self.config.font); let stroke_width = 1; // ooooo ooooo o888 // 888 888 ooooooooo8 888 ooooooooo ooooooooo8 oo oooooo oooooooo8 // 888ooo888 888oooooo8 888 888 888 888oooooo8 888 888 888ooooooo // 888 888 888 888 888 888 888 888 888 // o888o o888o 88oooo888 o888o 888ooo88 88oooo888 o888o 88oooooo88 // o888 // Essentially, the following functions brute force the optimal text arrangement for each cell // in the matrix to maximize text size. The algorithm tries different combinations of line breaks // in the cell text. /** * Divide distance into divisions equidistant anchor points S.T they all have equal * padding from each other and the beginning and end of the distance * @param distance distance to divide * @param divisions number of divisions * @return number[] where each number corresponds to a division-center offset */ function getSpacing(distance, divisions) { distance = distance - 1; //1px padding for border let spacing = distance/(divisions*2); let res = [] for (let i = 1; i <= divisions*2; i+=2) { res.push(1 + (spacing * i)) } return res }; /** * Magic function to insert line breaks. * @param {string[]} words array of words to space * @param {dom node} self the dom element with the text * @param {number} xpos x pos to place multiline text at * @param {number} ypos same but with y * @param {number} totalDistance total distance to contain broken text. * amt in excess of spacingDistance * becomes v padding. * @param {number} spacingDistance total distance to space text inside, * should be < totalDistance * @param {boolean} center if true, center the text in the node, else left-align * @param {number} cellWidth total width of the cell to put the text in */ function insertLineBreaks(words, node, padding, xpos, ypos, totalDistance, spacingDistance, center, cellWidth) { let el = d3.select(node) // el.attr("y", y + (totalDistance - spacingDistance) / 2); //clear previous content el.text(''); while(node.firstChild) node.removeChild(node.firstChild); let spacing = getSpacing(spacingDistance, words.length) for (var i = 0; i < words.length; i++) { var tspan = el.append('tspan').text(words[i]); if (center) tspan.attr("text-anchor","middle"); // if (i > 0) let offsetY = ((totalDistance - spacingDistance) / 2) + ypos + spacing[i] tspan .attr('x', center? xpos + (cellWidth/2) : xpos + padding) .attr('y', offsetY); } }; /** * Given an array of words, find the optimal font size for the array of words to be * broken onto 1 line each. * @param {string[]} words to be broken onto each line * @param {dom node} node the dom node of the cell * @param {cellWidth} number the width of the cell * @param {cellHeight} number the height of the cell * @param {boolean} center center the text? * @param {number} maxFontSize max font size, default is 12 * @return {number} the largest possible font size * not larger than 12 */ function findSpace(words: string[], node, cellWidth: number, cellHeight: number, center: boolean, maxFontSize=12) { let padding = 4; //the amount of padding on the left and right //break into multiple lines let breakDistance = Math.min(cellHeight, (maxFontSize + 3) * words.length) insertLineBreaks(words, node, padding, 0, 0, cellHeight, breakDistance, center, cellWidth) //find right size to fit the height of the cell let breakTextHeight = breakDistance / words.length; let fitTextHeight = Math.min(breakTextHeight, cellHeight) * 0.8; //0.8 //find right size to fit the width of the cell // let longestWord = words.sort(function(a,b) {return b.length - a.length})[0] let longestWordLength = -Infinity; for (let w = 0; w < words.length; w++) { let word = words[w]; longestWordLength = Math.max(longestWordLength, word.length) } let fitTextWidth = ((cellWidth - (2 * padding)) / longestWordLength) * 1.45; //the min fitting text size not larger than MaxFontSize let size = Math.min(maxFontSize, fitTextHeight, fitTextWidth); // if (size < 5) return "0px"; //enable for min text size return size; } /** * Given text, a dom node, and sizing parameters, * try all combinations of word breaks to maximize font size inside of the given space * returns font size in pixels * @param {string} text the text to render in the cell * @param {dom node} node the node for the cell * @param {number} cellWidth width of the cell to get the font size for * @param {number} cellHeight height of the cell to get the font size for * @param {boolean} center center the text? * @param {number} maxFontSize max font size, default is 12 * @return {string} the size in pixels */ function optimalFontSize(text: string, node, cellWidth: number, cellHeight: number, center: boolean, maxFontSize=12): number { let words = text.split(" "); let bestSize = -Infinity; //beat this size let bestWordArrangement = []; /** * determine placement of line breaks to try. Shorter lists of words can try more positions * @param {number} num_spaces the number of spaces in the words, aka words.length - 1 * @param {number} [num_breaks=3] the number of breaks to insert * @returns str[] where each index is a combination of breaks represented as [01]+ where 1 is a break and 0 is a space */ function find_breaks(num_spaces:number, num_breaks=3) { let breaks = new Set<string>(); function recurse(breakset_inherit, depth, num_breaks) { for (let i = 0; i < breakset_inherit.length; i++) { let breakset = JSON.parse(JSON.stringify(breakset_inherit)); //deep copy breakset[i] = 1; // insert break at this location breaks.add(breakset.join("")); //save this combination if (depth < num_breaks - 1) recurse(breakset, depth + 1, num_breaks); } } let initial_breaks = [] while (initial_breaks.length < num_spaces) initial_breaks.push(0); //fill with 0s breaks.add(initial_breaks.join("")); //save this combination recurse(initial_breaks, 0, num_breaks) return breaks } let num_spaces = words.length; // longer strings can't try as many combinations without the page lagging let num_breaks = 1; if (num_spaces < 20) num_breaks = 3; else if (num_spaces < 50) num_breaks = 2; else num_breaks = 1; let breaks = Array.from(find_breaks(num_spaces, num_breaks)) for (let binaryString of breaks) { // find the best option of the proposed placements generated by find_breaks //binaryString: binary representation of newline locations, e.g 001011 //where 1 is newline and 0 is no newline let wordSet = []; //build this array for (let k = 0; k < binaryString.length; k++) { if (binaryString[k] === "0") {//join with space if (wordSet.length == 0) wordSet.push(words[k]); else wordSet[wordSet.length - 1] = wordSet[wordSet.length - 1] + " " + words[k]; //append to previous word in array } else { //linebreak wordSet.push(words[k]) //new word in array } } let size = findSpace(wordSet, node, cellWidth, cellHeight, center, maxFontSize); if (size > bestSize) { //found new optimum bestSize = size; bestWordArrangement = wordSet; } if (size == maxFontSize) break; //if largest text found, no need to search more } findSpace(bestWordArrangement, node, cellWidth, cellHeight, center, maxFontSize); return bestSize; } // add properties to the node to set the vertical alignment to center without using // dominant-baseline, which isn't widely supported function centerValign(node, fontSize=null) { if (node.children && node.children.length > 0) { for (let child of node.children) centerValign(child, node.getAttribute("font-size")); } else { // base case // transform by half the font size - 1/2px for proper centering fontSize = fontSize ? fontSize : node.getAttribute("font-size"); if (fontSize.endsWith("px")) fontSize = Number(fontSize.split("px")[0]) let currY = node.hasAttribute("y") ? Number(node.getAttribute("y")) : 0; let newY = currY + Math.floor((fontSize * 0.3)) d3.select(node).attr("y", newY); } } class HeaderSectionContent { label: string; // either string to display in box, or a callback to create complex content in the box // callback function option takes params node, width, height, and appends data to node data: string | Function; } class HeaderSection { title: string; contents: HeaderSectionContent[]; } let legend = {"title": "legend", "contents": []}; if (self.hasScores && self.showGradient()) legend.contents.push({ "label": "gradient", "data": function(group, sectionWidth, sectionHeight) { let domain = []; for (let i = 0; i < self.viewModel.gradient.colors.length; i++) { let percent = i / (self.viewModel.gradient.colors.length - 1); domain.push(d3.interpolateNumber(self.viewModel.gradient.minValue, self.viewModel.gradient.maxValue)(percent)) } let colorScale = d3.scaleLinear() .domain(domain) .range(self.viewModel.gradient.colors.map(function (color) { return color.color; })) let nCells = domain.length * 2; let valuesRange = self.viewModel.gradient.maxValue - self.viewModel.gradient.minValue; group.append("g") .attr("transform", "translate(0, 5)") .call(d3.legendColor() .shapeWidth((sectionWidth / nCells)) .shapePadding(0) .cells(nCells) .shape("rect") .orient("horizontal") .scale(colorScale) .labelOffset(2) .labelFormat(d3.format("0.02r")) // .labelFormat( valuesRange < nCells ? d3.format("0.01f") : d3.format(".2")) ) } }); if (self.showLegend()) legend.contents.push({ "label": "legend", "data": function(group, sectionWidth, sectionHeight) { let colorScale = d3.scaleOrdinal() .domain(self.viewModel.legendItems.map(function(item) { return item.label; })) .range(self.viewModel.legendItems.map(function(item) { return item.color; })) group.append("g") .attr("transform", "translate(0, 5)") .call(d3.legendColor() .shapeWidth((sectionWidth / self.viewModel.legendItems.length)) .shapePadding(0) .shape("rect") .orient("horizontal") .scale(colorScale) .labelOffset(2) ) } }) function descriptiveBox(group, sectionData: HeaderSection, boxWidth: number, boxHeight: number) { let boxPadding = 5; let boxGroup = group.append("g") .attr("transform", `translate(0,${boxPadding})`); // adjust height for padding boxHeight -= 2 * boxPadding; let outerbox = boxGroup.append("rect") .attr("class", "header-box") .attr("width", boxWidth) .attr("height", boxHeight) .attr("stroke", "black") .attr("fill", "white") .attr("rx", boxPadding); //rounded corner let titleEl = boxGroup.append("text") .attr("class", "header-box-label") .text(sectionData.title) .attr("x", 2 * boxPadding) .attr("font-size", 12) .each(function() { centerValign(this); }) // .attr("dominant-baseline", "middle") // add cover mask so that the box lines crop around the text let bbox = titleEl.node().getBBox(); let coverPadding = 2; let cover = boxGroup.append("rect") .attr("class", "label-cover") .attr("x", bbox.x - coverPadding) .attr("y", bbox.y - coverPadding) .attr("width", bbox.width + 2*coverPadding) .attr("height", bbox.height + 2*coverPadding) .attr("fill", "white") .attr("rx", boxPadding); //rounded corner just in case it's being shown on a transparent background titleEl.raise(); //push title to front; // add content to box let boxContentGroup = boxGroup.append("g") .attr("class", "header-box-content") .attr("transform", `translate(${boxPadding}, 0)`) let boxContentHeight = boxHeight;// - 2*boxPadding; let boxContentWidth = boxWidth - 2*boxPadding; let boxGroupY = d3.scaleBand() .padding(0.05) .align(0.5) .domain(sectionData.contents.map(function(content) { return content.label })) .range([0, boxContentHeight]); for (let i = 0; i < sectionData.contents.length; i++) { let subsectionContent = sectionData.contents[i]; let contentGroup = boxContentGroup.append("g") .attr("transform", `translate(0, ${boxGroupY( subsectionContent.label )})`); if (typeof(subsectionContent.data) == "string") { // add text to contentGroup contentGroup.append("text") .text(subsectionContent) .attr("font-size", function() { return optimalFontSize(subsectionContent.data as string, this, boxContentWidth, boxGroupY.bandwidth(), false, 32) }) .each(function() { centerValign(this); }) // .attr("dominant-baseline", "middle") } else { //call callback to add complex data to contentGroup (subsectionContent.data as Function)(contentGroup, boxContentWidth, boxGroupY.bandwidth()); } if (i != sectionData.contents.length - 1) contentGroup.append("line") //dividing line .attr("x1", 0) .attr("x2", boxContentWidth) .attr("y1", boxGroupY.bandwidth()) .attr("y2", boxGroupY.bandwidth()) .attr("stroke", "#dddddd"); } } // ooooo ooooo oooo // 888 888 ooooooooo8 ooooooo ooooo888 ooooooooo8 oo oooooo // 888ooo888 888oooooo8 ooooo888 888 888 888oooooo8 888 888 // 888 888 888 888 888 888 888 888 888 // o888o o888o 88oooo888 88ooo88 8o 88ooo888o 88oooo888 o888o if (self.config.showHeader) { let headerSections: HeaderSection[] = [] if (self.showName() || self.showDescription()) { let about = {"title": "about", "contents": []}; if (self.showName()) about.contents.push({"label": "name", "data": this.viewModel.name}); if (self.showDescription()) about.contents.push({"label": "description", "data": this.viewModel.description}); headerSections.push(about) } const config = {"title": "domain", "contents": []}; let filterConfig = {"title": "platforms", "contents": []}; if (self.showDomain()) { let domain = this.dataService.getDomain(this.viewModel.domainVersionID); config.contents.push({"label": "domain", "data": domain.name + " " + domain.version}); } if (self.showFilters()) { const filterData = {"label": "platforms", "data": this.viewModel.filters.platforms.selection.join(", ")}; if (self.showAggregate()) { config.title = "domain & platforms"; config.contents.push(filterData); } else filterConfig.contents.push(filterData); } if (config.contents.length > 0) headerSections.push(config); if (filterConfig.contents.length > 0) headerSections.push(filterConfig); if (self.showAggregate()) { const aggregateConfig = { "title": "aggregate", "contents": []}; aggregateConfig.contents.push({"label": "function", "data": "showing aggregate scores using the " + this.viewModel.layout.aggregateFunction + " aggregate function"}); if (this.viewModel.layout.countUnscored) aggregateConfig.contents.push({"label": "unscored", "data": "includes unscored techniques as having a score of 0"}); headerSections.push(aggregateConfig); } if (self.showLegendContainer() && self.showLegendInHeader()) headerSections.push(legend); let headerGroup = svg.append("g"); let headerX = d3.scaleBand() .paddingInner(0.05) // .align(0.5) .domain(headerSections.map(function(section: HeaderSection) { return section.title })) .range([0, width]); for (let section of headerSections) { let sectionGroup = headerGroup.append("g"); if (headerSections.length > 1) sectionGroup.attr("transform", `translate(${headerX(section.title)}, 0)`); descriptiveBox(sectionGroup, section, headerSections.length == 1? width : headerX.bandwidth(), headerHeight); } if (headerSections.length == 0) headerHeight = 0; //no header sections to show } else { //no header headerHeight = 0 } // oooo oooo o8 o88 // 8888o 888 ooooooo o888oo oo oooooo oooo oooo oooo // 88 888o8 88 ooooo888 888 888 888 888 888o888 // 88 888 88 888 888 888 888 888 o88 88o // o88o 8 o88o 88ooo88 8o 888o o888o o888o o88o o88o let tablebody = svg.append("g") .attr("transform", "translate(0," + (headerHeight + 1) + ")") // build data model let matrices: RenderableMatrix[] = this.dataService.getDomain(this.viewModel.domainVersionID).matrices.map(function(matrix: Matrix) { return new RenderableMatrix(matrix, self.viewModel, self.config); }); let tactics: RenderableTactic[] = []; //flattened list of tactics for (let matrix of matrices) { tactics = tactics.concat(matrix.tactics); } let x = d3.scaleBand() .paddingInner(0.1) .align(0.01) .domain(tactics.map(function(tactic: RenderableTactic) { return tactic.tactic.id; })) .range([0, width]) let y = d3.scaleLinear() .domain([d3.max(tactics, function(tactic: RenderableTactic) { return tactic.height}), 0]) .range([height - (headerHeight), 0]) // let subtechniqueIndent = (1/3) * x.bandwidth(); //2/3 of full techinque width // let subtechniqueIndent = 2 * y(1); //2*the height of a cell, to make room for y(1) width sidebar let subtechniqueIndent = Math.min(2 * y(1), 15); //add tactic row backgroun if (self.viewModel.showTacticRowBackground) { tablebody.append("rect") .attr("class", "tactic-header-background") .attr("width", width) .attr("height", y(1)) .attr("fill", self.viewModel.tacticRowBackground) .attr("stroke", self.config.tableBorderColor) } let tacticGroups = tablebody.append("g").selectAll("g") .data(tactics) .enter().append("g") .attr("class", function(tactic: RenderableTactic) { return "tactic " + tactic.tactic.shortname; }) .attr("transform", function(tactic: RenderableTactic) { return `translate(${x(tactic.tactic.id)}, 0)`; }) // add technique and subtechnique groups let techniqueGroups = tacticGroups.append("g") .attr("class", "techniques").selectAll("g") .data(function(tactic: RenderableTactic) { return tactic.techniques}) .enter().append("g") .attr("class", function(technique: RenderableTechnique) { return "technique " + technique.technique.attackID; }) .attr("transform", function(technique: RenderableTechnique) { return `translate(0, ${y(technique.yPosition)})` }); let subtechniqueGroups = tacticGroups.append("g") .attr("class", "subtechniques").selectAll("g") .data(function(tactic: RenderableTactic) { return tactic.subtechniques}) .enter().append("g") .attr("class", function(subtechnique: RenderableTechnique) { return "subtechnique " + subtechnique.technique.attackID; }) .attr("transform", function(subtechnique: RenderableTechnique) { return `translate(${subtechniqueIndent}, ${y(subtechnique.yPosition)})` }); // add cells to techniques and subtechniques let techniqueRects = techniqueGroups.append("rect") .attr("class", "cell") .attr("height", y(1)) .attr("width", x.bandwidth()) .attr("fill", function(technique: RenderableTechnique) { return technique.fill }) .attr("stroke", self.config.tableBorderColor); let subtechniqueRects = subtechniqueGroups.append("rect") .attr("class", "cell") .attr("height", y(1)) .attr("width", x.bandwidth() - subtechniqueIndent) .attr("fill", function(subtechnique: RenderableTechnique) { return subtechnique.fill }) .attr("stroke", self.config.tableBorderColor); // add sidebar // let sidebarWidth = y(1); let sidebarWidth = 3; let sidebar = subtechniqueGroups.append("rect") .attr("class", "cell") .attr("height", y(1)) .attr("width", sidebarWidth) .attr("transform", `translate(${-sidebarWidth}, 0)`) .attr("fill", self.config.tableBorderColor) .attr("stroke", self.config.tableBorderColor); let sidebarAngle = techniqueGroups.append("polygon") .attr("class", "sidebar") .attr("transform", `translate(0, ${y(1)})`) .attr("points", function(technique: RenderableTechnique) { return [ "0,0", `${subtechniqueIndent - sidebarWidth},0`, `${subtechniqueIndent - sidebarWidth},${Math.min(subtechniqueIndent - sidebarWidth, y(self.viewModel.filterTechniques(technique.technique.subtechniques, technique.tactic, technique.matrix).length))}` ].join(" "); }) .attr("fill", self.config.tableBorderColor) .attr("visibility", function(technique: RenderableTechnique) { return technique.technique.subtechniques.length > 0 && technique.showSubtechniques ? "visible" : "hidden"}); // oooooooo8 o888 o888 ooooooooooo o8 // o888 88 ooooooooo8 888 888 88 888 88 ooooooooo8 oooo oooo o888oo // 888 888oooooo8 888 888 888 888oooooo8 888o888 888 // 888o oo 888 888 888 888 888 o88 88o 888 // 888oooo88 88oooo888 o888o o888o o888o 88oooo888 o88o o88o 888o techniqueGroups.append("text") .text(function(technique: RenderableTechnique) { return technique.text; }) .attr("font-size", function(technique: RenderableTechnique) { return optimalFontSize(technique.text, this, x.bandwidth(), y(1), false); }) // .attr("dominant-baseline", "middle") .each(function() { centerValign(this); }) .attr("fill", function(technique: RenderableTechnique) { return technique.textColor; }) subtechniqueGroups.append("text") .text(function(subtechnique: RenderableTechnique) { return subtechnique.text; }) .attr("font-size", function(subtechnique: RenderableTechnique) { return optimalFontSize(subtechnique.text, this, x.bandwidth() - subtechniqueIndent, y(1), false); }) // .attr("dominant-baseline", "middle") .attr("fill", function(subtechnique: RenderableTechnique) { return subtechnique.textColor; }) .each(function() { centerValign(this); }) let tacticLabels = tacticGroups.append("g") .attr("class", "tactic-label"); tacticLabels.append("text") .text(function(tactic: RenderableTactic) { return tactic.tactic.name; }) .attr("font-size", function(tactic: RenderableTactic) { return optimalFontSize(tactic.tactic.name, this, x.bandwidth(), y(1), true); }) // .attr("dominant-baseline", "middle") .attr("fill", function(tactic: RenderableTactic) { if (self.viewModel.showTacticRowBackground) return tinycolor.mostReadable(self.viewModel.tacticRowBackground, ["white", "black"]); else return "black"; }) .attr("font-weight", "bold") .each(function() { centerValign(this); }) //ooooo oooo oooo oooo oooo ooooo oooo // 888 88 oo oooooo ooooo888 ooooooo ooooooo 888 ooooo ooooooooo8 ooooo888 888 ooooooooo8 oooooooo8 ooooooooo8 oo oooooo ooooo888 // 888 88 888 888 888 888 888 888 888 888 888o888 888oooooo8 888 888 888 888oooooo8 888 88o 888oooooo8 888 888 888 888 // 888 88 888 888 888 888 888 888 888 8888 88o 888 888 888 888 o 888 888oo888o 888 888 888 888 888 // 888oo88 o888o o888o 88ooo888o 88ooo88 88ooo888 o888o o888o 88oooo888 88ooo888o o888ooooo88 88oooo888 888 888 88oooo888 o888o o888o 88ooo888o // 888ooo888 if (self.showLegendContainer() && !self.showLegendInHeader()) { let legendGroup = tablebody.append("g") .attr("transform", `translate(${legendX}, ${legendY})`) descriptiveBox(legendGroup, legend, legendWidth, legendHeight); } } downloadSVG() { let svgEl = document.getElementById("svg" + this.viewModel.uid); svgEl.setAttribute("xmlns", "http://www.w3.org/2000/svg"); let svgData = new XMLSerializer().serializeToString(svgEl); // // var svgData = svgEl.outerHTML; // console.log(svgData) // let svgData2 = new XMLSerializer().serializeToString(svgEl); // console.log(svgData2) let filename = this.viewModel.name.split(' ').join('_'); filename = filename.replace(/\W/g, "") + ".svg"; // remove all non alphanumeric characters var preface = '<?xml version="1.0" standalone="no"?>\r\n'; var svgBlob = new Blob([preface, svgData], {type:"image/svg+xml;charset=utf-8"}); if (is.ie()) { //internet explorer window.navigator.msSaveBlob(svgBlob, filename) } else { var svgUrl = URL.createObjectURL(svgBlob); var downloadLink = document.createElement("a"); downloadLink.href = svgUrl; downloadLink.download = filename document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } } /** * Convert any length in various units to pixels * @param quantity what length * @param unit which unit system (in, cm, px?) * @return that length in pixels */ convertToPx(quantity: number, unit: string): number { let factor; switch(unit) { case "in": { factor = 96 break } case "cm": { factor = 3.779375 * 10; break; } case "px": { factor = 1; break; } case "em": { factor = 16; break; } case "pt": { factor = 1.33; } default: { console.error("unknown unit", unit) factor = 0; } } return quantity * factor; } // wrap(text, width, padding) { // var self = d3.select(this), // textLength = self.node().getComputedTextLength(), // text = self.text(); // while (textLength > (width - 2 * padding) && text.length > 0) { // text = text.slice(0, -1); // self.text(text + '...'); // textLength = self.node().getComputedTextLength(); // } // } /** * wrap the given text svg element * @param text element to wrap * @param width width to wrap to * @param cellheight stop appending wraps after this height * @param self reference to self this component because of call context */ wrap(text, width, cellheight, self): void { text.each(function() { var text = d3.select(this), words = text.text().split(/\s+/).reverse(), word, line = [], lineHeight = 1.1, // ems y = text.attr("y"), dy = parseFloat(text.attr("dy")), tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em"); while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); if (tspan.node().getComputedTextLength() > width) { line.pop(); tspan.text(line.join(" ")); line = [word]; let thisdy = lineHeight + dy // if (self.convertToPx(thisdy, "em") > cellheight) return; tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", thisdy + "em").text(word); } } }); } /** * Recenter the selected element's tspan elements * @param height [description] * @param self [description] */ recenter(text, height, self): void { text.each(function() { text.selectAll('tspan').each(function(d, i, els) { let numTSpan = els.length; let location = self.getSpacing(height, numTSpan)[i] let tspan = d3.select(this) .attr("y", ( location)) .attr("dy", "0") }) }) } // Capitalizes the first letter of each word in a string toCamelCase(str){ return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); } //following two functions are only used for iterating over tableconfig options: remove when tableconfig options are hardcoded in html getKeys(obj) { return Object.keys(obj) } type(obj) { return typeof(obj) } /** * Return whether the given dropdown element would overflow the side of the page if aligned to the right of its anchor * @param dropdown the DOM node of the panel * @return true if it would overflow */ checkalign(dropdown): boolean { // console.log(anchor) let anchor = dropdown.parentNode; return anchor.getBoundingClientRect().left + dropdown.getBoundingClientRect().width > document.body.clientWidth; } /** * Divide distance into divisions equidestant anchor points S.T they all have equal * padding from each other and the beginning and end of the distance * @param distance distance to divide * @param divisions number of divisions * @return number[] where each number corresponds to a division-center offset */ getSpacing(distance: number, divisions: number): number[] { distance = distance - 1; //1px padding for border let spacing = distance/(divisions*2); let res = [] for (let i = 1; i <= divisions*2; i+=2) { res.push(1 + (spacing * i)) } return res } } class RenderableMatrix { public readonly matrix: Matrix; public readonly tactics: RenderableTactic[] = []; public get height() { let heights = this.tactics.map(function(tactic: RenderableTactic) { return tactic.height; }) return Math.max(...heights); } constructor(matrix: Matrix, viewModel: ViewModel, renderConfig: any) { this.matrix = matrix; let filteredTactics = viewModel.filterTactics(matrix.tactics, matrix); for (let tactic of filteredTactics) { this.tactics.push(new RenderableTactic(tactic, matrix, viewModel, renderConfig)); } } } class RenderableTactic { public readonly tactic: Tactic; public readonly techniques: RenderableTechnique[] = []; public readonly subtechniques: RenderableTechnique[] = []; public readonly height: number; constructor(tactic: Tactic, matrix: Matrix, viewModel: ViewModel, renderConfig: any) { this.tactic = tactic; let filteredTechniques = viewModel.sortTechniques(viewModel.filterTechniques(tactic.techniques, tactic, matrix), tactic); let yPosition = 1; //start at 1 to make space for tactic label for (let technique of filteredTechniques) { let techniqueVM = viewModel.getTechniqueVM(technique, tactic); let filteredSubtechniques = viewModel.filterTechniques(technique.subtechniques, tactic, matrix); let showSubtechniques = renderConfig.showSubtechniques == "all" || (renderConfig.showSubtechniques == "expanded" && techniqueVM.showSubtechniques) this.techniques.push(new RenderableTechnique(yPosition++, technique, tactic, matrix, viewModel, showSubtechniques)); if (filteredSubtechniques.length > 0 && showSubtechniques) { for (let subtechnique of filteredSubtechniques) { this.subtechniques.push(new RenderableTechnique(yPosition++, subtechnique, tactic, matrix, viewModel, renderConfig)); } } } this.height = yPosition; } } class RenderableTechnique { public readonly yPosition: number; public readonly technique: Technique; public readonly tactic: Tactic; public readonly matrix: Matrix; public readonly showSubtechniques; private readonly viewModel: ViewModel; constructor(yPosition, technique: Technique, tactic: Tactic, matrix: Matrix, viewModel: ViewModel, showSubtechniques=false) { this.yPosition = yPosition; this.technique = technique; this.tactic = tactic; this.matrix = matrix; this.viewModel = viewModel; this.showSubtechniques = showSubtechniques; } public get fill() { if (this.viewModel.hasTechniqueVM(this.technique, this.tactic)) { let techniqueVM: TechniqueVM = this.viewModel.getTechniqueVM(this.technique, this.tactic); if (!techniqueVM.enabled) return "white"; if (techniqueVM.color) return techniqueVM.color; if (this.viewModel.layout.showAggregateScores && techniqueVM.aggregateScoreColor) return techniqueVM.aggregateScoreColor; if (techniqueVM.score) return techniqueVM.scoreColor; } return "white"; //default } public get textColor() { if (this.viewModel.hasTechniqueVM(this.technique, this.tactic)) { let techniqueVM: TechniqueVM = this.viewModel.getTechniqueVM(this.technique, this.tactic); if (!techniqueVM.enabled) return "#aaaaaa"; } return tinycolor.mostReadable(this.fill, ["white", "black"]); //default; } public get text() { let text = []; if (this.viewModel.layout.showID) text.push(this.technique.attackID); if (this.viewModel.layout.showName) text.push(this.technique.name); return text.join(": ") } }
the_stack
import { GraphQLSchema, isSpecifiedDirective, isIntrospectionType, isSpecifiedScalarType, GraphQLNamedType, GraphQLDirective, isScalarType, isObjectType, isInterfaceType, isUnionType, isEnumType, isInputObjectType, GraphQLScalarType, GraphQLObjectType, GraphQLInterfaceType, GraphQLUnionType, GraphQLEnumType, GraphQLInputObjectType, GraphQLArgument, GraphQLInputField, astFromValue, print, GraphQLField, DEFAULT_DEPRECATION_REASON, } from 'graphql'; import { isFederationType, Maybe } from './types'; import { gatherDirectives, federationDirectives, otherKnownDirectives, isFederationDirective, } from './directives'; export function printSubgraphSchema(schema: GraphQLSchema): string { return printFilteredSchema( schema, // Apollo change: treat the directives defined by the federation spec // similarly to the directives defined by the GraphQL spec (ie, don't print // their definitions). (n) => !isSpecifiedDirective(n) && !isFederationDirective(n), isDefinedType, ); } export function printIntrospectionSchema(schema: GraphQLSchema): string { return printFilteredSchema(schema, isSpecifiedDirective, isIntrospectionType); } // Apollo change: treat the types defined by the federation spec // similarly to the directives defined by the GraphQL spec (ie, don't print // their definitions). function isDefinedType(type: GraphQLNamedType): boolean { return ( !isSpecifiedScalarType(type) && !isIntrospectionType(type) && !isFederationType(type) ); } function printFilteredSchema( schema: GraphQLSchema, directiveFilter: (type: GraphQLDirective) => boolean, typeFilter: (type: GraphQLNamedType) => boolean, ): string { const directives = schema.getDirectives().filter(directiveFilter); const types = Object.values(schema.getTypeMap()).filter(typeFilter); return ( [ printSchemaDefinition(schema), ...directives.map((directive) => printDirective(directive)), ...types.map((type) => printType(type)), ] .filter(Boolean) .join('\n\n') + '\n' ); } function printSchemaDefinition(schema: GraphQLSchema): string | undefined { if (isSchemaOfCommonNames(schema)) { return; } const operationTypes = []; const queryType = schema.getQueryType(); if (queryType) { operationTypes.push(` query: ${queryType.name}`); } const mutationType = schema.getMutationType(); if (mutationType) { operationTypes.push(` mutation: ${mutationType.name}`); } const subscriptionType = schema.getSubscriptionType(); if (subscriptionType) { operationTypes.push(` subscription: ${subscriptionType.name}`); } return printDescription(schema) + `schema {\n${operationTypes.join('\n')}\n}`; } /** * GraphQL schema define root types for each type of operation. These types are * the same as any other type and can be named in any manner, however there is * a common naming convention: * * schema { * query: Query * mutation: Mutation * } * * When using this naming convention, the schema description can be omitted. */ function isSchemaOfCommonNames(schema: GraphQLSchema): boolean { const queryType = schema.getQueryType(); if (queryType && queryType.name !== 'Query') { return false; } const mutationType = schema.getMutationType(); if (mutationType && mutationType.name !== 'Mutation') { return false; } const subscriptionType = schema.getSubscriptionType(); if (subscriptionType && subscriptionType.name !== 'Subscription') { return false; } return true; } export function printType(type: GraphQLNamedType): string { if (isScalarType(type)) { return printScalar(type); } if (isObjectType(type)) { return printObject(type); } if (isInterfaceType(type)) { return printInterface(type); } if (isUnionType(type)) { return printUnion(type); } if (isEnumType(type)) { return printEnum(type); } if (isInputObjectType(type)) { return printInputObject(type); } // graphql-js uses an internal fn `inspect` but this is a `never` case anyhow throw Error('Unexpected type: ' + (type as GraphQLNamedType).toString()); } function printScalar(type: GraphQLScalarType): string { return ( printDescription(type) + `scalar ${type.name}` + printSpecifiedByURL(type) ); } function printImplementedInterfaces( type: GraphQLObjectType | GraphQLInterfaceType, ): string { const interfaces = type.getInterfaces(); return interfaces.length ? ' implements ' + interfaces.map((i) => i.name).join(' & ') : ''; } function printObject(type: GraphQLObjectType): string { // Apollo change: print `extend` keyword on type extensions. // // The implementation assumes that an owned type will have fields defined // since that is required for a valid schema. Types that are *only* // extensions will not have fields on the astNode since that ast doesn't // exist. // // XXX revist extension checking const isExtension = type.extensionASTNodes && type.astNode && !type.astNode.fields; return ( printDescription(type) + // Apollo addition: print `extend` keyword on type extensions (isExtension ? 'extend ' : '') + `type ${type.name}` + printImplementedInterfaces(type) + // Apollo addition: print @key usages printFederationDirectives(type) + // Apollo addition: print @tag usages (or other known directives) printKnownDirectiveUsagesOnTypeOrField(type) + printFields(type) ); } function printInterface(type: GraphQLInterfaceType): string { // Apollo change: print `extend` keyword on type extensions. // See printObject for assumptions made. // // XXX revist extension checking const isExtension = type.extensionASTNodes && type.astNode && !type.astNode.fields; return ( printDescription(type) + // Apollo change: print `extend` keyword on interface extensions (isExtension ? 'extend ' : '') + `interface ${type.name}` + printImplementedInterfaces(type) + printFederationDirectives(type) + printKnownDirectiveUsagesOnTypeOrField(type) + printFields(type) ); } function printUnion(type: GraphQLUnionType): string { const types = type.getTypes(); const possibleTypes = types.length ? ' = ' + types.join(' | ') : ''; return ( printDescription(type) + 'union ' + type.name + // Apollo addition: print @tag usages printKnownDirectiveUsagesOnTypeOrField(type) + possibleTypes ); } function printEnum(type: GraphQLEnumType): string { const values = type .getValues() .map( (value, i) => printDescription(value, ' ', !i) + ' ' + value.name + printDeprecated(value.deprecationReason), ); return printDescription(type) + `enum ${type.name}` + printBlock(values); } function printInputObject(type: GraphQLInputObjectType): string { const fields = Object.values(type.getFields()).map( (f, i) => printDescription(f, ' ', !i) + ' ' + printInputValue(f), ); return printDescription(type) + `input ${type.name}` + printBlock(fields); } function printFields(type: GraphQLObjectType | GraphQLInterfaceType) { const fields = Object.values(type.getFields()).map( (f, i) => printDescription(f, ' ', !i) + ' ' + f.name + printArgs(f.args, ' ') + ': ' + String(f.type) + printDeprecated(f.deprecationReason) + // Apollo addition: print Apollo directives on fields printFederationDirectives(f) + printKnownDirectiveUsagesOnTypeOrField(f), ); return printBlock(fields); } // Apollo change: *do* print the usages of federation directives. function printFederationDirectives( typeOrField: GraphQLNamedType | GraphQLField<any, any>, ): string { if (!typeOrField.astNode) return ''; if (isInputObjectType(typeOrField)) return ''; const federationDirectivesOnTypeOrField = gatherDirectives(typeOrField) .filter((n) => federationDirectives.some((fedDir) => fedDir.name === n.name.value), ) .map(print); const dedupedDirectives = [...new Set(federationDirectivesOnTypeOrField)]; return dedupedDirectives.length > 0 ? ' ' + dedupedDirectives.join(' ') : ''; } // Apollo addition: print `@tag` directive usages (and possibly other future known // directive usages) found in subgraph SDL. function printKnownDirectiveUsagesOnTypeOrField( typeOrField: GraphQLNamedType | GraphQLField<any, any>, ): string { if (!typeOrField.astNode) return ''; if (isInputObjectType(typeOrField)) return ''; const knownSubgraphDirectivesOnTypeOrField = gatherDirectives(typeOrField) .filter((n) => otherKnownDirectives.some((directive) => directive.name === n.name.value), ) .map(print); return knownSubgraphDirectivesOnTypeOrField.length > 0 ? ' ' + knownSubgraphDirectivesOnTypeOrField.join(' ') : ''; } function printBlock(items: string[]) { return items.length !== 0 ? ' {\n' + items.join('\n') + '\n}' : ''; } function printArgs(args: GraphQLArgument[], indentation = '') { if (args.length === 0) { return ''; } // If every arg does not have a description, print them on one line. if (args.every((arg) => !arg.description)) { return '(' + args.map(printInputValue).join(', ') + ')'; } return ( '(\n' + args .map( (arg, i) => printDescription(arg, ' ' + indentation, !i) + ' ' + indentation + printInputValue(arg), ) .join('\n') + '\n' + indentation + ')' ); } function printInputValue(arg: GraphQLInputField) { const defaultAST = astFromValue(arg.defaultValue, arg.type); let argDecl = arg.name + ': ' + String(arg.type); if (defaultAST) { argDecl += ` = ${print(defaultAST)}`; } return argDecl + printDeprecated(arg.deprecationReason); } function printDirective(directive: GraphQLDirective) { return ( printDescription(directive) + 'directive @' + directive.name + printArgs(directive.args) + (directive.isRepeatable ? ' repeatable' : '') + ' on ' + directive.locations.join(' | ') ); } function printDeprecated(reason: Maybe<string>): string { if (reason == null) { return ''; } if (reason !== DEFAULT_DEPRECATION_REASON) { const astValue = print({ kind: 'StringValue', value: reason }); return ` @deprecated(reason: ${astValue})`; } return ' @deprecated'; } // Apollo addition: support both specifiedByUrl and specifiedByURL - these // happen across v15 and v16. function printSpecifiedByURL(scalar: GraphQLScalarType): string { if ( scalar.specifiedByUrl == null && // eslint-disable-next-line // @ts-ignore (accomodate breaking change across 15.x -> 16.x) scalar.specifiedByURL == null ) { return ''; } const astValue = print({ kind: 'StringValue', value: scalar.specifiedByUrl ?? // eslint-disable-next-line // @ts-ignore (accomodate breaking change across 15.x -> 16.x) scalar.specifiedByURL, }); return ` @specifiedBy(url: ${astValue})`; } function printDescription( def: { readonly description?: Maybe<string> }, indentation = '', firstInBlock = true, ): string { const { description } = def; if (description == null) { return ''; } const preferMultipleLines = description.length > 70; const blockString = printBlockString(description, preferMultipleLines); const prefix = indentation && !firstInBlock ? '\n' + indentation : indentation; return prefix + blockString.replace(/\n/g, '\n' + indentation) + '\n'; } /** * Print a block string in the indented block form by adding a leading and * trailing blank line. However, if a block string starts with whitespace and is * a single-line, adding a leading blank line would strip that whitespace. */ export function printBlockString( value: string, preferMultipleLines: boolean = false, ): string { const isSingleLine = !value.includes('\n'); const hasLeadingSpace = value[0] === ' ' || value[0] === '\t'; const hasTrailingQuote = value[value.length - 1] === '"'; const hasTrailingSlash = value[value.length - 1] === '\\'; const printAsMultipleLines = !isSingleLine || hasTrailingQuote || hasTrailingSlash || preferMultipleLines; let result = ''; // Format a multi-line block quote to account for leading space. if (printAsMultipleLines && !(isSingleLine && hasLeadingSpace)) { result += '\n'; } result += value; if (printAsMultipleLines) { result += '\n'; } return '"""' + result.replace(/"""/g, '\\"""') + '"""'; }
the_stack
import { clone, copy, equal, flatMerge, generateId, includesArray, isAsyncFunction, isFunction, isJsonString, isValidObject, normalizeArray, notEqual, createArrayFromObject, defineConfig, } from '../../src'; import { LogMock } from '../../../core/tests/helper/logMock'; describe('Utils Tests', () => { beforeEach(() => { LogMock.mockLogs(); jest.clearAllMocks(); }); describe('copy function tests', () => { it('should copy Array without any reference', () => { const myArray = [1, 2, 3, 4, 5]; const myCopiedArray = copy(myArray); const myDateArray = [new Date(), 2, new Date(), new Date()]; const myCopiedDateArray = copy(myDateArray); expect(myCopiedArray).toStrictEqual([1, 2, 3, 4, 5]); expect(myArray).toStrictEqual([1, 2, 3, 4, 5]); expect(myCopiedDateArray).toStrictEqual(myDateArray); expect(myDateArray).toStrictEqual(myDateArray); myCopiedArray.push(6); myCopiedDateArray.push(1); expect(myCopiedArray).toStrictEqual([1, 2, 3, 4, 5, 6]); expect(myArray).toStrictEqual([1, 2, 3, 4, 5]); expect(myCopiedDateArray).not.toStrictEqual(myDateArray); expect(myDateArray).toStrictEqual(myDateArray); }); it('should copy Object without any reference', () => { const myObject = { id: 1, name: 'jeff' }; const myCopiedObject = copy(myObject); expect(myCopiedObject).toStrictEqual({ id: 1, name: 'jeff' }); expect(myObject).toStrictEqual({ id: 1, name: 'jeff' }); myObject.name = 'hans'; expect(myObject).toStrictEqual({ id: 1, name: 'hans' }); expect(myCopiedObject).toStrictEqual({ id: 1, name: 'jeff' }); }); it('should copy deep Object without any reference', () => { const myObject = { id: 1, name: 'jeff', location: { country: 'Germany', state: 'Bayern' }, }; const myCopiedObject = copy(myObject); expect(myCopiedObject).toStrictEqual({ id: 1, name: 'jeff', location: { country: 'Germany', state: 'Bayern' }, }); expect(myObject).toStrictEqual({ id: 1, name: 'jeff', location: { country: 'Germany', state: 'Bayern' }, }); myObject.name = 'hans'; myObject.location.state = 'Sachsen'; expect(myObject).toStrictEqual({ id: 1, name: 'hans', location: { country: 'Germany', state: 'Sachsen' }, }); expect(myCopiedObject).toStrictEqual({ id: 1, name: 'jeff', location: { country: 'Germany', state: 'Bayern' }, }); }); it('should copy default Types', () => { const myNumber = 5; const myCopiedNumber = copy(myNumber); const myString = 'frank'; const myCopiedString = copy(myString); const myNull = null; const myCopiedNull = copy(myNull); const myUndefined = undefined; const myCopiedUndefined = copy(myUndefined); expect(myCopiedNumber).toBe(5); expect(myNumber).toBe(5); expect(myCopiedString).toBe('frank'); expect(myString).toBe('frank'); expect(myCopiedNull).toBe(null); expect(myNull).toBe(null); expect(myCopiedUndefined).toBe(undefined); expect(myUndefined).toBe(undefined); }); it("shouldn't copy classes", () => { const myDate = new Date(); const myCopiedDate = copy(myDate); expect(myCopiedDate).toBe(myDate); expect(myDate).toBe(myDate); }); }); describe('isValidObject function tests', () => { // Can't be Tested in not Web-Environment // it("should return false if passing HTML Element", () => { // expect(isValidObject(HTMLElement)).toBeFalsy(); // }); it('should return false if passed instance is invalid Object (default config)', () => { expect(isValidObject(null)).toBeFalsy(); expect(isValidObject('Hello')).toBeFalsy(); expect(isValidObject([1, 2])).toBeFalsy(); expect(isValidObject(123)).toBeFalsy(); }); it('should return true if passed instance is valid Object (default config)', () => { expect(isValidObject({ hello: 'jeff' })).toBeTruthy(); expect( isValidObject({ hello: 'jeff', deep: { hello: 'franz' } }) ).toBeTruthy(); }); it('should return true if passed instance is array (considerArray = true)', () => { expect(isValidObject([1, 2], true)).toBeTruthy(); }); }); describe('includesArray function tests', () => { it("should return false if Array1 doesn't include Array2", () => { expect(includesArray([1, 2], [5, 6])).toBeFalsy(); }); it('should return false if Array1 does only include parts of Array2', () => { expect(includesArray([1, 2], [2, 6])).toBeFalsy(); }); it('should return true if Array1 includes Array2', () => { expect(includesArray([1, 4, 2, 3], [1, 2])).toBeTruthy(); }); it('should return true if Array1 is equal to Array2', () => { expect(includesArray([1, 2], [1, 2])).toBeTruthy(); }); }); describe('normalizeArray function tests', () => { it('should normalize Array (default config)', () => { expect(normalizeArray([1, 2, undefined, 3, 'hi'])).toStrictEqual([ 1, 2, undefined, 3, 'hi', ]); }); it('should normalize single Item (default config)', () => { expect(normalizeArray(1)).toStrictEqual([1]); }); it('should normalize single 0 Item (default config)', () => { expect(normalizeArray(0)).toStrictEqual([0]); }); it("shouldn't normalize undefined (default config)", () => { expect(normalizeArray(undefined)).toStrictEqual([]); }); it('should normalize undefined (createUndefinedArray = true)', () => { expect(normalizeArray(undefined, true)).toStrictEqual([undefined]); }); }); describe('isFunction function tests', () => { it('should return true if passed instance is valid Function', () => { expect( isFunction(() => { /* empty function */ }) ).toBeTruthy(); }); it('should return false if passed instance is invalid Function', () => { expect(isFunction('hello')).toBeFalsy(); expect(isFunction(1)).toBeFalsy(); expect(isFunction([1, 2, 3])).toBeFalsy(); expect(isFunction({ hello: 'jeff' })).toBeFalsy(); }); }); describe('isAsyncFunction function tests', () => { it('should return true if passed instance is valid async Function', () => { expect( isAsyncFunction(async () => { /* empty function */ }) ).toBeTruthy(); expect( isAsyncFunction(async function () { /* empty function */ }) ).toBeTruthy(); }); it('should return false if passed instance is invalid async Function', () => { expect(isAsyncFunction('hello')).toBeFalsy(); expect(isAsyncFunction(1)).toBeFalsy(); expect(isAsyncFunction([1, 2, 3])).toBeFalsy(); expect(isAsyncFunction({ hello: 'jeff' })).toBeFalsy(); expect( isAsyncFunction(() => { /* empty function */ }) ).toBeFalsy(); expect( isAsyncFunction(function () { /* empty function */ }) ).toBeFalsy(); }); }); describe('isJsonString function tests', () => { it('should return true if passed instance is valid Json String', () => { expect(isJsonString('{"name":"John", "age":31, "city":"New York"}')).toBe( true ); }); it('should return false if passed instance is invalid Json String', () => { expect(isJsonString('frank')).toBeFalsy(); expect(isJsonString('{name":"John", "age":31, "city":"New York"}')).toBe( false ); expect(isJsonString(10)).toBeFalsy(); expect(isJsonString({ name: 'John', age: 31 })).toBeFalsy(); }); }); describe('defineConfig function tests', () => { it( 'should merge the defaults object into the config object ' + 'and overwrite undefined properties (default config)', () => { const config = { allowLogging: true, loops: 10, isHuman: undefined, notDefinedConfig: 'jeff', }; expect( defineConfig(config, { allowLogging: false, loops: 15, isHuman: true, isRobot: false, name: 'jeff', nested: { frank: 'hans', jeff: 'dieter', }, }) ).toStrictEqual({ allowLogging: true, loops: 10, isHuman: true, isRobot: false, name: 'jeff', notDefinedConfig: 'jeff', nested: { frank: 'hans', jeff: 'dieter', }, }); } ); it( 'should merge the defaults object into the config object ' + "and shouldn't overwrite undefined properties (overwriteUndefinedProperties = false)", () => { const config = { allowLogging: true, loops: 10, isHuman: undefined, notDefinedConfig: 'jeff', }; expect( defineConfig( config, { allowLogging: false, loops: 15, isHuman: true, isRobot: false, name: 'jeff', nested: { frank: 'hans', jeff: 'dieter', }, }, false ) ).toStrictEqual({ allowLogging: true, loops: 10, isHuman: undefined, isRobot: false, name: 'jeff', notDefinedConfig: 'jeff', nested: { frank: 'hans', jeff: 'dieter', }, }); } ); }); describe('flatMerge function tests', () => { it('should merge Changes Object into Source Object', () => { const source = { id: 123, name: 'jeff', size: 189, }; expect( flatMerge(source, { name: 'hans', size: 177, }) ).toStrictEqual({ id: 123, name: 'hans', size: 177, }); }); it('should add new properties to Source Object', () => { const source = { id: 123, name: 'jeff', size: 189, }; expect( flatMerge(source, { name: 'hans', size: 177, location: 'behind you', }) ).toStrictEqual({ id: 123, name: 'hans', size: 177, location: 'behind you', }); }); it("shouldn't add new properties to source Object (config.addNewProperties = false)", () => { const source = { id: 123, name: 'jeff', size: 189, }; expect( flatMerge( source, { name: 'hans', size: 177, location: 'behind you', }, { addNewProperties: false } ) ).toStrictEqual({ id: 123, name: 'hans', size: 177, }); }); it("shouldn't deep merge Changes Object into Source Object", () => { const source = { id: 123, name: 'jeff', address: { place: 'JeffsHome', country: 'Germany', }, }; expect( flatMerge(source, { place: 'JeffsNewHome', }) ).toStrictEqual({ id: 123, name: 'jeff', address: { place: 'JeffsHome', country: 'Germany', }, place: 'JeffsNewHome', }); }); }); describe('equal function tests', () => { it('should return true if value1 and value2 are equal', () => { expect(equal({ id: 123, name: 'jeff' }, { id: 123, name: 'jeff' })).toBe( true ); expect(equal([1, 2, 3], [1, 2, 3])).toBeTruthy(); expect(equal(12, 12)).toBeTruthy(); expect(equal('hi', 'hi')).toBeTruthy(); }); it("should return false if value1 and value2 aren't equal", () => { expect(equal({ id: 123, name: 'jeff' }, { id: 123, name: 'hans' })).toBe( false ); expect(equal([1, 2], [3, 5])).toBeFalsy(); expect(equal(12, 13)).toBeFalsy(); expect(equal('hi', 'bye')).toBeFalsy(); }); }); describe('notEqual function tests', () => { it('should return false if value1 and value2 are equal', () => { expect( notEqual({ id: 123, name: 'jeff' }, { id: 123, name: 'jeff' }) ).toBeFalsy(); expect(notEqual([1, 2, 3], [1, 2, 3])).toBeFalsy(); expect(notEqual(12, 12)).toBeFalsy(); expect(equal('hi', 'bye')).toBeFalsy(); }); it("should return true if value1 and value2 aren't equal", () => { expect( notEqual({ id: 123, name: 'jeff' }, { id: 123, name: 'hans' }) ).toBeTruthy(); expect(notEqual([1, 2], [3, 5])).toBeTruthy(); expect(notEqual(12, 13)).toBeTruthy(); expect(notEqual('hi', 'bye')).toBeTruthy(); }); }); describe('generateId function tests', () => { it('should returned generated Id that matches regex', () => { expect(generateId()).toMatch(/^[a-zA-Z0-9]*$/); }); it('should returned generated Id with correct length (length = x)', () => { expect(generateId(10)).toMatch(/^[a-zA-Z0-9]*$/); expect(generateId(10).length).toEqual(10); expect(generateId(5).length).toEqual(5); expect(generateId(-10).length).toEqual(0); }); }); describe('createArrayFromObject function tests', () => { it('should transform Object to Array', () => { const dummyObject = { jeff: { hello: 'there', }, frank: { see: 'you', }, hans: { how: 'are you', }, }; const generatedArray = createArrayFromObject(dummyObject); expect(generatedArray).toStrictEqual([ { key: 'jeff', instance: { hello: 'there', }, }, { key: 'frank', instance: { see: 'you', }, }, { key: 'hans', instance: { how: 'are you', }, }, ]); }); }); describe('clone function tests', () => { it('should clone Object/Class without any reference', () => { class DummyClass { constructor( public id: number, public name: string, public location: { country: string; state: string } ) {} } const dummyClass = new DummyClass(10, 'jeff', { country: 'USA', state: 'California', }); const clonedDummyClass = clone(dummyClass); expect(dummyClass).toBeInstanceOf(DummyClass); expect(clonedDummyClass).toBeInstanceOf(DummyClass); expect(dummyClass.name).toBe('jeff'); expect(dummyClass.id).toBe(10); expect(dummyClass.location).toStrictEqual({ country: 'USA', state: 'California', }); expect(clonedDummyClass.name).toBe('jeff'); expect(clonedDummyClass.id).toBe(10); expect(clonedDummyClass.location).toStrictEqual({ country: 'USA', state: 'California', }); dummyClass.name = 'frank'; dummyClass.location.state = 'Florida'; expect(dummyClass.name).toBe('frank'); expect(dummyClass.id).toBe(10); expect(dummyClass.location).toStrictEqual({ country: 'USA', state: 'Florida', }); expect(clonedDummyClass.name).toBe('jeff'); expect(clonedDummyClass.id).toBe(10); expect(clonedDummyClass.location).toStrictEqual({ country: 'USA', state: 'California', }); }); }); });
the_stack
import * as React from "react"; import { IBasePickerStyles, ITag, } from "office-ui-fabric-react/lib/Pickers"; import { Stack, } from "office-ui-fabric-react/lib/Stack"; import { Text, } from "office-ui-fabric-react/lib/Text"; import { TextField } from "office-ui-fabric-react/lib/TextField"; import { DefaultButton, PrimaryButton } from "office-ui-fabric-react/lib/components/Button"; import { DialogType, DialogFooter, IDialogContentProps } from "office-ui-fabric-react/lib/components/Dialog"; import { IModalProps } from "office-ui-fabric-react/lib/Modal"; import { Dropdown, IDropdownOption } from "office-ui-fabric-react/lib/components/Dropdown"; import { Link } from "office-ui-fabric-react/lib/components/Link"; import { DocumentCard, DocumentCardActivity, DocumentCardLocation, DocumentCardPreview, DocumentCardTitle, DocumentCardType, IDocumentCardPreviewProps } from "office-ui-fabric-react/lib/DocumentCard"; import { IIconProps } from "office-ui-fabric-react/lib/Icon"; import { Spinner, SpinnerSize } from 'office-ui-fabric-react/lib/Spinner'; import { ImageFit } from "office-ui-fabric-react/lib/Image"; import { PanelType } from "office-ui-fabric-react/lib/Panel"; import { mergeStyles } from "office-ui-fabric-react/lib/Styling"; import { ISize } from "office-ui-fabric-react/lib/Utilities"; import { DayOfWeek } from "office-ui-fabric-react/lib/utilities/dateValues/DateValues"; import { ExclamationCircleIcon, Flex, ScreenshareIcon, ShareGenericIcon, Text as NorthstarText } from "@fluentui/react-northstar"; import { DisplayMode, Environment, EnvironmentType } from "@microsoft/sp-core-library"; import { SPHttpClient } from "@microsoft/sp-http"; import { SPPermission } from "@microsoft/sp-page-context"; import { Accordion } from "../../../controls/accordion"; import { ChartControl, ChartType } from "../../../ChartControl"; import { Accordion as AccessibleAccordion, AccordionItem, AccordionItemButton, AccordionItemHeading, AccordionItemPanel } from "../../../controls/accessibleAccordion"; import { Carousel, CarouselButtonsDisplay, CarouselButtonsLocation, CarouselIndicatorsDisplay, CarouselIndicatorShape } from "../../../controls/carousel"; import { Dashboard, WidgetSize } from "../../../controls/dashboard"; import { TimeDisplayControlType } from "../../../controls/dateTimePicker/TimeDisplayControlType"; import { IconPicker } from "../../../controls/iconPicker"; import { ComboBoxListItemPicker } from "../../../controls/listItemPicker/ComboBoxListItemPicker"; import { Pagination } from "../../../controls/pagination"; import { TermActionsDisplayStyle } from "../../../controls/taxonomyPicker"; import { TermActionsDisplayMode } from "../../../controls/taxonomyPicker/termActions"; import { Toolbar } from "../../../controls/toolbar"; import { ITreeItem, TreeItemActionsDisplayMode, TreeView, TreeViewSelectionMode } from "../../../controls/treeView"; import { DateConvention, DateTimePicker, TimeConvention } from "../../../DateTimePicker"; import { CustomCollectionFieldType, FieldCollectionData } from "../../../FieldCollectionData"; import { FilePicker, IFilePickerResult } from "../../../FilePicker"; import { ApplicationType, FileTypeIcon, IconType, ImageSize } from "../../../FileTypeIcon"; import { FolderExplorer, IBreadcrumbItem, IFolder } from "../../../FolderExplorer"; import { FolderPicker } from "../../../FolderPicker"; import { GridLayout } from "../../../GridLayout"; import { IFrameDialog } from "../../../IFrameDialog"; import { IFramePanel } from "../../../IFramePanel"; import { ListItemPicker } from "../../../ListItemPicker"; import { ListPicker } from "../../../ListPicker"; import { GroupOrder, IGrouping, IViewField, ListView, SelectionMode } from "../../../ListView"; import { Map, MapType } from "../../../Map"; import { PeoplePicker, PrincipalType } from "../../../PeoplePicker"; import { Placeholder } from "../../../Placeholder"; import { IProgressAction, Progress } from "../../../Progress"; import { RichText } from "../../../RichText"; import { PermissionLevel, SecurityTrimmedControl } from "../../../SecurityTrimmedControl"; import { ITerm } from "../../../services/ISPTermStorePickerService"; import SPTermStorePickerService from "../../../services/SPTermStorePickerService"; import { SiteBreadcrumb } from "../../../SiteBreadcrumb"; import { IPickerTerms, TaxonomyPicker, UpdateType } from "../../../TaxonomyPicker"; import { WebPartTitle } from "../../../WebPartTitle"; import { AnimatedDialog } from "../../../AnimatedDialog"; import styles from "./ControlsTest.module.scss"; import { IControlsTestProps, IControlsTestState } from "./IControlsTestProps"; import { MyTeams } from "../../../controls/MyTeams"; import { TeamPicker } from "../../../TeamPicker"; import { TeamChannelPicker } from "../../../TeamChannelPicker"; import { DragDropFiles } from "../../../DragDropFiles"; import { SitePicker } from "../../../controls/sitePicker/SitePicker"; import { DynamicForm } from '../../../controls/dynamicForm'; import { LocationPicker } from "../../../controls/locationPicker/LocationPicker"; import { ILocationPickerItem } from "../../../controls/locationPicker/ILocationPicker"; import { debounce } from "lodash"; import { ModernTaxonomyPicker } from "../../../controls/modernTaxonomyPicker/ModernTaxonomyPicker"; // Used to render document card /** * The sample data below was randomly generated (except for the title). It is used by the grid layout */ const sampleGridData: any[] = [{ thumbnail: "https://pixabay.com/get/57e9dd474952a414f1dc8460825668204022dfe05555754d742e7bd6/hot-air-balloons-1984308_640.jpg", title: "Adventures in SPFx", name: "Perry Losselyong", profileImageSrc: "https://robohash.org/blanditiisadlabore.png?size=50x50&set=set1", location: "SharePoint", activity: "3/13/2019" }, { thumbnail: "https://pixabay.com/get/55e8d5474a52ad14f1dc8460825668204022dfe05555754d742d79d0/autumn-3804001_640.jpg", title: "The Wild, Untold Story of SharePoint!", name: "Ebonee Gallyhaock", profileImageSrc: "https://robohash.org/delectusetcorporis.bmp?size=50x50&set=set1", location: "SharePoint", activity: "6/29/2019" }, { thumbnail: "https://pixabay.com/get/57e8dd454c50ac14f1dc8460825668204022dfe05555754d742c72d7/log-cabin-1886620_640.jpg", title: "Low Code Solutions: PowerApps", name: "Seward Keith", profileImageSrc: "https://robohash.org/asperioresautquasi.jpg?size=50x50&set=set1", location: "PowerApps", activity: "12/31/2018" }, { thumbnail: "https://pixabay.com/get/55e3d445495aa514f1dc8460825668204022dfe05555754d742b7dd5/portrait-3316389_640.jpg", title: "Not Your Grandpa's SharePoint", name: "Sharona Selkirk", profileImageSrc: "https://robohash.org/velnammolestiae.png?size=50x50&set=set1", location: "SharePoint", activity: "11/20/2018" }, { thumbnail: "https://pixabay.com/get/57e6dd474352ae14f1dc8460825668204022dfe05555754d742a7ed1/faucet-1684902_640.jpg", title: "Get with the Flow", name: "Boyce Batstone", profileImageSrc: "https://robohash.org/nulladistinctiomollitia.jpg?size=50x50&set=set1", location: "Flow", activity: "5/26/2019" }]; const sampleItems = [ { Langue: { Nom: 'Français' }, Question: 'Charger des fichiers et dossiers', Reponse: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { Langue: { Nom: 'Français' }, Question: 'Enregistrer un fichier', Reponse: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { Langue: { Nom: 'Français' }, Question: 'Troisième exemple', Reponse: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { Langue: { Nom: 'Français' }, Question: 'Quatrième exemple', Reponse: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { Langue: { Nom: 'Français' }, Question: 'Cinquième exemple', Reponse: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' }, { Langue: { Nom: 'Français' }, Question: 'Sixième exemple', Reponse: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.' } ]; /** * Component that can be used to test out the React controls from this project */ export default class ControlsTest extends React.Component<IControlsTestProps, IControlsTestState> { private taxService: SPTermStorePickerService = null; private richTextValue: string = null; private theme = window["__themeState__"].theme; private pickerStylesSingle: Partial<IBasePickerStyles> = { root: { width: "100%", borderRadius: 0, marginTop: 0, }, input: { width: "100%", backgroundColor: this.theme.white, }, text: { borderStyle: "solid", width: "100%", borderWidth: 1, backgroundColor: this.theme.white, borderRadius: 0, borderColor: this.theme.neutralQuaternaryAlt, ":focus": { borderStyle: "solid", borderWidth: 1, borderColor: this.theme.themePrimary, }, ":hover": { borderStyle: "solid", borderWidth: 1, borderColor: this.theme.themePrimary, }, ":after": { borderWidth: 0, borderRadius: 0, }, }, }; private onSelectedChannel = (teamsId: string, channelId: string) => { alert(`TeamId: ${teamsId}\n ChannelId: ${channelId}\n`); console.log("TeamsId", teamsId); console.log("ChannelId", channelId); } /** * Static array for carousel control example. */ private carouselElements = [ <div id="1" key="1">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis a mattis libero, nec consectetur neque. Suspendisse potenti. Fusce ultrices faucibus consequat. Suspendisse ex diam, ullamcorper sit amet justo ac, accumsan congue neque. Vestibulum aliquam mauris non justo convallis, id molestie purus sodales. Maecenas scelerisque aliquet turpis, ac efficitur ex iaculis et. Vivamus finibus mi eget urna tempor, sed porta justo tempus. Vestibulum et lectus magna. Integer ante felis, ullamcorper venenatis lectus ac, vulputate pharetra magna. Morbi eget nisl tempus, viverra diam ac, mollis tortor. Nam odio ex, viverra bibendum mauris vehicula, consequat suscipit ligula. Nunc sed ultrices augue, eu tincidunt diam.</div>, <div id="2" key="2">Quisque metus lectus, facilisis id consectetur ac, hendrerit eget quam. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut faucibus posuere felis vel efficitur. Maecenas et massa in sem tincidunt finibus. Duis sit amet bibendum nisi. Vestibulum pretium pretium libero, vel tincidunt sem vestibulum sed. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin quam lorem, venenatis id bibendum id, tempus eu nibh. Sed tristique semper ligula, vitae gravida diam gravida vitae. Donec eget posuere mauris, pharetra semper lectus.</div>, <div id="3" key="3">Pellentesque tempor et leo at tincidunt. Vivamus et leo sed eros vehicula mollis vitae in dui. Duis posuere sodales enim ut ultricies. Cras in venenatis nulla. Ut sed neque dignissim, sollicitudin tellus convallis, placerat leo. Aliquam vestibulum, leo pharetra sollicitudin pretium, ipsum nisl tincidunt orci, in molestie ipsum dui et mi. Praesent aliquam accumsan risus sed bibendum. Cras consectetur elementum turpis, a mollis velit gravida sit amet. Praesent non augue cursus, varius justo at, molestie lorem. Nulla cursus tellus quis odio congue elementum. Vivamus sit amet quam nec lectus hendrerit blandit. Duis ac condimentum sem. Morbi hendrerit elementum purus, non facilisis arcu bibendum vitae. Vivamus commodo tristique euismod.</div>, <div id="4" key="4">Proin semper egestas porta. Nullam risus nisl, auctor ac hendrerit in, dapibus quis ex. Quisque vitae nisi quam. Etiam vel sapien ut libero ornare rhoncus nec vestibulum dolor. Curabitur lacinia aliquam arcu. Proin ultrices risus velit, in vehicula tellus vehicula at. Sed ultrices et felis fringilla ultricies.</div>, <div id="5" key="5">Donec orci lorem, imperdiet eu nisi sit amet, condimentum scelerisque tortor. Etiam nec lacinia dui. Duis non turpis neque. Sed pellentesque a erat et accumsan. Pellentesque elit odio, elementum nec placerat nec, ornare in tortor. Suspendisse gravida magna maximus mollis facilisis. Duis odio libero, finibus ac suscipit sed, aliquam et diam. Aenean posuere lacus ex. Donec dapibus, sem ac luctus ultrices, justo libero tempor eros, vitae lacinia ex ante non dolor. Curabitur condimentum, ligula id pharetra dictum, libero libero ullamcorper nunc, eu blandit sem arcu ut felis. Nullam lacinia dapibus auctor.</div> ]; private skypeCheckIcon: IIconProps = { iconName: 'SkypeCheck' }; private treeitems = [ { key: "R1", label: "Root", subLabel: "This is a sub label for node", iconProps: this.skypeCheckIcon, actions: [{ title: "Get item", iconProps: { iconName: 'Warning', style: { color: 'salmon', }, }, id: "GetItem", actionCallback: async (treeItem: ITreeItem) => { console.log(treeItem); } }], children: [ { key: "1", label: "Parent 1", selectable: false, children: [ { key: "3", label: "Child 1", subLabel: "This is a sub label for node", actions: [{ title: "Share", iconProps: { iconName: 'Share' }, id: "GetItem", actionCallback: async (treeItem: ITreeItem) => { console.log(treeItem); } }], children: [ { key: "gc1", label: "Grand Child 1", actions: [{ title: "Get Grand Child item", iconProps: { iconName: 'Mail' }, id: "GetItem", actionCallback: async (treeItem: ITreeItem) => { console.log(treeItem); } }] } ] }, { key: "4", label: "Child 2", iconProps: this.skypeCheckIcon } ] }, { key: "2", label: "Parent 2" }, { key: "5", label: "Parent 3", disabled: true }, { key: "6", label: "Parent 4", selectable: true } ] }, { key: "R2", label: "Root 2", children: [ { key: "8", label: "Parent 5" }, { key: "9", label: "Parent 6" }, { key: "10", label: "Parent 7" }, { key: "11", label: "Parent 8" } ] }, { key: "R3", label: "Root 3", children: [ { key: "12", label: "Parent 9" }, { key: "13", label: "Parent 10", children: [ { key: "gc3", label: "Child of Parent 10", children: [ { key: "ggc1", label: "Grandchild of Parent 10" } ] }, ] }, { key: "14", label: "Parent 11" }, { key: "15", label: "Parent 12" } ] } ]; constructor(props: IControlsTestProps) { super(props); this.state = { imgSize: ImageSize.small, items: [], iFrameDialogOpened: false, iFramePanelOpened: false, initialValues: [], authorEmails: [], selectedList: null, progressActions: this._initProgressActions(), dateTimeValue: new Date(), richTextValue: null, canMovePrev: false, canMoveNext: true, currentCarouselElement: this.carouselElements[0], comboBoxListItemPickerListId: '0ffa51d7-4ad1-4f04-8cfe-98209905d6da', comboBoxListItemPickerIds: [{ Id: 1, Title: '111' }], treeViewSelectedKeys: ['gc1', 'gc3'], showAnimatedDialog: false, showCustomisedAnimatedDialog: false, showSuccessDialog: false, showErrorDialog: false, selectedTeam: [], selectedTeamChannels: [], errorMessage: "This field is required" }; this._onIconSizeChange = this._onIconSizeChange.bind(this); this._onConfigure = this._onConfigure.bind(this); this._startProgress = this._startProgress.bind(this); this.onServicePickerChange = this.onServicePickerChange.bind(this); } /** * React componentDidMount lifecycle hook */ public componentDidMount() { const restApi = `${this.props.context.pageContext.web.absoluteUrl}/_api/web/GetFolderByServerRelativeUrl('Shared%20Documents')/files?$expand=ListItemAllFields`; this.props.context.spHttpClient.get(restApi, SPHttpClient.configurations.v1) .then(resp => { return resp.json(); }) .then(items => { this.setState({ items: items.value ? items.value : [] }); }); // // Get Authors in the SharePoint Document library -- For People Picker Testing // const restAuthorApi = `${this.props.context.pageContext.web.absoluteUrl}/_api/web/lists/GetByTitle('Documents')/Items?$select=Id, Author/EMail&$expand=Author/EMail`; // this.props.context.spHttpClient.get(restAuthorApi, SPHttpClient.configurations.v1) // .then(resp => { return resp.json(); }) // .then(items => { // let emails : string[] = items.value ? items.value.map((item, key)=> { return item.Author.EMail}) : []; // console.log(emails); // this.setState({ // authorEmails: emails // }); // }); } /** * Event handler when changing the icon size in the dropdown * @param element */ private _onIconSizeChange(element?: IDropdownOption): void { this.setState({ imgSize: parseInt(element.key.toString()) }); } /** * Open the property pane */ private _onConfigure() { this.props.context.propertyPane.open(); } /** * Method that retrieves the selected items in the list view * @param items */ private _getSelection(items: any[]) { console.log('Items:', items); } /** * Method that retrieves files from drag and drop * @param files */ private _getDropFiles = (files) => { for (var i = 0; i < files.length; i++) { console.log("File name: " + files[i].name); console.log("Folder Path: " + files[i].fullPath); } } /** * *Method that retrieves the selected terms from the taxonomy picker and sets state * @private * @param {IPickerTerms} terms * @memberof ControlsTest */ private onServicePickerChange = (terms: IPickerTerms): void => { this.setState({ initialValues: terms }); // console.log("serviceTerms", terms); } /** * Method that retrieves the selected terms from the taxonomy picker * @param terms */ private _onTaxPickerChange = (terms: IPickerTerms) => { this.setState({ initialValues: terms, errorMessage: terms.length > 0 ? '' : 'This field is required' }); console.log("Terms:", terms); } /** * Method that retrieves the selected date/time from the DateTime picker * @param dateTimeValue */ private _onDateTimePickerChange = (dateTimeValue: Date) => { this.setState({ dateTimeValue }); console.log("Selected Date/Time:", dateTimeValue.toLocaleString()); } /** * Selected lists change event * @param lists */ private onListPickerChange = (lists: string | string[]) => { console.log("Lists:", lists); this.setState({ selectedList: typeof lists === "string" ? lists : lists.pop() }); } /** * Deletes second item from the list */ private deleteItem = () => { const { items } = this.state; if (items.length >= 2) { items.splice(1, 1); this.setState({ items: items }); } } /** * Method that retrieves the selected items from People Picker * @param items */ private _getPeoplePickerItems(items: any[]) { console.log('Items:', items); } /** * Selected item from the list data picker */ private listItemPickerDataSelected(item: any) { console.log(item); } private _startProgress() { let currentIndex = 0; const intervalId = setInterval(() => { const actions = this.state.progressActions; if (currentIndex >= actions.length) { clearInterval(intervalId); } else { const action = actions[currentIndex]; if (currentIndex == 1) { // just a test for error action.hasError = true; action.errorMessage = 'some error message'; } } this.setState({ currentProgressActionIndex: currentIndex, progressActions: actions }); currentIndex++; }, 5000); } private _initProgressActions(): IProgressAction[] { return [{ title: 'First Step', subActionsTitles: [ 'Sub action 1', 'Sub action 2' ] }, { title: 'Second step' }, { title: 'Third Step', subActionsTitles: [ 'Sub action 1', 'Sub action 2', 'Sub action 3' ] }, { title: 'Fourth Step' }]; } /** * Triggers element change for the carousel example. */ private triggerNextElement = (index: number): void => { const canMovePrev = index > 0; const canMoveNext = index < this.carouselElements.length - 1; const nextElement = this.carouselElements[index]; setTimeout(() => { this.setState({ canMovePrev, canMoveNext, currentCarouselElement: nextElement }); }, 500); } private _onFilePickerSave = async (filePickerResult: IFilePickerResult[]) => { this.setState({ filePickerResult: filePickerResult }); if (filePickerResult && filePickerResult.length > 0) { for (var i = 0; i < filePickerResult.length; i++) { const item = filePickerResult[i]; const fileResultContent = await item.downloadFileContent(); console.log(fileResultContent); } } } private rootFolder: IFolder = { Name: "Site", ServerRelativeUrl: this.props.context.pageContext.web.serverRelativeUrl }; private _onFolderSelect = (folder: IFolder): void => { console.log('selected folder', folder); } private _onRenderGridItem = (item: any, _finalSize: ISize, isCompact: boolean): JSX.Element => { const previewProps: IDocumentCardPreviewProps = { previewImages: [ { previewImageSrc: item.thumbnail, imageFit: ImageFit.cover, height: 130 } ] }; return <div //className={styles.documentTile} data-is-focusable={true} role="listitem" aria-label={item.title} > <DocumentCard type={isCompact ? DocumentCardType.compact : DocumentCardType.normal} onClick={(ev: React.SyntheticEvent<HTMLElement>) => alert("You clicked on a grid item")} > <DocumentCardPreview {...previewProps} /> {!isCompact && <DocumentCardLocation location={item.location} />} <div> <DocumentCardTitle title={item.title} shouldTruncate={true} /> <DocumentCardActivity activity={item.activity} people={[{ name: item.name, profileImageSrc: item.profileImageSrc }]} /> </div> </DocumentCard> </div>; } /** * Renders the component */ public render(): React.ReactElement<IControlsTestProps> { // Size options for the icon size dropdown const sizeOptions: IDropdownOption[] = [ { key: ImageSize.small, text: ImageSize[ImageSize.small], selected: ImageSize.small === this.state.imgSize }, { key: ImageSize.medium, text: ImageSize[ImageSize.medium], selected: ImageSize.medium === this.state.imgSize }, { key: ImageSize.large, text: ImageSize[ImageSize.large], selected: ImageSize.large === this.state.imgSize } ]; // Specify the fields that need to be viewed in the listview const viewFields: IViewField[] = [ { name: 'ListItemAllFields.Id', displayName: 'ID', maxWidth: 40, sorting: true, isResizable: true }, { name: 'ListItemAllFields.Underscore_Field', displayName: "Underscore_Field", sorting: true, isResizable: true }, { name: 'Name', linkPropertyName: 'ServerRelativeUrl', sorting: true, isResizable: true }, { name: 'ServerRelativeUrl', displayName: 'Path', render: (item: any) => { return <a href={item['ServerRelativeUrl']}>Link</a>; }, isResizable: true }, { name: 'Title', isResizable: true } ]; // Specify the fields on which you want to group your items // Grouping is takes the field order into account from the array // const groupByFields: IGrouping[] = [{ name: "ListItemAllFields.City", order: GroupOrder.ascending }, { name: "ListItemAllFields.Country.Label", order: GroupOrder.descending }]; const groupByFields: IGrouping[] = [{ name: "ListItemAllFields.Department.Label", order: GroupOrder.ascending }]; let iframeUrl: string = '/temp/workbench.html'; if (Environment.type === EnvironmentType.SharePoint) { iframeUrl = '/_layouts/15/sharepoint.aspx'; } else if (Environment.type === EnvironmentType.ClassicSharePoint) { iframeUrl = this.context.pageContext.web.serverRelativeUrl; } const additionalBreadcrumbItems: IBreadcrumbItem[] = [{ text: 'Places', key: 'Places', onClick: () => { console.log('additional breadcrumb item'); }, }]; const linkExample = { href: "#" }; const calloutItemsExample = [ { id: "action_1", title: "Info", icon: <ExclamationCircleIcon />, }, { id: "action_2", title: "Popup", icon: <ScreenshareIcon /> }, { id: "action_3", title: "Share", icon: <ShareGenericIcon />, }, ]; /** * Animated dialog related */ const animatedDialogContentProps: IDialogContentProps = { type: DialogType.normal, title: 'Animated Dialog', subText: 'Do you like the animated dialog?', }; const animatedModalProps: IModalProps = { isDarkOverlay: true }; const customizedAnimatedModalProps: IModalProps = { isDarkOverlay: true, containerClassName: `${styles.dialogContainer}` }; const customizedAnimatedDialogContentProps: IDialogContentProps = { type: DialogType.normal, title: 'Animated Dialog' }; const successDialogContentProps: IDialogContentProps = { type: DialogType.normal, title: 'Good answer!' }; const errorDialogContentProps: IDialogContentProps = { type: DialogType.normal, title: 'Uh oh!' }; const timeout = (ms: number): Promise<void> => { return new Promise((resolve, reject) => setTimeout(resolve, ms)); }; return ( <div className={styles.controlsTest}> <div className="ms-font-m"> {/* Change the list Id and list item id before you start to test this control */} {/* <DynamicForm context={this.props.context} listId={"3071c058-549f-461d-9d73-8b9a52049a80"} listItemId={1} onCancelled={() => { console.log('Cancelled'); }} onSubmitted={async (listItem) => { let itemdata = await listItem.get(); console.log(itemdata["ID"]); }}></DynamicForm> */} </div> <WebPartTitle displayMode={this.props.displayMode} title={this.props.title} updateProperty={this.props.updateProperty} moreLink={ <Link href="https://pnp.github.io/sp-dev-fx-controls-react/">See all</Link> } /> <Stack styles={{ root: { marginBottom: 200 } }}> <MyTeams title="My Teams" webPartContext={this.props.context} themeVariant={this.props.themeVariant} enablePersonCardInteraction={true} onSelectedChannel={this.onSelectedChannel} /> </Stack> <Stack styles={{ root: { margin: "10px 10px 100px 10px" } }} tokens={{ childrenGap: 10 }} > <TeamPicker label="Select Team" themeVariant={this.props.themeVariant} selectedTeams={this.state.selectedTeam} appcontext={this.props.context} itemLimit={1} onSelectedTeams={(tagList: ITag[]) => { this.setState({ selectedTeamChannels: [] }); this.setState({ selectedTeam: tagList }); console.log(tagList); }} /> {this.state?.selectedTeam && this.state?.selectedTeam.length > 0 && ( <> <TeamChannelPicker label="Select Team Channel" themeVariant={this.props.themeVariant} selectedChannels={this.state.selectedTeamChannels} teamId={this.state.selectedTeam[0].key} appcontext={this.props.context} onSelectedChannels={(tagList: ITag[]) => { this.setState({ selectedTeamChannels: tagList }); console.log(tagList); }} /> </> )} </Stack> <AccessibleAccordion allowZeroExpanded> <AccordionItem key={"Headding 1"}> <AccordionItemHeading> <AccordionItemButton>{"Accordion Item Heading 1"}</AccordionItemButton> </AccordionItemHeading> <AccordionItemPanel> <div style={{ margin: 20 }}> <h2>Content Heading 1</h2> <Text variant={"mediumPlus"}>Text sample </Text> </div> </AccordionItemPanel> </AccordionItem> <AccordionItem key={"Headding 2"}> <AccordionItemHeading> <AccordionItemButton>Accordion Item Heading 2</AccordionItemButton> </AccordionItemHeading> <AccordionItemPanel> <div style={{ margin: 20 }}> <h2>Content Heading 2</h2> <Text variant={"mediumPlus"}>Text </Text> <TextField></TextField> </div> </AccordionItemPanel> </AccordionItem> </AccessibleAccordion> { sampleItems.map((item, index) => ( <Accordion title={item.Question} defaultCollapsed={false} className={"itemCell"} key={index}> <div className={"itemContent"}> <div className={"itemResponse"}>{item.Reponse}</div> <div className={"itemIndex"}>{`Langue : ${item.Langue.Nom}`}</div> </div> </Accordion> )) } <div className="ms-font-m">Services tester: <TaxonomyPicker allowMultipleSelections={true} selectChildrenIfParentSelected={true} //termsetNameOrID="61837936-29c5-46de-982c-d1adb6664b32" // id to termset that has a custom sort termsetNameOrID="8ea5ac06-fd7c-4269-8d0d-02f541df8eb9" initialValues={[{ key: "c05250ff-80e7-41e6-bfb3-db2db62d63d3", name: "Business", path: "Business", termSet: "8ea5ac06-fd7c-4269-8d0d-02f541df8eb9", termSetName: "Trip Types" }, { key: "a05250ff-80e7-41e6-bfb3-db2db62d63d3", name: "BBusiness", path: "BBusiness", termSet: "8ea5ac06-fd7c-4269-8d0d-02f541df8eb9", termSetName: "Trip Types" }]} validateOnLoad={true} panelTitle="Select Sorted Term" label="Service Picker with custom actions" context={this.props.context} onChange={this.onServicePickerChange} isTermSetSelectable={true} termActions={{ actions: [{ title: "Get term labels", iconName: "LocaleLanguage", id: "test", invokeActionOnRender: true, hidden: true, actionCallback: async (taxService: SPTermStorePickerService, term: ITerm) => { // const labels = await taxService.getTermLabels(term.Id); // if (labels) { // let termLabel: string = labels.join(" ; "); // const updateAction = { // updateActionType: UpdateType.updateTermLabel, // value: `${termLabel} (updated)` // }; // return updateAction; // } const updateAction = { updateActionType: UpdateType.updateTermLabel, value: `${term.Name} (updated)` }; return updateAction; }, applyToTerm: (term: ITerm) => (term && term.Name && term.Name.toLowerCase() === "about us") }, // new TermLabelAction("Get Labels") ], termActionsDisplayMode: TermActionsDisplayMode.buttons, termActionsDisplayStyle: TermActionsDisplayStyle.textAndIcon, }} onPanelSelectionChange={(prev, next) => { console.log(prev); console.log(next); }} /> <TaxonomyPicker allowMultipleSelections={true} termsetNameOrID="8ea5ac06-fd7c-4269-8d0d-02f541df8eb9" // id to termset that has a default sort panelTitle="Select Default Sorted Term" label="Service Picker" context={this.props.context} onChange={this.onServicePickerChange} isTermSetSelectable={false} placeholder="Select service" // validateInput={true} /* Uncomment this to enable validation of input text */ required={true} errorMessage='this field is required' onGetErrorMessage={(value) => { return 'comment errorMessage to see this one'; }} /> <TaxonomyPicker initialValues={this.state.initialValues} allowMultipleSelections={true} termsetNameOrID="41dec50a-3e09-4b3f-842a-7224cffc74c0" anchorId="436a6154-9691-4925-baa5-4c9bb9212cbf" // disabledTermIds={["943fd9f0-3d7c-415c-9192-93c0e54573fb", "0e415292-cce5-44ac-87c7-ef99dd1f01f4"]} // disabledTermIds={["943fd9f0-3d7c-415c-9192-93c0e54573fb", "73d18756-20af-41de-808c-2a1e21851e44", "0e415292-cce5-44ac-87c7-ef99dd1f01f4"]} // disabledTermIds={["cd6f6d3c-672d-4244-9320-c1e64cc0626f", "0e415292-cce5-44ac-87c7-ef99dd1f01f4"]} // disableChildrenOfDisabledParents={true} panelTitle="Select Term" label="Taxonomy Picker" context={this.props.context} onChange={this._onTaxPickerChange} isTermSetSelectable={false} hideDeprecatedTags={true} hideTagsNotAvailableForTagging={true} errorMessage={this.state.errorMessage} termActions={{ actions: [{ title: "Get term labels", iconName: "LocaleLanguage", id: "test", invokeActionOnRender: true, hidden: true, actionCallback: async (taxService: SPTermStorePickerService, term: ITerm) => { console.log(term.Name, term.TermsCount); return { updateActionType: UpdateType.updateTermLabel, value: `${term.Name} (updated)` }; }, applyToTerm: (term: ITerm) => (term && term.Name && term.Name === "internal") }, { title: "Hide term", id: "hideTerm", invokeActionOnRender: true, hidden: true, actionCallback: async (taxService: SPTermStorePickerService, term: ITerm) => { return { updateActionType: UpdateType.hideTerm, value: true }; }, applyToTerm: (term: ITerm) => (term && term.Name && (term.Name.toLowerCase() === "help desk" || term.Name.toLowerCase() === "multi-column valo site page")) }, { title: "Disable term", id: "disableTerm", invokeActionOnRender: true, hidden: true, actionCallback: async (taxService: SPTermStorePickerService, term: ITerm) => { return { updateActionType: UpdateType.disableTerm, value: true }; }, applyToTerm: (term: ITerm) => (term && term.Name && term.Name.toLowerCase() === "secured") }, { title: "Disable or hide term", id: "disableOrHideTerm", invokeActionOnRender: true, hidden: true, actionCallback: async (taxService: SPTermStorePickerService, term: ITerm) => { if (term.TermsCount > 0) { return { updateActionType: UpdateType.disableTerm, value: true }; } return { updateActionType: UpdateType.hideTerm, value: true }; }, applyToTerm: (term: ITerm) => true }], termActionsDisplayMode: TermActionsDisplayMode.buttons, termActionsDisplayStyle: TermActionsDisplayStyle.textAndIcon }} /> <DefaultButton text="Add" onClick={() => { this.setState({ initialValues: [{ key: "ab703558-2546-4b23-b8b8-2bcb2c0086f5", name: "HR", path: "HR", termSet: "b3e9b754-2593-4ae6-abc2-35345402e186" }], errorMessage: "" }); }} /> </div> <DateTimePicker label="DateTime Picker (unspecified = date and time)" isMonthPickerVisible={false} showSeconds={false} onChange={(value) => console.log("DateTimePicker value:", value)} placeholder="Pick a date" /> <DateTimePicker label="DateTime Picker 12-hour clock" showSeconds={true} onChange={(value) => console.log("DateTimePicker value:", value)} timeDisplayControlType={TimeDisplayControlType.Dropdown} minutesIncrementStep={15} /> <DateTimePicker label="DateTime Picker 24-hour clock" showSeconds={true} timeConvention={TimeConvention.Hours24} onChange={(value) => console.log("DateTimePicker value:", value)} /> <DateTimePicker label="DateTime Picker no seconds" value={new Date()} onChange={(value) => console.log("DateTimePicker value:", value)} /> <DateTimePicker label="DateTime Picker (unspecified = date and time)" timeConvention={TimeConvention.Hours24} value={new Date()} onChange={(value) => console.log("DateTimePicker value:", value)} /> <DateTimePicker label="DateTime Picker dropdown" showSeconds={true} timeDisplayControlType={TimeDisplayControlType.Dropdown} value={new Date()} onChange={(value) => console.log("DateTimePicker value:", value)} /> <DateTimePicker label="DateTime Picker date only" showLabels={false} dateConvention={DateConvention.Date} value={new Date()} onChange={(value) => console.log("DateTimePicker value:", value)} minDate={new Date("05/01/2019")} maxDate={new Date("05/01/2020")} /> {/* <RichText isEditMode={this.props.displayMode === DisplayMode.Edit} onChange={value => { this.richTextValue = value; return value; }} /> */} <RichText value={this.state.richTextValue} isEditMode={this.props.displayMode === DisplayMode.Edit} onChange={value => { this.setState({ richTextValue: value }); return value; }} /> <PrimaryButton text='Reset text' onClick={() => { this.setState({ richTextValue: 'test' }); }} /> {/* <ListItemAttachments listId='0ffa51d7-4ad1-4f04-8cfe-98209905d6da' itemId={1} context={this.props.context} disabled={false} /> */} <Placeholder iconName='Edit' iconText='Configure your web part' description={defaultClassNames => <span className={defaultClassNames}>Please configure the web part.</span>} buttonLabel='Configure' hideButton={this.props.displayMode === DisplayMode.Read} onConfigure={this._onConfigure} /> <PeoplePicker context={this.props.context} titleText="People Picker custom styles" styles={this.pickerStylesSingle} personSelectionLimit={5} ensureUser={true} principalTypes={[PrincipalType.User, PrincipalType.SharePointGroup, PrincipalType.SecurityGroup, PrincipalType.DistributionList]} onChange={this._getPeoplePickerItems} /> <PeoplePicker context={this.props.context} titleText="People Picker (Group not found)" webAbsoluteUrl={this.props.context.pageContext.site.absoluteUrl} groupName="Team Site Visitors 123" ensureUser={true} principalTypes={[PrincipalType.User, PrincipalType.SharePointGroup, PrincipalType.SecurityGroup, PrincipalType.DistributionList]} defaultSelectedUsers={["admin@tenant.onmicrosoft.com", "test@tenant.onmicrosoft.com"]} onChange={this._getPeoplePickerItems} /> <PeoplePicker context={this.props.context} titleText="People Picker (search for group)" groupName="Team Site Visitors" principalTypes={[PrincipalType.User, PrincipalType.SharePointGroup, PrincipalType.SecurityGroup, PrincipalType.DistributionList]} defaultSelectedUsers={["admin@tenant.onmicrosoft.com", "test@tenant.onmicrosoft.com"]} onChange={this._getPeoplePickerItems} /> <PeoplePicker context={this.props.context} titleText="People Picker (pre-set global users)" principalTypes={[PrincipalType.User, PrincipalType.SharePointGroup, PrincipalType.SecurityGroup, PrincipalType.DistributionList]} defaultSelectedUsers={["admin@tenant.onmicrosoft.com", "test@tenant.onmicrosoft.com"]} onChange={this._getPeoplePickerItems} personSelectionLimit={2} ensureUser={true} /> <PeoplePicker context={this.props.context} titleText="People Picker (pre-set local users)" webAbsoluteUrl={this.props.context.pageContext.site.absoluteUrl} principalTypes={[PrincipalType.User, PrincipalType.SharePointGroup, PrincipalType.SecurityGroup, PrincipalType.DistributionList]} defaultSelectedUsers={["admin@tenant.onmicrosoft.com", "test@tenant.onmicrosoft.com"]} onChange={this._getPeoplePickerItems} /> <PeoplePicker context={this.props.context} titleText="People Picker (tenant scoped)" personSelectionLimit={5} // groupName={"Team Site Owners"} showtooltip={true} required={true} //defaultSelectedUsers={["tenantUser@domain.onmicrosoft.com", "test@user.com"]} //defaultSelectedUsers={this.state.authorEmails} onChange={this._getPeoplePickerItems} showHiddenInUI={false} principalTypes={[PrincipalType.User, PrincipalType.SharePointGroup, PrincipalType.SecurityGroup, PrincipalType.DistributionList]} suggestionsLimit={2} resolveDelay={200} placeholder={'Select a SharePoint principal (User or Group)'} onGetErrorMessage={async (items: any[]) => { if (!items || items.length < 2) { return 'error'; } return ''; }} /> <PeoplePicker context={this.props.context} titleText="People Picker (local scoped)" webAbsoluteUrl={this.props.context.pageContext.site.absoluteUrl} personSelectionLimit={5} // groupName={"Team Site Owners"} showtooltip={true} required={true} //defaultSelectedUsers={["tenantUser@domain.onmicrosoft.com", "test@user.com"]} //defaultSelectedUsers={this.state.authorEmails} onChange={this._getPeoplePickerItems} showHiddenInUI={false} principalTypes={[PrincipalType.User, PrincipalType.SharePointGroup, PrincipalType.SecurityGroup, PrincipalType.DistributionList]} suggestionsLimit={2} resolveDelay={200} /> <PeoplePicker context={this.props.context} titleText="People Picker (disabled)" disabled={true} showtooltip={true} defaultSelectedUsers={['aleksei.dovzhyk@sharepointalist.com']} /> <DateTimePicker label="DateTime Picker (unspecified = date and time)" /> <DateTimePicker label="DateTime Picker (unspecified = date and time, no seconds)" /> <DateTimePicker label="DateTime Picker (date and time - default time = 12h)" dateConvention={DateConvention.DateTime} showSeconds={true} /> <DateTimePicker label="DateTime Picker (date and time - 12h)" dateConvention={DateConvention.DateTime} timeConvention={TimeConvention.Hours12} showSeconds={false} /> <DateTimePicker label="DateTime Picker (date and time - 24h)" dateConvention={DateConvention.DateTime} timeConvention={TimeConvention.Hours24} firstDayOfWeek={DayOfWeek.Monday} showSeconds={true} /> <DateTimePicker label="DateTime Picker (Controlled)" formatDate={d => `${d.getFullYear()} - ${d.getMonth() + 1} - ${d.getDate()}`} dateConvention={DateConvention.DateTime} timeConvention={TimeConvention.Hours24} firstDayOfWeek={DayOfWeek.Monday} value={this.state.dateTimeValue} onChange={this._onDateTimePickerChange} isMonthPickerVisible={false} showMonthPickerAsOverlay={true} showWeekNumbers={true} showSeconds={true} timeDisplayControlType={TimeDisplayControlType.Dropdown} /> <PrimaryButton text={'Clear Date'} onClick={() => { this.setState({ dateTimeValue: undefined }); }} /> <DateTimePicker label="DateTime Picker (date only)" dateConvention={DateConvention.Date} /> <DateTimePicker label="DateTime Picker (disabled)" disabled={true} /> <br></br> <b>Drag and Drop Files</b> <DragDropFiles dropEffect="copy" enable={true} onDrop={this._getDropFiles} iconName="Upload" labelMessage="My custom upload File" > <Placeholder iconName='BulkUpload' iconText='Drag files or folder with files here...' description={defaultClassNames => <span className={defaultClassNames}>Drag files or folder with files here...</span>} buttonLabel='Configure' hideButton={this.props.displayMode === DisplayMode.Read} onConfigure={this._onConfigure} /> </DragDropFiles> <br></br> <ListView items={this.state.items} viewFields={viewFields} iconFieldName='ServerRelativeUrl' groupByFields={groupByFields} compact={true} selectionMode={SelectionMode.single} selection={this._getSelection} showFilter={true} dragDropFiles={true} onDrop={this._getDropFiles} stickyHeader={true} className={styles.listViewWrapper} // defaultFilter="Team" /> <ChartControl type={ChartType.Bar} data={{ labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255,99,132,1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }} options={{ scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }} /> <Map titleText="New map control" coordinates={{ latitude: 51.507351, longitude: -0.127758 }} enableSearch={true} mapType={MapType.normal} onUpdateCoordinates={(coordinates) => console.log("Updated location:", coordinates)} // zoom={15} //mapType={MapType.cycle} //width="50" //height={150} //loadingMessage="Loading maps" //errorMessage="Hmmm, we do not have maps for Mars yet. Working on it..." /> <div className={styles.container}> <div className={`ms-Grid-row ms-bgColor-neutralLight ms-fontColor-neutralDark ${styles.row}`}> <div className="ms-Grid-col ms-lg10 ms-xl8 ms-xlPush2 ms-lgPush1"> <span className="ms-font-xl">Controls testing</span> <SecurityTrimmedControl context={this.props.context} level={PermissionLevel.currentWeb} permissions={[SPPermission.viewListItems]} className={"TestingClass"} noPermissionsControl={<p>You do not have permissions.</p>}> <p>You have permissions to view list items.</p> </SecurityTrimmedControl> <p className="ms-font-l"> File type icon control </p> <div className="ms-font-m"> Font icons:&nbsp; <FileTypeIcon type={IconType.font} path="https://contoso.sharepoint.com/documents/filename.docx" />&nbsp; <FileTypeIcon type={IconType.font} path="https://contoso.sharepoint.com/documents/filename.unknown" />&nbsp; <FileTypeIcon type={IconType.font} path="https://contoso.sharepoint.com/documents/filename.doc" />&nbsp; <FileTypeIcon type={IconType.font} application={ApplicationType.HTML} />&nbsp; <FileTypeIcon type={IconType.font} application={ApplicationType.Mail} />&nbsp; <FileTypeIcon type={IconType.font} application={ApplicationType.SASS} /> </div> <div className="ms-font-m"> Image icons:&nbsp; <FileTypeIcon type={IconType.image} path="https://contoso.sharepoint.com/documents/filename.docx" />&nbsp; <FileTypeIcon type={IconType.image} path="https://contoso.sharepoint.com/documents/filename.unknown" />&nbsp; <FileTypeIcon type={IconType.image} path="https://contoso.sharepoint.com/documents/filename.pptx?querystring='prop1'&amp;prop2='test'" /> &nbsp; <FileTypeIcon type={IconType.image} application={ApplicationType.Word} />&nbsp; <FileTypeIcon type={IconType.image} application={ApplicationType.PDF} />&nbsp; <FileTypeIcon type={IconType.image} path="https://contoso.sharepoint.com/documents/filename.pdf" /> </div> <div className="ms-font-m">Icon size tester: <Dropdown options={sizeOptions} onChanged={this._onIconSizeChange} /> <FileTypeIcon type={IconType.image} size={this.state.imgSize} application={ApplicationType.Excel} /> <FileTypeIcon type={IconType.image} size={this.state.imgSize} application={ApplicationType.PDF} /> <FileTypeIcon type={IconType.image} size={this.state.imgSize} /> </div> <div className="ms-font-m">Site picker tester: <SitePicker context={this.props.context} label={'select sites'} mode={'site'} allowSearch={true} multiSelect={false} onChange={(sites) => { console.log(sites); }} placeholder={'Select sites'} searchPlaceholder={'Filter sites'} /> </div> <div className="ms-font-m">List picker tester: <ListPicker context={this.props.context} label="Select your list(s)" placeholder="Select your list(s)" baseTemplate={100} includeHidden={false} multiSelect={true} contentTypeId="0x01" // filter="Title eq 'Test List'" onSelectionChanged={this.onListPickerChange} /> </div> <div className="ms-font-m">List Item picker list data tester: <ListItemPicker listId={'76a8231b-35b6-4703-b1f4-5d03d3dfb1ca'} columnInternalName="Title" keyColumnInternalName="Id" filter={"Title eq 'SPFx'"} orderBy={'Title desc'} itemLimit={5} context={this.props.context} placeholder={'Select list items'} onSelectedItem={this.listItemPickerDataSelected} /> </div> <div>Icon Picker</div> <div> <IconPicker renderOption="panel" onSave={(value) => { console.log(value); }} currentIcon={'Warning'} buttonLabel="Icon Picker"> </IconPicker> </div> <div className="ms-font-m">ComboBoxListItemPicker: <ComboBoxListItemPicker listId={this.state.comboBoxListItemPickerListId} columnInternalName='Title' keyColumnInternalName='Id' orderBy='Title desc' multiSelect={true} onSelectedItem={(data) => { console.log(`Item(s):`, data); }} defaultSelectedItems={this.state.comboBoxListItemPickerIds} webUrl={this.props.context.pageContext.web.absoluteUrl} spHttpClient={this.props.context.spHttpClient} /> <PrimaryButton text="Change List" onClick={() => { this.setState({ comboBoxListItemPickerListId: '71210430-8436-4962-a14d-5525475abd6b' }); }} /> <PrimaryButton text="Change default items" onClick={() => { this.setState({ comboBoxListItemPickerIds: [{ Id: 2, Title: '222' }] }); }} /> </div> <div className="ms-font-m">iframe dialog tester: <PrimaryButton text="Open iframe Dialog" onClick={() => { this.setState({ iFrameDialogOpened: true }); }} /> <IFrameDialog url={iframeUrl} iframeOnLoad={(iframe: any) => { console.log('iframe loaded'); }} hidden={!this.state.iFrameDialogOpened} onDismiss={() => { this.setState({ iFrameDialogOpened: false }); }} modalProps={{ isBlocking: true, styles: { root: { backgroundColor: '#00ff00' }, main: { backgroundColor: '#ff0000' } } }} dialogContentProps={{ type: DialogType.close, showCloseButton: true }} width={'570px'} height={'315px'} /> </div> <div className="ms-font-m">iframe Panel tester: <PrimaryButton text="Open iframe Panel" onClick={() => { this.setState({ iFramePanelOpened: true }); }} /> <IFramePanel url={iframeUrl} type={PanelType.medium} // height="300px" headerText="iframe panel title" closeButtonAriaLabel="Close" isOpen={this.state.iFramePanelOpened} onDismiss={() => { this.setState({ iFramePanelOpened: false }); }} iframeOnLoad={(iframe: any) => { console.log('iframe loaded'); }} /> </div> <div> <FolderPicker context={this.props.context} rootFolder={{ Name: 'Documents', ServerRelativeUrl: `${this.props.context.pageContext.web.serverRelativeUrl === '/' ? '' : this.props.context.pageContext.web.serverRelativeUrl}/Shared Documents` }} onSelect={this._onFolderSelect} label='Folder Picker' required={true} canCreateFolders={true} ></FolderPicker> </div> </div> </div> </div> <div> <h3>Carousel with fixed elements:</h3> <Carousel buttonsLocation={CarouselButtonsLocation.top} buttonsDisplay={CarouselButtonsDisplay.block} contentContainerStyles={styles.carouselContent} containerButtonsStyles={styles.carouselButtonsContainer} isInfinite={true} element={this.carouselElements} onMoveNextClicked={(index: number) => { console.log(`Next button clicked: ${index}`); }} onMovePrevClicked={(index: number) => { console.log(`Prev button clicked: ${index}`); }} /> </div> <div> <h3>Carousel with CarouselImage elements:</h3> <Carousel buttonsLocation={CarouselButtonsLocation.center} buttonsDisplay={CarouselButtonsDisplay.buttonsOnly} contentContainerStyles={styles.carouselImageContent} //containerButtonsStyles={styles.carouselButtonsContainer} isInfinite={true} indicatorShape={CarouselIndicatorShape.circle} indicatorsDisplay={CarouselIndicatorsDisplay.block} pauseOnHover={true} element={[ { imageSrc: 'https://images.unsplash.com/photo-1588614959060-4d144f28b207?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=3078&q=80', title: 'Colosseum', description: 'This is Colosseum', url: 'https://en.wikipedia.org/wiki/Colosseum', showDetailsOnHover: true, imageFit: ImageFit.cover }, { imageSrc: 'https://www.telegraph.co.uk/content/dam/science/2018/06/20/stonehenge-2326750_1920_trans%2B%2BZgEkZX3M936N5BQK4Va8RWtT0gK_6EfZT336f62EI5U.jpg', title: 'Stonehenge', description: 'This is Stonehendle', url: 'https://en.wikipedia.org/wiki/Stonehenge', showDetailsOnHover: true, imageFit: ImageFit.cover }, { imageSrc: 'https://upload.wikimedia.org/wikipedia/commons/thumb/a/af/All_Gizah_Pyramids.jpg/2560px-All_Gizah_Pyramids.jpg', title: 'Pyramids of Giza', description: 'This are Pyramids of Giza (Egypt)', url: 'https://en.wikipedia.org/wiki/Egyptian_pyramids', showDetailsOnHover: true, imageFit: ImageFit.cover } ]} onMoveNextClicked={(index: number) => { console.log(`Next button clicked: ${index}`); }} onMovePrevClicked={(index: number) => { console.log(`Prev button clicked: ${index}`); }} rootStyles={mergeStyles({ backgroundColor: '#C3C3C3' })} /> </div> <div> <h3>Carousel with triggerPageElement:</h3> <Carousel buttonsLocation={CarouselButtonsLocation.bottom} buttonsDisplay={CarouselButtonsDisplay.buttonsOnly} contentContainerStyles={styles.carouselContent} canMoveNext={this.state.canMoveNext} canMovePrev={this.state.canMovePrev} triggerPageEvent={this.triggerNextElement} element={this.state.currentCarouselElement} /> </div> <div className={styles.siteBreadcrumb}> <SiteBreadcrumb context={this.props.context} /> </div> <div> <h3>File Picker</h3> <TextField label="Default SiteFileTab Folder" onChange={debounce((ev, newVal) => { this.setState({ filePickerDefaultFolderAbsolutePath: newVal }); }, 500)} styles={{ root: { marginBottom: 10 } }} /> <FilePicker bingAPIKey="<BING API KEY>" defaultFolderAbsolutePath={this.state.filePickerDefaultFolderAbsolutePath} //accepts={[".gif", ".jpg", ".jpeg", ".bmp", ".dib", ".tif", ".tiff", ".ico", ".png", ".jxr", ".svg"]} buttonLabel="Add File" buttonIconProps={{ iconName: 'Add', styles: { root: { fontSize: 42 } } }} onSave={this._onFilePickerSave} onChange={(filePickerResult: IFilePickerResult[]) => { console.log(filePickerResult); }} context={this.props.context} hideRecentTab={false} includePageLibraries={true} /> { this.state.filePickerResult && <div> <div> FileName: {this.state.filePickerResult[0].fileName} </div> <div> File size: {this.state.filePickerResult[0].fileSize} </div> </div> } </div> <div> <h3>File Picker with target folder browser</h3> <FilePicker bingAPIKey="<BING API KEY>" //accepts={[".gif", ".jpg", ".jpeg", ".bmp", ".dib", ".tif", ".tiff", ".ico", ".png", ".jxr", ".svg"]} buttonLabel="Upload image" buttonIcon="FileImage" onSave={this._onFilePickerSave} onChange={(filePickerResult: IFilePickerResult[]) => { console.log(filePickerResult); }} context={this.props.context} hideRecentTab={false} renderCustomUploadTabContent={() => ( <FolderExplorer context={this.props.context} rootFolder={this.rootFolder} defaultFolder={this.rootFolder} onSelect={this._onFolderSelect} canCreateFolders={true} />)} /> </div> <p><a href="javascript:;" onClick={this.deleteItem}>Deletes second item</a></p> <div> <Progress title={'Progress Test'} showOverallProgress={true} showIndeterminateOverallProgress={false} hideNotStartedActions={false} actions={this.state.progressActions} currentActionIndex={this.state.currentProgressActionIndex} longRunningText={'This operation takes longer than expected'} longRunningTextDisplayDelay={7000} height={'350px'} inProgressIconName={'ChromeBackMirrored'} /> <PrimaryButton text={'Start Progress'} onClick={this._startProgress} /> </div> <div className="ms-font-l">Grid Layout</div> <GridLayout ariaLabel={"List of content, use right and left arrow keys to navigate, arrow down to access details."} items={sampleGridData} onRenderGridItem={(item: any, finalSize: ISize, isCompact: boolean) => this._onRenderGridItem(item, finalSize, isCompact)} /> <IconPicker buttonLabel={'Icon'} onChange={(iconName: string) => { console.log(iconName); }} onCancel={() => { console.log("Panel closed"); }} onSave={(iconName: string) => { console.log(iconName); }} /> <div> <FolderExplorer context={this.props.context} rootFolder={{ Name: 'Documents', ServerRelativeUrl: `${this.props.context.pageContext.web.serverRelativeUrl === '/' ? '' : this.props.context.pageContext.web.serverRelativeUrl}/Shared Documents` }} defaultFolder={{ Name: 'Documents', ServerRelativeUrl: `${this.props.context.pageContext.web.serverRelativeUrl === '/' ? '' : this.props.context.pageContext.web.serverRelativeUrl}/Shared Documents` }} onSelect={this._onFolderSelect} canCreateFolders={true} orderby='Name' //'ListItemAllFields/Created' orderAscending={true} /> </div> <div> <h3>Tree View</h3> <TreeView items={this.treeitems} defaultExpanded={false} selectionMode={TreeViewSelectionMode.Multiple} showCheckboxes={true} treeItemActionsDisplayMode={TreeItemActionsDisplayMode.ContextualMenu} defaultSelectedKeys={this.state.treeViewSelectedKeys} onExpandCollapse={this.onExpandCollapseTree} onSelect={this.onItemSelected} defaultExpandedChildren={true} //expandToSelected={true} // onRenderItem={this.renderCustomTreeItem} /> <PrimaryButton onClick={() => { this.setState({ treeViewSelectedKeys: [] }); }}>Clear selection</PrimaryButton> </div> <div> <Pagination currentPage={3} onChange={(page) => (this._getPage(page))} totalPages={this.props.totalPages || 13} //limiter={3} // hideFirstPageJump //hideLastPageJump //limiterIcon={"NumberedListText"} /> </div> <div> <FieldCollectionData key={"FieldCollectionData"} label={"Fields Collection"} itemsPerPage={3} manageBtnLabel={"Manage"} onChanged={(value) => { console.log(value); }} panelHeader={"Manage values"} enableSorting={true} fields={[ { id: "Field1", title: "String field", type: CustomCollectionFieldType.string, required: true }, { id: "Field2", title: "Number field", type: CustomCollectionFieldType.number }, { id: "Field3", title: "URL field", type: CustomCollectionFieldType.url }, { id: "Field4", title: "Boolean field", type: CustomCollectionFieldType.boolean }, ]} value={this.getRandomCollectionFieldData()} /> </div> <Dashboard widgets={[{ title: "Card 1", desc: "Last updated Monday, April 4 at 11:15 AM (PT)", widgetActionGroup: calloutItemsExample, size: WidgetSize.Triple, body: [ { id: "t1", title: "Tab 1", content: ( <Flex vAlign="center" hAlign="center" styles={{ height: "100%", border: "1px dashed rgb(179, 176, 173)" }} > <NorthstarText size="large" weight="semibold"> Content #1 </NorthstarText> </Flex> ), }, { id: "t2", title: "Tab 2", content: ( <Flex vAlign="center" hAlign="center" styles={{ height: "100%", border: "1px dashed rgb(179, 176, 173)" }} > <NorthstarText size="large" weight="semibold"> Content #2 </NorthstarText> </Flex> ), }, { id: "t3", title: "Tab 3", content: ( <Flex vAlign="center" hAlign="center" styles={{ height: "100%", border: "1px dashed rgb(179, 176, 173)" }} > <NorthstarText size="large" weight="semibold"> Content #3 </NorthstarText> </Flex> ), }, ], link: linkExample, }, { title: "Card 2", size: WidgetSize.Single, link: linkExample, }, { title: "Card 3", size: WidgetSize.Double, link: linkExample, }, { title: "Card 4", size: WidgetSize.Single, link: linkExample, }, { title: "Card 5", size: WidgetSize.Single, link: linkExample, }, { title: "Card 6", size: WidgetSize.Single, link: linkExample, }]} /> <Toolbar actionGroups={{ 'group1': { 'action1': { title: 'Edit', iconName: 'Edit', onClick: () => { console.log('Edit action click'); } }, 'action2': { title: 'New', iconName: 'Add', onClick: () => { console.log('New action click'); } } } }} /> <div> <h3>Animated Dialogs</h3> {/* Multiple elements added only for demo - can be controlled with fewer elements */} <PrimaryButton text='Show animated dialog' onClick={() => { this.setState({ showAnimatedDialog: true }); }} /> {/* Normal animated dialog */} <AnimatedDialog hidden={!this.state.showAnimatedDialog} onDismiss={() => { this.setState({ showAnimatedDialog: false }); }} dialogContentProps={animatedDialogContentProps} modalProps={animatedModalProps} > <DialogFooter> <PrimaryButton onClick={() => { this.setState({ showAnimatedDialog: false }); }} text="Yes" /> <DefaultButton onClick={() => { this.setState({ showAnimatedDialog: false }); }} text="No" /> </DialogFooter> </AnimatedDialog> <br /> <br /> <PrimaryButton text='Show animated dialog with icon' onClick={() => { this.setState({ showCustomisedAnimatedDialog: true }); }} /> {/* Animated dialog with icon */} <AnimatedDialog hidden={!this.state.showCustomisedAnimatedDialog} onDismiss={() => { this.setState({ showCustomisedAnimatedDialog: false }); }} dialogContentProps={customizedAnimatedDialogContentProps} modalProps={customizedAnimatedModalProps} dialogAnimationInType='fadeInDown' dialogAnimationOutType='fadeOutDown' iconName='UnknownSolid' iconAnimationType='zoomInDown' showAnimatedDialogFooter={true} okButtonText="Yes" cancelButtonText="No" onOkClick={() => timeout(1500)} onSuccess={() => { this.setState({ showCustomisedAnimatedDialog: false }); this.setState({ showSuccessDialog: true }); }} onError={() => { this.setState({ showCustomisedAnimatedDialog: false }); this.setState({ showErrorDialog: true }); }}> <div className={styles.dialogContent}> <span>Do you like the animated dialog?</span> </div> </AnimatedDialog> {/* Success animated dialog */} <AnimatedDialog hidden={!this.state.showSuccessDialog} onDismiss={() => { this.setState({ showSuccessDialog: false }); }} dialogContentProps={successDialogContentProps} modalProps={customizedAnimatedModalProps} iconName='CompletedSolid' > <div className={styles.dialogContent}><span>Thank you.</span></div> <div className={styles.dialogFooter}> <PrimaryButton onClick={() => { this.setState({ showSuccessDialog: false }); }} text="OK" > </PrimaryButton> </div> </AnimatedDialog> {/* Error animated dialog */} <AnimatedDialog hidden={!this.state.showErrorDialog} onDismiss={() => { this.setState({ showErrorDialog: false }); }} dialogContentProps={errorDialogContentProps} modalProps={customizedAnimatedModalProps} iconName='StatusErrorFull' > <div className={styles.dialogContent}><span>Ther was an error.</span></div> <div className={styles.dialogFooter}> <PrimaryButton onClick={() => { this.setState({ showErrorDialog: false }); }} text="OK" > </PrimaryButton> </div> </AnimatedDialog> <LocationPicker context={this.props.context} label="Location" onChange={(locValue: ILocationPickerItem) => { console.log(locValue.DisplayName + ", " + locValue.Address.Street); }}></LocationPicker> <ModernTaxonomyPicker allowMultipleSelections={true} termSetId={"7b84b0b6-50b8-4d26-8098-029eba42fe8a"} panelTitle="Panel title" label={"Modern Taxonomy Picker"} context={this.props.context} required={false} disabled={false} customPanelWidth={400} /> </div> </div> ); } private getRandomCollectionFieldData = () => { let result = []; for (let i = 1; i < 16; i++) { result.push({ "Field1": `String${i}`, "Field2": i, "Field3": "https://pnp.github.io/", "Field4": true }); } return result; } private onExpandCollapseTree(item: ITreeItem, isExpanded: boolean) { console.log((isExpanded ? "item expanded: " : "item collapsed: ") + item); } private onItemSelected(items: ITreeItem[]) { console.log("items selected: " + items.length); } private renderCustomTreeItem(item: ITreeItem): JSX.Element { return ( <span> { item.iconProps && <i className={"ms-Icon ms-Icon--" + item.iconProps.iconName} style={{ paddingRight: '4px' }} /> } {item.label} </span> ); } private _getPage(page: number) { console.log('Page:', page); } // private _onFolderSelect = (folder: IFolder): void => { // console.log('selected folder', folder); // } }
the_stack
import chai, { expect } from 'chai'; import fs from 'fs-extra'; import * as path from 'path'; import Helper from '../../src/e2e-helper/e2e-helper'; import * as fixtures from '../../src/fixtures/fixtures'; import NpmCiRegistry, { supportNpmCiRegistryTesting } from '../npm-ci-registry'; chai.use(require('chai-fs')); describe('custom module resolutions', function () { this.timeout(0); let helper: Helper; before(() => { helper = new Helper(); helper.command.setFeatures('legacy-workspace-config'); }); after(() => { helper.scopeHelper.destroy(); }); describe('using custom module directory', () => { before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); const bitJson = helper.bitJson.read(); bitJson.resolveModules = { modulesDirectories: ['src'] }; helper.bitJson.write(bitJson); helper.fs.createFile('src/utils', 'is-type.js', fixtures.isType); const isStringFixture = "const isType = require('utils/is-type'); module.exports = function isString() { return isType() + ' and got is-string'; };"; const barFooFixture = "const isString = require('utils/is-string'); module.exports = function foo() { return isString() + ' and got foo'; };"; helper.fs.createFile('src/utils', 'is-string.js', isStringFixture); helper.fs.createFile('src/bar', 'foo.js', barFooFixture); helper.command.addComponent('src/utils/is-type.js', { i: 'utils/is-type' }); helper.command.addComponent('src/utils/is-string.js', { i: 'utils/is-string' }); helper.command.addComponent('src/bar/foo.js', { i: 'bar/foo' }); }); it('bit status should not warn about missing packages', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('missing'); }); it('bit show should show the dependencies correctly', () => { const output = helper.command.showComponentParsed('bar/foo'); expect(output.dependencies).to.have.lengthOf(1); const dependency = output.dependencies[0]; expect(dependency.id).to.equal('utils/is-string'); expect(dependency.relativePaths[0].sourceRelativePath).to.equal('src/utils/is-string.js'); expect(dependency.relativePaths[0].destinationRelativePath).to.equal('src/utils/is-string.js'); expect(dependency.relativePaths[0].importSource).to.equal('utils/is-string'); expect(dependency.relativePaths[0].isCustomResolveUsed).to.be.true; }); describe('isolation the component using the capsule', () => { let capsuleDir; before(() => { capsuleDir = helper.general.generateRandomTmpDirName(); helper.command.runCmd(`bit isolate bar/foo --use-capsule --directory ${capsuleDir}`); }); it('should not delete the dependencies file paths', () => { const packageJson = helper.packageJson.read(capsuleDir); expect(packageJson.dependencies) .to.have.property('@bit/utils.is-string') .that.equal(path.normalize('file:.dependencies/utils/is-string')); expect(packageJson.dependencies) .to.have.property('@bit/utils.is-type') .that.equal(path.normalize('file:.dependencies/utils/is-type')); }); }); describe('importing the component', () => { before(() => { helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), fixtures.appPrintBarFoo); }); it('should generate the non-relative links correctly', () => { const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); it('should not show the component as modified', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('modified'); }); it('should add the resolve aliases mapping into package.json for the pnp feature', () => { const packageJson = helper.packageJson.read(path.join(helper.scopes.localPath, 'components/bar/foo')); expect(packageJson).to.have.property('bit'); expect(packageJson.bit).to.have.property('resolveAliases'); expect(packageJson.bit.resolveAliases).to.have.property('utils/is-string'); expect(packageJson.bit.resolveAliases['utils/is-string']).to.equal( `@bit/${helper.scopes.remote}.utils.is-string` ); }); describe('importing the component using isolated environment', () => { let isolatePath; before(() => { isolatePath = helper.command.isolateComponent('bar/foo', '-olws'); }); it('should be able to generate the links correctly and require the dependencies', () => { const appJsFixture = `const barFoo = require('./'); console.log(barFoo());`; helper.command.runCmd('npm run postinstall', isolatePath); const isStringPath = path.join( isolatePath, 'node_modules', '@bit', `${helper.scopes.remote}.utils.is-string` ); helper.command.runCmd('npm run postinstall', isStringPath); fs.outputFileSync(path.join(isolatePath, 'app.js'), appJsFixture); const result = helper.command.runCmd('node app.js', isolatePath); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); }); describe('npm packing the component using an extension pack', () => { let packDir; let untarDir; before(() => { packDir = path.join(helper.scopes.localPath, 'pack'); untarDir = path.join(packDir, 'package'); const componentId = `${helper.scopes.remote}/bar/foo`; const options = { d: packDir, }; helper.command.packComponent(componentId, options, true); }); it('should create the specified directory', () => { expect(untarDir).to.be.a.path(); }); it('should generate .bit.postinstall.js file', () => { expect(path.join(untarDir, '.bit.postinstall.js')).to.be.a.file(); }); it('should add the postinstall script to the package.json file', () => { const packageJson = helper.packageJson.read(untarDir); expect(packageJson).to.have.property('scripts'); expect(packageJson.scripts).to.have.property('postinstall'); expect(packageJson.scripts.postinstall).to.equal('node .bit.postinstall.js'); }); it('should add the resolve aliases mapping into package.json for the pnp feature', () => { const packageJson = helper.packageJson.read(untarDir); expect(packageJson).to.have.property('bit'); expect(packageJson.bit).to.have.property('resolveAliases'); expect(packageJson.bit.resolveAliases).to.have.property('utils/is-string'); expect(packageJson.bit.resolveAliases['utils/is-string']).to.equal( `@bit/${helper.scopes.remote}.utils.is-string` ); }); }); }); }); describe('using custom module directory when two files in the same component requires each other', () => { describe('with dependencies', () => { before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); const bitJson = helper.bitJson.read(); bitJson.resolveModules = { modulesDirectories: ['src'] }; helper.bitJson.write(bitJson); helper.fs.createFile('src/utils', 'is-type.js', fixtures.isType); const isStringFixture = "const isType = require('utils/is-type');\n module.exports = function isString() { return isType() + ' and got is-string'; };"; const barFooFixture = "const isString = require('utils/is-string');\n module.exports = function foo() { return isString() + ' and got foo'; };"; helper.fs.createFile('src/utils', 'is-string.js', isStringFixture); helper.fs.createFile('src/bar', 'foo.js', barFooFixture); helper.command.addComponent('src/utils/is-type.js', { i: 'utils/is-type' }); helper.command.addComponent('src/bar/foo.js src/utils/is-string.js', { i: 'bar/foo', m: 'src/bar/foo.js', }); }); it('bit status should not warn about missing packages', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('missing'); }); it('bit show should show the dependencies correctly', () => { const output = helper.command.showComponentParsed('bar/foo'); expect(output.dependencies).to.have.lengthOf(1); const dependency = output.dependencies[0]; expect(dependency.id).to.equal('utils/is-type'); expect(dependency.relativePaths[0].sourceRelativePath).to.equal('src/utils/is-type.js'); expect(dependency.relativePaths[0].destinationRelativePath).to.equal('src/utils/is-type.js'); expect(dependency.relativePaths[0].importSource).to.equal('utils/is-type'); expect(dependency.relativePaths[0].isCustomResolveUsed).to.be.true; }); describe('importing the component', () => { before(() => { helper.command.tagAllComponents(); // an intermediate step, make sure it saves the customResolvedPaths in the model const catComponent = helper.command.catComponent('bar/foo@latest'); expect(catComponent).to.have.property('customResolvedPaths'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(catComponent.customResolvedPaths[0].destinationPath).to.equal('src/utils/is-string.js'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(catComponent.customResolvedPaths[0].importSource).to.equal('utils/is-string'); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), fixtures.appPrintBarFoo); }); it('should generate the non-relative links correctly', () => { const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); it('should not show the component as modified', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('modified'); }); }); }); describe('without dependencies', () => { before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); const bitJson = helper.bitJson.read(); bitJson.resolveModules = { modulesDirectories: ['src'] }; helper.bitJson.write(bitJson); helper.fs.createFile('src/utils', 'is-type.js', fixtures.isType); const isStringFixture = "const isType = require('utils/is-type');\n module.exports = function isString() { return isType() + ' and got is-string'; };"; const barFooFixture = "const isString = require('utils/is-string');\n module.exports = function foo() { return isString() + ' and got foo'; };"; helper.fs.createFile('src/utils', 'is-string.js', isStringFixture); helper.fs.createFile('src/bar', 'foo.js', barFooFixture); helper.command.addComponent('src', { i: 'bar/foo', m: 'src/bar/foo.js' }); helper.command.tagAllComponents(); }); it('bit status should not warn about missing packages', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('missing'); }); it('should show the customResolvedPaths correctly', () => { const barFoo = helper.command.catComponent('bar/foo@latest'); expect(barFoo).to.have.property('customResolvedPaths'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(barFoo.customResolvedPaths).to.have.lengthOf(2); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(barFoo.customResolvedPaths).to.deep.include({ destinationPath: 'src/utils/is-string.js', importSource: 'utils/is-string', }); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(barFoo.customResolvedPaths).to.deep.include({ destinationPath: 'src/utils/is-type.js', importSource: 'utils/is-type', }); }); describe('importing the component', () => { before(() => { helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), fixtures.appPrintBarFoo); }); it('should generate the non-relative links correctly', () => { const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); it('should not show the component as modified', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('modified'); }); describe('npm packing the component using an extension pack', () => { let packDir; let untarDir; before(() => { packDir = path.join(helper.scopes.localPath, 'pack'); untarDir = path.join(packDir, 'package'); const componentId = `${helper.scopes.remote}/bar/foo`; const options = { d: packDir, }; helper.command.packComponent(componentId, options, true); }); it('should create the specified directory', () => { expect(untarDir).to.be.a.path(); }); it('should generate .bit.postinstall.js file', () => { expect(path.join(untarDir, '.bit.postinstall.js')).to.be.a.file(); }); it('should add the postinstall script to the package.json file', () => { const packageJson = helper.packageJson.read(untarDir); expect(packageJson).to.have.property('scripts'); expect(packageJson.scripts).to.have.property('postinstall'); expect(packageJson.scripts.postinstall).to.equal('node .bit.postinstall.js'); }); it('npm install should create the custom-resolved dir inside node_modules', () => { helper.command.runCmd('npm i', untarDir); expect(path.join(untarDir, 'node_modules/utils/is-string.js')).to.be.a.file(); expect(path.join(untarDir, 'node_modules/utils/is-type.js')).to.be.a.file(); expect(() => helper.command.runCmd(`node ${untarDir}/bar/foo.js`)).to.not.throw(); }); it('should add the resolve aliases mapping into package.json for the pnp feature', () => { const packageJson = helper.packageJson.read(untarDir); const packageName = helper.general.getRequireBitPath('bar', 'foo'); expect(packageJson.bit.resolveAliases) .to.have.property('utils/is-string') .that.equal(`${packageName}/utils/is-string.js`); expect(packageJson.bit.resolveAliases) .to.have.property('utils/is-type') .that.equal(`${packageName}/utils/is-type.js`); }); }); }); }); // see https://github.com/teambit/bit/issues/2006 for a bug about it. describe('when one alias is a parent of another one', () => { before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); const bitJson = helper.bitJson.read(); bitJson.resolveModules = { aliases: { '@': 'src' } }; helper.bitJson.write(bitJson); helper.fs.createFile('src/utils', 'is-type.js', fixtures.isType); const isStringFixture = "const isType = require('@/utils/is-type');\n module.exports = function isString() { return isType() + ' and got is-string'; };"; const barFooFixture = "const isString = require('@/utils');\n module.exports = function foo() { return isString() + ' and got foo'; };"; const indexFixture = "module.exports = require('./is-string');"; helper.fs.createFile('src/utils', 'is-string.js', isStringFixture); helper.fs.createFile('src/utils', 'index.js', indexFixture); helper.fs.createFile('src/bar', 'foo.js', barFooFixture); helper.command.addComponent('src', { i: 'bar/foo', m: 'src/bar/foo.js' }); helper.command.tagAllComponents(); }); it('bit status should not warn about missing packages', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('missing'); }); it('should show the customResolvedPaths correctly', () => { const barFoo = helper.command.catComponent('bar/foo@latest'); expect(barFoo).to.have.property('customResolvedPaths'); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(barFoo.customResolvedPaths).to.have.lengthOf(2); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(barFoo.customResolvedPaths).to.deep.include({ destinationPath: 'src/utils/index.js', importSource: '@/utils', }); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! expect(barFoo.customResolvedPaths).to.deep.include({ destinationPath: 'src/utils/is-type.js', importSource: '@/utils/is-type', }); }); describe('importing the component', () => { before(() => { helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), fixtures.appPrintBarFoo); }); it('should generate the non-relative links correctly', () => { const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); it('should not show the component as modified', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('modified'); }); describe('npm packing the component using an extension pack', () => { let packDir; let untarDir; before(() => { packDir = path.join(helper.scopes.localPath, 'pack'); untarDir = path.join(packDir, 'package'); const componentId = `${helper.scopes.remote}/bar/foo`; const options = { d: packDir, }; helper.command.packComponent(componentId, options, true); }); it('should create the specified directory', () => { expect(untarDir).to.be.a.path(); }); it('should generate .bit.postinstall.js file', () => { expect(path.join(untarDir, '.bit.postinstall.js')).to.be.a.file(); }); it('should add the postinstall script to the package.json file', () => { const packageJson = helper.packageJson.read(untarDir); expect(packageJson).to.have.property('scripts'); expect(packageJson.scripts).to.have.property('postinstall'); expect(packageJson.scripts.postinstall).to.equal('node .bit.postinstall.js'); }); it('npm install should create the custom-resolved dir inside node_modules', () => { helper.command.runCmd('npm i', untarDir); expect(path.join(untarDir, 'node_modules/@/utils/index.js')).to.be.a.file(); expect(path.join(untarDir, 'node_modules/@/utils/is-type.js')).to.be.a.file(); expect(() => helper.command.runCmd(`node ${untarDir}/bar/foo.js`)).to.not.throw(); }); it('should add the resolve aliases mapping into package.json for the pnp feature', () => { const packageJson = helper.packageJson.read(untarDir); const packageName = helper.general.getRequireBitPath('bar', 'foo'); expect(packageJson.bit.resolveAliases) .to.have.property('@/utils') .that.equal(`${packageName}/utils/index.js`); expect(packageJson.bit.resolveAliases) .to.have.property('@/utils/is-type') .that.equal(`${packageName}/utils/is-type.js`); }); }); }); }); }); describe('using custom module directory when a component uses an internal file of another component', () => { let npmCiRegistry; before(() => { npmCiRegistry = new NpmCiRegistry(helper); helper.scopeHelper.setNewLocalAndRemoteScopes(); const bitJson = helper.bitJson.read(); bitJson.resolveModules = { modulesDirectories: ['src'] }; helper.bitJson.write(bitJson); npmCiRegistry.setCiScopeInBitJson(); helper.fs.createFile('src/utils', 'is-type.js', ''); helper.fs.createFile('src/utils', 'is-type-internal.js', fixtures.isType); helper.command.addComponent('src/utils/is-type.js src/utils/is-type-internal.js', { i: 'utils/is-type', m: 'src/utils/is-type.js', }); const isStringFixture = "const isType = require('utils/is-type-internal');\n module.exports = function isString() { return isType() + ' and got is-string'; };"; helper.fs.createFile('src/utils', 'is-string.js', ''); helper.fs.createFile('src/utils', 'is-string-internal.js', isStringFixture); helper.command.addComponent('src/utils/is-string.js src/utils/is-string-internal.js', { i: 'utils/is-string', m: 'src/utils/is-string.js', }); const barFooFixture = "const isString = require('utils/is-string-internal');\n module.exports = function foo() { return isString() + ' and got foo'; };"; helper.fs.createFile('src/bar', 'foo.js', barFooFixture); helper.command.addComponent('src/bar/foo.js', { i: 'bar/foo', m: 'src/bar/foo.js' }); }); it('bit status should not warn about missing packages', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('missing'); }); it('bit show should show the dependencies correctly', () => { const output = helper.command.showComponentParsed('bar/foo'); expect(output.dependencies).to.have.lengthOf(1); const dependency = output.dependencies[0]; expect(dependency.id).to.equal('utils/is-string'); expect(dependency.relativePaths[0].sourceRelativePath).to.equal('src/utils/is-string-internal.js'); expect(dependency.relativePaths[0].destinationRelativePath).to.equal('src/utils/is-string-internal.js'); expect(dependency.relativePaths[0].importSource).to.equal('utils/is-string-internal'); expect(dependency.relativePaths[0].isCustomResolveUsed).to.be.true; }); describe('importing the component', () => { before(() => { helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), fixtures.appPrintBarFoo); }); it('should generate the non-relative links correctly', () => { const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); it('should not show the component as modified', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('modified'); }); (supportNpmCiRegistryTesting ? describe : describe.skip)('when dependencies are saved as packages', () => { before(async () => { await npmCiRegistry.init(); helper.scopeHelper.removeRemoteScope(); npmCiRegistry.publishComponent('utils/is-type'); npmCiRegistry.publishComponent('utils/is-string'); npmCiRegistry.publishComponent('bar/foo'); helper.scopeHelper.reInitLocalScope(); helper.command.runCmd('npm init -y'); helper.command.runCmd(`npm install @ci/${helper.scopes.remote}.bar.foo`); }); after(() => { npmCiRegistry.destroy(); }); it('should be able to require its direct dependency and print results from all dependencies', () => { const appJsFixture = `const barFoo = require('@ci/${helper.scopes.remote}.bar.foo'); console.log(barFoo());`; fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), appJsFixture); const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); }); }); }); describe('using custom module directory when a component uses an internal binary file of the same component', () => { let npmCiRegistry; before(() => { helper = new Helper(); helper.command.setFeatures('legacy-workspace-config'); npmCiRegistry = new NpmCiRegistry(helper); helper.scopeHelper.setNewLocalAndRemoteScopes(); const bitJson = helper.bitJson.read(); bitJson.resolveModules = { modulesDirectories: ['src'] }; helper.bitJson.write(bitJson); npmCiRegistry.setCiScopeInBitJson(); const sourcePngFile = path.join(__dirname, '..', 'fixtures', 'png_fixture.png'); const destPngFile = path.join(helper.scopes.localPath, 'src/assets', 'png_fixture.png'); fs.copySync(sourcePngFile, destPngFile); const barFooFixture = "require('assets/png_fixture.png');"; helper.fs.createFile('src/bar', 'foo.js', barFooFixture); helper.command.addComponent('src/bar/foo.js src/assets/png_fixture.png', { i: 'bar/foo', m: 'src/bar/foo.js', }); }); it('bit status should not warn about missing packages', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('missing'); }); describe('importing the component', () => { before(() => { helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); }); it('should not show the component as modified', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('modified'); }); it('should create a symlink on node_modules pointing to the binary file', () => { const expectedDest = path.join( helper.scopes.localPath, 'components/bar/foo/node_modules/assets/png_fixture.png' ); expect(expectedDest).to.be.a.file(); const symlinkValue = fs.readlinkSync(expectedDest); expect(symlinkValue).to.have.string(path.normalize('components/bar/foo/assets/png_fixture.png')); }); (supportNpmCiRegistryTesting ? describe : describe.skip)('when installed via npm', () => { before(async () => { await npmCiRegistry.init(); helper.scopeHelper.removeRemoteScope(); npmCiRegistry.publishComponent('bar/foo'); helper.scopeHelper.reInitLocalScope(); helper.command.runCmd('npm init -y'); helper.command.runCmd(`npm install @ci/${helper.scopes.remote}.bar.foo`); }); after(() => { npmCiRegistry.destroy(); }); it('should be able to install the package successfully and generate the symlink to the file', () => { const expectedDest = path.join( helper.scopes.localPath, `node_modules/@ci/${helper.scopes.remote}.bar.foo/node_modules/assets/png_fixture.png` ); expect(expectedDest).to.be.a.file(); const symlinkValue = fs.readlinkSync(expectedDest); expect(symlinkValue).to.be.a.file(); }); }); }); }); describe('using alias', () => { let scopeAfterAdding; before(() => { helper.scopeHelper.setNewLocalAndRemoteScopes(); const bitJson = helper.bitJson.read(); bitJson.resolveModules = { aliases: { '@': 'src' } }; helper.bitJson.write(bitJson); helper.fs.createFile('src/utils', 'is-type.js', fixtures.isType); const isStringFixture = "const isType = require('@/utils/is-type'); module.exports = function isString() { return isType() + ' and got is-string'; };"; const barFooFixture = "const isString = require('@/utils/is-string'); module.exports = function foo() { return isString() + ' and got foo'; };"; helper.fs.createFile('src/utils', 'is-string.js', isStringFixture); helper.fs.createFile('src/bar', 'foo.js', barFooFixture); helper.command.addComponent('src/utils/is-type.js', { i: 'utils/is-type' }); helper.command.addComponent('src/utils/is-string.js', { i: 'utils/is-string' }); helper.command.addComponent('src/bar/foo.js', { i: 'bar/foo' }); scopeAfterAdding = helper.scopeHelper.cloneLocalScope(); }); it('bit status should not warn about missing packages', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('missing'); }); it('bit show should show the dependencies correctly', () => { const output = helper.command.showComponentParsed('bar/foo'); expect(output.dependencies).to.have.lengthOf(1); const dependency = output.dependencies[0]; expect(dependency.id).to.equal('utils/is-string'); expect(dependency.relativePaths[0].sourceRelativePath).to.equal('src/utils/is-string.js'); expect(dependency.relativePaths[0].destinationRelativePath).to.equal('src/utils/is-string.js'); expect(dependency.relativePaths[0].importSource).to.equal('@/utils/is-string'); expect(dependency.relativePaths[0].isCustomResolveUsed).to.be.true; }); describe('when there is already a package with the same name of the alias and is possible to resolve to the package', () => { before(() => { helper.npm.addNpmPackage('@'); // makes sure the package is there helper.fs.outputFile('node_modules/@/utils/is-string.js', ''); // makes sure it's possible to resolve to the package }); // @see https://github.com/teambit/bit/issues/1779 it('should still resolve to the custom-resolve and not to the package', () => { const output = helper.command.showComponentParsed('bar/foo'); expect(output.dependencies).to.have.lengthOf(1); const dependency = output.dependencies[0]; expect(dependency.id).to.equal('utils/is-string'); expect(dependency.relativePaths[0].sourceRelativePath).to.equal('src/utils/is-string.js'); expect(dependency.relativePaths[0].destinationRelativePath).to.equal('src/utils/is-string.js'); expect(dependency.relativePaths[0].importSource).to.equal('@/utils/is-string'); expect(dependency.relativePaths[0].isCustomResolveUsed).to.be.true; }); }); describe('importing the component', () => { before(() => { helper.scopeHelper.getClonedLocalScope(scopeAfterAdding); helper.command.tagAllComponents(); helper.command.exportAllComponents(); helper.scopeHelper.reInitLocalScope(); helper.scopeHelper.addRemoteScope(); helper.command.importComponent('bar/foo'); fs.outputFileSync(path.join(helper.scopes.localPath, 'app.js'), fixtures.appPrintBarFoo); }); it('should generate the non-relative links correctly', () => { const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); it('should not show the component as modified', () => { const output = helper.command.runCmd('bit status'); expect(output).to.not.have.string('modified'); }); describe('deleting the link generated for the custom-module-resolution', () => { before(() => { fs.removeSync(path.join(helper.scopes.localPath, 'components/bar/foo/node_modules')); }); it('bit status should show it as missing links and not as missing package dependencies', () => { const output = helper.command.runCmd('bit status'); expect(output).to.have.string('missing links'); expect(output).to.not.have.string('missing package dependencies'); }); describe('bit link', () => { let linkOutput; before(() => { linkOutput = helper.command.runCmd('bit link'); }); it.skip('should recreate the missing link', () => { // it doesn't show it for now, as it's not a symlink expect(linkOutput).to.have.string('components/bar/foo/node_modules/@/utils/is-string'); }); it('should recreate the links correctly', () => { const result = helper.command.runCmd('node app.js'); expect(result.trim()).to.equal('got is-type and got is-string and got foo'); }); }); }); }); }); });
the_stack
import ArtistForAlbumContract from '@DataContracts/ArtistForAlbumContract'; import ReleaseEventContract from '@DataContracts/ReleaseEvents/ReleaseEventContract'; import SongContract from '@DataContracts/Song/SongContract'; import SongForEditContract from '@DataContracts/Song/SongForEditContract'; import TranslatedEnumField from '@DataContracts/TranslatedEnumField'; import ArtistHelper from '@Helpers/ArtistHelper'; import KnockoutHelper from '@Helpers/KnockoutHelper'; import SongHelper from '@Helpers/SongHelper'; import { ArtistAutoCompleteParams } from '@KnockoutExtensions/AutoCompleteParams'; import { SongAutoCompleteParams } from '@KnockoutExtensions/AutoCompleteParams'; import EntryType from '@Models/EntryType'; import PVType from '@Models/PVs/PVType'; import SongType from '@Models/Songs/SongType'; import ArtistRepository from '@Repositories/ArtistRepository'; import PVRepository from '@Repositories/PVRepository'; import SongRepository from '@Repositories/SongRepository'; import UserRepository from '@Repositories/UserRepository'; import { IDialogService } from '@Shared/DialogService'; import GlobalValues from '@Shared/GlobalValues'; import UrlMapper from '@Shared/UrlMapper'; import $ from 'jquery'; import ko, { Computed, Observable, ObservableArray } from 'knockout'; import _ from 'lodash'; import moment from 'moment'; import { AlbumArtistRolesEditViewModel } from '../Artist/ArtistRolesEditViewModel'; import ArtistForAlbumEditViewModel from '../ArtistForAlbumEditViewModel'; import BasicEntryLinkViewModel from '../BasicEntryLinkViewModel'; import CustomNameEditViewModel from '../CustomNameEditViewModel'; import DeleteEntryViewModel from '../DeleteEntryViewModel'; import EnglishTranslatedStringEditViewModel from '../Globalization/EnglishTranslatedStringEditViewModel'; import NamesEditViewModel from '../Globalization/NamesEditViewModel'; import PVListEditViewModel from '../PVs/PVListEditViewModel'; import WebLinksEditViewModel from '../WebLinksEditViewModel'; import { LyricsForSongListEditViewModel } from './LyricsForSongEditViewModel'; export default class SongEditViewModel { private albumEventId: number; public albumReleaseDate: moment.Moment; // List of artist links for this song. public artistLinks: ObservableArray<ArtistForAlbumEditViewModel>; public artistSearchParams: ArtistAutoCompleteParams; public canHaveOriginalVersion: Computed<boolean>; public defaultNameLanguage: Observable<string>; public deleted: boolean; public editedArtistLink = new CustomNameEditViewModel(); public eventDate: Computed<moment.Moment>; public firstPvDate: Computed<moment.Moment>; public id: number; public length: Observable<number>; public lengthFormatted: Computed<string>; public lyrics: LyricsForSongListEditViewModel; public names: NamesEditViewModel; public notes: EnglishTranslatedStringEditViewModel; public originalVersion: BasicEntryLinkViewModel<SongContract>; public originalVersionSearchParams: SongAutoCompleteParams; public originalVersionSuggestions = ko.observableArray<SongContract>(); public publishDate: Observable<Date>; public pvs: PVListEditViewModel; public releaseEvent: BasicEntryLinkViewModel<ReleaseEventContract>; public showLyricsNote: Computed<boolean>; public songType: Computed<SongType>; public songTypeStr: Observable<string>; public status: Observable<string>; public submittedJson = ko.observable(''); public submitting = ko.observable(false); public suggestedPublishDate: Computed<PotentialDate>; private tags: number[]; public updateNotes = ko.observable(''); public validationExpanded = ko.observable(false); public webLinks: WebLinksEditViewModel; public hasMaxMilliBpm: Observable<boolean>; public minMilliBpm: Observable<number>; public maxMilliBpm: Observable<number>; public minBpm: Computed<string>; public maxBpm: Computed<string>; // Adds a new artist to the album // artistId: Id of the artist being added, if it's an existing artist. Can be null, if custom artist. // customArtistName: Name of the custom artist being added. Can be null, if existing artist. public addArtist = (artistId?: number, customArtistName?: string): void => { if (artistId) { this.artistRepository .getOne({ id: artistId, lang: this.values.languagePreference }) .then((artist) => { var data: ArtistForAlbumContract = { artist: artist, isSupport: false, name: artist.name, id: 0, roles: 'Default', }; var link = new ArtistForAlbumEditViewModel(null!, data); this.artistLinks.push(link); }); } else { var data: ArtistForAlbumContract = { artist: null!, name: customArtistName, isSupport: false, id: 0, roles: 'Default', }; var link = new ArtistForAlbumEditViewModel(null!, data); this.artistLinks.push(link); } }; public artistRolesEditViewModel: AlbumArtistRolesEditViewModel; // Clears fields that are not valid for the selected song type. private clearInvalidData = (): void => { if (!this.canHaveOriginalVersion()) { this.originalVersion.clear(); } }; public customizeName = (artistLink: ArtistForAlbumEditViewModel): void => { this.editedArtistLink.open(artistLink); }; public deleteViewModel = new DeleteEntryViewModel((notes) => { $.ajax( this.urlMapper.mapRelative( 'api/songs/' + this.id + '?notes=' + encodeURIComponent(notes), ), { type: 'DELETE', success: () => { window.location.href = this.urlMapper.mapRelative( '/Song/Details/' + this.id, ); }, }, ); }); public editArtistRoles = (artist: ArtistForAlbumEditViewModel): void => { this.artistRolesEditViewModel.show(artist); }; public async findOriginalSongSuggestions(): Promise<void> { this.originalVersionSuggestions.removeAll(); const names = _.map( this.names.getPrimaryNames().length ? this.names.getPrimaryNames() : this.names.getAllNames(), (n) => n.value(), ); const [all, originals] = await Promise.all([ this.songRepository.getByNames({ names: names, ignoreIds: [this.id], lang: this.values.languagePreference, }), this.songRepository.getByNames({ names: names, ignoreIds: [this.id], lang: this.values.languagePreference, songTypes: [SongType.Original, SongType.Remaster], }), ]); const suggestions = _.chain(originals) .unionBy(all, (i) => i.id) .take(3) .value(); this.originalVersionSuggestions(suggestions); } public hasAlbums: boolean; // Removes an artist from this album. public removeArtist = (artist: ArtistForAlbumEditViewModel): void => { this.artistLinks.remove(artist); }; public selectOriginalVersion = (song: SongContract): void => { this.originalVersion.entry(song); }; public submit = (): boolean => { if ( this.hasValidationErrors() && this.status() !== 'Draft' && this.dialogService.confirm(vdb.resources.entryEdit.saveWarning) === false ) { return false; } this.clearInvalidData(); this.submitting(true); var submittedModel: SongForEditContract = { artists: _.map(this.artistLinks(), (artist) => artist.toContract()), defaultNameLanguage: this.defaultNameLanguage(), deleted: this.deleted, hasAlbums: this.hasAlbums, id: this.id, lengthSeconds: this.length(), lyrics: this.lyrics.toContracts(), names: this.names.toContracts(), notes: this.notes.toContract(), originalVersion: this.originalVersion.entry(), publishDate: this.publishDate() ? this.publishDate().toISOString() : null!, pvs: this.pvs.toContracts(), releaseEvent: this.releaseEvent.entry(), songType: this.songTypeStr(), status: this.status(), tags: this.tags, updateNotes: this.updateNotes(), webLinks: this.webLinks.toContracts(), minMilliBpm: this.minMilliBpm(), maxMilliBpm: this.hasMaxMilliBpm() ? this.maxMilliBpm() : null!, }; this.submittedJson(ko.toJSON(submittedModel)); return true; }; public translateArtistRole = (role: string): string => { return this.artistRoleNames[role]; }; public hasValidationErrors: Computed<boolean>; public showInstrumentalNote: Computed<boolean>; public validationError_duplicateArtist: Computed<boolean>; public validationError_needArtist: Computed<boolean>; public validationError_needOriginal: Computed<boolean>; public validationError_needProducer: Computed<boolean>; public validationError_needReferences: Computed<boolean>; public validationError_needType: Computed<boolean>; public validationError_nonInstrumentalSongNeedsVocalists: Computed<boolean>; public validationError_redundantEvent: Computed<boolean>; public validationError_unspecifiedNames: Computed<boolean>; public constructor( private readonly values: GlobalValues, private songRepository: SongRepository, private artistRepository: ArtistRepository, pvRepository: PVRepository, userRepository: UserRepository, private urlMapper: UrlMapper, private readonly artistRoleNames: { [key: string]: string }, webLinkCategories: TranslatedEnumField[], data: SongForEditContract, canBulkDeletePVs: boolean, private dialogService: IDialogService, private instrumentalTagId: number, public languageNames: any, ) { this.albumEventId = data.albumEventId!; this.albumReleaseDate = data.albumReleaseDate ? moment(data.albumReleaseDate) : null!; this.artistLinks = ko.observableArray( _.map( data.artists, (artist) => new ArtistForAlbumEditViewModel(null!, artist), ), ); this.defaultNameLanguage = ko.observable(data.defaultNameLanguage); this.deleted = data.deleted; this.id = data.id; this.length = ko.observable(data.lengthSeconds); this.lyrics = new LyricsForSongListEditViewModel(data.lyrics); this.names = NamesEditViewModel.fromContracts(data.names); this.notes = new EnglishTranslatedStringEditViewModel(data.notes); this.originalVersion = new BasicEntryLinkViewModel<SongContract>( data.originalVersion, (entryId) => songRepository.getOne({ id: entryId, lang: values.languagePreference, }), ); this.publishDate = ko.observable( data.publishDate ? moment(data.publishDate).toDate() : null!, ); // Assume server date is UTC this.pvs = new PVListEditViewModel( pvRepository, urlMapper, data.pvs, canBulkDeletePVs, true, true, ); this.releaseEvent = new BasicEntryLinkViewModel<ReleaseEventContract>( data.releaseEvent, null!, ); this.songTypeStr = ko.observable(data.songType); this.songType = ko.computed( () => SongType[this.songTypeStr() as keyof typeof SongType], ); this.status = ko.observable(data.status); this.tags = data.tags; this.webLinks = new WebLinksEditViewModel(data.webLinks, webLinkCategories); this.hasMaxMilliBpm = ko.observable(data.maxMilliBpm! > data.minMilliBpm!); this.minMilliBpm = ko.observable(data.minMilliBpm!); this.maxMilliBpm = ko.observable( data.maxMilliBpm! > data.minMilliBpm! ? data.maxMilliBpm! : null!, ); this.artistRolesEditViewModel = new AlbumArtistRolesEditViewModel( artistRoleNames, ); this.artistSearchParams = { createNewItem: vdb.resources.song.addExtraArtist, acceptSelection: this.addArtist, height: 300, }; this.canHaveOriginalVersion = ko.computed( () => this.songType() !== SongType.Original, ); this.hasAlbums = data.hasAlbums; this.originalVersionSearchParams = { acceptSelection: this.originalVersion.id, extraQueryParams: { songTypes: 'Unspecified,Original,Remaster,Remix,Cover,Arrangement,Mashup,DramaPV,Other', }, ignoreId: this.id, height: 250, }; this.lengthFormatted = KnockoutHelper.lengthFormatted(this.length); this.showInstrumentalNote = ko.computed(() => { return ( this.pvs.isPossibleInstrumental() && this.songType() !== SongType.Instrumental && !_.some(this.tags, (t) => t === this.instrumentalTagId) ); }); this.showLyricsNote = ko.computed( () => this.songType() !== SongType.Instrumental && !this.originalVersion.isEmpty(), ); this.validationError_duplicateArtist = ko.computed(() => { return _.some( _.groupBy(this.artistLinks(), (a: ArtistForAlbumEditViewModel) => a.artist ? a.artist.id.toString() : a.name(), ), (a) => a.length > 1, ); }); this.validationError_needArtist = ko.computed( () => !_.some(this.artistLinks(), (a) => a.artist != null), ); this.validationError_needOriginal = ko.computed(() => { var songType = SongType; var derivedTypes = [ songType.Remaster, songType.Cover, songType.Instrumental, songType.MusicPV, songType.Other, songType.Remix, songType.Arrangement, ]; return ( (this.notes.original() === null || this.notes.original() === '') && this.originalVersion.entry() == null && _.includes(derivedTypes, this.songType()) ); }); this.validationError_needProducer = ko.computed( () => !this.validationError_needArtist() && !_.some( this.artistLinks(), (a) => a.artist != null && ArtistHelper.isProducerRole( a.artist, a.rolesArrayTyped(), SongHelper.getContentFocus(this.songType()), ), ), ); this.validationError_needReferences = ko.computed( () => !this.hasAlbums && _.isEmpty(this.notes.original()) && _.isEmpty(this.webLinks.items()) && _.isEmpty(this.pvs.pvs()), ); this.validationError_needType = ko.computed( () => this.songType() === SongType.Unspecified, ); this.validationError_nonInstrumentalSongNeedsVocalists = ko.computed(() => { return ( !this.validationError_needArtist() && !SongHelper.isInstrumental(this.songType()) && this.songType() !== SongType.Arrangement && // Arrangements are considered possible instrumentals in this context !_.some(this.tags, (t) => t === this.instrumentalTagId) && !_.some(this.artistLinks(), (a) => ArtistHelper.isVocalistRole(a.artist, a.rolesArrayTyped()), ) ); }); this.validationError_redundantEvent = ko.computed( () => !!this.albumEventId && !this.releaseEvent.isEmpty() && this.releaseEvent.id() === this.albumEventId, ); this.validationError_unspecifiedNames = ko.computed( () => !this.names.hasPrimaryName(), ); this.hasValidationErrors = ko.computed( () => this.validationError_duplicateArtist() || this.validationError_needArtist() || this.validationError_needOriginal() || this.validationError_needProducer() || this.validationError_needReferences() || this.validationError_needType() || this.validationError_nonInstrumentalSongNeedsVocalists() || this.validationError_redundantEvent() || this.validationError_unspecifiedNames(), ); this.eventDate = ko.computed(() => this.releaseEvent.entry() && this.releaseEvent.entry().date ? moment(this.releaseEvent.entry().date!) : null!, ); this.firstPvDate = ko.computed(() => { var val = _.chain(this.pvs.pvs()) .filter( (pv) => !!pv.publishDate && pv.pvType === PVType[PVType.Original], ) .map((pv) => moment(pv.publishDate)) .sortBy((p) => p) .head() .value(); return val; }); this.suggestedPublishDate = ko.computed(() => _.chain([ { date: this.albumReleaseDate, source: 'Album' }, { date: this.firstPvDate(), source: 'PV' }, ]) .filter((d) => d.date != null) .sortBy((d) => d.date) .head() .value(), ); this.minBpm = KnockoutHelper.bpm(this.minMilliBpm); this.maxBpm = KnockoutHelper.bpm(this.maxMilliBpm); window.setInterval( () => userRepository.refreshEntryEdit({ entryType: EntryType.Song, entryId: data.id, }), 10000, ); } } export interface PotentialDate { date: moment.Moment; source: string; }
the_stack
import { CaretRightOutlined } from '@ant-design/icons' import { t, Trans } from '@lingui/macro' import { BigNumber } from '@ethersproject/bignumber' import { Space } from 'antd' import Modal from 'antd/lib/modal/Modal' import CurrencySymbol from 'components/shared/CurrencySymbol' import Loading from 'components/shared/Loading' import { ThemeContext } from 'contexts/themeContext' import { useContext, useEffect, useState } from 'react' import { formatHistoricalDate } from 'utils/formatDate' import { formatWad } from 'utils/formatNumber' import FundingCycleDetails from 'components/v2/V2Project/V2FundingCycleSection/FundingCycleDetails' import { V2FundingCycle } from 'models/v2/fundingCycle' import { V2CurrencyName } from 'utils/v2/currency' import { V2CurrencyOption } from 'models/v2/currencyOption' import { V2ProjectContext } from 'contexts/v2/projectContext' import useProjectDistributionLimit from 'hooks/v2/contractReader/ProjectDistributionLimit' import useUsedDistributionLimit from 'hooks/v2/contractReader/UsedDistributionLimit' import { V2UserContext } from 'contexts/v2/userContext' import { formatDiscountRate, MAX_DISTRIBUTION_LIMIT } from 'utils/v2/math' import { decodeV2FundingCycleMetadata } from 'utils/v2/fundingCycle' // Fill in gaps between first funding cycle of each configuration: // - derives starts from duration and start time of the first FC of that configuration // - derives weights from discount rate and weight of the first FC of the configuration // - derives number by incrementing // - everything else the same as the first FC of the configuration const deriveFundingCyclesBetweenEachConfiguration = ({ firstFCOfEachConfiguration, currentFundingCycle, }: { firstFCOfEachConfiguration: V2FundingCycle[] currentFundingCycle: V2FundingCycle }) => { const allFundingCycles: V2FundingCycle[] = [] firstFCOfEachConfiguration.forEach( (firstFundingCycleOfConfiguration, configurationIndex) => { allFundingCycles.push(firstFundingCycleOfConfiguration) const currentReconfigurationStart = firstFundingCycleOfConfiguration.start const nextConfigurationStart = configurationIndex < firstFCOfEachConfiguration.length - 1 ? firstFCOfEachConfiguration[configurationIndex + 1].start : currentFundingCycle.start const currentDuration = firstFundingCycleOfConfiguration.duration const currentDiscountRate = firstFundingCycleOfConfiguration.discountRate let numInterimFundingCycles: number if (currentDuration && !currentDuration.eq(0)) { numInterimFundingCycles = nextConfigurationStart .sub(currentReconfigurationStart) .div(currentDuration) .toNumber() } else { numInterimFundingCycles = 0 } const isLastConfiguration = configurationIndex === firstFCOfEachConfiguration.length - 1 let interimIndex = 0 // Initially set to first of the reconfiguration let interimWeight: BigNumber = firstFundingCycleOfConfiguration.weight let interimStart: BigNumber = firstFundingCycleOfConfiguration.start let interimNumber: BigNumber = firstFundingCycleOfConfiguration.number let interimFundingCycle: V2FundingCycle = firstFundingCycleOfConfiguration while (interimIndex < numInterimFundingCycles) { // This is to prevent doubling up of an extrapolated FC and the first FC // of the next configuration. if ( !isLastConfiguration && interimIndex === numInterimFundingCycles - 1 ) { break } const nextInterimWeight = interimWeight.sub( interimWeight.mul(formatDiscountRate(currentDiscountRate)).div(100), ) const nextInterimStart = interimStart.add(currentDuration) const nextInterimNumber = interimNumber.add(1) let nextFundingCycle = { duration: interimFundingCycle.duration, weight: nextInterimWeight, discountRate: interimFundingCycle.discountRate, ballot: interimFundingCycle.ballot, number: nextInterimNumber, configuration: interimFundingCycle.configuration, start: nextInterimStart, metadata: interimFundingCycle.metadata, } as V2FundingCycle interimWeight = nextInterimWeight interimStart = nextInterimStart interimNumber = nextInterimNumber interimIndex++ allFundingCycles.push(nextFundingCycle) } }, ) return allFundingCycles } function HistoricalFundingCycle({ fundingCycle, numFundingCycles, index, onClick, }: { fundingCycle: V2FundingCycle numFundingCycles: number index: number onClick: VoidFunction }) { const { projectId, primaryTerminal } = useContext(V2ProjectContext) const { theme: { colors }, } = useContext(ThemeContext) const { data: distributionLimitData } = useProjectDistributionLimit({ projectId, configuration: fundingCycle?.configuration?.toString(), terminal: primaryTerminal, }) const { data: usedDistributionLimit } = useUsedDistributionLimit({ projectId, terminal: primaryTerminal, fundingCycleNumber: fundingCycle?.number, }) const [distributionLimit, distributionLimitCurrency] = distributionLimitData ?? [] const distributionLimitIsInfinite = distributionLimit?.eq( MAX_DISTRIBUTION_LIMIT, ) const distributionLimitIsZero = !distributionLimit || distributionLimit?.eq(0) const isLastFundingCycle = index < numFundingCycles - 1 return ( <div key={fundingCycle.number.toString()} role="button" onClick={onClick} style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', cursor: 'pointer', ...(isLastFundingCycle ? { paddingBottom: 20, borderBottom: '1px solid ' + colors.stroke.tertiary, } : {}), }} > <Space align="baseline"> <h3>#{fundingCycle.number.toString()}</h3> <div style={{ fontSize: '.8rem', marginLeft: 10 }}> <CurrencySymbol currency={V2CurrencyName( distributionLimitCurrency?.toNumber() as V2CurrencyOption, )} /> {!(distributionLimitIsInfinite || distributionLimitIsZero) ? ( <> <Trans> {formatWad(usedDistributionLimit, { precision: 2 })}/ {formatWad(distributionLimit, { precision: 2 })} withdrawn </Trans> </> ) : ( <> <Trans> {formatWad(usedDistributionLimit, { precision: 2 })} withdrawn </Trans> </> )} </div> </Space> <Space align="baseline" style={{ fontSize: '.8rem' }}> {formatHistoricalDate( fundingCycle.start.add(fundingCycle.duration).mul(1000).toNumber(), )} <CaretRightOutlined /> </Space> </div> ) } export default function FundingCycleHistory() { const { projectId, fundingCycle: currentFundingCycle, primaryTerminal, } = useContext(V2ProjectContext) const { contracts } = useContext(V2UserContext) const [selectedIndex, setSelectedIndex] = useState<number>() const [pastFundingCycles, setPastFundingCycles] = useState<V2FundingCycle[]>( [], ) const selectedFundingCycle = selectedIndex !== undefined ? pastFundingCycles[selectedIndex] : undefined const { data: distributionLimitData } = useProjectDistributionLimit({ projectId, configuration: selectedFundingCycle?.configuration?.toString(), terminal: primaryTerminal, }) const [distributionLimit, distributionLimitCurrency] = distributionLimitData ?? [] useEffect(() => { const loadPastFundingCycles = async () => { if (!(projectId && currentFundingCycle)) return [] const firstFCOfCurrentConfiguration = await contracts?.JBFundingCycleStore.get( projectId, currentFundingCycle.configuration, ) let firstFCOfEachConfiguration: V2FundingCycle[] = [ firstFCOfCurrentConfiguration, ] let previousReconfiguration = currentFundingCycle.basedOn // Get first funding cycle of each configuration using basedOn while (!previousReconfiguration.eq(BigNumber.from(0))) { const previousReconfigurationFirstFundingCycle: V2FundingCycle = (await contracts?.JBFundingCycleStore.get( projectId, previousReconfiguration, )) as V2FundingCycle if (previousReconfigurationFirstFundingCycle) { // Add it to the start of list firstFCOfEachConfiguration = [ previousReconfigurationFirstFundingCycle, ].concat(firstFCOfEachConfiguration) previousReconfiguration = previousReconfigurationFirstFundingCycle.basedOn } } const allFundingCycles = deriveFundingCyclesBetweenEachConfiguration({ firstFCOfEachConfiguration, currentFundingCycle, }) // Cut off the current funding cycle const allPastFundingCycles = allFundingCycles.slice(0, -1) return allPastFundingCycles.reverse() } loadPastFundingCycles().then(pastFundingCycles => { setPastFundingCycles(pastFundingCycles) }) }, [contracts, projectId, currentFundingCycle]) if (!projectId || !currentFundingCycle || !currentFundingCycle?.number) return null const allCyclesLoaded = pastFundingCycles.length >= currentFundingCycle.number.toNumber() - 1 const FundingCycles = () => ( <Space direction="vertical" size="large" style={{ width: '100%', maxHeight: '80vh', overflow: 'scroll' }} > {pastFundingCycles.length ? ( pastFundingCycles.map((fundingCycle: V2FundingCycle, i) => ( <HistoricalFundingCycle fundingCycle={fundingCycle} numFundingCycles={pastFundingCycles.length} index={i} onClick={() => setSelectedIndex(i)} /> )) ) : ( <div> <Trans>No past funding cycles</Trans> </div> )} </Space> ) return ( <div> <FundingCycles /> {allCyclesLoaded ? null : <Loading />} {selectedFundingCycle && ( <Modal visible={Boolean(selectedFundingCycle)} width={600} title={`Cycle #${selectedFundingCycle.number.toString()}`} onCancel={() => setSelectedIndex(undefined)} onOk={() => setSelectedIndex(undefined)} cancelButtonProps={{ hidden: true }} okText={t`Done`} > <FundingCycleDetails fundingCycle={selectedFundingCycle} fundingCycleMetadata={decodeV2FundingCycleMetadata( selectedFundingCycle.metadata, )} distributionLimit={distributionLimit} distributionLimitCurrency={distributionLimitCurrency} /> </Modal> )} </div> ) }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * Creates a job on Dataflow, which is an implementation of Apache Beam running on Google Compute Engine. For more information see * the official documentation for * [Beam](https://beam.apache.org) and [Dataflow](https://cloud.google.com/dataflow/). * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const bigDataJob = new gcp.dataflow.Job("big_data_job", { * parameters: { * baz: "qux", * foo: "bar", * }, * tempGcsLocation: "gs://my-bucket/tmp_dir", * templateGcsPath: "gs://my-bucket/templates/template_file", * }); * ``` * ### Streaming Job * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const topic = new gcp.pubsub.Topic("topic", {}); * const bucket1 = new gcp.storage.Bucket("bucket1", { * location: "US", * forceDestroy: true, * }); * const bucket2 = new gcp.storage.Bucket("bucket2", { * location: "US", * forceDestroy: true, * }); * const pubsubStream = new gcp.dataflow.Job("pubsubStream", { * templateGcsPath: "gs://my-bucket/templates/template_file", * tempGcsLocation: "gs://my-bucket/tmp_dir", * enableStreamingEngine: true, * parameters: { * inputFilePattern: pulumi.interpolate`${bucket1.url}/*.json`, * outputTopic: topic.id, * }, * transformNameMapping: { * name: "test_job", * env: "test", * }, * onDelete: "cancel", * }); * ``` * ## Note on "destroy" / "apply" * * There are many types of Dataflow jobs. Some Dataflow jobs run constantly, getting new data from (e.g.) a GCS bucket, and outputting data continuously. Some jobs process a set amount of data then terminate. All jobs can fail while running due to programming errors or other issues. In this way, Dataflow jobs are different from most other Google resources. * * The Dataflow resource is considered 'existing' while it is in a nonterminal state. If it reaches a terminal state (e.g. 'FAILED', 'COMPLETE', 'CANCELLED'), it will be recreated on the next 'apply'. This is as expected for jobs which run continuously, but may surprise users who use this resource for other kinds of Dataflow jobs. * * A Dataflow job which is 'destroyed' may be "cancelled" or "drained". If "cancelled", the job terminates - any data written remains where it is, but no new data will be processed. If "drained", no new data will enter the pipeline, but any data currently in the pipeline will finish being processed. The default is "drain". When `onDelete` is set to `"drain"` in the configuration, you may experience a long wait for your `pulumi destroy` to complete. * * ## Import * * This resource does not support import. */ export class Job extends pulumi.CustomResource { /** * Get an existing Job 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?: JobState, opts?: pulumi.CustomResourceOptions): Job { return new Job(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:dataflow/job:Job'; /** * Returns true if the given object is an instance of Job. 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 Job { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Job.__pulumiType; } /** * List of experiments that should be used by the job. An example value is `["enableStackdriverAgentMetrics"]`. */ public readonly additionalExperiments!: pulumi.Output<string[] | undefined>; /** * Enable/disable the use of [Streaming Engine](https://cloud.google.com/dataflow/docs/guides/deploying-a-pipeline#streaming-engine) for the job. Note that Streaming Engine is enabled by default for pipelines developed against the Beam SDK for Python v2.21.0 or later when using Python 3. */ public readonly enableStreamingEngine!: pulumi.Output<boolean | undefined>; /** * The configuration for VM IPs. Options are `"WORKER_IP_PUBLIC"` or `"WORKER_IP_PRIVATE"`. */ public readonly ipConfiguration!: pulumi.Output<string | undefined>; /** * The unique ID of this job. */ public /*out*/ readonly jobId!: pulumi.Output<string>; /** * The name for the Cloud KMS key for the job. Key format is: `projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY` */ public readonly kmsKeyName!: pulumi.Output<string | undefined>; /** * User labels to be specified for the job. Keys and values should follow the restrictions * specified in the [labeling restrictions](https://cloud.google.com/compute/docs/labeling-resources#restrictions) page. * **NOTE**: Google-provided Dataflow templates often provide default labels that begin with `goog-dataflow-provided`. * Unless explicitly set in config, these labels will be ignored to prevent diffs on re-apply. * <<<<<<< HEAD */ public readonly labels!: pulumi.Output<{[key: string]: any} | undefined>; /** * The machine type to use for the job. */ public readonly machineType!: pulumi.Output<string | undefined>; /** * The number of workers permitted to work on the job. More workers may improve processing speed at additional cost. */ public readonly maxWorkers!: pulumi.Output<number | undefined>; /** * A unique name for the resource, required by Dataflow. */ public readonly name!: pulumi.Output<string>; /** * The network to which VMs will be assigned. If it is not provided, "default" will be used. */ public readonly network!: pulumi.Output<string | undefined>; /** * One of "drain" or "cancel". Specifies behavior of deletion during `pulumi destroy`. See above note. */ public readonly onDelete!: pulumi.Output<string | undefined>; /** * Key/Value pairs to be passed to the Dataflow job (as used in the template). */ public readonly parameters!: pulumi.Output<{[key: string]: any} | undefined>; /** * The project in which the resource belongs. If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * The region in which the created job should run. */ public readonly region!: pulumi.Output<string | undefined>; /** * The Service Account email used to create the job. */ public readonly serviceAccountEmail!: pulumi.Output<string | undefined>; /** * The current state of the resource, selected from the [JobState enum](https://cloud.google.com/dataflow/docs/reference/rest/v1b3/projects.jobs#Job.JobState) */ public /*out*/ readonly state!: pulumi.Output<string>; /** * The subnetwork to which VMs will be assigned. Should be of the form "regions/REGION/subnetworks/SUBNETWORK". If the [subnetwork is located in a Shared VPC network](https://cloud.google.com/dataflow/docs/guides/specifying-networks#shared), you must use the complete URL. For example `"googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/subnetworks/SUBNET_NAME"` */ public readonly subnetwork!: pulumi.Output<string | undefined>; /** * A writeable location on GCS for the Dataflow job to dump its temporary data. */ public readonly tempGcsLocation!: pulumi.Output<string>; /** * The GCS path to the Dataflow job template. */ public readonly templateGcsPath!: pulumi.Output<string>; /** * Only applicable when updating a pipeline. Map of transform name prefixes of the job to be replaced with the corresponding name prefixes of the new job. This field is not used outside of update. * >>>>>>> v4.1.0 */ public readonly transformNameMapping!: pulumi.Output<{[key: string]: any} | undefined>; /** * The type of this job, selected from the [JobType enum](https://cloud.google.com/dataflow/docs/reference/rest/v1b3/projects.jobs#Job.JobType) */ public /*out*/ readonly type!: pulumi.Output<string>; /** * The zone in which the created job should run. If it is not provided, the provider zone is used. */ public readonly zone!: pulumi.Output<string | undefined>; /** * Create a Job 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: JobArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: JobArgs | JobState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as JobState | undefined; inputs["additionalExperiments"] = state ? state.additionalExperiments : undefined; inputs["enableStreamingEngine"] = state ? state.enableStreamingEngine : undefined; inputs["ipConfiguration"] = state ? state.ipConfiguration : undefined; inputs["jobId"] = state ? state.jobId : undefined; inputs["kmsKeyName"] = state ? state.kmsKeyName : undefined; inputs["labels"] = state ? state.labels : undefined; inputs["machineType"] = state ? state.machineType : undefined; inputs["maxWorkers"] = state ? state.maxWorkers : undefined; inputs["name"] = state ? state.name : undefined; inputs["network"] = state ? state.network : undefined; inputs["onDelete"] = state ? state.onDelete : undefined; inputs["parameters"] = state ? state.parameters : undefined; inputs["project"] = state ? state.project : undefined; inputs["region"] = state ? state.region : undefined; inputs["serviceAccountEmail"] = state ? state.serviceAccountEmail : undefined; inputs["state"] = state ? state.state : undefined; inputs["subnetwork"] = state ? state.subnetwork : undefined; inputs["tempGcsLocation"] = state ? state.tempGcsLocation : undefined; inputs["templateGcsPath"] = state ? state.templateGcsPath : undefined; inputs["transformNameMapping"] = state ? state.transformNameMapping : undefined; inputs["type"] = state ? state.type : undefined; inputs["zone"] = state ? state.zone : undefined; } else { const args = argsOrState as JobArgs | undefined; if ((!args || args.tempGcsLocation === undefined) && !opts.urn) { throw new Error("Missing required property 'tempGcsLocation'"); } if ((!args || args.templateGcsPath === undefined) && !opts.urn) { throw new Error("Missing required property 'templateGcsPath'"); } inputs["additionalExperiments"] = args ? args.additionalExperiments : undefined; inputs["enableStreamingEngine"] = args ? args.enableStreamingEngine : undefined; inputs["ipConfiguration"] = args ? args.ipConfiguration : undefined; inputs["kmsKeyName"] = args ? args.kmsKeyName : undefined; inputs["labels"] = args ? args.labels : undefined; inputs["machineType"] = args ? args.machineType : undefined; inputs["maxWorkers"] = args ? args.maxWorkers : undefined; inputs["name"] = args ? args.name : undefined; inputs["network"] = args ? args.network : undefined; inputs["onDelete"] = args ? args.onDelete : undefined; inputs["parameters"] = args ? args.parameters : undefined; inputs["project"] = args ? args.project : undefined; inputs["region"] = args ? args.region : undefined; inputs["serviceAccountEmail"] = args ? args.serviceAccountEmail : undefined; inputs["subnetwork"] = args ? args.subnetwork : undefined; inputs["tempGcsLocation"] = args ? args.tempGcsLocation : undefined; inputs["templateGcsPath"] = args ? args.templateGcsPath : undefined; inputs["transformNameMapping"] = args ? args.transformNameMapping : undefined; inputs["zone"] = args ? args.zone : undefined; inputs["jobId"] = undefined /*out*/; inputs["state"] = undefined /*out*/; inputs["type"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Job.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Job resources. */ export interface JobState { /** * List of experiments that should be used by the job. An example value is `["enableStackdriverAgentMetrics"]`. */ additionalExperiments?: pulumi.Input<pulumi.Input<string>[]>; /** * Enable/disable the use of [Streaming Engine](https://cloud.google.com/dataflow/docs/guides/deploying-a-pipeline#streaming-engine) for the job. Note that Streaming Engine is enabled by default for pipelines developed against the Beam SDK for Python v2.21.0 or later when using Python 3. */ enableStreamingEngine?: pulumi.Input<boolean>; /** * The configuration for VM IPs. Options are `"WORKER_IP_PUBLIC"` or `"WORKER_IP_PRIVATE"`. */ ipConfiguration?: pulumi.Input<string>; /** * The unique ID of this job. */ jobId?: pulumi.Input<string>; /** * The name for the Cloud KMS key for the job. Key format is: `projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY` */ kmsKeyName?: pulumi.Input<string>; /** * User labels to be specified for the job. Keys and values should follow the restrictions * specified in the [labeling restrictions](https://cloud.google.com/compute/docs/labeling-resources#restrictions) page. * **NOTE**: Google-provided Dataflow templates often provide default labels that begin with `goog-dataflow-provided`. * Unless explicitly set in config, these labels will be ignored to prevent diffs on re-apply. * <<<<<<< HEAD */ labels?: pulumi.Input<{[key: string]: any}>; /** * The machine type to use for the job. */ machineType?: pulumi.Input<string>; /** * The number of workers permitted to work on the job. More workers may improve processing speed at additional cost. */ maxWorkers?: pulumi.Input<number>; /** * A unique name for the resource, required by Dataflow. */ name?: pulumi.Input<string>; /** * The network to which VMs will be assigned. If it is not provided, "default" will be used. */ network?: pulumi.Input<string>; /** * One of "drain" or "cancel". Specifies behavior of deletion during `pulumi destroy`. See above note. */ onDelete?: pulumi.Input<string>; /** * Key/Value pairs to be passed to the Dataflow job (as used in the template). */ parameters?: pulumi.Input<{[key: string]: any}>; /** * The project in which the resource belongs. If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The region in which the created job should run. */ region?: pulumi.Input<string>; /** * The Service Account email used to create the job. */ serviceAccountEmail?: pulumi.Input<string>; /** * The current state of the resource, selected from the [JobState enum](https://cloud.google.com/dataflow/docs/reference/rest/v1b3/projects.jobs#Job.JobState) */ state?: pulumi.Input<string>; /** * The subnetwork to which VMs will be assigned. Should be of the form "regions/REGION/subnetworks/SUBNETWORK". If the [subnetwork is located in a Shared VPC network](https://cloud.google.com/dataflow/docs/guides/specifying-networks#shared), you must use the complete URL. For example `"googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/subnetworks/SUBNET_NAME"` */ subnetwork?: pulumi.Input<string>; /** * A writeable location on GCS for the Dataflow job to dump its temporary data. */ tempGcsLocation?: pulumi.Input<string>; /** * The GCS path to the Dataflow job template. */ templateGcsPath?: pulumi.Input<string>; /** * Only applicable when updating a pipeline. Map of transform name prefixes of the job to be replaced with the corresponding name prefixes of the new job. This field is not used outside of update. * >>>>>>> v4.1.0 */ transformNameMapping?: pulumi.Input<{[key: string]: any}>; /** * The type of this job, selected from the [JobType enum](https://cloud.google.com/dataflow/docs/reference/rest/v1b3/projects.jobs#Job.JobType) */ type?: pulumi.Input<string>; /** * The zone in which the created job should run. If it is not provided, the provider zone is used. */ zone?: pulumi.Input<string>; } /** * The set of arguments for constructing a Job resource. */ export interface JobArgs { /** * List of experiments that should be used by the job. An example value is `["enableStackdriverAgentMetrics"]`. */ additionalExperiments?: pulumi.Input<pulumi.Input<string>[]>; /** * Enable/disable the use of [Streaming Engine](https://cloud.google.com/dataflow/docs/guides/deploying-a-pipeline#streaming-engine) for the job. Note that Streaming Engine is enabled by default for pipelines developed against the Beam SDK for Python v2.21.0 or later when using Python 3. */ enableStreamingEngine?: pulumi.Input<boolean>; /** * The configuration for VM IPs. Options are `"WORKER_IP_PUBLIC"` or `"WORKER_IP_PRIVATE"`. */ ipConfiguration?: pulumi.Input<string>; /** * The name for the Cloud KMS key for the job. Key format is: `projects/PROJECT_ID/locations/LOCATION/keyRings/KEY_RING/cryptoKeys/KEY` */ kmsKeyName?: pulumi.Input<string>; /** * User labels to be specified for the job. Keys and values should follow the restrictions * specified in the [labeling restrictions](https://cloud.google.com/compute/docs/labeling-resources#restrictions) page. * **NOTE**: Google-provided Dataflow templates often provide default labels that begin with `goog-dataflow-provided`. * Unless explicitly set in config, these labels will be ignored to prevent diffs on re-apply. * <<<<<<< HEAD */ labels?: pulumi.Input<{[key: string]: any}>; /** * The machine type to use for the job. */ machineType?: pulumi.Input<string>; /** * The number of workers permitted to work on the job. More workers may improve processing speed at additional cost. */ maxWorkers?: pulumi.Input<number>; /** * A unique name for the resource, required by Dataflow. */ name?: pulumi.Input<string>; /** * The network to which VMs will be assigned. If it is not provided, "default" will be used. */ network?: pulumi.Input<string>; /** * One of "drain" or "cancel". Specifies behavior of deletion during `pulumi destroy`. See above note. */ onDelete?: pulumi.Input<string>; /** * Key/Value pairs to be passed to the Dataflow job (as used in the template). */ parameters?: pulumi.Input<{[key: string]: any}>; /** * The project in which the resource belongs. If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The region in which the created job should run. */ region?: pulumi.Input<string>; /** * The Service Account email used to create the job. */ serviceAccountEmail?: pulumi.Input<string>; /** * The subnetwork to which VMs will be assigned. Should be of the form "regions/REGION/subnetworks/SUBNETWORK". If the [subnetwork is located in a Shared VPC network](https://cloud.google.com/dataflow/docs/guides/specifying-networks#shared), you must use the complete URL. For example `"googleapis.com/compute/v1/projects/PROJECT_ID/regions/REGION/subnetworks/SUBNET_NAME"` */ subnetwork?: pulumi.Input<string>; /** * A writeable location on GCS for the Dataflow job to dump its temporary data. */ tempGcsLocation: pulumi.Input<string>; /** * The GCS path to the Dataflow job template. */ templateGcsPath: pulumi.Input<string>; /** * Only applicable when updating a pipeline. Map of transform name prefixes of the job to be replaced with the corresponding name prefixes of the new job. This field is not used outside of update. * >>>>>>> v4.1.0 */ transformNameMapping?: pulumi.Input<{[key: string]: any}>; /** * The zone in which the created job should run. If it is not provided, the provider zone is used. */ zone?: pulumi.Input<string>; }
the_stack
import { AddressZero } from "@ethersproject/constants"; import { SignerWithAddress } from "@nomiclabs/hardhat-ethers/signers"; import { assert, expect } from "chai"; import { BigNumber, ethers } from "ethers"; import { MerkleTree } from "merkletreejs"; import { expectError, sdk, signers, storage } from "./before-setup"; import { createSnapshot } from "../src/common"; import { ClaimEligibility } from "../src/enums"; import { NFTDrop, Token } from "../src"; import { NATIVE_TOKEN_ADDRESS } from "../src/constants/currency"; import invariant from "tiny-invariant"; global.fetch = require("cross-fetch"); describe("NFT Drop Contract", async () => { let dropContract: NFTDrop; let adminWallet: SignerWithAddress, samWallet: SignerWithAddress, abbyWallet: SignerWithAddress, bobWallet: SignerWithAddress, w1: SignerWithAddress, w2: SignerWithAddress, w3: SignerWithAddress, w4: SignerWithAddress; beforeEach(async () => { [adminWallet, samWallet, bobWallet, abbyWallet, w1, w2, w3, w4] = signers; sdk.updateSignerOrProvider(adminWallet); const address = await sdk.deployer.deployNFTDrop({ name: `Testing drop from SDK`, description: "Test contract from tests", image: "https://pbs.twimg.com/profile_images/1433508973215367176/XBCfBn3g_400x400.jpg", primary_sale_recipient: adminWallet.address, seller_fee_basis_points: 500, fee_recipient: AddressZero, platform_fee_basis_points: 10, platform_fee_recipient: AddressZero, }); dropContract = sdk.getNFTDrop(address); }); it("should allow a snapshot to be set", async () => { await dropContract.claimConditions.set([ { startTime: new Date(Date.now() / 2), snapshot: [bobWallet.address, samWallet.address, abbyWallet.address], price: 1, }, { startTime: new Date(), snapshot: [bobWallet.address], }, ]); const metadata = await dropContract.metadata.get(); const merkles = metadata.merkle; expect(merkles).have.property( "0xd89eb21bf7ee4dd07d88e8f90a513812d9d38ac390a58722762c9f3afc4e0feb", ); expect(merkles).have.property( "0xb1a60ad68b77609a455696695fbdd02b850d03ec285e7fe1f4c4093797457b24", ); const roots = (await dropContract.claimConditions.getAll()).map( (c) => c.merkleRootHash, ); expect(roots).length(2); }); it("should return snapshot data on claim conditions", async () => { await dropContract.createBatch([ { name: "test", description: "test" }, { name: "test", description: "test" }, ]); await dropContract.claimConditions.set([ { snapshot: [samWallet.address], }, ]); const conditions = await dropContract.claimConditions.getAll(); assert.lengthOf(conditions, 1); invariant(conditions[0].snapshot); expect(conditions[0].snapshot[0].address).to.eq(samWallet.address); }); it("should remove merkles from the metadata when claim conditions are removed", async () => { await dropContract.claimConditions.set([ { startTime: new Date(), waitInSeconds: 10, snapshot: [bobWallet.address, samWallet.address, abbyWallet.address], }, { startTime: new Date(Date.now() + 60 * 60 * 1000), snapshot: [bobWallet.address], }, ]); const metadata = await dropContract.metadata.get(); const merkles = metadata.merkle; expect(merkles).have.property( "0xd89eb21bf7ee4dd07d88e8f90a513812d9d38ac390a58722762c9f3afc4e0feb", ); expect(merkles).have.property( "0xb1a60ad68b77609a455696695fbdd02b850d03ec285e7fe1f4c4093797457b24", ); const roots = (await dropContract.claimConditions.getAll()).map( (c) => c.merkleRootHash, ); expect(roots).length(2); await dropContract.claimConditions.set([{}]); const newMetadata = await dropContract.metadata.get(); const newMerkles = newMetadata.merkle; expect(JSON.stringify(newMerkles)).to.eq("{}"); }); it("allow all addresses in the merkle tree to claim", async () => { const testWallets: SignerWithAddress[] = [ bobWallet, samWallet, abbyWallet, w1, w2, w3, w4, ]; const members = testWallets.map((w, i) => i % 3 === 0 ? w.address.toLowerCase() : i % 3 === 1 ? w.address.toUpperCase().replace("0X", "0x") : w.address, ); await dropContract.claimConditions.set([ { snapshot: members, }, ]); const metadata = []; for (let i = 0; i < 10; i++) { metadata.push({ name: `test ${i}`, }); } await dropContract.createBatch(metadata); /** * Claiming 1 tokens with proofs: 0xe9707d0e6171f728f7473c24cc0432a9b07eaaf1efed6a137a4a8c12c79552d9,0xb1a5bda84b83f7f014abcf0cf69cab5a4de1c3ececa8123a5e4aaacb01f63f83 */ for (const member of testWallets) { await sdk.updateSignerOrProvider(member); await dropContract.claim(1); } }); it("allow one address in the merkle tree to claim", async () => { const testWallets: SignerWithAddress[] = [bobWallet]; const members = testWallets.map((w) => w.address); await dropContract.claimConditions.set([ { snapshot: members, }, ]); const metadata = []; for (let i = 0; i < 2; i++) { metadata.push({ name: `test ${i}`, }); } await dropContract.createBatch(metadata); /** * Claiming 1 tokens with proofs: 0xe9707d0e6171f728f7473c24cc0432a9b07eaaf1efed6a137a4a8c12c79552d9,0xb1a5bda84b83f7f014abcf0cf69cab5a4de1c3ececa8123a5e4aaacb01f63f83 */ for (const member of testWallets) { await sdk.updateSignerOrProvider(member); await dropContract.claim(1); } try { await sdk.updateSignerOrProvider(samWallet); await dropContract.claim(1); assert.fail("should have thrown"); } catch (e) { // expected } }); it("should correctly upload metadata for each nft", async () => { const metadatas = []; for (let i = 0; i < 100; i++) { metadatas.push({ name: `test ${i}`, }); } await dropContract.createBatch(metadatas); const all = await dropContract.getAll(); expect(all.length).to.eq(100); await dropContract.claimConditions.set([{}]); await dropContract.claim(1); const claimed = await dropContract.getAllClaimed(); const unclaimed = await dropContract.getAllUnclaimed({ start: 0, count: 30, }); expect(claimed.length).to.eq(1); expect(unclaimed.length).to.eq(30); expect(unclaimed[0].name).to.eq("test 1"); expect(unclaimed[unclaimed.length - 1].name).to.eq("test 30"); }); it("should correctly update total supply after burning", async () => { const metadatas = []; for (let i = 0; i < 20; i++) { metadatas.push({ name: `test ${i}`, }); } await dropContract.createBatch(metadatas); await dropContract.claimConditions.set([{}]); await dropContract.claim(10); const ts = await dropContract.totalSupply(); expect(ts.toNumber()).to.eq(20); await dropContract.burn(0); const ts2 = await dropContract.totalSupply(); expect(ts2.toNumber()).to.eq(20); }); it("should not allow claiming to someone not in the merkle tree", async () => { await dropContract.claimConditions.set( [ { snapshot: [bobWallet.address, samWallet.address, abbyWallet.address], }, ], false, ); await dropContract.createBatch([ { name: "name", description: "description" }, ]); await sdk.updateSignerOrProvider(w1); try { await dropContract.claim(1); } catch (err: any) { expect(err).to.have.property( "message", "No claim found for this address", "", ); return; } assert.fail("should not reach this point, claim should have failed"); }); it("should allow claims with default settings", async () => { await dropContract.createBatch([ { name: "name", description: "description" }, ]); await dropContract.claimConditions.set([{}]); await dropContract.claim(1); }); it("should allow setting max claims per wallet", async () => { await dropContract.createBatch([ { name: "name", description: "description" }, { name: "name2", description: "description" }, { name: "name3", description: "description" }, { name: "name4", description: "description" }, ]); await dropContract.claimConditions.set([ { snapshot: [ { address: w1.address, maxClaimable: 2 }, { address: w2.address, maxClaimable: 1 }, ], }, ]); await sdk.updateSignerOrProvider(w1); const tx = await dropContract.claim(2); expect(tx.length).to.eq(2); try { await sdk.updateSignerOrProvider(w2); await dropContract.claim(2); } catch (e) { expectError(e, "invalid quantity proof"); } }); it("should generate valid proofs", async () => { const members = [ bobWallet.address, samWallet.address, abbyWallet.address, w1.address, w2.address, w3.address, w4.address, ]; const hashedLeafs = members.map((l) => ethers.utils.solidityKeccak256(["address", "uint256"], [l, 0]), ); const tree = new MerkleTree(hashedLeafs, ethers.utils.keccak256, { sort: true, sortLeaves: true, sortPairs: true, }); const input = members.map((address) => ({ address, maxClaimable: 0, })); const snapshot = await createSnapshot(input, 0, storage); for (const leaf of members) { const expectedProof = tree.getHexProof( ethers.utils.solidityKeccak256(["address", "uint256"], [leaf, 0]), ); const actualProof = snapshot.snapshot.claims.find( (c) => c.address === leaf, ); assert.isDefined(actualProof); expect(actualProof?.proof).to.include.ordered.members(expectedProof); const verified = tree.verify( actualProof?.proof as string[], ethers.utils.solidityKeccak256(["address", "uint256"], [leaf, 0]), tree.getHexRoot(), ); expect(verified).to.eq(true); } }); it("should return the newly claimed token", async () => { await dropContract.claimConditions.set([{}]); await dropContract.createBatch([ { name: "test 0", }, { name: "test 1", }, { name: "test 2", }, ]); try { await dropContract.createBatch([ { name: "test 0", }, { name: "test 1", }, { name: "test 2", }, ]); } catch (err) { expect(err).to.have.property("message", "Batch already created!", ""); } const token = await dropContract.claim(2); assert.lengthOf(token, 2); }); describe("eligibility", () => { beforeEach(async () => { await dropContract.createBatch([ { name: "test", description: "test", }, ]); }); it("should return false if there isn't an active claim condition", async () => { const reasons = await dropContract.claimConditions.getClaimIneligibilityReasons( "1", bobWallet.address, ); expect(reasons).to.include(ClaimEligibility.NoClaimConditionSet); assert.lengthOf(reasons, 1); const canClaim = await dropContract.claimConditions.canClaim( 1, w1.address, ); assert.isFalse(canClaim); }); it("should check for the total supply", async () => { await dropContract.claimConditions.set([{ maxQuantity: 1 }]); const reasons = await dropContract.claimConditions.getClaimIneligibilityReasons( "2", w1.address, ); expect(reasons).to.include(ClaimEligibility.NotEnoughSupply); const canClaim = await dropContract.claimConditions.canClaim( 2, w1.address, ); assert.isFalse(canClaim); }); it("should check if an address has valid merkle proofs", async () => { await dropContract.claimConditions.set([ { maxQuantity: 1, snapshot: [w2.address, adminWallet.address], }, ]); const reasons = await dropContract.claimConditions.getClaimIneligibilityReasons( "1", w1.address, ); expect(reasons).to.include(ClaimEligibility.AddressNotAllowed); const canClaim = await dropContract.claimConditions.canClaim( 1, w1.address, ); assert.isFalse(canClaim); }); it("should check if its been long enough since the last claim", async () => { await dropContract.claimConditions.set([ { maxQuantity: 10, waitInSeconds: 24 * 60 * 60, }, ]); await sdk.updateSignerOrProvider(bobWallet); await dropContract.claim(1); const reasons = await dropContract.claimConditions.getClaimIneligibilityReasons( "1", bobWallet.address, ); expect(reasons).to.include( ClaimEligibility.WaitBeforeNextClaimTransaction, ); const canClaim = await dropContract.claimConditions.canClaim(1); assert.isFalse(canClaim); }); it("should check if an address has enough native currency", async () => { await dropContract.claimConditions.set([ { maxQuantity: 10, price: "1000000000000000", currencyAddress: NATIVE_TOKEN_ADDRESS, }, ]); await sdk.updateSignerOrProvider(bobWallet); const reasons = await dropContract.claimConditions.getClaimIneligibilityReasons( "1", bobWallet.address, ); expect(reasons).to.include(ClaimEligibility.NotEnoughTokens); const canClaim = await dropContract.claimConditions.canClaim(1); assert.isFalse(canClaim); }); it("should check if an address has enough erc20 currency", async () => { const currencyAddress = await sdk.deployer.deployBuiltInContract( Token.contractType, { name: "test", symbol: "test", primary_sale_recipient: adminWallet.address, }, ); await dropContract.claimConditions.set([ { maxQuantity: 10, price: "1000000000000000", currencyAddress, }, ]); await sdk.updateSignerOrProvider(bobWallet); const reasons = await dropContract.claimConditions.getClaimIneligibilityReasons( "1", bobWallet.address, ); expect(reasons).to.include(ClaimEligibility.NotEnoughTokens); const canClaim = await dropContract.claimConditions.canClaim(1); assert.isFalse(canClaim); }); it("should return nothing if the claim is eligible", async () => { await dropContract.claimConditions.set([ { maxQuantity: 10, price: "100", currencyAddress: NATIVE_TOKEN_ADDRESS, snapshot: [w1.address, w2.address, w3.address], }, ]); const reasons = await dropContract.claimConditions.getClaimIneligibilityReasons( "1", w1.address, ); assert.lengthOf(reasons, 0); const canClaim = await dropContract.claimConditions.canClaim( "1", w1.address, ); assert.isTrue(canClaim); }); }); it("should verify claim correctly after resetting claim conditions", async () => { await dropContract.claimConditions.set([ { snapshot: [w1.address], }, ]); const reasons = await dropContract.claimConditions.getClaimIneligibilityReasons( "1", w2.address, ); expect(reasons).to.contain(ClaimEligibility.AddressNotAllowed); await dropContract.claimConditions.set([{}]); const reasons2 = await dropContract.claimConditions.getClaimIneligibilityReasons( "1", w2.address, ); expect(reasons2.length).to.eq(0); }); it("should verify claim correctly after updating claim conditions", async () => { await dropContract.claimConditions.set([ { snapshot: [w1.address], }, ]); const reasons = await dropContract.claimConditions.getClaimIneligibilityReasons( "1", w2.address, ); expect(reasons).to.contain(ClaimEligibility.AddressNotAllowed); await dropContract.claimConditions.update(0, { snapshot: [w1.address, w2.address], }); const reasons2 = await dropContract.claimConditions.getClaimIneligibilityReasons( "1", w2.address, ); expect(reasons2.length).to.eq(0); }); it("should allow you to update claim conditions", async () => { await dropContract.claimConditions.set([{}]); const conditions = await dropContract.claimConditions.getAll(); await dropContract.claimConditions.set([{}]); assert.lengthOf(conditions, 1); }); it("should be able to use claim as function expected", async () => { await dropContract.createBatch([ { name: "test", }, ]); await dropContract.claimConditions.set([{}]); await dropContract.claim(1); assert((await dropContract.getOwned()).length === 1); assert((await dropContract.getOwnedTokenIds()).length === 1); }); it("should be able to use claimTo function as expected", async () => { await dropContract.claimConditions.set([{}]); await dropContract.createBatch([ { name: "test", }, ]); await dropContract.claimTo(samWallet.address, 1); assert((await dropContract.getOwned(samWallet.address)).length === 1); assert( (await dropContract.getOwnedTokenIds(samWallet.address)).length === 1, ); }); it("canClaim: 1 address", async () => { const metadata = []; for (let i = 0; i < 10; i++) { metadata.push({ name: `test ${i}`, }); } await dropContract.createBatch(metadata); await dropContract.claimConditions.set([{ snapshot: [w1.address] }]); assert.isTrue( await dropContract.claimConditions.canClaim(1, w1.address), "can claim", ); assert.isFalse( await dropContract.claimConditions.canClaim(1, w2.address), "!can claim", ); }); it("canClaim: 3 address", async () => { const metadata = []; for (let i = 0; i < 10; i++) { metadata.push({ name: `test ${i}`, }); } await dropContract.createBatch(metadata); const members = [ w1.address.toUpperCase().replace("0X", "0x"), w2.address.toLowerCase(), w3.address, ]; await dropContract.claimConditions.set([ { snapshot: members, }, ]); assert.isTrue( await dropContract.claimConditions.canClaim(1, w1.address), "can claim", ); assert.isTrue( await dropContract.claimConditions.canClaim(1, w2.address), "can claim", ); assert.isTrue( await dropContract.claimConditions.canClaim(1, w3.address), "can claim", ); assert.isFalse( await dropContract.claimConditions.canClaim(1, bobWallet.address), "!can claim", ); }); it("set claim condition and reset claim condition", async () => { await dropContract.claimConditions.set([ { startTime: new Date(Date.now() / 2) }, { startTime: new Date() }, ]); expect((await dropContract.claimConditions.getAll()).length).to.be.equal(2); await dropContract.claimConditions.set([]); expect((await dropContract.claimConditions.getAll()).length).to.be.equal(0); }); it("set claim condition with snapshot and remove it afterwards", async () => { await dropContract.claimConditions.set([{ snapshot: [samWallet.address] }]); expect( await dropContract.claimConditions.canClaim(1, samWallet.address), ).to.eq(true); expect( await dropContract.claimConditions.canClaim(1, bobWallet.address), ).to.eq(false); const cc = await dropContract.claimConditions.getActive(); await dropContract.claimConditions.set([ { merkleRootHash: cc.merkleRootHash, snapshot: undefined, }, ]); expect( await dropContract.claimConditions.canClaim(1, samWallet.address), ).to.eq(true); expect( await dropContract.claimConditions.canClaim(1, bobWallet.address), ).to.eq(true); }); it("update claim condition to remove snapshot", async () => { await dropContract.claimConditions.set([{ snapshot: [samWallet.address] }]); expect( await dropContract.claimConditions.canClaim(1, samWallet.address), ).to.eq(true); expect( await dropContract.claimConditions.canClaim(1, bobWallet.address), ).to.eq(false); await dropContract.claimConditions.update(0, { snapshot: [], }); expect( await dropContract.claimConditions.canClaim(1, samWallet.address), ).to.eq(true); expect( await dropContract.claimConditions.canClaim(1, bobWallet.address), ).to.eq(true); }); it("set claim condition and update claim condition", async () => { await dropContract.claimConditions.set([ { startTime: new Date(Date.now() / 2), maxQuantity: 1, price: 0.15 }, { startTime: new Date(), waitInSeconds: 60 }, ]); expect((await dropContract.claimConditions.getAll()).length).to.be.equal(2); await dropContract.claimConditions.update(0, { waitInSeconds: 10 }); let updatedConditions = await dropContract.claimConditions.getAll(); expect(updatedConditions[0].maxQuantity).to.be.deep.equal("1"); expect(updatedConditions[0].price).to.be.deep.equal( ethers.utils.parseUnits("0.15"), ); expect(updatedConditions[0].waitInSeconds).to.be.deep.equal( BigNumber.from(10), ); expect(updatedConditions[1].waitInSeconds).to.be.deep.equal( BigNumber.from(60), ); await dropContract.claimConditions.update(1, { maxQuantity: 10, waitInSeconds: 10, }); updatedConditions = await dropContract.claimConditions.getAll(); expect(updatedConditions[0].maxQuantity).to.be.deep.equal("1"); expect(updatedConditions[1].maxQuantity).to.be.deep.equal("10"); expect(updatedConditions[1].waitInSeconds).to.be.deep.equal( BigNumber.from(10), ); }); it("set claim condition and update claim condition with diff timestamps should reorder", async () => { await dropContract.claimConditions.set([ { startTime: new Date(Date.now() / 2), maxQuantity: 1 }, { startTime: new Date(), maxQuantity: 2 }, ]); expect((await dropContract.claimConditions.getAll()).length).to.be.equal(2); await dropContract.claimConditions.update(0, { startTime: new Date(Date.now() + 24 * 60 * 60 * 1000), }); // max quantities should be inverted now const updatedConditions = await dropContract.claimConditions.getAll(); expect(updatedConditions[0].maxQuantity).to.be.deep.equal("2"); expect(updatedConditions[1].maxQuantity).to.be.deep.equal("1"); }); it("set claim condition in the future should not be claimable now", async () => { await dropContract.claimConditions.set([ { startTime: new Date(Date.now() + 60 * 60 * 24 * 1000 * 1000), }, ]); const canClaim = await dropContract.claimConditions.canClaim(1); expect(canClaim).to.eq(false); }); describe("Delay Reveal", () => { it("metadata should reveal correctly", async () => { await dropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #1", }, [{ name: "NFT #1" }, { name: "NFT #2" }], "my secret password", ); expect((await dropContract.get("0")).metadata.name).to.be.equal( "Placeholder #1", ); await dropContract.revealer.reveal(0, "my secret password"); expect((await dropContract.get("0")).metadata.name).to.be.equal("NFT #1"); }); it("different reveal order and should return correct unreveal list", async () => { await dropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #1", }, [ { name: "NFT #1", }, { name: "NFT #2", }, ], "my secret key", ); await dropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #2", }, [ { name: "NFT #3", }, { name: "NFT #4", }, ], "my secret key", ); await dropContract.createBatch([ { name: "NFT #00", }, { name: "NFT #01", }, ]); await dropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #3", }, [ { name: "NFT #5", }, { name: "NFT #6", }, { name: "NFT #7", }, ], "my secret key", ); let unrevealList = await dropContract.revealer.getBatchesToReveal(); expect(unrevealList.length).to.be.equal(3); expect(unrevealList[0].batchId.toNumber()).to.be.equal(0); expect(unrevealList[0].placeholderMetadata.name).to.be.equal( "Placeholder #1", ); expect(unrevealList[1].batchId.toNumber()).to.be.equal(1); expect(unrevealList[1].placeholderMetadata.name).to.be.equal( "Placeholder #2", ); // skipped 2 because it is a revealed batch expect(unrevealList[2].batchId.toNumber()).to.be.equal(3); expect(unrevealList[2].placeholderMetadata.name).to.be.equal( "Placeholder #3", ); await dropContract.revealer.reveal( unrevealList[0].batchId, "my secret key", ); unrevealList = await dropContract.revealer.getBatchesToReveal(); expect(unrevealList.length).to.be.equal(2); expect(unrevealList[0].batchId.toNumber()).to.be.equal(1); expect(unrevealList[0].placeholderMetadata.name).to.be.equal( "Placeholder #2", ); expect(unrevealList[1].batchId.toNumber()).to.be.equal(3); expect(unrevealList[1].placeholderMetadata.name).to.be.equal( "Placeholder #3", ); await dropContract.revealer.reveal( unrevealList[unrevealList.length - 1].batchId, "my secret key", ); unrevealList = await dropContract.revealer.getBatchesToReveal(); expect(unrevealList.length).to.be.equal(1); expect(unrevealList[0].batchId.toNumber()).to.be.equal(1); expect(unrevealList[0].placeholderMetadata.name).to.be.equal( "Placeholder #2", ); }); it("should not be able to re-used published password for next batch", async () => { await dropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #1", }, [{ name: "NFT #1" }, { name: "NFT #2" }], "my secret password", ); await dropContract.revealer.createDelayedRevealBatch( { name: "Placeholder #2", }, [{ name: "NFT #3" }, { name: "NFT #4" }], "my secret password", ); await dropContract.revealer.reveal(0, "my secret password"); const transactions = (await adminWallet.provider?.getBlockWithTransactions("latest")) ?.transactions ?? []; const { index, _key } = dropContract.encoder.decode( "reveal", transactions[0].data, ); // re-using broadcasted _key to decode :) try { await dropContract.revealer.reveal(index.add(1), _key); assert.fail("should not be able to re-used published password"); } catch (e) { expect((e as Error).message).to.be.equal("invalid password"); } // original password should work await dropContract.revealer.reveal(1, "my secret password"); }); }); });
the_stack
import '@aws-cdk/assert-internal/jest'; import { ABSENT } from '@aws-cdk/assert-internal'; import * as acm from '@aws-cdk/aws-certificatemanager'; import * as iam from '@aws-cdk/aws-iam'; import * as cdk from '@aws-cdk/core'; import * as appmesh from '../lib'; describe('virtual gateway', () => { describe('When creating a VirtualGateway', () => { test('should have expected defaults', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); new appmesh.VirtualGateway(stack, 'testGateway', { mesh: mesh, }); new appmesh.VirtualGateway(stack, 'httpGateway', { mesh: mesh, listeners: [appmesh.VirtualGatewayListener.http({ port: 443, healthCheck: appmesh.HealthCheck.http({ interval: cdk.Duration.seconds(10), }), })], }); new appmesh.VirtualGateway(stack, 'http2Gateway', { mesh: mesh, listeners: [appmesh.VirtualGatewayListener.http2({ port: 443, healthCheck: appmesh.HealthCheck.http2({ interval: cdk.Duration.seconds(10) }), })], }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { Spec: { Listeners: [ { PortMapping: { Port: 8080, Protocol: appmesh.Protocol.HTTP, }, }, ], }, VirtualGatewayName: 'testGateway', }); expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { Spec: { Listeners: [ { HealthCheck: { HealthyThreshold: 2, IntervalMillis: 10000, Port: 443, Protocol: appmesh.Protocol.HTTP, TimeoutMillis: 2000, UnhealthyThreshold: 2, Path: '/', }, PortMapping: { Port: 443, Protocol: appmesh.Protocol.HTTP, }, }, ], }, VirtualGatewayName: 'httpGateway', MeshOwner: ABSENT, }); expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { Spec: { Listeners: [ { HealthCheck: { HealthyThreshold: 2, IntervalMillis: 10000, Port: 443, Protocol: appmesh.Protocol.HTTP2, TimeoutMillis: 2000, UnhealthyThreshold: 2, Path: '/', }, PortMapping: { Port: 443, Protocol: appmesh.Protocol.HTTP2, }, }, ], }, VirtualGatewayName: 'http2Gateway', }); }); test('should have expected features', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); new appmesh.VirtualGateway(stack, 'testGateway', { virtualGatewayName: 'test-gateway', listeners: [appmesh.VirtualGatewayListener.grpc({ port: 80, healthCheck: appmesh.HealthCheck.grpc(), })], mesh: mesh, accessLog: appmesh.AccessLog.fromFilePath('/dev/stdout'), }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { Spec: { Listeners: [ { HealthCheck: { HealthyThreshold: 2, IntervalMillis: 5000, Port: 80, Protocol: appmesh.Protocol.GRPC, TimeoutMillis: 2000, UnhealthyThreshold: 2, }, PortMapping: { Port: 80, Protocol: appmesh.Protocol.GRPC, }, }, ], Logging: { AccessLog: { File: { Path: '/dev/stdout', }, }, }, }, VirtualGatewayName: 'test-gateway', }); }); test('with an http listener with a TLS certificate from ACM', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); const cert = new acm.Certificate(stack, 'cert', { domainName: '', }); new appmesh.VirtualGateway(stack, 'testGateway', { virtualGatewayName: 'test-gateway', mesh: mesh, listeners: [appmesh.VirtualGatewayListener.http({ port: 8080, tls: { mode: appmesh.TlsMode.STRICT, certificate: appmesh.TlsCertificate.acm(cert), }, })], }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { Spec: { Listeners: [ { TLS: { Mode: appmesh.TlsMode.STRICT, Certificate: { ACM: { CertificateArn: { Ref: 'cert56CA94EB', }, }, }, }, }, ], }, }); }); test('with an grpc listener with a TLS certificate from file', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); new appmesh.VirtualGateway(stack, 'testGateway', { virtualGatewayName: 'test-gateway', mesh: mesh, listeners: [appmesh.VirtualGatewayListener.grpc({ port: 8080, tls: { mode: appmesh.TlsMode.STRICT, certificate: appmesh.TlsCertificate.file('path/to/certChain', 'path/to/privateKey'), }, })], }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { Spec: { Listeners: [ { TLS: { Mode: appmesh.TlsMode.STRICT, Certificate: { File: { CertificateChain: 'path/to/certChain', PrivateKey: 'path/to/privateKey', }, }, }, }, ], }, }); }); test('with an http2 listener with a TLS certificate from SDS', () => { // GIVEN const stack = new cdk.Stack(); const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); // WHEN new appmesh.VirtualGateway(stack, 'testGateway', { virtualGatewayName: 'test-gateway', mesh: mesh, listeners: [appmesh.VirtualGatewayListener.http2({ port: 8080, tls: { mode: appmesh.TlsMode.STRICT, certificate: appmesh.TlsCertificate.sds('secret_certificate'), }, })], }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { Spec: { Listeners: [ { TLS: { Mode: appmesh.TlsMode.STRICT, Certificate: { SDS: { SecretName: 'secret_certificate', }, }, }, }, ], }, }); }); describe('with an grpc listener with a TLS validation from file', () => { test('the listener should include the TLS configuration', () => { // GIVEN const stack = new cdk.Stack(); const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); // WHEN new appmesh.VirtualGateway(stack, 'testGateway', { virtualGatewayName: 'test-gateway', mesh: mesh, listeners: [appmesh.VirtualGatewayListener.grpc({ port: 8080, tls: { mode: appmesh.TlsMode.STRICT, certificate: appmesh.TlsCertificate.file('path/to/certChain', 'path/to/privateKey'), mutualTlsValidation: { trust: appmesh.TlsValidationTrust.file('path/to/certChain'), }, }, })], }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { Spec: { Listeners: [ { TLS: { Mode: appmesh.TlsMode.STRICT, Certificate: { File: { CertificateChain: 'path/to/certChain', PrivateKey: 'path/to/privateKey', }, }, Validation: { Trust: { File: { CertificateChain: 'path/to/certChain', }, }, }, }, }, ], }, }); }); }); describe('with an http2 listener with a TLS validation from SDS', () => { test('the listener should include the TLS configuration', () => { // GIVEN const stack = new cdk.Stack(); const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); // WHEN new appmesh.VirtualGateway(stack, 'testGateway', { virtualGatewayName: 'test-gateway', mesh: mesh, listeners: [appmesh.VirtualGatewayListener.http2({ port: 8080, tls: { mode: appmesh.TlsMode.STRICT, certificate: appmesh.TlsCertificate.sds('secret_certificate'), mutualTlsValidation: { subjectAlternativeNames: appmesh.SubjectAlternativeNames.matchingExactly('mesh-endpoint.apps.local'), trust: appmesh.TlsValidationTrust.sds('secret_validation'), }, }, })], }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { Spec: { Listeners: [ { TLS: { Mode: appmesh.TlsMode.STRICT, Certificate: { SDS: { SecretName: 'secret_certificate', }, }, Validation: { SubjectAlternativeNames: { Match: { Exact: ['mesh-endpoint.apps.local'], }, }, }, }, }, ], }, }); }); }); test('with an grpc listener with the TLS mode permissive', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); new appmesh.VirtualGateway(stack, 'testGateway', { virtualGatewayName: 'test-gateway', mesh: mesh, listeners: [appmesh.VirtualGatewayListener.grpc({ port: 8080, tls: { mode: appmesh.TlsMode.PERMISSIVE, certificate: appmesh.TlsCertificate.file('path/to/certChain', 'path/to/privateKey'), }, })], }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { Spec: { Listeners: [ { TLS: { Mode: appmesh.TlsMode.PERMISSIVE, Certificate: { File: { CertificateChain: 'path/to/certChain', PrivateKey: 'path/to/privateKey', }, }, }, }, ], }, }); }); describe('with shared service mesh', () => { test('Mesh Owner is the AWS account ID of the account that shared the mesh with your account', () => { // GIVEN const app = new cdk.App(); const meshEnv = { account: '1234567899', region: 'us-west-2' }; const virtualGatewayEnv = { account: '9987654321', region: 'us-west-2' }; // Creating stack in Account 9987654321 const stack = new cdk.Stack(app, 'mySharedStack', { env: virtualGatewayEnv }); // Mesh is in Account 1234567899 const sharedMesh = appmesh.Mesh.fromMeshArn(stack, 'shared-mesh', `arn:aws:appmesh:${meshEnv.region}:${meshEnv.account}:mesh/shared-mesh`); // WHEN new appmesh.VirtualGateway(stack, 'test-node', { mesh: sharedMesh, }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { MeshOwner: meshEnv.account, }); }); }); }); describe('When adding a gateway route to existing VirtualGateway ', () => { test('should create gateway route resource', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); const virtualGateway = new appmesh.VirtualGateway(stack, 'testGateway', { virtualGatewayName: 'test-gateway', mesh: mesh, }); const virtualService = new appmesh.VirtualService(stack, 'virtualService', { virtualServiceProvider: appmesh.VirtualServiceProvider.none(mesh), }); virtualGateway.addGatewayRoute('testGatewayRoute', { gatewayRouteName: 'test-gateway-route', routeSpec: appmesh.GatewayRouteSpec.http({ routeTarget: virtualService, }), }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::GatewayRoute', { GatewayRouteName: 'test-gateway-route', Spec: { HttpRoute: { Action: { Target: { VirtualService: { VirtualServiceName: { 'Fn::GetAtt': ['virtualService03A04B87', 'VirtualServiceName'], }, }, }, }, Match: { Prefix: '/', }, }, }, }); }); }); describe('When adding gateway routes to a VirtualGateway with existing gateway routes', () => { test('should add gateway routes and not overwite', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); const virtualService = new appmesh.VirtualService(stack, 'virtualService', { virtualServiceProvider: appmesh.VirtualServiceProvider.none(mesh), }); const virtualGateway = mesh.addVirtualGateway('gateway'); virtualGateway.addGatewayRoute('testGatewayRoute', { gatewayRouteName: 'test-gateway-route', routeSpec: appmesh.GatewayRouteSpec.http({ routeTarget: virtualService, }), }); virtualGateway.addGatewayRoute('testGatewayRoute2', { gatewayRouteName: 'test-gateway-route-2', routeSpec: appmesh.GatewayRouteSpec.http({ routeTarget: virtualService, }), }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::GatewayRoute', { GatewayRouteName: 'test-gateway-route', }); expect(stack).toHaveResourceLike('AWS::AppMesh::GatewayRoute', { GatewayRouteName: 'test-gateway-route-2', }); }); }); describe('When creating a VirtualGateway with backend defaults', () => { test('should add backend defaults to the VirtualGateway', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); new appmesh.VirtualGateway(stack, 'virtual-gateway', { virtualGatewayName: 'virtual-gateway', mesh: mesh, backendDefaults: { tlsClientPolicy: { validation: { trust: appmesh.TlsValidationTrust.file('path-to-certificate'), }, }, }, }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { VirtualGatewayName: 'virtual-gateway', Spec: { BackendDefaults: { ClientPolicy: { TLS: { Validation: { Trust: { File: { CertificateChain: 'path-to-certificate', }, }, }, }, }, }, }, }); }); describe("with client's TLS certificate from SDS", () => { test('should add a backend default to the resource with TLS certificate', () => { // GIVEN const stack = new cdk.Stack(); const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); // WHEN new appmesh.VirtualGateway(stack, 'virtual-gateway', { virtualGatewayName: 'virtual-gateway', mesh: mesh, backendDefaults: { tlsClientPolicy: { mutualTlsCertificate: appmesh.TlsCertificate.sds( 'secret_certificate'), validation: { subjectAlternativeNames: appmesh.SubjectAlternativeNames.matchingExactly('mesh-endpoint.apps.local'), trust: appmesh.TlsValidationTrust.sds('secret_validation'), }, }, }, }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { VirtualGatewayName: 'virtual-gateway', Spec: { BackendDefaults: { ClientPolicy: { TLS: { Certificate: { SDS: { SecretName: 'secret_certificate', }, }, Validation: { SubjectAlternativeNames: { Match: { Exact: ['mesh-endpoint.apps.local'], }, }, Trust: { SDS: { SecretName: 'secret_validation', }, }, }, }, }, }, }, }); }); }); }); test('Can add an http connection pool to listener', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); new appmesh.VirtualGateway(stack, 'virtual-gateway', { virtualGatewayName: 'virtual-gateway', mesh: mesh, listeners: [ appmesh.VirtualGatewayListener.http({ port: 80, connectionPool: { maxConnections: 100, maxPendingRequests: 10, }, }), ], }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { VirtualGatewayName: 'virtual-gateway', Spec: { Listeners: [ { ConnectionPool: { HTTP: { MaxConnections: 100, MaxPendingRequests: 10, }, }, }, ], }, }); }); test('Can add an grpc connection pool to listener', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); new appmesh.VirtualGateway(stack, 'virtual-gateway', { virtualGatewayName: 'virtual-gateway', mesh: mesh, listeners: [ appmesh.VirtualGatewayListener.grpc({ port: 80, connectionPool: { maxRequests: 10, }, }), ], }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { VirtualGatewayName: 'virtual-gateway', Spec: { Listeners: [ { ConnectionPool: { GRPC: { MaxRequests: 10, }, }, }, ], }, }); }); test('Can add an http2 connection pool to listener', () => { // GIVEN const stack = new cdk.Stack(); // WHEN const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); new appmesh.VirtualGateway(stack, 'virtual-gateway', { virtualGatewayName: 'virtual-gateway', mesh: mesh, listeners: [ appmesh.VirtualGatewayListener.http2({ port: 80, connectionPool: { maxRequests: 10, }, }), ], }); // THEN expect(stack).toHaveResourceLike('AWS::AppMesh::VirtualGateway', { VirtualGatewayName: 'virtual-gateway', Spec: { Listeners: [ { ConnectionPool: { HTTP2: { MaxRequests: 10, }, }, }, ], }, }); }); test('Can import VirtualGateways using an ARN', () => { const app = new cdk.App(); // GIVEN const stack = new cdk.Stack(app, 'Imports', { env: { account: '123456789012', region: 'us-east-1' }, }); const meshName = 'testMesh'; const virtualGatewayName = 'test-gateway'; const arn = `arn:aws:appmesh:us-east-1:123456789012:mesh/${meshName}/virtualGateway/${virtualGatewayName}`; // WHEN const virtualGateway = appmesh.VirtualGateway.fromVirtualGatewayArn( stack, 'importedGateway', arn); // THEN expect(virtualGateway.mesh.meshName).toEqual(meshName); expect(virtualGateway.virtualGatewayName).toEqual(virtualGatewayName); }); test('Can import VirtualGateways using attributes', () => { const app = new cdk.App(); // GIVEN const stack = new cdk.Stack(app, 'Imports', { env: { account: '123456789012', region: 'us-east-1' }, }); const meshName = 'testMesh'; const virtualGatewayName = 'test-gateway'; // WHEN const virtualGateway = appmesh.VirtualGateway.fromVirtualGatewayAttributes(stack, 'importedGateway', { mesh: appmesh.Mesh.fromMeshName(stack, 'Mesh', meshName), virtualGatewayName: virtualGatewayName, }); // THEN expect(virtualGateway.mesh.meshName).toEqual(meshName); expect(virtualGateway.virtualGatewayName).toEqual(virtualGatewayName); }); test('Can grant an identity StreamAggregatedResources for a given VirtualGateway', () => { // GIVEN const stack = new cdk.Stack(); const mesh = new appmesh.Mesh(stack, 'mesh', { meshName: 'test-mesh', }); const gateway = new appmesh.VirtualGateway(stack, 'testGateway', { mesh: mesh, }); // WHEN const user = new iam.User(stack, 'test'); gateway.grantStreamAggregatedResources(user); // THEN expect(stack).toHaveResourceLike('AWS::IAM::Policy', { PolicyDocument: { Statement: [ { Action: 'appmesh:StreamAggregatedResources', Effect: 'Allow', Resource: { Ref: 'testGatewayF09EC349', }, }, ], }, }); }); });
the_stack
import { DataProvider } from '../ojdataprovider'; import { dvtBaseComponent, dvtBaseComponentEventMap, dvtBaseComponentSettableProperties } from '../ojdvt-base'; import { JetElement, JetSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface ojTagCloud<K, D> extends dvtBaseComponent<ojTagCloudSettableProperties<K, D>> { animationOnDataChange: 'auto' | 'none'; animationOnDisplay: 'auto' | 'none'; as: string; data: DataProvider<K, D> | null; hiddenCategories: string[]; highlightMatch: 'any' | 'all'; highlightedCategories: string[]; hoverBehavior: 'dim' | 'none'; layout: 'cloud' | 'rectangular'; selection: K[]; selectionMode: 'single' | 'multiple' | 'none'; styleDefaults: { animationDuration?: number; hoverBehaviorDelay?: number; svgStyle?: object; }; tooltip: { renderer: ((context: ojTagCloud.TooltipContext<K>) => ({ insert: Element | string; } | { preventDefault: boolean; })); }; touchResponse: 'touchStart' | 'auto'; translations: { componentName?: string; labelAndValue?: string; labelClearSelection?: string; labelCountWithTotal?: string; labelDataVisualization?: string; labelInvalidData?: string; labelNoData?: string; stateCollapsed?: string; stateDrillable?: string; stateExpanded?: string; stateHidden?: string; stateIsolated?: string; stateMaximized?: string; stateMinimized?: string; stateSelected?: string; stateUnselected?: string; stateVisible?: string; }; onAnimationOnDataChangeChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["animationOnDataChange"]>) => any) | null; onAnimationOnDisplayChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["animationOnDisplay"]>) => any) | null; onAsChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["as"]>) => any) | null; onDataChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["data"]>) => any) | null; onHiddenCategoriesChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["hiddenCategories"]>) => any) | null; onHighlightMatchChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["highlightMatch"]>) => any) | null; onHighlightedCategoriesChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["highlightedCategories"]>) => any) | null; onHoverBehaviorChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["hoverBehavior"]>) => any) | null; onLayoutChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["layout"]>) => any) | null; onSelectionChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["selection"]>) => any) | null; onSelectionModeChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["selectionMode"]>) => any) | null; onStyleDefaultsChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["styleDefaults"]>) => any) | null; onTooltipChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["tooltip"]>) => any) | null; onTouchResponseChanged: ((event: JetElementCustomEvent<ojTagCloud<K, D>["touchResponse"]>) => any) | null; addEventListener<T extends keyof ojTagCloudEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojTagCloudEventMap<K, D>[T]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; getProperty<T extends keyof ojTagCloudSettableProperties<K, D>>(property: T): ojTagCloud<K, D>[T]; getProperty(property: string): any; setProperty<T extends keyof ojTagCloudSettableProperties<K, D>>(property: T, value: ojTagCloudSettableProperties<K, D>[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTagCloudSettableProperties<K, D>>): void; setProperties(properties: ojTagCloudSettablePropertiesLenient<K, D>): void; getContextByNode(node: Element): ojTagCloud.NodeContext | null; getItem(index: number): ojTagCloud.ItemContext | null; getItemCount(): number; } export interface ojTagCloudEventMap<K, D> extends dvtBaseComponentEventMap<ojTagCloudSettableProperties<K, D>> { 'animationOnDataChangeChanged': JetElementCustomEvent<ojTagCloud<K, D>["animationOnDataChange"]>; 'animationOnDisplayChanged': JetElementCustomEvent<ojTagCloud<K, D>["animationOnDisplay"]>; 'asChanged': JetElementCustomEvent<ojTagCloud<K, D>["as"]>; 'dataChanged': JetElementCustomEvent<ojTagCloud<K, D>["data"]>; 'hiddenCategoriesChanged': JetElementCustomEvent<ojTagCloud<K, D>["hiddenCategories"]>; 'highlightMatchChanged': JetElementCustomEvent<ojTagCloud<K, D>["highlightMatch"]>; 'highlightedCategoriesChanged': JetElementCustomEvent<ojTagCloud<K, D>["highlightedCategories"]>; 'hoverBehaviorChanged': JetElementCustomEvent<ojTagCloud<K, D>["hoverBehavior"]>; 'layoutChanged': JetElementCustomEvent<ojTagCloud<K, D>["layout"]>; 'selectionChanged': JetElementCustomEvent<ojTagCloud<K, D>["selection"]>; 'selectionModeChanged': JetElementCustomEvent<ojTagCloud<K, D>["selectionMode"]>; 'styleDefaultsChanged': JetElementCustomEvent<ojTagCloud<K, D>["styleDefaults"]>; 'tooltipChanged': JetElementCustomEvent<ojTagCloud<K, D>["tooltip"]>; 'touchResponseChanged': JetElementCustomEvent<ojTagCloud<K, D>["touchResponse"]>; } export interface ojTagCloudSettableProperties<K, D> extends dvtBaseComponentSettableProperties { animationOnDataChange: 'auto' | 'none'; animationOnDisplay: 'auto' | 'none'; as: string; data: DataProvider<K, D> | null; hiddenCategories: string[]; highlightMatch: 'any' | 'all'; highlightedCategories: string[]; hoverBehavior: 'dim' | 'none'; layout: 'cloud' | 'rectangular'; selection: K[]; selectionMode: 'single' | 'multiple' | 'none'; styleDefaults: { animationDuration?: number; hoverBehaviorDelay?: number; svgStyle?: object; }; tooltip: { renderer: ((context: ojTagCloud.TooltipContext<K>) => ({ insert: Element | string; } | { preventDefault: boolean; })); }; touchResponse: 'touchStart' | 'auto'; translations: { componentName?: string; labelAndValue?: string; labelClearSelection?: string; labelCountWithTotal?: string; labelDataVisualization?: string; labelInvalidData?: string; labelNoData?: string; stateCollapsed?: string; stateDrillable?: string; stateExpanded?: string; stateHidden?: string; stateIsolated?: string; stateMaximized?: string; stateMinimized?: string; stateSelected?: string; stateUnselected?: string; stateVisible?: string; }; } export interface ojTagCloudSettablePropertiesLenient<K, D> extends Partial<ojTagCloudSettableProperties<K, D>> { [key: string]: any; } export namespace ojTagCloud { // tslint:disable-next-line interface-over-type-literal type ItemContext = { color: string; label: string; selected: boolean; tooltip: string; value: number; }; // tslint:disable-next-line interface-over-type-literal type NodeContext = { subId: string; index: number; }; // tslint:disable-next-line interface-over-type-literal type TooltipContext<K> = { color: string; componentElement: Element; id: K; label: string; parentElement: Element; value: number; }; } export interface ojTagCloudItem extends JetElement<ojTagCloudItemSettableProperties> { categories: string[]; color?: string; label: string; shortDesc: string; svgClassName: string; svgStyle: object; url: string; value: number | null; onCategoriesChanged: ((event: JetElementCustomEvent<ojTagCloudItem["categories"]>) => any) | null; onColorChanged: ((event: JetElementCustomEvent<ojTagCloudItem["color"]>) => any) | null; onLabelChanged: ((event: JetElementCustomEvent<ojTagCloudItem["label"]>) => any) | null; onShortDescChanged: ((event: JetElementCustomEvent<ojTagCloudItem["shortDesc"]>) => any) | null; onSvgClassNameChanged: ((event: JetElementCustomEvent<ojTagCloudItem["svgClassName"]>) => any) | null; onSvgStyleChanged: ((event: JetElementCustomEvent<ojTagCloudItem["svgStyle"]>) => any) | null; onUrlChanged: ((event: JetElementCustomEvent<ojTagCloudItem["url"]>) => any) | null; onValueChanged: ((event: JetElementCustomEvent<ojTagCloudItem["value"]>) => any) | null; addEventListener<T extends keyof ojTagCloudItemEventMap>(type: T, listener: (this: HTMLElement, ev: ojTagCloudItemEventMap[T]) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; getProperty<T extends keyof ojTagCloudItemSettableProperties>(property: T): ojTagCloudItem[T]; getProperty(property: string): any; setProperty<T extends keyof ojTagCloudItemSettableProperties>(property: T, value: ojTagCloudItemSettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojTagCloudItemSettableProperties>): void; setProperties(properties: ojTagCloudItemSettablePropertiesLenient): void; } export interface ojTagCloudItemEventMap extends HTMLElementEventMap { 'categoriesChanged': JetElementCustomEvent<ojTagCloudItem["categories"]>; 'colorChanged': JetElementCustomEvent<ojTagCloudItem["color"]>; 'labelChanged': JetElementCustomEvent<ojTagCloudItem["label"]>; 'shortDescChanged': JetElementCustomEvent<ojTagCloudItem["shortDesc"]>; 'svgClassNameChanged': JetElementCustomEvent<ojTagCloudItem["svgClassName"]>; 'svgStyleChanged': JetElementCustomEvent<ojTagCloudItem["svgStyle"]>; 'urlChanged': JetElementCustomEvent<ojTagCloudItem["url"]>; 'valueChanged': JetElementCustomEvent<ojTagCloudItem["value"]>; } export interface ojTagCloudItemSettableProperties extends JetSettableProperties { categories: string[]; color?: string; label: string; shortDesc: string; svgClassName: string; svgStyle: object; url: string; value: number | null; } export interface ojTagCloudItemSettablePropertiesLenient extends Partial<ojTagCloudItemSettableProperties> { [key: string]: any; }
the_stack
import * as GObject from "@gi-types/gobject"; import * as GLib from "@gi-types/glib"; export const BINARY_AGE: number; export const INTERFACE_AGE: number; export const MAJOR_VERSION: number; export const MICRO_VERSION: number; export const MINOR_VERSION: number; export const VERSION_MIN_REQUIRED: number; export function attribute_set_free(attrib_set: AttributeSet): void; export function focus_tracker_notify(object: Object): void; export function get_binary_age(): number; export function get_default_registry(): Registry; export function get_focus_object(): Object; export function get_interface_age(): number; export function get_major_version(): number; export function get_micro_version(): number; export function get_minor_version(): number; export function get_root(): Object; export function get_toolkit_name(): string; export function get_toolkit_version(): string; export function get_version(): string; export function relation_type_for_name(name: string): RelationType; export function relation_type_get_name(type: RelationType): string; export function relation_type_register(name: string): RelationType; export function remove_focus_tracker(tracker_id: number): void; export function remove_global_event_listener(listener_id: number): void; export function remove_key_event_listener(listener_id: number): void; export function role_for_name(name: string): Role; export function role_get_localized_name(role: Role): string; export function role_get_name(role: Role): string; export function role_register(name: string): Role; export function state_type_for_name(name: string): StateType; export function state_type_get_name(type: StateType): string; export function state_type_register(name: string): StateType; export function text_attribute_for_name(name: string): TextAttribute; export function text_attribute_get_name(attr: TextAttribute): string; export function text_attribute_get_value(attr: TextAttribute, index_: number): string | null; export function text_attribute_register(name: string): TextAttribute; export function text_free_ranges(ranges: TextRange[]): void; export function value_type_get_localized_name(value_type: ValueType): string; export function value_type_get_name(value_type: ValueType): string; export type EventListener = (obj: Object) => void; export type EventListenerInit = () => void; export type FocusHandler = (object: Object, focus_in: boolean) => void; export type Function = () => boolean; export type KeySnoopFunc = (event: KeyEventStruct) => number; export type PropertyChangeHandler = (obj: Object, vals: PropertyValues) => void; export namespace CoordType { export const $gtype: GObject.GType<CoordType>; } export enum CoordType { SCREEN = 0, WINDOW = 1, PARENT = 2, } export namespace KeyEventType { export const $gtype: GObject.GType<KeyEventType>; } export enum KeyEventType { PRESS = 0, RELEASE = 1, LAST_DEFINED = 2, } export namespace Layer { export const $gtype: GObject.GType<Layer>; } export enum Layer { INVALID = 0, BACKGROUND = 1, CANVAS = 2, WIDGET = 3, MDI = 4, POPUP = 5, OVERLAY = 6, WINDOW = 7, } export namespace RelationType { export const $gtype: GObject.GType<RelationType>; } export enum RelationType { NULL = 0, CONTROLLED_BY = 1, CONTROLLER_FOR = 2, LABEL_FOR = 3, LABELLED_BY = 4, MEMBER_OF = 5, NODE_CHILD_OF = 6, FLOWS_TO = 7, FLOWS_FROM = 8, SUBWINDOW_OF = 9, EMBEDS = 10, EMBEDDED_BY = 11, POPUP_FOR = 12, PARENT_WINDOW_OF = 13, DESCRIBED_BY = 14, DESCRIPTION_FOR = 15, NODE_PARENT_OF = 16, DETAILS = 17, DETAILS_FOR = 18, ERROR_MESSAGE = 19, ERROR_FOR = 20, LAST_DEFINED = 21, } export namespace Role { export const $gtype: GObject.GType<Role>; } export enum Role { INVALID = 0, ACCELERATOR_LABEL = 1, ALERT = 2, ANIMATION = 3, ARROW = 4, CALENDAR = 5, CANVAS = 6, CHECK_BOX = 7, CHECK_MENU_ITEM = 8, COLOR_CHOOSER = 9, COLUMN_HEADER = 10, COMBO_BOX = 11, DATE_EDITOR = 12, DESKTOP_ICON = 13, DESKTOP_FRAME = 14, DIAL = 15, DIALOG = 16, DIRECTORY_PANE = 17, DRAWING_AREA = 18, FILE_CHOOSER = 19, FILLER = 20, FONT_CHOOSER = 21, FRAME = 22, GLASS_PANE = 23, HTML_CONTAINER = 24, ICON = 25, IMAGE = 26, INTERNAL_FRAME = 27, LABEL = 28, LAYERED_PANE = 29, LIST = 30, LIST_ITEM = 31, MENU = 32, MENU_BAR = 33, MENU_ITEM = 34, OPTION_PANE = 35, PAGE_TAB = 36, PAGE_TAB_LIST = 37, PANEL = 38, PASSWORD_TEXT = 39, POPUP_MENU = 40, PROGRESS_BAR = 41, PUSH_BUTTON = 42, RADIO_BUTTON = 43, RADIO_MENU_ITEM = 44, ROOT_PANE = 45, ROW_HEADER = 46, SCROLL_BAR = 47, SCROLL_PANE = 48, SEPARATOR = 49, SLIDER = 50, SPLIT_PANE = 51, SPIN_BUTTON = 52, STATUSBAR = 53, TABLE = 54, TABLE_CELL = 55, TABLE_COLUMN_HEADER = 56, TABLE_ROW_HEADER = 57, TEAR_OFF_MENU_ITEM = 58, TERMINAL = 59, TEXT = 60, TOGGLE_BUTTON = 61, TOOL_BAR = 62, TOOL_TIP = 63, TREE = 64, TREE_TABLE = 65, UNKNOWN = 66, VIEWPORT = 67, WINDOW = 68, HEADER = 69, FOOTER = 70, PARAGRAPH = 71, RULER = 72, APPLICATION = 73, AUTOCOMPLETE = 74, EDIT_BAR = 75, EMBEDDED = 76, ENTRY = 77, CHART = 78, CAPTION = 79, DOCUMENT_FRAME = 80, HEADING = 81, PAGE = 82, SECTION = 83, REDUNDANT_OBJECT = 84, FORM = 85, LINK = 86, INPUT_METHOD_WINDOW = 87, TABLE_ROW = 88, TREE_ITEM = 89, DOCUMENT_SPREADSHEET = 90, DOCUMENT_PRESENTATION = 91, DOCUMENT_TEXT = 92, DOCUMENT_WEB = 93, DOCUMENT_EMAIL = 94, COMMENT = 95, LIST_BOX = 96, GROUPING = 97, IMAGE_MAP = 98, NOTIFICATION = 99, INFO_BAR = 100, LEVEL_BAR = 101, TITLE_BAR = 102, BLOCK_QUOTE = 103, AUDIO = 104, VIDEO = 105, DEFINITION = 106, ARTICLE = 107, LANDMARK = 108, LOG = 109, MARQUEE = 110, MATH = 111, RATING = 112, TIMER = 113, DESCRIPTION_LIST = 114, DESCRIPTION_TERM = 115, DESCRIPTION_VALUE = 116, STATIC = 117, MATH_FRACTION = 118, MATH_ROOT = 119, SUBSCRIPT = 120, SUPERSCRIPT = 121, FOOTNOTE = 122, CONTENT_DELETION = 123, CONTENT_INSERTION = 124, MARK = 125, SUGGESTION = 126, LAST_DEFINED = 127, } export namespace ScrollType { export const $gtype: GObject.GType<ScrollType>; } export enum ScrollType { TOP_LEFT = 0, BOTTOM_RIGHT = 1, TOP_EDGE = 2, BOTTOM_EDGE = 3, LEFT_EDGE = 4, RIGHT_EDGE = 5, ANYWHERE = 6, } export namespace StateType { export const $gtype: GObject.GType<StateType>; } export enum StateType { INVALID = 0, ACTIVE = 1, ARMED = 2, BUSY = 3, CHECKED = 4, DEFUNCT = 5, EDITABLE = 6, ENABLED = 7, EXPANDABLE = 8, EXPANDED = 9, FOCUSABLE = 10, FOCUSED = 11, HORIZONTAL = 12, ICONIFIED = 13, MODAL = 14, MULTI_LINE = 15, MULTISELECTABLE = 16, OPAQUE = 17, PRESSED = 18, RESIZABLE = 19, SELECTABLE = 20, SELECTED = 21, SENSITIVE = 22, SHOWING = 23, SINGLE_LINE = 24, STALE = 25, TRANSIENT = 26, VERTICAL = 27, VISIBLE = 28, MANAGES_DESCENDANTS = 29, INDETERMINATE = 30, TRUNCATED = 31, REQUIRED = 32, INVALID_ENTRY = 33, SUPPORTS_AUTOCOMPLETION = 34, SELECTABLE_TEXT = 35, DEFAULT = 36, ANIMATED = 37, VISITED = 38, CHECKABLE = 39, HAS_POPUP = 40, HAS_TOOLTIP = 41, READ_ONLY = 42, LAST_DEFINED = 43, } export namespace TextAttribute { export const $gtype: GObject.GType<TextAttribute>; } export enum TextAttribute { INVALID = 0, LEFT_MARGIN = 1, RIGHT_MARGIN = 2, INDENT = 3, INVISIBLE = 4, EDITABLE = 5, PIXELS_ABOVE_LINES = 6, PIXELS_BELOW_LINES = 7, PIXELS_INSIDE_WRAP = 8, BG_FULL_HEIGHT = 9, RISE = 10, UNDERLINE = 11, STRIKETHROUGH = 12, SIZE = 13, SCALE = 14, WEIGHT = 15, LANGUAGE = 16, FAMILY_NAME = 17, BG_COLOR = 18, FG_COLOR = 19, BG_STIPPLE = 20, FG_STIPPLE = 21, WRAP_MODE = 22, DIRECTION = 23, JUSTIFICATION = 24, STRETCH = 25, VARIANT = 26, STYLE = 27, TEXT_POSITION = 28, LAST_DEFINED = 29, } export namespace TextBoundary { export const $gtype: GObject.GType<TextBoundary>; } export enum TextBoundary { CHAR = 0, WORD_START = 1, WORD_END = 2, SENTENCE_START = 3, SENTENCE_END = 4, LINE_START = 5, LINE_END = 6, } export namespace TextClipType { export const $gtype: GObject.GType<TextClipType>; } export enum TextClipType { NONE = 0, MIN = 1, MAX = 2, BOTH = 3, } export namespace TextGranularity { export const $gtype: GObject.GType<TextGranularity>; } export enum TextGranularity { CHAR = 0, WORD = 1, SENTENCE = 2, LINE = 3, PARAGRAPH = 4, } export namespace ValueType { export const $gtype: GObject.GType<ValueType>; } export enum ValueType { VERY_WEAK = 0, WEAK = 1, ACCEPTABLE = 2, STRONG = 3, VERY_STRONG = 4, VERY_LOW = 5, LOW = 6, MEDIUM = 7, HIGH = 8, VERY_HIGH = 9, VERY_BAD = 10, BAD = 11, GOOD = 12, VERY_GOOD = 13, BEST = 14, LAST_DEFINED = 15, } export namespace HyperlinkStateFlags { export const $gtype: GObject.GType<HyperlinkStateFlags>; } export enum HyperlinkStateFlags { INLINE = 1, } export module GObjectAccessible { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; } } export class GObjectAccessible extends Object { static $gtype: GObject.GType<GObjectAccessible>; constructor(properties?: Partial<GObjectAccessible.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<GObjectAccessible.ConstructorProperties>, ...args: any[]): void; // Members get_object<T = GObject.Object>(): T; static for_object(obj: GObject.Object): Object; } export module Hyperlink { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; end_index: number; endIndex: number; number_of_anchors: number; numberOfAnchors: number; selected_link: boolean; selectedLink: boolean; start_index: number; startIndex: number; } } export class Hyperlink extends GObject.Object implements Action { static $gtype: GObject.GType<Hyperlink>; constructor(properties?: Partial<Hyperlink.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Hyperlink.ConstructorProperties>, ...args: any[]): void; // Properties end_index: number; endIndex: number; number_of_anchors: number; numberOfAnchors: number; selected_link: boolean; selectedLink: boolean; start_index: number; startIndex: number; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "link-activated", callback: (_source: this) => void): number; connect_after(signal: "link-activated", callback: (_source: this) => void): number; emit(signal: "link-activated"): void; // Members get_end_index(): number; get_n_anchors(): number; get_object(i: number): Object; get_start_index(): number; get_uri(i: number): string; is_inline(): boolean; is_selected_link(): boolean; is_valid(): boolean; vfunc_get_end_index(): number; vfunc_get_n_anchors(): number; vfunc_get_object(i: number): Object; vfunc_get_start_index(): number; vfunc_get_uri(i: number): string; vfunc_is_selected_link(): boolean; vfunc_is_valid(): boolean; vfunc_link_activated(): void; vfunc_link_state(): number; // Implemented Members do_action(i: number): boolean; get_description(i: number): string | null; get_keybinding(i: number): string | null; get_localized_name(i: number): string | null; get_n_actions(): number; get_name(i: number): string | null; set_description(i: number, desc: string): boolean; vfunc_do_action(i: number): boolean; vfunc_get_description(i: number): string | null; vfunc_get_keybinding(i: number): string | null; vfunc_get_localized_name(i: number): string | null; vfunc_get_n_actions(): number; vfunc_get_name(i: number): string | null; vfunc_set_description(i: number, desc: string): boolean; } export module Misc { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Misc extends GObject.Object { static $gtype: GObject.GType<Misc>; constructor(properties?: Partial<Misc.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Misc.ConstructorProperties>, ...args: any[]): void; // Members threads_enter(): void; threads_leave(): void; vfunc_threads_enter(): void; vfunc_threads_leave(): void; static get_instance(): Misc; } export module NoOpObject { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; } } export class NoOpObject extends Object implements Action, Component, Document, EditableText, Hypertext, Image, Selection, Table, TableCell, Text, Value, Window { static $gtype: GObject.GType<NoOpObject>; constructor(properties?: Partial<NoOpObject.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<NoOpObject.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](obj: GObject.Object): NoOpObject; // Implemented Members do_action(i: number): boolean; get_description(i: number): string | null; get_description(...args: never[]): never; get_keybinding(i: number): string | null; get_localized_name(i: number): string | null; get_n_actions(): number; get_name(i: number): string | null; get_name(...args: never[]): never; set_description(i: number, desc: string): boolean; set_description(...args: never[]): never; vfunc_do_action(i: number): boolean; vfunc_get_description(i: number): string | null; vfunc_get_description(...args: never[]): never; vfunc_get_keybinding(i: number): string | null; vfunc_get_localized_name(i: number): string | null; vfunc_get_n_actions(): number; vfunc_get_name(i: number): string | null; vfunc_get_name(...args: never[]): never; vfunc_set_description(i: number, desc: string): boolean; vfunc_set_description(...args: never[]): never; contains(x: number, y: number, coord_type: CoordType): boolean; get_alpha(): number; get_extents(coord_type: CoordType): [number | null, number | null, number | null, number | null]; get_layer(): Layer; get_mdi_zorder(): number; get_position(coord_type: CoordType): [number | null, number | null]; get_position(...args: never[]): never; get_size(): [number | null, number | null]; grab_focus(): boolean; ref_accessible_at_point(x: number, y: number, coord_type: CoordType): Object | null; remove_focus_handler(handler_id: number): void; scroll_to(type: ScrollType): boolean; scroll_to_point(coords: CoordType, x: number, y: number): boolean; set_extents(x: number, y: number, width: number, height: number, coord_type: CoordType): boolean; set_position(x: number, y: number, coord_type: CoordType): boolean; set_size(width: number, height: number): boolean; vfunc_bounds_changed(bounds: Rectangle): void; vfunc_contains(x: number, y: number, coord_type: CoordType): boolean; vfunc_get_alpha(): number; vfunc_get_extents(coord_type: CoordType): [number | null, number | null, number | null, number | null]; vfunc_get_layer(): Layer; vfunc_get_mdi_zorder(): number; vfunc_get_position(coord_type: CoordType): [number | null, number | null]; vfunc_get_position(...args: never[]): never; vfunc_get_size(): [number | null, number | null]; vfunc_grab_focus(): boolean; vfunc_ref_accessible_at_point(x: number, y: number, coord_type: CoordType): Object | null; vfunc_remove_focus_handler(handler_id: number): void; vfunc_scroll_to(type: ScrollType): boolean; vfunc_scroll_to_point(coords: CoordType, x: number, y: number): boolean; vfunc_set_extents(x: number, y: number, width: number, height: number, coord_type: CoordType): boolean; vfunc_set_position(x: number, y: number, coord_type: CoordType): boolean; vfunc_set_size(width: number, height: number): boolean; get_attribute_value(attribute_name: string): string | null; get_attributes(): AttributeSet; get_current_page_number(): number; get_document(): any | null; get_document_type(): string; get_locale(): string; get_page_count(): number; set_attribute_value(attribute_name: string, attribute_value: string): boolean; vfunc_get_current_page_number(): number; vfunc_get_document(): any | null; vfunc_get_document_attribute_value(attribute_name: string): string | null; vfunc_get_document_attributes(): AttributeSet; vfunc_get_document_locale(): string; vfunc_get_document_type(): string; vfunc_get_page_count(): number; vfunc_set_document_attribute(attribute_name: string, attribute_value: string): boolean; copy_text(start_pos: number, end_pos: number): void; cut_text(start_pos: number, end_pos: number): void; delete_text(start_pos: number, end_pos: number): void; insert_text(string: string, length: number, position: number): void; paste_text(position: number): void; set_run_attributes(attrib_set: AttributeSet, start_offset: number, end_offset: number): boolean; set_text_contents(string: string): void; vfunc_copy_text(start_pos: number, end_pos: number): void; vfunc_cut_text(start_pos: number, end_pos: number): void; vfunc_delete_text(start_pos: number, end_pos: number): void; vfunc_insert_text(string: string, length: number, position: number): void; vfunc_paste_text(position: number): void; vfunc_set_run_attributes(attrib_set: AttributeSet, start_offset: number, end_offset: number): boolean; vfunc_set_text_contents(string: string): void; get_link(link_index: number): Hyperlink; get_link_index(char_index: number): number; get_n_links(): number; vfunc_get_link(link_index: number): Hyperlink; vfunc_get_link_index(char_index: number): number; vfunc_get_n_links(): number; vfunc_link_selected(link_index: number): void; get_image_description(): string; get_image_locale(): string | null; get_image_position(coord_type: CoordType): [number | null, number | null]; get_image_size(): [number | null, number | null]; set_image_description(description: string): boolean; vfunc_get_image_description(): string; vfunc_get_image_locale(): string | null; vfunc_get_image_position(coord_type: CoordType): [number | null, number | null]; vfunc_get_image_size(): [number | null, number | null]; vfunc_set_image_description(description: string): boolean; add_selection(i: number): boolean; add_selection(...args: never[]): never; clear_selection(): boolean; get_selection_count(): number; is_child_selected(i: number): boolean; ref_selection(i: number): Object | null; remove_selection(i: number): boolean; select_all_selection(): boolean; vfunc_add_selection(i: number): boolean; vfunc_add_selection(...args: never[]): never; vfunc_clear_selection(): boolean; vfunc_get_selection_count(): number; vfunc_is_child_selected(i: number): boolean; vfunc_ref_selection(i: number): Object | null; vfunc_remove_selection(i: number): boolean; vfunc_select_all_selection(): boolean; vfunc_selection_changed(): void; add_column_selection(column: number): boolean; add_row_selection(row: number): boolean; get_caption(): Object | null; get_column_at_index(index_: number): number; get_column_description(column: number): string; get_column_extent_at(row: number, column: number): number; get_column_header(column: number): Object | null; get_index_at(row: number, column: number): number; get_n_columns(): number; get_n_rows(): number; get_row_at_index(index_: number): number; get_row_description(row: number): string | null; get_row_extent_at(row: number, column: number): number; get_row_header(row: number): Object | null; get_selected_columns(selected: number): number; get_selected_rows(selected: number): number; get_summary(): Object; is_column_selected(column: number): boolean; is_row_selected(row: number): boolean; is_selected(row: number, column: number): boolean; ref_at(row: number, column: number): Object; remove_column_selection(column: number): boolean; remove_row_selection(row: number): boolean; set_caption(caption: Object): void; set_column_description(column: number, description: string): void; set_column_header(column: number, header: Object): void; set_row_description(row: number, description: string): void; set_row_header(row: number, header: Object): void; set_summary(accessible: Object): void; vfunc_add_column_selection(column: number): boolean; vfunc_add_row_selection(row: number): boolean; vfunc_column_deleted(column: number, num_deleted: number): void; vfunc_column_inserted(column: number, num_inserted: number): void; vfunc_column_reordered(): void; vfunc_get_caption(): Object | null; vfunc_get_column_at_index(index_: number): number; vfunc_get_column_description(column: number): string; vfunc_get_column_extent_at(row: number, column: number): number; vfunc_get_column_header(column: number): Object | null; vfunc_get_index_at(row: number, column: number): number; vfunc_get_n_columns(): number; vfunc_get_n_rows(): number; vfunc_get_row_at_index(index_: number): number; vfunc_get_row_description(row: number): string | null; vfunc_get_row_extent_at(row: number, column: number): number; vfunc_get_row_header(row: number): Object | null; vfunc_get_selected_columns(selected: number): number; vfunc_get_selected_rows(selected: number): number; vfunc_get_summary(): Object; vfunc_is_column_selected(column: number): boolean; vfunc_is_row_selected(row: number): boolean; vfunc_is_selected(row: number, column: number): boolean; vfunc_model_changed(): void; vfunc_ref_at(row: number, column: number): Object; vfunc_remove_column_selection(column: number): boolean; vfunc_remove_row_selection(row: number): boolean; vfunc_row_deleted(row: number, num_deleted: number): void; vfunc_row_inserted(row: number, num_inserted: number): void; vfunc_row_reordered(): void; vfunc_set_caption(caption: Object): void; vfunc_set_column_description(column: number, description: string): void; vfunc_set_column_header(column: number, header: Object): void; vfunc_set_row_description(row: number, description: string): void; vfunc_set_row_header(row: number, header: Object): void; vfunc_set_summary(accessible: Object): void; get_column_header_cells(): Object[]; get_column_span(): number; get_position(): [boolean, number, number]; get_position(...args: never[]): never; get_row_column_span(): [boolean, number, number, number, number]; get_row_header_cells(): Object[]; get_row_span(): number; get_table(): Object; vfunc_get_column_header_cells(): Object[]; vfunc_get_column_span(): number; vfunc_get_position(): [boolean, number, number]; vfunc_get_position(...args: never[]): never; vfunc_get_row_column_span(): [boolean, number, number, number, number]; vfunc_get_row_header_cells(): Object[]; vfunc_get_row_span(): number; vfunc_get_table(): Object; add_selection(start_offset: number, end_offset: number): boolean; add_selection(...args: never[]): never; get_bounded_ranges( rect: TextRectangle, coord_type: CoordType, x_clip_type: TextClipType, y_clip_type: TextClipType ): TextRange[]; get_caret_offset(): number; get_character_at_offset(offset: number): number; get_character_count(): number; get_character_extents( offset: number, coords: CoordType ): [number | null, number | null, number | null, number | null]; get_default_attributes(): AttributeSet; get_n_selections(): number; get_offset_at_point(x: number, y: number, coords: CoordType): number; get_range_extents(start_offset: number, end_offset: number, coord_type: CoordType): TextRectangle; get_run_attributes(offset: number): [AttributeSet, number, number]; get_selection(selection_num: number): [string, number, number]; get_string_at_offset(offset: number, granularity: TextGranularity): [string | null, number, number]; get_text(start_offset: number, end_offset: number): string; get_text_after_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; get_text_at_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; get_text_before_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; remove_selection(selection_num: number): boolean; scroll_substring_to(start_offset: number, end_offset: number, type: ScrollType): boolean; scroll_substring_to_point( start_offset: number, end_offset: number, coords: CoordType, x: number, y: number ): boolean; set_caret_offset(offset: number): boolean; set_selection(selection_num: number, start_offset: number, end_offset: number): boolean; vfunc_add_selection(start_offset: number, end_offset: number): boolean; vfunc_add_selection(...args: never[]): never; vfunc_get_bounded_ranges( rect: TextRectangle, coord_type: CoordType, x_clip_type: TextClipType, y_clip_type: TextClipType ): TextRange[]; vfunc_get_caret_offset(): number; vfunc_get_character_at_offset(offset: number): number; vfunc_get_character_count(): number; vfunc_get_character_extents( offset: number, coords: CoordType ): [number | null, number | null, number | null, number | null]; vfunc_get_default_attributes(): AttributeSet; vfunc_get_n_selections(): number; vfunc_get_offset_at_point(x: number, y: number, coords: CoordType): number; vfunc_get_range_extents(start_offset: number, end_offset: number, coord_type: CoordType): TextRectangle; vfunc_get_run_attributes(offset: number): [AttributeSet, number, number]; vfunc_get_selection(selection_num: number): [string, number, number]; vfunc_get_string_at_offset(offset: number, granularity: TextGranularity): [string | null, number, number]; vfunc_get_text(start_offset: number, end_offset: number): string; vfunc_get_text_after_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; vfunc_get_text_at_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; vfunc_get_text_before_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; vfunc_remove_selection(selection_num: number): boolean; vfunc_scroll_substring_to(start_offset: number, end_offset: number, type: ScrollType): boolean; vfunc_scroll_substring_to_point( start_offset: number, end_offset: number, coords: CoordType, x: number, y: number ): boolean; vfunc_set_caret_offset(offset: number): boolean; vfunc_set_selection(selection_num: number, start_offset: number, end_offset: number): boolean; vfunc_text_attributes_changed(): void; vfunc_text_caret_moved(location: number): void; vfunc_text_changed(position: number, length: number): void; vfunc_text_selection_changed(): void; get_current_value(): unknown; get_increment(): number; get_maximum_value(): unknown; get_minimum_increment(): unknown; get_minimum_value(): unknown; get_range(): Range | null; get_sub_ranges(): Range[]; get_value_and_text(): [number, string | null]; set_current_value(value: any): boolean; set_value(new_value: number): void; vfunc_get_current_value(): unknown; vfunc_get_increment(): number; vfunc_get_maximum_value(): unknown; vfunc_get_minimum_increment(): unknown; vfunc_get_minimum_value(): unknown; vfunc_get_range(): Range | null; vfunc_get_sub_ranges(): Range[]; vfunc_get_value_and_text(): [number, string | null]; vfunc_set_current_value(value: any): boolean; vfunc_set_value(new_value: number): void; } export module NoOpObjectFactory { export interface ConstructorProperties extends ObjectFactory.ConstructorProperties { [key: string]: any; } } export class NoOpObjectFactory extends ObjectFactory { static $gtype: GObject.GType<NoOpObjectFactory>; constructor(properties?: Partial<NoOpObjectFactory.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<NoOpObjectFactory.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): NoOpObjectFactory; } export module Object { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; accessible_component_layer: number; accessibleComponentLayer: number; accessible_component_mdi_zorder: number; accessibleComponentMdiZorder: number; accessible_description: string; accessibleDescription: string; accessible_hypertext_nlinks: number; accessibleHypertextNlinks: number; accessible_name: string; accessibleName: string; accessible_parent: Object; accessibleParent: Object; accessible_role: Role; accessibleRole: Role; accessible_table_caption: string; accessibleTableCaption: string; accessible_table_caption_object: Object; accessibleTableCaptionObject: Object; accessible_table_column_description: string; accessibleTableColumnDescription: string; accessible_table_column_header: Object; accessibleTableColumnHeader: Object; accessible_table_row_description: string; accessibleTableRowDescription: string; accessible_table_row_header: Object; accessibleTableRowHeader: Object; accessible_table_summary: Object; accessibleTableSummary: Object; accessible_value: number; accessibleValue: number; } } export class Object extends GObject.Object { static $gtype: GObject.GType<Object>; constructor(properties?: Partial<Object.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Object.ConstructorProperties>, ...args: any[]): void; // Properties accessible_component_layer: number; accessibleComponentLayer: number; accessible_component_mdi_zorder: number; accessibleComponentMdiZorder: number; accessible_description: string; accessibleDescription: string; accessible_hypertext_nlinks: number; accessibleHypertextNlinks: number; accessible_name: string; accessibleName: string; accessible_parent: Object; accessibleParent: Object; accessible_role: Role; accessibleRole: Role; accessible_table_caption: string; accessibleTableCaption: string; accessible_table_caption_object: Object; accessibleTableCaptionObject: Object; accessible_table_column_description: string; accessibleTableColumnDescription: string; accessible_table_column_header: Object; accessibleTableColumnHeader: Object; accessible_table_row_description: string; accessibleTableRowDescription: string; accessible_table_row_header: Object; accessibleTableRowHeader: Object; accessible_table_summary: Object; accessibleTableSummary: Object; accessible_value: number; accessibleValue: number; // Fields description: string; name: string; role: Role; relation_set: RelationSet; layer: Layer; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "active-descendant-changed", callback: (_source: this, arg1: Object) => void): number; connect_after(signal: "active-descendant-changed", callback: (_source: this, arg1: Object) => void): number; emit(signal: "active-descendant-changed", arg1: Object): void; connect(signal: "children-changed", callback: (_source: this, arg1: number, arg2: Object) => void): number; connect_after(signal: "children-changed", callback: (_source: this, arg1: number, arg2: Object) => void): number; emit(signal: "children-changed", arg1: number, arg2: Object): void; connect(signal: "focus-event", callback: (_source: this, arg1: boolean) => void): number; connect_after(signal: "focus-event", callback: (_source: this, arg1: boolean) => void): number; emit(signal: "focus-event", arg1: boolean): void; connect(signal: "property-change", callback: (_source: this, arg1: PropertyValues) => void): number; connect_after(signal: "property-change", callback: (_source: this, arg1: PropertyValues) => void): number; emit(signal: "property-change", arg1: PropertyValues): void; connect(signal: "state-change", callback: (_source: this, arg1: string, arg2: boolean) => void): number; connect_after(signal: "state-change", callback: (_source: this, arg1: string, arg2: boolean) => void): number; emit(signal: "state-change", arg1: string, arg2: boolean): void; connect(signal: "visible-data-changed", callback: (_source: this) => void): number; connect_after(signal: "visible-data-changed", callback: (_source: this) => void): number; emit(signal: "visible-data-changed"): void; // Members add_relationship(relationship: RelationType, target: Object): boolean; get_accessible_id(): string; get_attributes(): AttributeSet; get_description(): string; get_index_in_parent(): number; get_layer(): Layer; get_mdi_zorder(): number; get_n_accessible_children(): number; get_name(): string; get_object_locale(): string; get_parent(): Object; get_role(): Role; initialize(data?: any | null): void; notify_state_change(state: State, value: boolean): void; peek_parent(): Object; ref_accessible_child(i: number): Object; ref_relation_set(): RelationSet; ref_state_set(): StateSet; remove_property_change_handler(handler_id: number): void; remove_relationship(relationship: RelationType, target: Object): boolean; set_accessible_id(name: string): void; set_description(description: string): void; set_name(name: string): void; set_parent(parent: Object): void; set_role(role: Role): void; vfunc_active_descendant_changed(child?: any | null): void; vfunc_children_changed(change_index: number, changed_child?: any | null): void; vfunc_focus_event(focus_in: boolean): void; vfunc_get_attributes(): AttributeSet; vfunc_get_description(): string; vfunc_get_index_in_parent(): number; vfunc_get_layer(): Layer; vfunc_get_mdi_zorder(): number; vfunc_get_n_children(): number; vfunc_get_name(): string; vfunc_get_object_locale(): string; vfunc_get_parent(): Object; vfunc_get_role(): Role; vfunc_initialize(data?: any | null): void; vfunc_property_change(values: PropertyValues): void; vfunc_ref_relation_set(): RelationSet; vfunc_ref_state_set(): StateSet; vfunc_remove_property_change_handler(handler_id: number): void; vfunc_set_description(description: string): void; vfunc_set_name(name: string): void; vfunc_set_parent(parent: Object): void; vfunc_set_role(role: Role): void; vfunc_state_change(name: string, state_set: boolean): void; vfunc_visible_data_changed(): void; } export module ObjectFactory { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class ObjectFactory extends GObject.Object { static $gtype: GObject.GType<ObjectFactory>; constructor(properties?: Partial<ObjectFactory.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<ObjectFactory.ConstructorProperties>, ...args: any[]): void; // Members create_accessible(obj: GObject.Object): Object; get_accessible_type(): GObject.GType; invalidate(): void; vfunc_invalidate(): void; } export module Plug { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; } } export class Plug extends Object implements Component { static $gtype: GObject.GType<Plug>; constructor(properties?: Partial<Plug.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Plug.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): Plug; // Members get_id(): string; set_child(child: Object): void; vfunc_get_object_id(): string; // Implemented Members contains(x: number, y: number, coord_type: CoordType): boolean; get_alpha(): number; get_extents(coord_type: CoordType): [number | null, number | null, number | null, number | null]; get_layer(): Layer; get_mdi_zorder(): number; get_position(coord_type: CoordType): [number | null, number | null]; get_size(): [number | null, number | null]; grab_focus(): boolean; ref_accessible_at_point(x: number, y: number, coord_type: CoordType): Object | null; remove_focus_handler(handler_id: number): void; scroll_to(type: ScrollType): boolean; scroll_to_point(coords: CoordType, x: number, y: number): boolean; set_extents(x: number, y: number, width: number, height: number, coord_type: CoordType): boolean; set_position(x: number, y: number, coord_type: CoordType): boolean; set_size(width: number, height: number): boolean; vfunc_bounds_changed(bounds: Rectangle): void; vfunc_contains(x: number, y: number, coord_type: CoordType): boolean; vfunc_get_alpha(): number; vfunc_get_extents(coord_type: CoordType): [number | null, number | null, number | null, number | null]; vfunc_get_layer(): Layer; vfunc_get_mdi_zorder(): number; vfunc_get_position(coord_type: CoordType): [number | null, number | null]; vfunc_get_size(): [number | null, number | null]; vfunc_grab_focus(): boolean; vfunc_ref_accessible_at_point(x: number, y: number, coord_type: CoordType): Object | null; vfunc_remove_focus_handler(handler_id: number): void; vfunc_scroll_to(type: ScrollType): boolean; vfunc_scroll_to_point(coords: CoordType, x: number, y: number): boolean; vfunc_set_extents(x: number, y: number, width: number, height: number, coord_type: CoordType): boolean; vfunc_set_position(x: number, y: number, coord_type: CoordType): boolean; vfunc_set_size(width: number, height: number): boolean; } export module Registry { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Registry extends GObject.Object { static $gtype: GObject.GType<Registry>; constructor(properties?: Partial<Registry.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Registry.ConstructorProperties>, ...args: any[]): void; // Fields factory_type_registry: GLib.HashTable<any, any>; factory_singleton_cache: GLib.HashTable<any, any>; // Members get_factory(type: GObject.GType): ObjectFactory; get_factory_type(type: GObject.GType): GObject.GType; set_factory_type(type: GObject.GType, factory_type: GObject.GType): void; } export module Relation { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; relation_type: RelationType; relationType: RelationType; target: GObject.ValueArray; } } export class Relation extends GObject.Object { static $gtype: GObject.GType<Relation>; constructor(properties?: Partial<Relation.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Relation.ConstructorProperties>, ...args: any[]): void; // Properties relation_type: RelationType; relationType: RelationType; target: GObject.ValueArray; // Fields relationship: RelationType; // Constructors static ["new"](targets: Object[], relationship: RelationType): Relation; // Members add_target(target: Object): void; get_relation_type(): RelationType; get_target(): Object[]; remove_target(target: Object): boolean; } export module RelationSet { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class RelationSet extends GObject.Object { static $gtype: GObject.GType<RelationSet>; constructor(properties?: Partial<RelationSet.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<RelationSet.ConstructorProperties>, ...args: any[]): void; // Fields relations: any[]; // Constructors static ["new"](): RelationSet; // Members add(relation: Relation): void; add_relation_by_type(relationship: RelationType, target: Object): void; contains(relationship: RelationType): boolean; contains_target(relationship: RelationType, target: Object): boolean; get_n_relations(): number; get_relation(i: number): Relation; get_relation_by_type(relationship: RelationType): Relation; remove(relation: Relation): void; } export module Socket { export interface ConstructorProperties extends Object.ConstructorProperties { [key: string]: any; } } export class Socket extends Object implements Component { static $gtype: GObject.GType<Socket>; constructor(properties?: Partial<Socket.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Socket.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): Socket; // Members embed(plug_id: string): void; is_occupied(): boolean; vfunc_embed(plug_id: string): void; // Implemented Members contains(x: number, y: number, coord_type: CoordType): boolean; get_alpha(): number; get_extents(coord_type: CoordType): [number | null, number | null, number | null, number | null]; get_layer(): Layer; get_mdi_zorder(): number; get_position(coord_type: CoordType): [number | null, number | null]; get_size(): [number | null, number | null]; grab_focus(): boolean; ref_accessible_at_point(x: number, y: number, coord_type: CoordType): Object | null; remove_focus_handler(handler_id: number): void; scroll_to(type: ScrollType): boolean; scroll_to_point(coords: CoordType, x: number, y: number): boolean; set_extents(x: number, y: number, width: number, height: number, coord_type: CoordType): boolean; set_position(x: number, y: number, coord_type: CoordType): boolean; set_size(width: number, height: number): boolean; vfunc_bounds_changed(bounds: Rectangle): void; vfunc_contains(x: number, y: number, coord_type: CoordType): boolean; vfunc_get_alpha(): number; vfunc_get_extents(coord_type: CoordType): [number | null, number | null, number | null, number | null]; vfunc_get_layer(): Layer; vfunc_get_mdi_zorder(): number; vfunc_get_position(coord_type: CoordType): [number | null, number | null]; vfunc_get_size(): [number | null, number | null]; vfunc_grab_focus(): boolean; vfunc_ref_accessible_at_point(x: number, y: number, coord_type: CoordType): Object | null; vfunc_remove_focus_handler(handler_id: number): void; vfunc_scroll_to(type: ScrollType): boolean; vfunc_scroll_to_point(coords: CoordType, x: number, y: number): boolean; vfunc_set_extents(x: number, y: number, width: number, height: number, coord_type: CoordType): boolean; vfunc_set_position(x: number, y: number, coord_type: CoordType): boolean; vfunc_set_size(width: number, height: number): boolean; } export module StateSet { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class StateSet extends GObject.Object { static $gtype: GObject.GType<StateSet>; constructor(properties?: Partial<StateSet.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<StateSet.ConstructorProperties>, ...args: any[]): void; // Constructors static ["new"](): StateSet; // Members add_state(type: StateType): boolean; add_states(types: StateType[]): void; and_sets(compare_set: StateSet): StateSet; clear_states(): void; contains_state(type: StateType): boolean; contains_states(types: StateType[]): boolean; is_empty(): boolean; or_sets(compare_set: StateSet): StateSet | null; remove_state(type: StateType): boolean; xor_sets(compare_set: StateSet): StateSet; } export module Util { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class Util extends GObject.Object { static $gtype: GObject.GType<Util>; constructor(properties?: Partial<Util.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Util.ConstructorProperties>, ...args: any[]): void; } export class Attribute { static $gtype: GObject.GType<Attribute>; constructor( properties?: Partial<{ name?: string; value?: string; }> ); constructor(copy: Attribute); // Fields name: string; value: string; // Members static set_free(attrib_set: AttributeSet): void; } export class Implementor { static $gtype: GObject.GType<Implementor>; constructor(copy: Implementor); // Members ref_accessible(): Object; } export class KeyEventStruct { static $gtype: GObject.GType<KeyEventStruct>; constructor( properties?: Partial<{ type?: number; state?: number; keyval?: number; length?: number; string?: string; keycode?: number; timestamp?: number; }> ); constructor(copy: KeyEventStruct); // Fields type: number; state: number; keyval: number; length: number; string: string; keycode: number; timestamp: number; } export class PropertyValues { static $gtype: GObject.GType<PropertyValues>; constructor(copy: PropertyValues); // Fields property_name: string; old_value: GObject.Value; new_value: GObject.Value; } export class Range { static $gtype: GObject.GType<Range>; constructor(lower_limit: number, upper_limit: number, description: string); constructor(copy: Range); // Constructors static ["new"](lower_limit: number, upper_limit: number, description: string): Range; // Members copy(): Range; free(): void; get_description(): string; get_lower_limit(): number; get_upper_limit(): number; } export class Rectangle { static $gtype: GObject.GType<Rectangle>; constructor( properties?: Partial<{ x?: number; y?: number; width?: number; height?: number; }> ); constructor(copy: Rectangle); // Fields x: number; y: number; width: number; height: number; } export class TextRange { static $gtype: GObject.GType<TextRange>; constructor( properties?: Partial<{ bounds?: TextRectangle; start_offset?: number; end_offset?: number; content?: string; }> ); constructor(copy: TextRange); // Fields bounds: TextRectangle; start_offset: number; end_offset: number; content: string; } export class TextRectangle { static $gtype: GObject.GType<TextRectangle>; constructor( properties?: Partial<{ x?: number; y?: number; width?: number; height?: number; }> ); constructor(copy: TextRectangle); // Fields x: number; y: number; width: number; height: number; } export interface ActionNamespace { $gtype: GObject.GType<Action>; prototype: ActionPrototype; } export type Action = ActionPrototype; export interface ActionPrototype extends GObject.Object { // Members do_action(i: number): boolean; get_description(i: number): string | null; get_keybinding(i: number): string | null; get_localized_name(i: number): string | null; get_n_actions(): number; get_name(i: number): string | null; set_description(i: number, desc: string): boolean; vfunc_do_action(i: number): boolean; vfunc_get_description(i: number): string | null; vfunc_get_keybinding(i: number): string | null; vfunc_get_localized_name(i: number): string | null; vfunc_get_n_actions(): number; vfunc_get_name(i: number): string | null; vfunc_set_description(i: number, desc: string): boolean; } export const Action: ActionNamespace; export interface ComponentNamespace { $gtype: GObject.GType<Component>; prototype: ComponentPrototype; } export type Component = ComponentPrototype; export interface ComponentPrototype extends GObject.Object { // Members contains(x: number, y: number, coord_type: CoordType): boolean; get_alpha(): number; get_extents(coord_type: CoordType): [number | null, number | null, number | null, number | null]; get_layer(): Layer; get_mdi_zorder(): number; get_position(coord_type: CoordType): [number | null, number | null]; get_size(): [number | null, number | null]; grab_focus(): boolean; ref_accessible_at_point(x: number, y: number, coord_type: CoordType): Object | null; remove_focus_handler(handler_id: number): void; scroll_to(type: ScrollType): boolean; scroll_to_point(coords: CoordType, x: number, y: number): boolean; set_extents(x: number, y: number, width: number, height: number, coord_type: CoordType): boolean; set_position(x: number, y: number, coord_type: CoordType): boolean; set_size(width: number, height: number): boolean; vfunc_bounds_changed(bounds: Rectangle): void; vfunc_contains(x: number, y: number, coord_type: CoordType): boolean; vfunc_get_alpha(): number; vfunc_get_extents(coord_type: CoordType): [number | null, number | null, number | null, number | null]; vfunc_get_layer(): Layer; vfunc_get_mdi_zorder(): number; vfunc_get_position(coord_type: CoordType): [number | null, number | null]; vfunc_get_size(): [number | null, number | null]; vfunc_grab_focus(): boolean; vfunc_ref_accessible_at_point(x: number, y: number, coord_type: CoordType): Object | null; vfunc_remove_focus_handler(handler_id: number): void; vfunc_scroll_to(type: ScrollType): boolean; vfunc_scroll_to_point(coords: CoordType, x: number, y: number): boolean; vfunc_set_extents(x: number, y: number, width: number, height: number, coord_type: CoordType): boolean; vfunc_set_position(x: number, y: number, coord_type: CoordType): boolean; vfunc_set_size(width: number, height: number): boolean; } export const Component: ComponentNamespace; export interface DocumentNamespace { $gtype: GObject.GType<Document>; prototype: DocumentPrototype; } export type Document = DocumentPrototype; export interface DocumentPrototype extends GObject.Object { // Members get_attribute_value(attribute_name: string): string | null; get_attributes(): AttributeSet; get_current_page_number(): number; get_document(): any | null; get_document_type(): string; get_locale(): string; get_page_count(): number; set_attribute_value(attribute_name: string, attribute_value: string): boolean; vfunc_get_current_page_number(): number; vfunc_get_document(): any | null; vfunc_get_document_attribute_value(attribute_name: string): string | null; vfunc_get_document_attributes(): AttributeSet; vfunc_get_document_locale(): string; vfunc_get_document_type(): string; vfunc_get_page_count(): number; vfunc_set_document_attribute(attribute_name: string, attribute_value: string): boolean; } export const Document: DocumentNamespace; export interface EditableTextNamespace { $gtype: GObject.GType<EditableText>; prototype: EditableTextPrototype; } export type EditableText = EditableTextPrototype; export interface EditableTextPrototype extends GObject.Object { // Members copy_text(start_pos: number, end_pos: number): void; cut_text(start_pos: number, end_pos: number): void; delete_text(start_pos: number, end_pos: number): void; insert_text(string: string, length: number, position: number): void; paste_text(position: number): void; set_run_attributes(attrib_set: AttributeSet, start_offset: number, end_offset: number): boolean; set_text_contents(string: string): void; vfunc_copy_text(start_pos: number, end_pos: number): void; vfunc_cut_text(start_pos: number, end_pos: number): void; vfunc_delete_text(start_pos: number, end_pos: number): void; vfunc_insert_text(string: string, length: number, position: number): void; vfunc_paste_text(position: number): void; vfunc_set_run_attributes(attrib_set: AttributeSet, start_offset: number, end_offset: number): boolean; vfunc_set_text_contents(string: string): void; } export const EditableText: EditableTextNamespace; export interface HyperlinkImplNamespace { $gtype: GObject.GType<HyperlinkImpl>; prototype: HyperlinkImplPrototype; } export type HyperlinkImpl = HyperlinkImplPrototype; export interface HyperlinkImplPrototype extends GObject.Object { // Members get_hyperlink(): Hyperlink; vfunc_get_hyperlink(): Hyperlink; } export const HyperlinkImpl: HyperlinkImplNamespace; export interface HypertextNamespace { $gtype: GObject.GType<Hypertext>; prototype: HypertextPrototype; } export type Hypertext = HypertextPrototype; export interface HypertextPrototype extends GObject.Object { // Members get_link(link_index: number): Hyperlink; get_link_index(char_index: number): number; get_n_links(): number; vfunc_get_link(link_index: number): Hyperlink; vfunc_get_link_index(char_index: number): number; vfunc_get_n_links(): number; vfunc_link_selected(link_index: number): void; } export const Hypertext: HypertextNamespace; export interface ImageNamespace { $gtype: GObject.GType<Image>; prototype: ImagePrototype; } export type Image = ImagePrototype; export interface ImagePrototype extends GObject.Object { // Members get_image_description(): string; get_image_locale(): string | null; get_image_position(coord_type: CoordType): [number | null, number | null]; get_image_size(): [number | null, number | null]; set_image_description(description: string): boolean; vfunc_get_image_description(): string; vfunc_get_image_locale(): string | null; vfunc_get_image_position(coord_type: CoordType): [number | null, number | null]; vfunc_get_image_size(): [number | null, number | null]; vfunc_set_image_description(description: string): boolean; } export const Image: ImageNamespace; export interface ImplementorIfaceNamespace { $gtype: GObject.GType<ImplementorIface>; prototype: ImplementorIfacePrototype; } export type ImplementorIface = ImplementorIfacePrototype; export interface ImplementorIfacePrototype extends GObject.Object {} export const ImplementorIface: ImplementorIfaceNamespace; export interface SelectionNamespace { $gtype: GObject.GType<Selection>; prototype: SelectionPrototype; } export type Selection = SelectionPrototype; export interface SelectionPrototype extends GObject.Object { // Members add_selection(i: number): boolean; clear_selection(): boolean; get_selection_count(): number; is_child_selected(i: number): boolean; ref_selection(i: number): Object | null; remove_selection(i: number): boolean; select_all_selection(): boolean; vfunc_add_selection(i: number): boolean; vfunc_clear_selection(): boolean; vfunc_get_selection_count(): number; vfunc_is_child_selected(i: number): boolean; vfunc_ref_selection(i: number): Object | null; vfunc_remove_selection(i: number): boolean; vfunc_select_all_selection(): boolean; vfunc_selection_changed(): void; } export const Selection: SelectionNamespace; export interface StreamableContentNamespace { $gtype: GObject.GType<StreamableContent>; prototype: StreamableContentPrototype; } export type StreamableContent = StreamableContentPrototype; export interface StreamableContentPrototype extends GObject.Object { // Members get_mime_type(i: number): string; get_n_mime_types(): number; get_stream(mime_type: string): GLib.IOChannel; get_uri(mime_type: string): string | null; vfunc_get_mime_type(i: number): string; vfunc_get_n_mime_types(): number; vfunc_get_stream(mime_type: string): GLib.IOChannel; vfunc_get_uri(mime_type: string): string | null; } export const StreamableContent: StreamableContentNamespace; export interface TableNamespace { $gtype: GObject.GType<Table>; prototype: TablePrototype; } export type Table = TablePrototype; export interface TablePrototype extends GObject.Object { // Members add_column_selection(column: number): boolean; add_row_selection(row: number): boolean; get_caption(): Object | null; get_column_at_index(index_: number): number; get_column_description(column: number): string; get_column_extent_at(row: number, column: number): number; get_column_header(column: number): Object | null; get_index_at(row: number, column: number): number; get_n_columns(): number; get_n_rows(): number; get_row_at_index(index_: number): number; get_row_description(row: number): string | null; get_row_extent_at(row: number, column: number): number; get_row_header(row: number): Object | null; get_selected_columns(selected: number): number; get_selected_rows(selected: number): number; get_summary(): Object; is_column_selected(column: number): boolean; is_row_selected(row: number): boolean; is_selected(row: number, column: number): boolean; ref_at(row: number, column: number): Object; remove_column_selection(column: number): boolean; remove_row_selection(row: number): boolean; set_caption(caption: Object): void; set_column_description(column: number, description: string): void; set_column_header(column: number, header: Object): void; set_row_description(row: number, description: string): void; set_row_header(row: number, header: Object): void; set_summary(accessible: Object): void; vfunc_add_column_selection(column: number): boolean; vfunc_add_row_selection(row: number): boolean; vfunc_column_deleted(column: number, num_deleted: number): void; vfunc_column_inserted(column: number, num_inserted: number): void; vfunc_column_reordered(): void; vfunc_get_caption(): Object | null; vfunc_get_column_at_index(index_: number): number; vfunc_get_column_description(column: number): string; vfunc_get_column_extent_at(row: number, column: number): number; vfunc_get_column_header(column: number): Object | null; vfunc_get_index_at(row: number, column: number): number; vfunc_get_n_columns(): number; vfunc_get_n_rows(): number; vfunc_get_row_at_index(index_: number): number; vfunc_get_row_description(row: number): string | null; vfunc_get_row_extent_at(row: number, column: number): number; vfunc_get_row_header(row: number): Object | null; vfunc_get_selected_columns(selected: number): number; vfunc_get_selected_rows(selected: number): number; vfunc_get_summary(): Object; vfunc_is_column_selected(column: number): boolean; vfunc_is_row_selected(row: number): boolean; vfunc_is_selected(row: number, column: number): boolean; vfunc_model_changed(): void; vfunc_ref_at(row: number, column: number): Object; vfunc_remove_column_selection(column: number): boolean; vfunc_remove_row_selection(row: number): boolean; vfunc_row_deleted(row: number, num_deleted: number): void; vfunc_row_inserted(row: number, num_inserted: number): void; vfunc_row_reordered(): void; vfunc_set_caption(caption: Object): void; vfunc_set_column_description(column: number, description: string): void; vfunc_set_column_header(column: number, header: Object): void; vfunc_set_row_description(row: number, description: string): void; vfunc_set_row_header(row: number, header: Object): void; vfunc_set_summary(accessible: Object): void; } export const Table: TableNamespace; export interface TableCellNamespace { $gtype: GObject.GType<TableCell>; prototype: TableCellPrototype; } export type TableCell = TableCellPrototype; export interface TableCellPrototype extends Object { // Members get_column_header_cells(): Object[]; get_column_span(): number; get_position(): [boolean, number, number]; get_row_column_span(): [boolean, number, number, number, number]; get_row_header_cells(): Object[]; get_row_span(): number; get_table(): Object; vfunc_get_column_header_cells(): Object[]; vfunc_get_column_span(): number; vfunc_get_position(): [boolean, number, number]; vfunc_get_row_column_span(): [boolean, number, number, number, number]; vfunc_get_row_header_cells(): Object[]; vfunc_get_row_span(): number; vfunc_get_table(): Object; } export const TableCell: TableCellNamespace; export interface TextNamespace { $gtype: GObject.GType<Text>; prototype: TextPrototype; free_ranges(ranges: TextRange[]): void; } export type Text = TextPrototype; export interface TextPrototype extends GObject.Object { // Members add_selection(start_offset: number, end_offset: number): boolean; get_bounded_ranges( rect: TextRectangle, coord_type: CoordType, x_clip_type: TextClipType, y_clip_type: TextClipType ): TextRange[]; get_caret_offset(): number; get_character_at_offset(offset: number): number; get_character_count(): number; get_character_extents( offset: number, coords: CoordType ): [number | null, number | null, number | null, number | null]; get_default_attributes(): AttributeSet; get_n_selections(): number; get_offset_at_point(x: number, y: number, coords: CoordType): number; get_range_extents(start_offset: number, end_offset: number, coord_type: CoordType): TextRectangle; get_run_attributes(offset: number): [AttributeSet, number, number]; get_selection(selection_num: number): [string, number, number]; get_string_at_offset(offset: number, granularity: TextGranularity): [string | null, number, number]; get_text(start_offset: number, end_offset: number): string; get_text_after_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; get_text_at_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; get_text_before_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; remove_selection(selection_num: number): boolean; scroll_substring_to(start_offset: number, end_offset: number, type: ScrollType): boolean; scroll_substring_to_point( start_offset: number, end_offset: number, coords: CoordType, x: number, y: number ): boolean; set_caret_offset(offset: number): boolean; set_selection(selection_num: number, start_offset: number, end_offset: number): boolean; vfunc_add_selection(start_offset: number, end_offset: number): boolean; vfunc_get_bounded_ranges( rect: TextRectangle, coord_type: CoordType, x_clip_type: TextClipType, y_clip_type: TextClipType ): TextRange[]; vfunc_get_caret_offset(): number; vfunc_get_character_at_offset(offset: number): number; vfunc_get_character_count(): number; vfunc_get_character_extents( offset: number, coords: CoordType ): [number | null, number | null, number | null, number | null]; vfunc_get_default_attributes(): AttributeSet; vfunc_get_n_selections(): number; vfunc_get_offset_at_point(x: number, y: number, coords: CoordType): number; vfunc_get_range_extents(start_offset: number, end_offset: number, coord_type: CoordType): TextRectangle; vfunc_get_run_attributes(offset: number): [AttributeSet, number, number]; vfunc_get_selection(selection_num: number): [string, number, number]; vfunc_get_string_at_offset(offset: number, granularity: TextGranularity): [string | null, number, number]; vfunc_get_text(start_offset: number, end_offset: number): string; vfunc_get_text_after_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; vfunc_get_text_at_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; vfunc_get_text_before_offset(offset: number, boundary_type: TextBoundary): [string, number, number]; vfunc_remove_selection(selection_num: number): boolean; vfunc_scroll_substring_to(start_offset: number, end_offset: number, type: ScrollType): boolean; vfunc_scroll_substring_to_point( start_offset: number, end_offset: number, coords: CoordType, x: number, y: number ): boolean; vfunc_set_caret_offset(offset: number): boolean; vfunc_set_selection(selection_num: number, start_offset: number, end_offset: number): boolean; vfunc_text_attributes_changed(): void; vfunc_text_caret_moved(location: number): void; vfunc_text_changed(position: number, length: number): void; vfunc_text_selection_changed(): void; } export const Text: TextNamespace; export interface ValueNamespace { $gtype: GObject.GType<Value>; prototype: ValuePrototype; } export type Value = ValuePrototype; export interface ValuePrototype extends GObject.Object { // Members get_current_value(): unknown; get_increment(): number; get_maximum_value(): unknown; get_minimum_increment(): unknown; get_minimum_value(): unknown; get_range(): Range | null; get_sub_ranges(): Range[]; get_value_and_text(): [number, string | null]; set_current_value(value: any): boolean; set_value(new_value: number): void; vfunc_get_current_value(): unknown; vfunc_get_increment(): number; vfunc_get_maximum_value(): unknown; vfunc_get_minimum_increment(): unknown; vfunc_get_minimum_value(): unknown; vfunc_get_range(): Range | null; vfunc_get_sub_ranges(): Range[]; vfunc_get_value_and_text(): [number, string | null]; vfunc_set_current_value(value: any): boolean; vfunc_set_value(new_value: number): void; } export const Value: ValueNamespace; export interface WindowNamespace { $gtype: GObject.GType<Window>; prototype: WindowPrototype; } export type Window = WindowPrototype; export interface WindowPrototype extends Object {} export const Window: WindowNamespace; export type AttributeSet = GLib.SList; export type State = number;
the_stack
import {Utils as _, NumberSequence} from "../../utils"; import {RowNode} from "../../entities/rowNode"; import {Context, Autowired, PostConstruct, Qualifier} from "../../context/context"; import {EventService} from "../../eventService"; import {Events} from "../../events"; import {LoggerFactory, Logger} from "../../logger"; import {IDatasource} from "../iDatasource"; import {VirtualPage} from "./virtualPage"; export interface CacheParams { pageSize: number; rowHeight: number; maxPagesInCache: number; maxConcurrentDatasourceRequests: number; paginationOverflowSize: number; paginationInitialRowCount: number; sortModel: any; filterModel: any; datasource: IDatasource; lastAccessedSequence: NumberSequence; } export class VirtualPageCache { @Autowired('eventService') private eventService: EventService; @Autowired('context') private context: Context; private pages: {[pageNumber: string]: VirtualPage} = {}; private activePageLoadsCount = 0; private pagesInCacheCount = 0; private cacheParams: CacheParams; private virtualRowCount: number; private maxRowFound = false; private logger: Logger; private active = true; constructor(cacheSettings: CacheParams) { this.cacheParams = cacheSettings; this.virtualRowCount = cacheSettings.paginationInitialRowCount; } private setBeans(@Qualifier('loggerFactory') loggerFactory: LoggerFactory) { this.logger = loggerFactory.create('VirtualPageCache'); } @PostConstruct private init(): void { // start load of data, as the virtualRowCount will remain at 0 otherwise, // so we need this to kick things off, otherwise grid would never call getRow() this.getRow(0); } public getRowCombinedHeight(): number { return this.virtualRowCount * this.cacheParams.rowHeight; } public forEachNode(callback: (rowNode: RowNode, index: number)=> void): void { var index = 0; _.iterateObject(this.pages, (key: string, cachePage: VirtualPage)=> { var start = cachePage.getStartRow(); var end = cachePage.getEndRow(); for (let rowIndex = start; rowIndex < end; rowIndex++) { // we check against virtualRowCount as this page may be the last one, and if it is, then // it's probable that the last rows are not part of the set if (rowIndex < this.virtualRowCount) { var rowNode = cachePage.getRow(rowIndex); callback(rowNode, index); index++; } } }); } public getRowIndexAtPixel(pixel: number): number { if (this.cacheParams.rowHeight !== 0) { // avoid divide by zero error var rowIndexForPixel = Math.floor(pixel / this.cacheParams.rowHeight); if (rowIndexForPixel >= this.virtualRowCount) { return this.virtualRowCount - 1; } else { return rowIndexForPixel; } } else { return 0; } } private moveItemsDown(page: VirtualPage, moveFromIndex: number, moveCount: number): void { let startRow = page.getStartRow(); let endRow = page.getEndRow(); var indexOfLastRowToMove = moveFromIndex + moveCount; // all rows need to be moved down below the insertion index for (let currentRowIndex = endRow - 1; currentRowIndex >= startRow; currentRowIndex--) { // don't move rows at or before the insertion index if (currentRowIndex < indexOfLastRowToMove) { continue; } let indexOfNodeWeWant = currentRowIndex - moveCount; let nodeForThisIndex = this.getRow(indexOfNodeWeWant, true); if (nodeForThisIndex) { page.setRowNode(currentRowIndex, nodeForThisIndex); } else { page.setBlankRowNode(currentRowIndex); page.setDirty(); } } } private insertItems(page: VirtualPage, indexToInsert: number, items: any[]): RowNode[] { let pageStartRow = page.getStartRow(); let pageEndRow = page.getEndRow(); let newRowNodes: RowNode[] = []; // next stage is insert the rows into this page, if applicable for (let index = 0; index < items.length; index++) { var rowIndex = indexToInsert + index; let currentRowInThisPage = rowIndex >= pageStartRow && rowIndex < pageEndRow; if (currentRowInThisPage) { var dataItem = items[index]; var newRowNode = page.setNewData(rowIndex, dataItem); newRowNodes.push(newRowNode); } } return newRowNodes; } public insertItemsAtIndex(indexToInsert: number, items: any[]): void { // get all page id's as NUMBERS (not strings, as we need to sort as numbers) and in descending order let pageIds = Object.keys(this.pages).map(str => parseInt(str)).sort().reverse(); let newNodes: RowNode[] = []; pageIds.forEach(pageId => { let page = this.pages[pageId]; let pageEndRow = page.getEndRow(); // if the insertion is after this page, then this page is not impacted if (pageEndRow <= indexToInsert) { return; } this.moveItemsDown(page, indexToInsert, items.length); let newNodesThisPage = this.insertItems(page, indexToInsert, items); newNodesThisPage.forEach(rowNode => newNodes.push(rowNode)); }); if (this.maxRowFound) { this.virtualRowCount += items.length; } this.dispatchModelUpdated(); this.eventService.dispatchEvent(Events.EVENT_ITEMS_ADDED, newNodes); } public getRowCount(): number { return this.virtualRowCount; } private onPageLoaded(event: any): void { // if we are not active, then we ignore all events, otherwise we could end up getting the // grid to refresh even though we are no longer the active cache if (!this.active) { return; } this.logger.log(`onPageLoaded: page = ${event.page.getPageNumber()}, lastRow = ${event.lastRow}`); this.activePageLoadsCount--; this.checkPageToLoad(); if (event.success) { this.checkVirtualRowCount(event.page, event.lastRow); } } // as we are not a context managed bean, we cannot use @PreDestroy public destroy(): void { this.active = false; } // the rowRenderer will not pass dontCreatePage, meaning when rendering the grid, // it will want new pages in teh cache as it asks for rows. only when we are inserting / // removing rows via the api is dontCreatePage set, where we move rows between the pages. public getRow(rowIndex: number, dontCreatePage = false): RowNode { var pageNumber = Math.floor(rowIndex / this.cacheParams.pageSize); var page = this.pages[pageNumber]; if (!page) { if (dontCreatePage) { return null; } else { page = this.createPage(pageNumber); } } return page.getRow(rowIndex); } private createPage(pageNumber: number): VirtualPage { let newPage = new VirtualPage(pageNumber, this.cacheParams); this.context.wireBean(newPage); newPage.addEventListener(VirtualPage.EVENT_LOAD_COMPLETE, this.onPageLoaded.bind(this)); this.pages[pageNumber] = newPage; this.pagesInCacheCount++; let needToPurge = _.exists(this.cacheParams.maxPagesInCache) && this.pagesInCacheCount > this.cacheParams.maxPagesInCache; if (needToPurge) { var lruPage = this.findLeastRecentlyUsedPage(newPage); this.removePageFromCache(lruPage); } this.checkPageToLoad(); return newPage; } private removePageFromCache(pageToRemove: VirtualPage): void { if (!pageToRemove) { return; } delete this.pages[pageToRemove.getPageNumber()]; this.pagesInCacheCount--; // we do not want to remove the 'loaded' event listener, as the // concurrent loads count needs to be updated when the load is complete // if the purged page is in loading state } private printCacheStatus(): void { this.logger.log(`checkPageToLoad: activePageLoadsCount = ${this.activePageLoadsCount}, pages = ${JSON.stringify(this.getPageState())}`); } private checkPageToLoad() { this.printCacheStatus(); if (this.activePageLoadsCount >= this.cacheParams.maxConcurrentDatasourceRequests) { this.logger.log(`checkPageToLoad: max loads exceeded`); return; } var pageToLoad: VirtualPage = null; _.iterateObject(this.pages, (key: string, cachePage: VirtualPage)=> { if (cachePage.getState() === VirtualPage.STATE_DIRTY) { pageToLoad = cachePage; } }); if (pageToLoad) { pageToLoad.load(); this.activePageLoadsCount++; this.logger.log(`checkPageToLoad: loading page ${pageToLoad.getPageNumber()}`); this.printCacheStatus(); } else { this.logger.log(`checkPageToLoad: no pages to load`); } } private findLeastRecentlyUsedPage(pageToExclude: VirtualPage): VirtualPage { var lruPage: VirtualPage = null; _.iterateObject(this.pages, (key: string, page: VirtualPage)=> { // we exclude checking for the page just created, as this has yet to be accessed and hence // the lastAccessed stamp will not be updated for the first time yet if (page === pageToExclude) { return; } if (_.missing(lruPage) || page.getLastAccessed() < lruPage.getLastAccessed()) { lruPage = page; } }); return lruPage; } private checkVirtualRowCount(page: VirtualPage, lastRow: any): void { // if client provided a last row, we always use it, as it could change between server calls // if user deleted data and then called refresh on the grid. if (typeof lastRow === 'number' && lastRow >= 0) { this.virtualRowCount = lastRow; this.maxRowFound = true; this.dispatchModelUpdated(); } else if (!this.maxRowFound) { // otherwise, see if we need to add some virtual rows var lastRowIndex = (page.getPageNumber() + 1) * this.cacheParams.pageSize; var lastRowIndexPlusOverflow = lastRowIndex + this.cacheParams.paginationOverflowSize; if (this.virtualRowCount < lastRowIndexPlusOverflow) { this.virtualRowCount = lastRowIndexPlusOverflow; this.dispatchModelUpdated(); } } } private dispatchModelUpdated(): void { if (this.active) { this.eventService.dispatchEvent(Events.EVENT_MODEL_UPDATED); } } public getPageState(): any { var result: any[] = []; _.iterateObject(this.pages, (pageNumber: string, page: VirtualPage)=> { result.push({pageNumber: pageNumber, startRow: page.getStartRow(), endRow: page.getEndRow(), pageStatus: page.getState()}); }); return result; } public refreshVirtualPageCache(): void { _.iterateObject(this.pages, (pageId: string, page: VirtualPage)=> { page.setDirty(); }); this.checkPageToLoad(); } public purgeVirtualPageCache(): void { var pagesList = _.values(this.pages); pagesList.forEach( virtualPage => this.removePageFromCache(virtualPage) ); this.dispatchModelUpdated(); } public getVirtualRowCount(): number { return this.virtualRowCount; } public isMaxRowFound(): boolean { return this.maxRowFound; } public setVirtualRowCount(rowCount: number, maxRowFound?: boolean): void { this.virtualRowCount = rowCount; // if undefined is passed, we do not set this value, if one of {true,false} // is passed, we do set the value. if (_.exists(maxRowFound)) { this.maxRowFound = maxRowFound; } // if we are still searching, then the row count must not end at the end // of a particular page, otherwise the searching will not pop into the // next page if (!this.maxRowFound) { if (this.virtualRowCount % this.cacheParams.pageSize === 0) { this.virtualRowCount++; } } this.dispatchModelUpdated(); } }
the_stack
import { cnst, flip, ident } from "../../../Data/Function" import { fmap, fmapF } from "../../../Data/Functor" import { over, set } from "../../../Data/Lens" import { appendStr, countWith, filter, foldl, ifoldr, isList, List, map, notElem, notNull, subscript, subscriptF, sum } from "../../../Data/List" import { any, bind, bindF, elem, elemF, ensure, fromJust, fromMaybe, isJust, isNothing, joinMaybeList, Just, liftM2, listToMaybe, mapMaybe, Maybe, maybe, Nothing } from "../../../Data/Maybe" import { add, dec, gt, multiply, negate } from "../../../Data/Num" import { lookup, lookupF } from "../../../Data/OrderedMap" import { Record } from "../../../Data/Record" import { Pair } from "../../../Data/Tuple" import { Category } from "../../Constants/Categories" import { AdvantageId, DisadvantageId, SpecialAbilityId } from "../../Constants/Ids" import { ActivatableDependent, isActivatableDependent } from "../../Models/ActiveEntries/ActivatableDependent" import { ActiveObject } from "../../Models/ActiveEntries/ActiveObject" import { ActiveObjectWithId } from "../../Models/ActiveEntries/ActiveObjectWithId" import { HeroModel, HeroModelRecord } from "../../Models/Hero/HeroModel" import { ActivatableNameCost, ActivatableNameCostA_, ActivatableNameCostL, ActivatableNameCostL_, ActivatableNameCostSafeCost } from "../../Models/View/ActivatableNameCost" import { Advantage } from "../../Models/Wiki/Advantage" import { Disadvantage, isDisadvantage } from "../../Models/Wiki/Disadvantage" import { Skill } from "../../Models/Wiki/Skill" import { StaticData, StaticDataRecord } from "../../Models/Wiki/WikiModel" import { Activatable, EntryWithCategory, SkillishEntry } from "../../Models/Wiki/wikiTypeHelpers" import { isMaybeActive } from "../Activatable/isActive" import { getSelectOptionCost } from "../Activatable/selectionUtils" import { nbsp, nobr } from "../Chars" import { getHeroStateItem } from "../heroStateUtils" import { translate } from "../I18n" import { getCategoryById } from "../IDUtils" import { toRoman } from "../NumberUtils" import { pipe, pipe_ } from "../pipe" import { isNumber, misNumberM, misStringM } from "../typeCheckUtils" import { getWikiEntry, isActivatableWikiEntry, isSkillishWikiEntry } from "../WikiUtils" const HA = HeroModel.A const AAL = Advantage.AL const AOWIA = ActiveObjectWithId.A const isDisadvantageActive = (id: string) => pipe ( HA.disadvantages, lookup (id), isMaybeActive ) const getCostForEntryWithSkillSel = (ensureId: (x: Maybe<number | string>) => Maybe<string>) => (wiki: StaticDataRecord) => (mcurrent_sid: Maybe<string | number>) => (mcurrent_cost: Maybe<number | List<number>>) => pipe_ ( mcurrent_sid, ensureId, bindF (getWikiEntry (wiki)), bindF<EntryWithCategory, SkillishEntry> (ensure (isSkillishWikiEntry)), bindF (skill => pipe_ ( mcurrent_cost, bindF (ensure (isList)), // Use the IC as an index for the list // of AP bindF (subscriptF (Skill.AL.ic (skill) - 1)) )) ) const isPersonalityFlawNotPaid = (sid: number) => (paid_entries_max: number) => (isEntryToAdd: boolean) => (all_active: List<Record<ActiveObject>>) => (mcurrent_sid: Maybe<string | number>) => elemF (mcurrent_sid) (sid) && countWith ((e: Record<ActiveObject>) => pipe (ActiveObject.AL.sid, elem<string | number> (sid)) (e) // Entries with custom cost are ignored for the rule && isNothing (ActiveObject.AL.cost (e))) (all_active) > (isEntryToAdd ? paid_entries_max - 1 : paid_entries_max) /** * A function for folding over a list of `ActiveObject`s to get the highest * level. Ignores entries with custom cost. * * `foldl compareMaxLevel 0 all_entries` */ export const compareMaxLevel = (previous_max: number) => (active: Record<ActiveObject>) => { const mactive_level = ActiveObject.AL.tier (active) if (isJust (mactive_level)) { const active_level = fromJust (mactive_level) return active_level > previous_max && isNothing (ActiveObject.AL.cost (active)) ? active_level : previous_max } return previous_max } /** * A function for folding over a list of `ActiveObject`s to get the * second-highest level. Ignores entries with custom cost. * * `foldl (compareSubMaxLevel max_level) 0 all_entries` */ export const compareSubMaxLevel = (max: number) => (previous_max: number) => (active: Record<ActiveObject>) => { const mactive_level = ActiveObject.AL.tier (active) if (isJust (mactive_level)) { const active_level = fromJust (mactive_level) return active_level > previous_max && active_level < max && isNothing (ActiveObject.AL.cost (active)) ? active_level : previous_max } return previous_max } /** * Returns the value(s) how the spent AP value would change after removing the * respective entry. * * @param isEntryToAdd If `entry` has not been added to the list of active * entries yet, this must be `true`, otherwise `false`. */ const getEntrySpecificCost = (isEntryToAdd: boolean) => (wiki: StaticDataRecord) => (hero: HeroModelRecord) => (wiki_entry: Activatable) => (hero_entry: Maybe<Record<ActivatableDependent>>) => // tslint:disable-next-line: cyclomatic-complexity (entry: Record<ActiveObjectWithId>): Maybe<number | List<number>> => { const current_id = AOWIA.id (entry) const mcurrent_sid = AOWIA.sid (entry) const mcurrent_sid2 = AOWIA.sid2 (entry) const mcurrent_sid3 = AOWIA.sid3 (entry) const mcurrent_level = AOWIA.tier (entry) const mcurrent_cost = AAL.cost (wiki_entry) const all_active = joinMaybeList (fmap (ActivatableDependent.A.active) (hero_entry)) switch (current_id) { // Entry with Skill selection case AdvantageId.Aptitude: case AdvantageId.ExceptionalSkill: case AdvantageId.ExceptionalCombatTechnique: case AdvantageId.WeaponAptitude: case DisadvantageId.Incompetent: case SpecialAbilityId.AdaptionZauber: case SpecialAbilityId.FavoriteSpellwork: case SpecialAbilityId.Forschungsgebiet: case SpecialAbilityId.Expertenwissen: case SpecialAbilityId.Wissensdurst: case SpecialAbilityId.Lieblingsliturgie: case SpecialAbilityId.WegDerGelehrten: case SpecialAbilityId.WegDerKuenstlerin: case SpecialAbilityId.Fachwissen: { return getCostForEntryWithSkillSel (misStringM) (wiki) (mcurrent_sid) (mcurrent_cost) } case DisadvantageId.PersonalityFlaw: { if ( // 7 = "Prejudice" => more than one entry possible // more than one entry of Prejudice does not contribute to AP spent isPersonalityFlawNotPaid (7) (1) (isEntryToAdd) (all_active) (mcurrent_sid) // 8 = "Unworldly" => more than one entry possible // more than two entries of Unworldly do not contribute to AP spent || isPersonalityFlawNotPaid (8) (2) (isEntryToAdd) (all_active) (mcurrent_sid) ) { return Just (0) } return getSelectOptionCost (wiki_entry) (mcurrent_sid) } case DisadvantageId.Principles: case DisadvantageId.Obligations: { const current_max_level = foldl (compareMaxLevel) (0) (all_active) const current_second_max_level = foldl (compareSubMaxLevel (current_max_level)) (0) (all_active) if (isNothing (mcurrent_level)) { return Nothing } const current_level = fromJust (mcurrent_level) if ( // If the entry is not the one with the highest level, adding or // removing it won't affect AP spent at all current_max_level > current_level // If there is more than one entry on the same level if this entry is // active, it won't affect AP spent at all. Thus, if the entry is to // be added, there must be at least one (> 0) entry for this rule to // take effect. || countWith (pipe (ActiveObject.AL.tier, elem (current_level))) (all_active) > (isEntryToAdd ? 0 : 1) ) { return Nothing } // Otherwise, the level difference results in the cost. return fmapF (misNumberM (mcurrent_cost)) (multiply (current_level - current_second_max_level)) } case DisadvantageId.BadHabit: { // more than three entries cannot contribute to AP spent; entries with // custom cost are ignored for the rule's effect if (countWith (pipe (ActiveObject.AL.cost, isNothing)) (all_active) > (isEntryToAdd ? 2 : 3)) { return Nothing } return mcurrent_cost } case SpecialAbilityId.SkillSpecialization: { return pipe_ ( mcurrent_sid, misStringM, bindF ( current_sid => fmapF (lookup (current_sid) (StaticData.A.skills (wiki))) (skill => // Multiply number of final occurences of the // same skill... (countWith ((e: Record<ActiveObject>) => pipe ( ActiveObject.AL.sid, elem<string | number> (current_sid) ) (e) // Entries with custom cost are ignored for the rule && isNothing (ActiveObject.AL.cost (e))) (all_active) + (isEntryToAdd ? 1 : 0)) // ...with the skill's IC * Skill.AL.ic (skill)) ) ) } case SpecialAbilityId.Language: { // Native Tongue (level 4) does not cost anything return elem (4) (mcurrent_level) ? Nothing : mcurrent_cost } case SpecialAbilityId.PropertyKnowledge: case SpecialAbilityId.AspectKnowledge: { // Does not include custom cost activations in terms of calculated cost const amount = countWith (pipe (ActiveObject.AL.cost, isNothing)) (all_active) const index = amount + (isEntryToAdd ? 0 : -1) if (isNothing (mcurrent_cost)) { return Nothing } const current_cost = fromJust (mcurrent_cost) return isList (current_cost) ? subscript (current_cost) (index) : Nothing } case SpecialAbilityId.TraditionWitches: { // There are two disadvantages that, when active, decrease the cost of // this tradition by 10 AP each const decreaseCost = (id: string) => (cost: number) => isDisadvantageActive (id) (hero) ? cost - 10 : cost return pipe_ ( mcurrent_cost, misNumberM, fmap (pipe ( decreaseCost (DisadvantageId.NoFlyingBalm), decreaseCost (DisadvantageId.NoFamiliar) )) ) } case SpecialAbilityId.Recherchegespuer: { // The AP cost for this SA consist of two parts: AP based on the IC of // the main subject (from "SA_531"/Wissensdurst) in addition to AP based // on the IC of the side subject selected in this SA. const mhero_entry_SA_531 = lookup<string> (SpecialAbilityId.Wissensdurst) (HA.specialAbilities (hero)) if (isNothing (mhero_entry_SA_531)) { return Nothing } if (isNothing (mcurrent_cost) || isNothing (mcurrent_cost)) { return Nothing } const current_cost = fromJust (mcurrent_cost) if (isNumber (current_cost)) { return Nothing } const hero_entry_SA_531 = fromJust (mhero_entry_SA_531) const getCostFromHeroEntry = pipe ( ActiveObject.AL.sid, misStringM, bindF (lookupF (StaticData.A.skills (wiki))), bindF (pipe (Skill.A.ic, dec, subscript (current_cost))) ) return liftM2 (add) (getCostFromHeroEntry (entry)) (pipe_ ( hero_entry_SA_531, ActivatableDependent.A.active, listToMaybe, bindF (getCostFromHeroEntry) )) } case SpecialAbilityId.Handwerkskunst: case SpecialAbilityId.KindDerNatur: case SpecialAbilityId.KoerperlichesGeschick: case SpecialAbilityId.SozialeKompetenz: case SpecialAbilityId.Universalgenie: { return pipe_ ( List (mcurrent_sid, mcurrent_sid2, mcurrent_sid3), mapMaybe (sid => getCostForEntryWithSkillSel (misStringM) (wiki) (sid) (mcurrent_cost)), sum, ensure (gt (0)) ) } default: { if (any (notNull) (Advantage.AL.select (wiki_entry)) && isNothing (mcurrent_cost)) { return getSelectOptionCost (wiki_entry) (mcurrent_sid) } return mcurrent_cost } } } /** * Returns the AP value and if the entry is an automatic entry */ const getTotalCost = (isEntryToAdd: boolean) => (automatic_advantages: List<string>) => (wiki: StaticDataRecord) => (hero: HeroModelRecord) => (entry: Record<ActiveObjectWithId>) => (hero_entry: Maybe<Record<ActivatableDependent>>) => (wiki_entry: Activatable): Pair<number | List<number>, boolean> => { const custom_cost = AOWIA.cost (entry) const is_automatic = List.elem (AAL.id (wiki_entry)) (automatic_advantages) if (isJust (custom_cost)) { const is_disadvantage = Disadvantage.is (wiki_entry) return Pair (is_disadvantage ? -fromJust (custom_cost) : fromJust (custom_cost), is_automatic) } const mentry_specifc_cost = getEntrySpecificCost (isEntryToAdd) (wiki) (hero) (wiki_entry) (hero_entry) (entry) const current_cost = fromMaybe<number | List<number>> (0) (mentry_specifc_cost) if (isDisadvantage (wiki_entry)) { return Pair ( isList (current_cost) ? map (negate) (current_cost) : -current_cost, is_automatic ) } return Pair (current_cost, is_automatic) } /** * Returns the AP you get when removing the ActiveObject. * * @param isEntryToAdd If `entry` has not been added to the list of active * entries yet, this must be `true`, otherwise `false`. */ export const getCost = (isEntryToAdd: boolean) => (automatic_advantages: List<string>) => (wiki: StaticDataRecord) => (hero: HeroModelRecord) => (entry: Record<ActiveObjectWithId>): Maybe<Pair<number | List<number>, boolean>> => { const current_id = AOWIA.id (entry) return pipe_ ( getWikiEntry (wiki) (current_id), bindF (ensure (isActivatableWikiEntry)), fmap (getTotalCost (isEntryToAdd) (automatic_advantages) (wiki) (hero) (entry) (bind (getHeroStateItem (hero) (current_id)) (ensure (isActivatableDependent)))) ) } /** * Uses the results from `getCost` saved in `ActivatableNameCost` to calculate * the final cost value (and no list). */ const putCurrentCost = (entry: Record<ActivatableNameCost>): Record<ActivatableNameCostSafeCost> => over (ActivatableNameCostL.finalCost) ((current_cost): number => { const current_id = ActivatableNameCostA_.id (entry) const category = getCategoryById (current_id) const mcurrent_level = ActivatableNameCostA_.tier (entry) // If the AP cost is still a List, and it is a Special Ability, it // must be a list that represents the cost *for* each level separate, // thus all relevant values must be summed up. In case of an // advantage or disadvantage, it represents the cost *at* each level, // so it does not need to be accumulated. if (isList (current_cost)) { const current_level = fromMaybe (1) (mcurrent_level) if (elem (Category.SPECIAL_ABILITIES) (category)) { return ifoldr (i => i <= (current_level - 1) ? add : cnst (ident as ident<number>)) (0) (current_cost) } return fromMaybe (0) (subscript (current_cost) (current_level - 1)) } // Usually, a single AP value represents the value has to be // multiplied by the level to result in the final cost. There are two // disadvantages where this is not valid. if ( isJust (mcurrent_level) && current_id !== DisadvantageId.Principles && current_id !== DisadvantageId.Obligations && isNothing (ActivatableNameCostA_.customCost (entry)) ) { return maybe (0) (multiply (current_cost)) (mcurrent_level) } return current_cost }) (entry) as Record<ActivatableNameCostSafeCost> /** * Gets the level string that has to be appended to the name. */ const getLevel = (level: number) => `${nbsp}${toRoman (level)}` /** * Gets the level string that has to be appended to the name. For special * abilities, where levels are bought separately, this means it has to display a * range when multiple levels have been bought. */ const getSpecialAbilityLevel = (level: number) => level > 1 ? `${nbsp}I${nobr}–${nobr}${toRoman (level)}` : getLevel (level) /** * Id-based check if the entry is a special ability. */ const isSpecialAbilityById = pipe (getCategoryById, elem<Category> (Category.SPECIAL_ABILITIES)) /** * Gets the level string that hast to be appended to the name. This string is * aware of differences between dis/advantages and special abilties as well as * it handles the Native Tongue level for languages. */ const getFinalLevelName = (staticData: StaticDataRecord) => (entry: Record<ActivatableNameCost>) => /** * @param current_level This is the same value from param `entry`, but this is * ensured to be a number. */ (current_level: number) => { const current_id = ActivatableNameCostA_.id (entry) const current_cost = ActivatableNameCost.A.finalCost (entry) if (current_id === SpecialAbilityId.Language && current_level === 4) { return `${nbsp}${translate (staticData) ("specialabilities.nativetonguelevel")}` } if (isList (current_cost) || isSpecialAbilityById (current_id)) { return getSpecialAbilityLevel (current_level) } return getLevel (current_level) } /** * Returns a `Just` of the level string, if no level string available, returns * `Nothing`. */ const getLevelNameIfValid = (staticData: StaticDataRecord) => (entry: Record<ActivatableNameCost>): Maybe<string> => { const current_id = ActivatableNameCostA_.id (entry) const mcurrent_level = ActivatableNameCostA_.tier (entry) if (isJust (mcurrent_level) && notElem (current_id) (List (DisadvantageId.Principles, DisadvantageId.Obligations))) { return Just (getFinalLevelName (staticData) (entry) (fromJust (mcurrent_level))) } return Nothing } export const putLevelName = (addLevelToName: boolean) => (staticData: StaticDataRecord) => (entry: Record<ActivatableNameCost>): Record<ActivatableNameCost> => pipe_ ( entry, getLevelNameIfValid (staticData), fmap (levelName => addLevelToName ? pipe_ ( entry, over (ActivatableNameCostL_.name) (flip (appendStr) (levelName)), set (ActivatableNameCostL_.levelName) (Just (levelName)) ) : set (ActivatableNameCostL_.levelName) (Just (levelName)) (entry)), fromMaybe (entry) ) /** * Calculates level name and level-based cost and (optionally) updates `name`. * @param locale * @param addLevelToName If true, does not add `current_level` to `name`. */ export const convertPerTierCostToFinalCost = (addLevelToName: boolean) => (staticData: StaticDataRecord) => pipe ( putLevelName (addLevelToName) (staticData), putCurrentCost ) export const getActiveWithNoCustomCost = filter (pipe (ActiveObject.A.cost, isNothing))
the_stack
import React, { useLayoutEffect, useState, useEffect } from 'react'; import { Image, Video, Placeholder } from 'cloudinary-react'; import { Route, Switch, BrowserRouter } from 'react-router-dom'; import { Wrapper as ExtensionWrapper, useUiExtensionDialog, useUiExtension, FieldExtensionType, FieldExtensionFeature, FieldExtensionDeclaration, } from '@graphcms/uix-react-sdk'; type Media = { public_id: string; resource_type: string; }; function isMediaType(item: any): item is Media { return Boolean(item) && 'public_id' in item && 'resource_type' in item; } function isMediaList(media: Media | Media[] | string): media is Media[] { return ( Array.isArray(media) && media.length > 0 && media.every((item) => isMediaType(item)) ); } // useUiExtensionDialog hook accepts two type parameters: // 1. The return value type, will be null or undefined if nothing is returned; falls back to any type DialogReturn = Media | Media[] | null; // 2. Optional props you'd like to access in the dialog type DialogProps = { isList: boolean; media: Media | Media[] | '' }; // Typing the declaration will ensure correct types for the values returned by useUiExtension const declaration: FieldExtensionDeclaration = { extensionType: 'field', fieldType: FieldExtensionType.JSON, name: 'Cloudinary asset', description: 'Pick asset object in Cloudinary', features: [ // Enables rendering of a form field FieldExtensionFeature.FieldRenderer, // Enables handling lists of values // Don't forget to enable multiple values when creating a UI extension field in GraphCMS! FieldExtensionFeature.ListRenderer, // Enables rendering in content table view FieldExtensionFeature.TableRenderer, ], // Optional fields that will when adding or updating a UI extension in GraphCMS config: { CLOUD_NAME: { displayName: 'Cloudinary cloud name', type: 'string', required: true, }, API_KEY: { displayName: 'Cloudinary public api key', type: 'string', required: true, }, }, }; function noop() {} // Treat the dialog as a separate extension and render it at a dedicated route // The dialog path you set here should later be passed as the first argument to the openDialog function function App() { return ( <ExtensionWrapper declaration={declaration}> <BrowserRouter> <Switch> <Route path="/" exact> <Extension /> </Route> <Route path="/cloudinary" exact> <CloudinaryDialog /> </Route> </Switch> </BrowserRouter> </ExtensionWrapper> ); } function Extension() { // Pass a type parameter to useUiExtension hook for better developer experience const { isTableCell } = useUiExtension<typeof declaration>(); // isTableCell can be used to detect whether the extension is currently rendered in content table if (isTableCell) { return <TableCellRenderer />; } return <FormFieldRenderer />; } function FormFieldRenderer() { const { value: media, // field.isList reveals whether a field handles multiple values field: { isList }, onChange, onFocus, onBlur, // expand opens a full-screen view expand, isExpanded, openDialog, extension: { config }, } = useUiExtension<typeof declaration>(); const [isTransitioning, setIsTransitioning] = useState(false); useEffect(() => { setIsTransitioning(false); }, [isExpanded]); const [clickedMedia, setClickedMedia] = React.useState<Media>(); // Note that in a form, an empty field's initial value is an empty string const showMedia = Array.isArray(media) ? media.length > 0 : Boolean(media); return ( <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', padding: '10px', opacity: isTransitioning ? 0 : 1, }} > {isExpanded ? null : ( <button style={{ cursor: 'pointer', marginBottom: '10px', boxSizing: 'border-box', userSelect: 'none', color: '#6663FD', backgroundColor: '#F2F1FF', textAlign: 'center', lineHeight: '16px', display: 'inline-flex', border: '0px', borderRadius: '4px', fontWeight: 600, fontFamily: 'Inter, -apple-system, system-ui, "Segoe UI", Helvetica, Arial, sans-serif', fontSize: '14px', verticalAlign: 'middle', padding: '8px', }} onClick={() => { onFocus(); // openDialog accepts a route path as the first argument and, // optionally, an object with props that will be passed to the dialog. // These props will be returned by the useUiExtensionDialog hook // openDialog<DialogReturn, DialogProps>('/cloudinary', { // By default, native GraphCMS dialogs have a maxWidth of 600px. // You can overwrite it by passing a maxWidth prop maxWidth: '90vw', isList, media, // openDialog returns a Promise with the value that was passed to onCloseDialog }).then((value) => { if (value) { onChange(value); } onBlur(); }); }} > Choose from Cloudinary </button> )} {showMedia && (isMediaList(media) ? ( media.map((item, index) => ( <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'flex-start', opacity: isExpanded && item.public_id !== clickedMedia?.public_id ? 0 : 1, }} key={item.public_id + index} > <FormAsset cloudName={config.CLOUD_NAME} media={item} isExpanded={ item.public_id === clickedMedia?.public_id && isExpanded } onOpen={() => { // expand accepts a boolean that will be accessible as isExpanded expand(true); setIsTransitioning(true); setClickedMedia(item); }} onClose={() => { expand(false); setIsTransitioning(true); setClickedMedia(undefined); }} /> <button style={{ marginLeft: '10px', cursor: 'pointer', boxSizing: 'border-box', userSelect: 'none', color: '#6663FD', backgroundColor: 'transparent', textAlign: 'center', lineHeight: '14px', display: 'inline-flex', border: '0px', fontWeight: 500, fontFamily: 'sans-serif', fontSize: '12px', verticalAlign: 'middle', padding: '4px', }} onClick={() => { const newValues = media.filter( (value) => value.public_id !== item.public_id ); onChange(newValues); }} > X </button> </div> )) ) : ( <FormAsset cloudName={config.CLOUD_NAME} isExpanded={ media.public_id === clickedMedia?.public_id && isExpanded } onOpen={() => { expand(true); setIsTransitioning(true); setClickedMedia(media); }} onClose={() => { expand(false); setIsTransitioning(true); setClickedMedia(undefined); }} media={media} /> ))} </div> ); } function TableCellRenderer() { const { value: media, isExpanded, expand, field: { isList }, extension: { config }, } = useUiExtension<typeof declaration>(); const [isTransitioning, setIsTransitioning] = useState(false); useEffect(() => { setIsTransitioning(false); }, [isExpanded]); if (Array.isArray(media) ? media.length === 0 : Boolean(media) === false) { return null; } if (isExpanded && isList) { return ( <TableAssetsPreviewModal cloudName={config.CLOUD_NAME} media={media} closeModal={() => { expand(false); setIsTransitioning(true); }} /> ); } return ( <div style={{ display: 'flex', opacity: isTransitioning ? 0 : 1, }} > {isMediaList(media) ? ( media.map((item: Media, index: number) => ( <div key={item.public_id + index} style={{ width: 59, height: 59, marginRight: index === media.length - 1 ? 0 : 10, }} > <TableAsset cloudName={config.CLOUD_NAME} media={item} onOpen={() => { expand(true); setIsTransitioning(true); }} isExpanded={false} onClose={noop} /> </div> )) ) : ( <div style={{ width: 59, height: 59 }}> <TableAsset cloudName={config.CLOUD_NAME} isExpanded={isExpanded} onClose={() => { expand(false); setIsTransitioning(true); }} onOpen={() => { expand(true); setIsTransitioning(true); }} media={media} /> </div> )} </div> ); } function FormAsset({ media, onOpen, onClose, isExpanded, cloudName, }: { style?: React.CSSProperties; isExpanded: boolean; media: Media; onOpen: () => void; onClose: () => void; cloudName: string; }) { if (isExpanded) { return ( <FullScreenPreview cloudName={cloudName} media={media} onClose={onClose} /> ); } if (media.resource_type === 'image') return ( <button onClick={onOpen} style={{ border: 'none', outline: 'none', background: 'transparent', cursor: 'pointer', }} > <Image cloudName={cloudName} publicId={media.public_id} width="400" crop="scale" > <Placeholder /> </Image> </button> ); if (media.resource_type === 'video') return ( <Video cloudName={cloudName} publicId={media.public_id} width="400" controls /> ); return null; } function TableAsset({ isExpanded, media, onOpen, onClose, cloudName, style, }: { style?: React.CSSProperties; isExpanded: boolean; media: Media; onOpen: () => void; onClose: () => void; cloudName: string; }) { if (isExpanded) { return ( <FullScreenPreview media={media} onClose={onClose} cloudName={cloudName} /> ); } return ( <div tabIndex={0} onClick={onOpen} onKeyPress={(e) => { if (e.key === 'Enter') { onOpen(); } }} style={{ width: 59, height: 59, flexShrink: 0, ...style, }} > {media.resource_type === 'image' ? ( <Image publicId={media.public_id} cloudName={cloudName} width="auto" crop="scale" style={{ objectFit: 'cover', width: '100%', height: '100%', cursor: 'pointer', }} > <Placeholder /> </Image> ) : media.resource_type === 'video' ? ( <Video cloudName={cloudName} publicId={media.public_id} width="auto" style={{ objectFit: 'cover', width: '100%', height: '100%', cursor: 'pointer', }} /> ) : null} </div> ); } function TableAssetsPreviewModal({ closeModal, media, cloudName, }: { media: Media[]; closeModal: () => void; cloudName: string; }) { const [maximizedAsset, setMaximizedAsset] = useState<Media | null>(null); if (maximizedAsset) { return ( <TableAsset cloudName={cloudName} media={maximizedAsset} isExpanded onOpen={noop} onClose={() => { setMaximizedAsset(null); }} /> ); } return ( <div aria-modal="true" role="dialog" style={{ position: 'fixed', inset: 0, display: 'flex', }} onClick={closeModal} > <div style={{ margin: 'auto' }} onClick={(e) => { e.stopPropagation(); }} > <CloseModalButton closeModal={closeModal} /> <div style={{ display: 'flex', borderRadius: '4px', backgroundColor: 'white', maxWidth: '800px', maxHeight: '400px', padding: '16px', overflowY: 'auto', }} > {media.map((item, index) => ( <TableAsset isExpanded={false} cloudName={cloudName} media={item} key={item.public_id + index} onOpen={() => { setMaximizedAsset(item); }} onClose={() => { setMaximizedAsset(null); }} style={{ width: 250, height: 200, marginRight: index === media.length - 1 ? 0 : 16, }} /> ))} </div> </div> </div> ); } function FullScreenPreview({ media, cloudName, onClose, }: { media: Media; onClose: () => void; cloudName: string; }) { useEffect(() => { const handler = (e: KeyboardEvent) => { if (e.key === 'Escape') { onClose(); } }; window.addEventListener('keyup', handler); return () => { window.removeEventListener('keyup', handler); }; }, [onClose]); return ( <div aria-modal="true" role="dialog" style={{ position: 'fixed', inset: 0, display: 'flex', alignItems: 'center', overflow: 'auto', }} onClick={(e) => { e.stopPropagation(); onClose(); }} > <CloseModalButton closeModal={onClose} /> {media.resource_type === 'image' ? ( <Image cloudName={cloudName} publicId={media.public_id} width="auto" style={{ maxWidth: '100%', margin: 'auto', maxHeight: '100%' }} crop="scale" > <Placeholder /> </Image> ) : media.resource_type === 'video' ? ( <Video cloudName={cloudName} publicId={media.public_id} controls style={{ maxWidth: '70vw', margin: 'auto', maxHeight: '100%' }} /> ) : null} </div> ); } function CloudinaryDialog() { const { extension: { config }, } = useUiExtension<typeof declaration>(); // You can pass type parameters to useUiExtensionDialog // onCloseDialog function is always returned from the hook const { onCloseDialog, isList, media } = useUiExtensionDialog< DialogReturn, DialogProps >(); useLayoutEffect(() => { // @ts-expect-error const mediaLibrary = window.cloudinary.createMediaLibrary( { cloud_name: config.CLOUD_NAME, api_key: config.API_KEY, remove_header: false, max_files: '10', multiple: isList, insert_caption: 'Add & close', inline_container: '#cloudinary_dialog', default_transformations: [ [{ quality: 'auto' }, { fetch_format: 'auto' }], [ { width: 80, height: 80, crop: 'fill', gravity: 'auto', radius: 'max', }, { fetch_format: 'auto', quality: 'auto' }, ], ], }, { hideHandler: function () { // To close the dialog without returning a value to the fields, // call onCloseDialog with null or without an argument onCloseDialog(); }, insertHandler: function (data: { assets: Media[] }) { // Pass a single value to onCloseDialog to set it as the field value // or an array, if the field handles multiple values if (isList) { if (isMediaList(media)) { onCloseDialog([...media, ...data.assets]); } else { // initial field value is an empty string const newArray = isMediaType(media) ? [media, ...data.assets] : data.assets; onCloseDialog(newArray); } } else { onCloseDialog(data.assets[0]); } }, } ); mediaLibrary.show(); }, [config.API_KEY, config.CLOUD_NAME, isList, media, onCloseDialog]); return ( <div id="cloudinary_dialog" style={{ height: '800px', }} /> ); } function CloseModalButton({ closeModal }: { closeModal: () => void }) { return ( <button type="button" style={{ cursor: 'pointer', userSelect: 'none', backgroundColor: 'transparent', textAlign: 'center', lineHeight: '16px', display: 'inline-flex', border: '0px', position: 'absolute', right: '10px', top: '10px', fontWeight: 500, background: 'white', color: 'black', fontSize: '16px', borderRadius: '4px', padding: '4px 8px', verticalAlign: 'middle', margin: 0, }} onClick={(event) => { event.preventDefault(); event.stopPropagation(); closeModal(); }} onKeyPress={(event) => { event.preventDefault(); event.stopPropagation(); if (event.key === 'Enter') { closeModal(); } }} > Close </button> ); } export default App; /* if full screen preview then close on escape */
the_stack
declare namespace WebAssembly { interface Module { } } declare namespace Emscripten { interface FileSystemType { } type EnvironmentType = "WEB" | "NODE" | "SHELL" | "WORKER"; type JSType = "number" | "string" | "array" | "boolean"; type TypeCompatibleWithC = number | string | any[] | boolean; type CIntType = 'i8' | 'i16' | 'i32' | 'i64'; type CFloatType = 'float' | 'double'; type CPointerType = 'i8*' | 'i16*' | 'i32*' | 'i64*' | 'float*' | 'double*' | '*'; type CType = CIntType | CFloatType | CPointerType; type WebAssemblyImports = Array<{ name: string; kind: string; }>; type WebAssemblyExports = Array<{ module: string; name: string; kind: string; }>; interface CCallOpts { async?: boolean; } } interface EmscriptenModule { /** * Initializes an EmscriptenModule object and returns it. The initialized * obejct will be passed to then(). Works only when -s MODULARIZE=1 is * enabled. This is default exported function when -s EXPORT_ES6=1 is * enabled. * https://emscripten.org/docs/getting_started/FAQ.html#how-can-i-tell-when-the-page-is-fully-loaded-and-it-is-safe-to-call-compiled-functions * @param moduleOverrides Properties of an initialized module to override. */ (moduleOverrides?: Partial<this>): this; /** * Promise-like then() inteface. * WRANGING: Emscripten's then() is not really promise-based 'thenable'. * Don't try to use it with Promise.resolve() or in an async function * without deleting delete Module["then"] in the callback. * https://github.com/kripken/emscripten/issues/5820 * Works only when -s MODULARIZE=1 is enabled. * @param callback A callback chained from Module() with an Module instance. */ then(callback: (module: this) => void): this; print(str: string): void; printErr(str: string): void; arguments: string[]; environment: Emscripten.EnvironmentType; preInit: Array<{ (): void }>; preRun: Array<{ (): void }>; postRun: Array<{ (): void }>; onAbort: { (what: any): void }; onRuntimeInitialized: { (): void }; preinitializedWebGLContext: WebGLRenderingContext; noInitialRun: boolean; noExitRuntime: boolean; logReadFiles: boolean; filePackagePrefixURL: string; wasmBinary: ArrayBuffer; destroy(object: object): void; getPreloadedPackage(remotePackageName: string, remotePackageSize: number): ArrayBuffer; instantiateWasm( imports: Emscripten.WebAssemblyImports, successCallback: (module: WebAssembly.Module) => void ): Emscripten.WebAssemblyExports; locateFile(url: string, scriptDirectory: string): string; onCustomMessage(event: MessageEvent): void; // USE_TYPED_ARRAYS == 1 HEAP: Int32Array; IHEAP: Int32Array; FHEAP: Float64Array; // USE_TYPED_ARRAYS == 2 HEAP8: Int8Array; HEAP16: Int16Array; HEAP32: Int32Array; HEAPU8: Uint8Array; HEAPU16: Uint16Array; HEAPU32: Uint32Array; HEAPF32: Float32Array; HEAPF64: Float64Array; TOTAL_STACK: number; TOTAL_MEMORY: number; FAST_MEMORY: number; addOnPreRun(cb: () => any): void; addOnInit(cb: () => any): void; addOnPreMain(cb: () => any): void; addOnExit(cb: () => any): void; addOnPostRun(cb: () => any): void; preloadedImages: any; preloadedAudios: any; _malloc(size: number): number; _free(ptr: number): void; } // By default Emscripten emits a single global Module. Users setting -s // MODULARIZE=1 -s EXPORT_NAME=MyMod should declare their own types, e.g. // declare var MyMod: EmscriptenModule; declare var Module: EmscriptenModule; declare namespace FS { interface Lookup { path: string; node: FSNode; } interface FSStream {} interface FSNode {} interface ErrnoError {} let ignorePermissions: boolean; let trackingDelegate: any; let tracking: any; let genericErrors: any; // // paths // function lookupPath(path: string, opts: any): Lookup; function getPath(node: FSNode): string; // // nodes // function isFile(mode: number): boolean; function isDir(mode: number): boolean; function isLink(mode: number): boolean; function isChrdev(mode: number): boolean; function isBlkdev(mode: number): boolean; function isFIFO(mode: number): boolean; function isSocket(mode: number): boolean; // // devices // function major(dev: number): number; function minor(dev: number): number; function makedev(ma: number, mi: number): number; function registerDevice(dev: number, ops: any): void; // // core // function syncfs(populate: boolean, callback: (e: any) => any): void; function syncfs(callback: (e: any) => any, populate?: boolean): void; function mount(type: Emscripten.FileSystemType, opts: any, mountpoint: string): any; function unmount(mountpoint: string): void; function mkdir(path: string, mode?: number): any; function mkdev(path: string, mode?: number, dev?: number): any; function symlink(oldpath: string, newpath: string): any; function rename(old_path: string, new_path: string): void; function rmdir(path: string): void; function readdir(path: string): any; function unlink(path: string): void; function readlink(path: string): string; function stat(path: string, dontFollow?: boolean): any; function lstat(path: string): any; function chmod(path: string, mode: number, dontFollow?: boolean): void; function lchmod(path: string, mode: number): void; function fchmod(fd: number, mode: number): void; function chown(path: string, uid: number, gid: number, dontFollow?: boolean): void; function lchown(path: string, uid: number, gid: number): void; function fchown(fd: number, uid: number, gid: number): void; function truncate(path: string, len: number): void; function ftruncate(fd: number, len: number): void; function utime(path: string, atime: number, mtime: number): void; function open(path: string, flags: string, mode?: number, fd_start?: number, fd_end?: number): FSStream; function close(stream: FSStream): void; function llseek(stream: FSStream, offset: number, whence: number): any; function read(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number): number; function write(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position?: number, canOwn?: boolean): number; function allocate(stream: FSStream, offset: number, length: number): void; function mmap(stream: FSStream, buffer: ArrayBufferView, offset: number, length: number, position: number, prot: number, flags: number): any; function ioctl(stream: FSStream, cmd: any, arg: any): any; function readFile(path: string, opts: { encoding: "binary", flags?: string }): Uint8Array; function readFile(path: string, opts: { encoding: "utf8", flags?: string }): string; function readFile(path: string, opts?: { flags?: string }): Uint8Array; function writeFile(path: string, data: string | ArrayBufferView, opts?: { flags?: string }): void; // // module-level FS code // function cwd(): string; function chdir(path: string): void; function init( input: null | (() => number | null), output: null | ((c: number) => any), error: null | ((c: number) => any), ): void; function createLazyFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean): FSNode; function createPreloadedFile(parent: string | FSNode, name: string, url: string, canRead: boolean, canWrite: boolean, onload?: () => void, onerror?: () => void, dontCreateFile?: boolean, canOwn?: boolean): void; function createDataFile(parent: string | FSNode, name: string, data: ArrayBufferView, canRead: boolean, canWrite: boolean, canOwn: boolean): FSNode; } declare var MEMFS: Emscripten.FileSystemType; declare var NODEFS: Emscripten.FileSystemType; declare var IDBFS: Emscripten.FileSystemType; // Below runtime function/variable declarations are exportable by // -s EXTRA_EXPORTED_RUNTIME_METHODS. You can extend or merge // EmscriptenModule interface to add runtime functions. // // For example, by using -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall']" // You can access ccall() via Module["ccall"]. In this case, you should // extend EmscriptenModule to pass the compiler check like the following: // // interface YourOwnEmscriptenModule extends EmscriptenModule { // ccall: typeof ccall; // } // // See: https://emscripten.org/docs/getting_started/FAQ.html#why-do-i-get-typeerror-module-something-is-not-a-function declare function ccall(ident: string, returnType: Emscripten.JSType | null, argTypes: Emscripten.JSType[], args: Emscripten.TypeCompatibleWithC[], opts?: Emscripten.CCallOpts): any; declare function cwrap(ident: string, returnType: Emscripten.JSType | null, argTypes: Emscripten.JSType[], opts?: Emscripten.CCallOpts): (...args: any[]) => any; declare function setValue(ptr: number, value: any, type: Emscripten.CType, noSafe?: boolean): void; declare function getValue(ptr: number, type: Emscripten.CType, noSafe?: boolean): number; declare function allocate(slab: number[] | ArrayBufferView | number, types: Emscripten.CType | Emscripten.CType[], allocator: number, ptr?: number): number; declare function stackAlloc(size: number): number; declare function stackSave(): number; declare function stackRestore(ptr: number): void; declare function UTF8ToString(ptr: number, maxBytesToRead?: number): string; declare function stringToUTF8(str: string, outPtr: number, maxBytesToRead?: number): void; declare function lengthBytesUTF8(str: string): number; declare function allocateUTF8(str: string): number; declare function allocateUTF8OnStack(str: string): number; declare function UTF16ToString(ptr: number): string; declare function stringToUTF16(str: string, outPtr: number, maxBytesToRead?: number): void; declare function lengthBytesUTF16(str: string): number; declare function UTF32ToString(ptr: number): string; declare function stringToUTF32(str: string, outPtr: number, maxBytesToRead?: number): void; declare function lengthBytesUTF32(str: string): number; declare function intArrayFromString(stringy: string, dontAddNull?: boolean, length?: number): number[]; declare function intArrayToString(array: number[]): string; declare function writeStringToMemory(str: string, buffer: number, dontAddNull: boolean): void; declare function writeArrayToMemory(array: number[], buffer: number): void; declare function writeAsciiToMemory(str: string, buffer: number, dontAddNull: boolean): void; declare function addRunDependency(id: any): void; declare function removeRunDependency(id: any): void; declare function addFunction(func: () => any, signature?: string): number; declare function removeFunction(funcPtr: number): void; declare var ALLOC_NORMAL: number; declare var ALLOC_STACK: number; declare var ALLOC_STATIC: number; declare var ALLOC_DYNAMIC: number; declare var ALLOC_NONE: number;
the_stack
import { Test } from '@nestjs/testing'; import { Version, VersionManagerService } from './version-manager.service'; import { HttpService } from '@nestjs/common'; import { of } from 'rxjs'; import { mocked } from 'ts-jest/utils'; import { LOGGER } from '../constants'; import * as chalk from 'chalk'; import { ConfigService } from './config.service'; import { resolve } from 'path'; import * as os from 'os'; import { TestingModule } from '@nestjs/testing/testing-module'; jest.mock('fs-extra'); // eslint-disable-next-line @typescript-eslint/no-var-requires const fs = mocked(require('fs-extra'), true); describe('VersionManagerService', () => { let fixture: VersionManagerService; const get = jest.fn(); const log = jest.fn(); const getVersion = jest.fn().mockReturnValue('4.3.0'); const getStorageDir = jest.fn().mockReturnValue(undefined); const setVersion = jest.fn(); let testBed: TestingModule const compile = async () => { testBed = await Test.createTestingModule({ providers: [ VersionManagerService, { provide: HttpService, useValue: { get } }, { provide: ConfigService, useValue: { get: (k) => { if (k === 'generator-cli.storageDir') { return getStorageDir(k); } if (k === 'generator-cli.repository.queryUrl') { return undefined; // return 'https://search.maven.custom/solrsearch/select?q=g:${repository.groupId}+AND+a:${repository.artifactId}&core=gav&start=0&rows=250'; } if (k === 'generator-cli.repository.downloadUrl') { return undefined; // return 'https://search.maven.custom/solrsearch/select?q=g:${repository.groupId}+AND+a:${repository.artifactId}&core=gav&start=0&rows=250'; } return getVersion(k); }, set: setVersion, cwd: '/c/w/d' } }, { provide: LOGGER, useValue: { log } } ] }).compile(); fixture = testBed.get(VersionManagerService); } beforeEach(async () => { [get].forEach(fn => fn.mockClear()); getStorageDir.mockReturnValue(undefined) await compile() fs.existsSync.mockReset().mockImplementation(filePath => filePath.indexOf('4.2') !== -1); }); const expectedVersions = { '4.2.0': { downloadLink: 'https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.0/openapi-generator-cli-4.2.0.jar', installed: true, releaseDate: new Date(1599197918000), version: '4.2.0', versionTags: ['4.2.0', 'stable'] }, '5.0.0-beta': { downloadLink: 'https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta/openapi-generator-cli-5.0.0-beta.jar', installed: false, releaseDate: new Date(1593445793000), version: '5.0.0-beta', versionTags: ['5.0.0-beta', '5.0.0', 'beta', 'beta'] }, '4.3.1': { downloadLink: 'https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/4.3.1/openapi-generator-cli-4.3.1.jar', installed: false, releaseDate: new Date(1588758220000), version: '4.3.1', versionTags: ['4.3.1', 'stable', 'latest'] }, '5.0.0-beta2': { downloadLink: 'https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/5.0.0-beta2/openapi-generator-cli-5.0.0-beta2.jar', installed: false, releaseDate: new Date(1599197918000), version: '5.0.0-beta2', versionTags: ['5.0.0-beta2', '5.0.0', 'beta2', 'beta'] }, '3.0.0-alpha': { downloadLink: 'https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/3.0.0-alpha/openapi-generator-cli-3.0.0-alpha.jar', installed: false, releaseDate: new Date(1527849204000), version: '3.0.0-alpha', versionTags: ['3.0.0-alpha', '3.0.0', 'alpha', 'alpha'] } }; describe('API', () => { describe('getAll()', () => { let returnValue: Version[]; beforeEach(async () => { get.mockReturnValue(of({ data: { response: { docs: [ { v: '4.2.0', timestamp: 1599197918000 }, { v: '5.0.0-beta', timestamp: 1593445793000 }, { v: '4.3.1', timestamp: 1588758220000 }, { v: '5.0.0-beta2', timestamp: 1599197918000 }, { v: '3.0.0-alpha', timestamp: 1527849204000 } ] } } })); returnValue = await fixture.getAll().toPromise(); }); it('executes one get request', () => { expect(get).toHaveBeenNthCalledWith(1, 'https://search.maven.org/solrsearch/select?q=g:org.openapitools+AND+a:openapi-generator-cli&core=gav&start=0&rows=200'); }); it('returns the correct versions', () => { expect(returnValue).toEqual([ expectedVersions['4.2.0'], expectedVersions['5.0.0-beta'], expectedVersions['4.3.1'], expectedVersions['5.0.0-beta2'], expectedVersions['3.0.0-alpha'] ]); }); }); describe('search()', () => { let returnValue: Version[]; describe('using empty tags array', () => { beforeEach(async () => { get.mockReturnValue(of({ data: { response: { docs: [ { v: '4.2.0', timestamp: 1599197918000 }, { v: '5.0.0-beta', timestamp: 1593445793000 }, { v: '4.3.1', timestamp: 1588758220000 }, { v: '5.0.0-beta2', timestamp: 1599197918000 }, { v: '3.0.0-alpha', timestamp: 1527849204000 } ] } } })); returnValue = await fixture.search([]).toPromise(); }); it('executes one get request', () => { expect(get).toHaveBeenNthCalledWith(1, 'https://search.maven.org/solrsearch/select?q=g:org.openapitools+AND+a:openapi-generator-cli&core=gav&start=0&rows=200'); }); it('returns all versions', () => { expect(returnValue).toEqual([ expectedVersions['4.2.0'], expectedVersions['5.0.0-beta'], expectedVersions['4.3.1'], expectedVersions['5.0.0-beta2'], expectedVersions['3.0.0-alpha'] ]); }); }); describe.each([ [['beta'], [expectedVersions['5.0.0-beta'], expectedVersions['5.0.0-beta2']]], [['beta', 'alpha'], []], [['5'], [expectedVersions['5.0.0-beta'], expectedVersions['5.0.0-beta2']]], [['4.2'], [expectedVersions['4.2.0']]], [['stable'], [expectedVersions['4.2.0'], expectedVersions['4.3.1']]] ])('using tags %s', (tags, expectation) => { beforeEach(async () => { returnValue = await fixture.search(tags).toPromise(); }); it('executes one get request', () => { expect(get).toHaveBeenNthCalledWith(1, 'https://search.maven.org/solrsearch/select?q=g:org.openapitools+AND+a:openapi-generator-cli&core=gav&start=0&rows=200'); }); it('returns the correct versions', () => { expect(returnValue).toEqual(expectation); }); }); }); describe('isSelectedVersion()', () => { it('return true if equal to the selected version', () => { expect(fixture.isSelectedVersion('4.3.0')).toBeTruthy(); }); it('return false if equal to the selected version', () => { expect(fixture.isSelectedVersion('4.3.1')).toBeFalsy(); }); }); describe('getSelectedVersion', () => { it('returns the value from the config service', () => { expect(fixture.getSelectedVersion()).toEqual('4.3.0'); expect(getVersion).toHaveBeenNthCalledWith(1, 'generator-cli.version'); }); }); describe('setSelectedVersion', () => { let downloadIfNeeded: jest.SpyInstance; beforeEach(() => { log.mockReset(); setVersion.mockReset(); }); describe('was download or exists', () => { beforeEach(async () => { downloadIfNeeded = jest.spyOn(fixture, 'downloadIfNeeded').mockResolvedValue(true); await fixture.setSelectedVersion('1.2.3'); }); it('calls downloadIfNeeded once', () => { expect(downloadIfNeeded).toHaveBeenNthCalledWith(1, '1.2.3'); }); it('sets the correct config value', () => { expect(setVersion).toHaveBeenNthCalledWith(1, 'generator-cli.version', '1.2.3'); }); it('logs a success message', () => { expect(log).toHaveBeenNthCalledWith(1, chalk.green('Did set selected version to 1.2.3')); }); }); describe('was not downloaded nor exists', () => { beforeEach(async () => { downloadIfNeeded = jest.spyOn(fixture, 'downloadIfNeeded').mockResolvedValue(false); await fixture.setSelectedVersion('1.2.3'); }); it('calls downloadIfNeeded once', () => { expect(downloadIfNeeded).toHaveBeenNthCalledWith(1, '1.2.3'); }); it('does not set the config value', () => { expect(setVersion).toBeCalledTimes(0); }); it('logs no success message', () => { expect(log).toBeCalledTimes(0); }); }); }); describe('remove()', () => { let logMessages = { before: [], after: [] }; beforeEach(() => { logMessages = { before: [], after: [] }; log.mockReset().mockImplementation(m => logMessages.before.push(m)); fs.removeSync.mockImplementation(() => { log.mockReset().mockImplementation(m => logMessages.after.push(m)); }); fixture.remove('4.3.1'); }); it('removes the correct file', () => { expect(fs.removeSync).toHaveBeenNthCalledWith(1, `${fixture.storage}/4.3.1.jar`); }); it('logs the correct messages', () => { expect(logMessages).toEqual({ before: [], after: [chalk.green(`Removed 4.3.1`)] }); }); }); describe('download()', () => { let returnValue: boolean; let logMessages = { before: [], after: [] }; describe('the server responds with an error', () => { beforeEach(async () => { get.mockImplementation(() => { log.mockReset().mockImplementation(m => logMessages.after.push(m)); throw new Error('HTTP 404 Not Found'); }); logMessages = { before: [], after: [] }; log.mockReset().mockImplementation(m => logMessages.before.push(m)); returnValue = await fixture.download('4.2.0'); }); it('returns false', () => { expect(returnValue).toBeFalsy(); }); it('logs the correct messages', () => { expect(logMessages).toEqual({ before: [chalk.yellow(`Download 4.2.0 ...`)], after: [chalk.red(`Download failed, because of: "HTTP 404 Not Found"`)] }); }); }); describe('the server responds a file', () => { const data = { pipe: jest.fn(), }; const file = { on: jest.fn().mockImplementation((listener, res) => { if (listener === 'finish') { return res(); } }) } beforeEach(async () => { data.pipe.mockReset(); fs.mkdtempSync.mockReset().mockReturnValue('/tmp/generator-cli-abcDEF'); fs.ensureDirSync.mockReset(); fs.createWriteStream.mockReset().mockReturnValue(file); get.mockImplementation(() => { log.mockReset().mockImplementation(m => logMessages.after.push(m)); return of({ data }); }); logMessages = { before: [], after: [] }; log.mockReset().mockImplementation(m => logMessages.before.push(m)); returnValue = await fixture.download('4.2.0'); }); it('returns true', () => { expect(returnValue).toBeTruthy(); }); describe('logging', () => { it('logs the correct messages', () => { expect(logMessages).toEqual({ before: [chalk.yellow(`Download 4.2.0 ...`)], after: [chalk.green(`Downloaded 4.2.0`)] }); }); describe('there is a custom storage location', () => { it.each([ ['/c/w/d/custom/dir', './custom/dir'], ['/custom/dir', '/custom/dir'], ])('returns %s for %s', async (expected, cfgValue) => { getStorageDir.mockReturnValue(cfgValue) logMessages = {before: [], after: []}; log.mockReset().mockImplementation(m => logMessages.before.push(m)); await compile() await fixture.download('4.2.0') expect(logMessages).toEqual({ before: [chalk.yellow(`Download 4.2.0 ...`)], after: [chalk.green(`Downloaded 4.2.0 to custom storage location ${expected}`)] }); }); }); }) it('provides the correct params to get', () => { expect(get).toHaveBeenNthCalledWith(1, 'https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/4.2.0/openapi-generator-cli-4.2.0.jar', { responseType: 'stream' }); }); describe('file saving', () => { it('ensures the save dir', () => { expect(fs.ensureDirSync).toHaveBeenNthCalledWith(1, fixture.storage); }); it('creates a temporary directory', () => { expect(fs.mkdtempSync).toHaveBeenNthCalledWith(1, '/tmp/generator-cli-'); }); it('creates the correct write stream', () => { expect(fs.createWriteStream).toHaveBeenNthCalledWith(1, '/tmp/generator-cli-abcDEF/4.2.0'); }); it('moves the file to the target location', () => { expect(fs.moveSync).toHaveBeenNthCalledWith(1, '/tmp/generator-cli-abcDEF/4.2.0', `${fixture.storage}/4.2.0.jar`, {overwrite: true}); }); it('receives the data piped', () => { expect(data.pipe).toHaveBeenNthCalledWith(1, file); }); }); }); }); describe('downloadIfNeeded()', () => { let downloadSpy: jest.SpyInstance; let isDownloadedSpy: jest.SpyInstance; beforeEach(() => { isDownloadedSpy = jest.spyOn(fixture, 'isDownloaded').mockReset(); downloadSpy = jest.spyOn(fixture, 'download').mockReset(); }); describe('the version exists', () => { let returnValue: boolean; beforeEach(async () => { isDownloadedSpy.mockReturnValueOnce(true); returnValue = await fixture.downloadIfNeeded('4.2.0'); }); it('does not call download', () => { expect(downloadSpy).toBeCalledTimes(0); }); it('returns true', () => { expect(returnValue).toBeTruthy(); }); }); describe('the version does not exists', () => { beforeEach(async () => { isDownloadedSpy.mockReturnValueOnce(false); await fixture.downloadIfNeeded('4.2.0'); }); it('calls download once', () => { expect(downloadSpy).toHaveBeenNthCalledWith(1, '4.2.0'); }); it('returns true, if download return true', async () => { downloadSpy.mockReturnValueOnce(true); expect(await fixture.downloadIfNeeded('4.2.0')).toBeTruthy(); }); it('returns true, if download return true', async () => { downloadSpy.mockReturnValueOnce(false); expect(await fixture.downloadIfNeeded('4.2.0')).toBeFalsy(); }); }); }); describe('isDownloaded()', () => { it('returns true, if the file exists', () => { fs.existsSync.mockReturnValue(true); expect(fixture.isDownloaded('4.3.1')).toBeTruthy(); }); it('returns false, if the file does not exists', () => { fs.existsSync.mockReturnValue(false); expect(fixture.isDownloaded('4.3.1')).toBeFalsy(); }); it('provides the correct file path', () => { fixture.isDownloaded('4.3.1'); expect(fs.existsSync).toHaveBeenNthCalledWith(1, fixture.storage + '/4.3.1.jar'); }); }); describe('filePath()', () => { it('returns the path to the given version name', () => { expect(fixture.filePath('1.2.3')).toEqual(`${fixture.storage}/1.2.3.jar`); }); it('returns the path to the selected version name as default', () => { expect(fixture.filePath()).toEqual(`${fixture.storage}/4.3.0.jar`); }); }); describe('storage', () => { describe('there is no custom storage location', () => { it('returns the correct location path', () => { expect(fixture.storage).toEqual(resolve(__dirname, './versions')); }); }); describe('there is a custom storage location', () => { it.each([ ['/c/w/d/custom/dir', './custom/dir'], ['/custom/dir', '/custom/dir'], ['/custom/dir', '/custom/dir/'], [`${os.homedir()}/oa`, '~/oa/'], [`${os.homedir()}/oa`, '~/oa'], ])('returns %s for %s', async (expected, cfgValue) => { getStorageDir.mockReturnValue(cfgValue) await compile() expect(fixture.storage).toEqual(expected); }); }); }); }); });
the_stack
import { act } from "react-dom/test-utils"; import { renderHook } from "@testing-library/react-hooks"; import { MockJSONServer, TestWrapper } from "@test"; import { useTable } from "."; import { CrudFilters } from "src/interfaces"; const defaultPagination = { pageSize: 10, current: 1, }; const customPagination = { current: 2, defaultCurrent: 2, defaultPageSize: 1, pageSize: 1, }; describe("useTable Hook", () => { it("default", async () => { const { result, waitFor } = renderHook(() => useTable(), { wrapper: TestWrapper({ dataProvider: MockJSONServer, resources: [{ name: "posts" }], }), }); await waitFor(() => { return !result.current.tableQueryResult.isLoading; }); const { tableQueryResult: { data }, pageSize, current, pageCount, } = result.current; expect(data?.data).toHaveLength(2); expect(pageSize).toEqual(defaultPagination.pageSize); expect(current).toEqual(defaultPagination.current); expect(pageCount).toEqual(1); }); it("with initial pagination parameters", async () => { const { result, waitFor } = renderHook( () => useTable({ initialCurrent: customPagination.defaultCurrent, initialPageSize: customPagination.defaultPageSize, }), { wrapper: TestWrapper({ dataProvider: MockJSONServer, resources: [{ name: "posts" }], }), }, ); await waitFor(() => { return !result.current.tableQueryResult.isLoading; }); const { pageSize, current, pageCount } = result.current; expect(pageSize).toEqual(customPagination.pageSize); expect(current).toEqual(customPagination.current); expect(pageCount).toEqual(2); }); it("with custom resource", async () => { const { result, waitFor } = renderHook( () => useTable({ resource: "categories", }), { wrapper: TestWrapper({ dataProvider: MockJSONServer, resources: [ { name: "posts", route: "posts" }, { name: "categories", route: "categories" }, ], }), }, ); await waitFor(() => { return !result.current.tableQueryResult.isLoading; }); const { tableQueryResult: { data }, } = result.current; expect(data?.data).toHaveLength(2); }); it("with syncWithLocation", async () => { const { result, waitFor } = renderHook( () => useTable({ resource: "categories", syncWithLocation: true, }), { wrapper: TestWrapper({ dataProvider: MockJSONServer, resources: [ { name: "posts", route: "posts" }, { name: "categories", route: "categories" }, ], }), }, ); await waitFor(() => { return !result.current.tableQueryResult.isLoading; }); const { tableQueryResult: { data }, } = result.current; expect(data?.data).toHaveLength(2); }); it("should success data with resource", async () => { const { result, waitFor } = renderHook( () => useTable({ resource: "categories", }), { wrapper: TestWrapper({ dataProvider: MockJSONServer, resources: [ { name: "posts", route: "posts" }, { name: "categories", route: "categories" }, ], }), }, ); await waitFor(() => { return result.current.tableQueryResult.isSuccess; }); }); }); describe("useTable Filters", () => { const wrapper = TestWrapper({ dataProvider: MockJSONServer, resources: [{ name: "posts" }], }); it("should be empty initially", () => { const { result } = renderHook(() => useTable(), { wrapper, }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toHaveLength(0); }); it("should only present permanentFilters initially", () => { const permanentFilter = [ { field: "id", operator: "gte", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ permanentFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(permanentFilter); expect(result.current.filters).toHaveLength(1); }); it("should only present initialFilters initially", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(initialFilter); expect(result.current.filters).toHaveLength(1); }); it("should include both initial and permanent filters initially", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const permanentFilter = [ { field: "id", operator: "gte", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, permanentFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual([ ...initialFilter, ...permanentFilter, ]); expect(result.current.filters).toHaveLength(2); expect(result.current.filters).toEqual( expect.arrayContaining(initialFilter), ); expect(result.current.filters).toEqual( expect.arrayContaining(permanentFilter), ); }); it("permanent filter should take precedence over initial filter", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const permanentFilter = [ { field: "name", operator: "contains", value: "foo", }, ] as CrudFilters; const { result } = renderHook( () => useTable({ permanentFilter, initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(permanentFilter); expect(result.current.filters).toHaveLength(1); }); it("[behavior=merge] should merge new filters with existing ones", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const newFilters = [ { field: "id", operator: "gte", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(initialFilter); expect(result.current.filters).toHaveLength(1); act(() => { result.current.setFilters(newFilters, "merge"); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual( expect.arrayContaining([...initialFilter, ...newFilters]), ); expect(result.current.filters).toHaveLength(2); }); it("[behavior=merge] permanent filter should not be overwritten", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const permanentFilter = [ { field: "id", operator: "ne", value: 3, }, ] as CrudFilters; const newFilters = [ { field: "id", operator: "ne", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ permanentFilter, initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual( expect.arrayContaining([...initialFilter, ...permanentFilter]), ); expect(result.current.filters).toHaveLength(2); act(() => { result.current.setFilters(newFilters, "merge"); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual( expect.arrayContaining([...initialFilter, ...permanentFilter]), ); expect(result.current.filters).toHaveLength(2); // should not contain newFilters elements expect(result.current.filters).toEqual( expect.not.arrayContaining(newFilters), ); }); it("[behavior=merge] should merge new filters and remove duplicates", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const permanentFilter = [ { field: "id", operator: "ne", value: 3, }, ] as CrudFilters; const newFilters = [ { field: "name", operator: "contains", value: "foo", }, ] as CrudFilters; const { result } = renderHook( () => useTable({ permanentFilter, initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual([ ...initialFilter, ...permanentFilter, ]); expect(result.current.filters).toHaveLength(2); act(() => { result.current.setFilters(newFilters, "merge"); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual( expect.arrayContaining([...newFilters, ...permanentFilter]), ); expect(result.current.filters).toHaveLength(2); // should not contain initialFilter elements expect(result.current.filters).toEqual( expect.not.arrayContaining(initialFilter), ); // should contain newFilter elements expect(result.current.filters).toEqual( expect.arrayContaining(newFilters), ); }); it("[behavior=merge] should remove the filter when value is undefined/null", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const newFilters = [ { field: "name", operator: "contains", value: undefined, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(initialFilter); expect(result.current.filters).toHaveLength(1); act(() => { result.current.setFilters(newFilters, "merge"); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toHaveLength(0); // should not contain initialFilter elements expect(result.current.filters).toEqual( expect.not.arrayContaining(initialFilter), ); // should contain newFilter elements expect(result.current.filters).toEqual( expect.not.arrayContaining(newFilters), ); }); it("[behavior=replace] should replace the existing filters with newFilters", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const newFilters = [ { field: "id", operator: "ne", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(initialFilter); expect(result.current.filters).toHaveLength(1); act(() => { result.current.setFilters(newFilters, "replace"); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(newFilters); expect(result.current.filters).toHaveLength(1); }); it("[behavior=replace] replace behavior should not overwrite permanent filters", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const permanentFilter = [ { field: "id", operator: "ne", value: 3, }, ] as CrudFilters; const newFilters = [ { field: "id", operator: "ne", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ permanentFilter, initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual([ ...initialFilter, ...permanentFilter, ]); expect(result.current.filters).toHaveLength(2); act(() => { result.current.setFilters(newFilters, "replace"); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(permanentFilter); // should not contain newFilters elements expect(result.current.filters).toEqual( expect.not.arrayContaining(newFilters), ); // should not contain initialFilter elements (because of replace behavior) expect(result.current.filters).toEqual( expect.not.arrayContaining(initialFilter), ); }); it("[behavior=replace] should remove duplicates in the newFilters array", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const newFilters = [ { field: "id", operator: "ne", value: 5, }, { field: "name", operator: "contains", value: "this-should-be-in-it", }, { field: "name", operator: "contains", value: "foo", }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(initialFilter); expect(result.current.filters).toHaveLength(1); act(() => { result.current.setFilters(newFilters, "replace"); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual( expect.arrayContaining([newFilters[0], newFilters[1]]), ); expect(result.current.filters).toHaveLength(2); // should not contain initialFilter elements expect(result.current.filters).toEqual( expect.not.arrayContaining(initialFilter), ); // item at index = 2 should be ignored because of index = 1 expect(result.current.filters).toEqual( expect.not.arrayContaining([newFilters[2]]), ); }); it("should use behavior = merge (default) by default", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const newFilters = [ { field: "id", operator: "gte", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(initialFilter); expect(result.current.filters).toHaveLength(1); act(() => { result.current.setFilters(newFilters); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual( expect.arrayContaining([...initialFilter, ...newFilters]), ); expect(result.current.filters).toHaveLength(2); }); it("should use `defaultSetFiltersBehavior` property as default behavior (replace)", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const newFilters = [ { field: "id", operator: "ne", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, defaultSetFilterBehavior: "replace", }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(initialFilter); expect(result.current.filters).toHaveLength(1); act(() => { result.current.setFilters(newFilters); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(newFilters); expect(result.current.filters).toHaveLength(1); }); it("[setter function] should set the return value of the setter function as filters", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const newFilters = [ { field: "id", operator: "ne", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(initialFilter); expect(result.current.filters).toHaveLength(1); act(() => { result.current.setFilters(() => newFilters); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(newFilters); expect(result.current.filters).toHaveLength(1); }); it("[setter function] should pass the existing filters as first argument", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const newFilters = [ { field: "id", operator: "ne", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual(initialFilter); expect(result.current.filters).toHaveLength(1); const setterFunction = jest.fn( (prevFilters) => [...prevFilters, ...newFilters] as CrudFilters, ); act(() => { result.current.setFilters(setterFunction); }); expect(setterFunction).toBeCalledTimes(1); expect(setterFunction).toBeCalledWith(initialFilter); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual( expect.arrayContaining([...initialFilter, ...newFilters]), ); expect(result.current.filters).toHaveLength(2); }); it("[setter function] should not be able to overwrite permanent filters", () => { const initialFilter = [ { field: "name", operator: "contains", value: "test", }, ] as CrudFilters; const newFilters = [ { field: "id", operator: "gte", value: 3, }, ] as CrudFilters; const permanentFilter = [ { field: "id", operator: "gte", value: 5, }, ] as CrudFilters; const { result } = renderHook( () => useTable({ initialFilter, permanentFilter, }), { wrapper, }, ); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual( expect.arrayContaining([...initialFilter, ...permanentFilter]), ); expect(result.current.filters).toHaveLength(2); act(() => { result.current.setFilters(() => newFilters); }); expect(result.current.filters).toBeInstanceOf(Array); expect(result.current.filters).toEqual( expect.arrayContaining(permanentFilter), ); expect(result.current.filters).toEqual( expect.not.arrayContaining(newFilters), ); expect(result.current.filters).toEqual( expect.not.arrayContaining(initialFilter), ); expect(result.current.filters).toHaveLength(1); }); });
the_stack
import { parse as parseQS, stringify as stringifyQS } from 'qs' import { isError, isLoginPage } from '@/helper/judger' import { notifyError, notifyWarning, RequireOnlyOne } from '@/helper/util' import Vue, { VNode, VNodeData, VueConstructor } from 'vue' import { emitDataAnalysisEvent } from '@/plugins/data-analysis' import { equals } from 'ramda' export interface Route { path: string name?: string params?: Record<string, unknown> } export type RouteHookNextFunction = ( param?: | boolean | string | (RequireOnlyOne< { path: string name: string }, 'name' | 'path' > & { params?: Record<string, unknown> }) | Error | null ) => void export interface RouteConfig { path: string name?: string component: VueConstructor<Vue> componentOptions?: VNodeData beforeEnter?: (next: RouteHookNextFunction, to: Route, from?: Route) => void } const routes: RouteConfig[] = [] const history: Route[] = [] let currentRouteIndexInHistory: number | undefined = undefined export const addRoute = (r: RouteConfig): number => { const hasDuplicationOfPath = (routes: RouteConfig[], path: string) => routes.map(({ path }) => path).includes(path) const hasDuplicationOfName = (routes: RouteConfig[], name: string) => routes.map(({ name }) => name).includes(name) const routeIndexOf = (routes: RouteConfig[], { name, path }: RouteConfig) => routes .map(({ name, path }) => `${name}(${path})`) .indexOf(`${name}(${path})`) const hasDuplicationOfRoute = (routes: RouteConfig[], route: RouteConfig) => routeIndexOf(routes, route) !== -1 if (hasDuplicationOfRoute(routes, r)) { notifyWarning( `路由 ${r.name}(${r.path}) 已被注册,无法重复注册`, '[添加路由] 路由重复' ) return routeIndexOf(routes, r) } if (hasDuplicationOfPath(routes, r.path)) { notifyWarning( `路由路径 ${r.path} 已被注册,可能导致路由跳转出错`, '[添加路由] 路由路径重复' ) } if (r.name && hasDuplicationOfName(routes, r.name)) { notifyWarning( `路由名称 ${r.name} 已被注册,可能导致路由跳转出错`, '[添加路由] 路由名称重复' ) } const newLength = routes.push(r) return newLength - 1 } export const removeRoute = ({ name, path, index }: RequireOnlyOne< { name: string path: string index: number }, 'name' | 'path' | 'index' >): void => { let i = -1 let type = '' if (index) { i = index type = '路由索引' } else if (path) { i = routes.map(({ path }) => path).indexOf(path) type = '路由路径' } else if (name) { i = routes.map(({ name }) => name).indexOf(name) type = '路由名称' } if (i >= 0 && i < routes.length) { routes.splice(i, 1) } else { notifyWarning( `传入${type}参数有误,路由删除失败`, '[删除路由] 路由删除失败' ) } } export const getAllRoutesConfig = (): RouteConfig[] => routes export const getHistory = (): Route[] => history export const getCurrentRoutePath = (): string => { if (!isLoginPage()) { const { sua_route: suaRoute } = parseQS( window.location.hash.replace(/^#/, '') ) return (suaRoute ?? '').toString() } return '' } export const getCurrentRoute = (): Route | undefined => currentRouteIndexInHistory === undefined ? currentRouteIndexInHistory : history[currentRouteIndexInHistory] export const getCurrentRouteParams = (): | Record<string, unknown> | undefined => { if (getCurrentRoute()?.params) { return getCurrentRoute()?.params } const { sua_route_params: params } = parseQS(window.location.hash) if (typeof params === 'string') { return undefined } else if (Array.isArray(params)) { return undefined } return params as Record<string, unknown> | undefined } export const getCurrentRouteConfigByRoutePath = (): RouteConfig => routes.filter(({ path }) => getCurrentRoutePath() === path)[0] export const getRouteConfigByName = (name: string): RouteConfig | null => { const result = routes.filter(v => name === v.name) if (result.length) { return result[0] } return null } export const getRouteConfigByPath = (path: string): RouteConfig | null => { const result = routes.filter(v => path === v.path) if (result.length) { return result[0] } return null } /** * 生成 Vue 单文件组件渲染函数 * * @param name 组件名称 * @param component 组件对象 * @param componentOptions 组件对象选项 */ export const createComponentRender = ( name: string, component: VueConstructor<Vue>, componentOptions?: VNodeData ) => (root: HTMLElement): void => { const className = `sua-container-${name}` $(root).append(`<div class="${className}"></div>`) if (componentOptions) { new Vue({ render: (h): VNode => h(component, componentOptions) }).$mount(`.${className}`) } else { new Vue({ render: (h): VNode => h(component) }).$mount(`.${className}`) } emitDataAnalysisEvent(name, '显示成功') } const convertRoutePathToName = (path: string): string => path.replace(/\//g, '--').replace(/_/g, '-') function replace( path: string, routeOptions?: { params?: Record<string, unknown> } ): Route | undefined function replace(routeOptions: { path: string params?: Record<string, unknown> }): Route | undefined function replace(routeOptions: { name: string params?: Record<string, unknown> }): Route | undefined function replace( p: | string | (RequireOnlyOne< { path: string name: string }, 'name' | 'path' > & { params?: Record<string, unknown> }), ps?: { params?: Record<string, unknown> } ): Route | undefined { const r: Partial<Route> = { path: undefined, name: undefined, params: undefined } if (typeof p === 'string') { r.path = p r.params = ps?.params } else { // param 的 path 和 name 是二选一的关系,一个存在另一个就一定不存在 if (p.path) { r.path = p.path } if (p.name) { r.name = p.name } if (p.params) { r.params = p.params } } try { const result = changeRouter(r, 'replace') return result } catch (error) { console.error(error) return undefined } } function push( path: string, routeOptions?: { params?: Record<string, unknown> } ): Route | undefined function push(routeOptions: { path: string params?: Record<string, unknown> }): Route | undefined function push(routeOptions: { name: string params?: Record<string, unknown> }): Route | undefined function push( p: | string | (RequireOnlyOne< { path: string name: string }, 'name' | 'path' > & { params?: Record<string, unknown> }), ps?: { params?: Record<string, unknown> } ): Route | undefined { const r: Partial<Route> = { path: undefined, name: undefined, params: undefined } if (typeof p === 'string') { r.path = p r.params = ps?.params } else { // param 的 path 和 name 是二选一的关系,一个存在另一个就一定不存在 if (p.path) { r.path = p.path } if (p.name) { r.name = p.name } if (p.params) { r.params = p.params } } try { const result = changeRouter(r, 'push') return result } catch (error) { console.error(error) return undefined } } const go = (n: number): Route | undefined => { if (!currentRouteIndexInHistory) { return undefined } const newIndex = currentRouteIndexInHistory + n if (newIndex < 0 || newIndex >= history.length) { return undefined } return changeRouter(newIndex, 'history') } const back = (): Route | undefined => go(-1) const forward = (): Route | undefined => go(1) type RouterChangeMode = 'push' | 'replace' | 'history' function changeRouter(newIndex: number, changeMode: 'history'): Route function changeRouter(r: Partial<Route>, changeMode: 'push' | 'replace'): Route function changeRouter( r: Partial<Route> | number, changeMode: RouterChangeMode ): Route { let path: string | undefined = undefined let name: string | undefined = undefined let routeConfig: RouteConfig | null = null let params: Record<string, unknown> | undefined = undefined if (typeof r === 'number') { path = history[r].path name = history[r].name params = history[r].params routeConfig = getRouteConfigByPath(history[r].path) } else { if (r.path) { routeConfig = getRouteConfigByPath(r.path) if (routeConfig) { path = routeConfig.path name = routeConfig.name } else { if (r.name) { routeConfig = getRouteConfigByName(r.name) if (routeConfig) { path = routeConfig.path name = r.name } } } } if (r.params) { params = r.params } } if (!path || !routeConfig) { notifyWarning( `传入参数 ${JSON.stringify(r)} 有误,路由跳转失败`, '[路由跳转] 路由跳转失败' ) throw new Error(`路由跳转失败: 传入参数 ${JSON.stringify(r)} 有误`) } const routeToBeEnter: Route = { path, name, params } const { component, componentOptions, beforeEnter } = routeConfig const render = createComponentRender( name ?? convertRoutePathToName(path), component, componentOptions ) const createRouteHookNextFunction = (): RouteHookNextFunction => ( param?: | string | boolean | (RequireOnlyOne< { path: string name: string }, 'name' | 'path' > & { params?: Record<string, unknown> }) | Error | null ): void => { if (param === undefined || param === null) { param = true } if (param === false) { return } if (typeof param === 'boolean') { const $pageContent = $('.main-content>.page-content') $pageContent.empty() // 因为需要兼容书签版,只有修改 hashtag 不会触发页面的刷新 const hashObject: Record<string, unknown> = parseQS( window.location.hash.replace(/^#/, '') ) if (routeToBeEnter.path) { hashObject.sua_route = routeToBeEnter.path } if (routeToBeEnter.params) { hashObject.sua_route_params = routeToBeEnter.params } else { delete hashObject.sua_route_params } // NOTE: 如果不这么写,hash就会被莫名其妙的清除掉。。。 setTimeout(() => { window.location.hash = `#${stringifyQS(hashObject)}` }, 0) switch (changeMode) { case 'push': { if (history.length) { if (currentRouteIndexInHistory !== undefined) { history.length = currentRouteIndexInHistory + 1 } if ( history[history.length - 1].path !== routeToBeEnter.path || !equals(history[history.length - 1].params, routeToBeEnter.params) ) { history.push(routeToBeEnter) } } else { history.push(routeToBeEnter) } currentRouteIndexInHistory = history.length - 1 break } case 'replace': { if (history.length) { if (currentRouteIndexInHistory !== undefined) { history.length = currentRouteIndexInHistory + 1 } history[history.length - 1] = routeToBeEnter } else { history.push(routeToBeEnter) } currentRouteIndexInHistory = history.length - 1 break } case 'history': { if (typeof r === 'number') { currentRouteIndexInHistory = r break } } default: notifyError( '路由跳转模式设置有误!', `[路由跳转] ${routeToBeEnter.path}` ) } render($('.main-content>.page-content')[0]) } else if (typeof param === 'string') { replace(param) } else if (isError(param)) { notifyError(param, `[路由跳转] ${param.name}`) } else { if (param.path) { replace({ path: param.path, params: param.params }) } else if (param.name) { replace({ name: param.name, params: param.params }) } } } const routeHookNextFunction = createRouteHookNextFunction() if (beforeEnter) { beforeEnter(routeHookNextFunction, routeToBeEnter, getCurrentRoute()) } else { routeHookNextFunction() } return routeToBeEnter } export const router = { get allRoutesConfig(): RouteConfig[] { return getAllRoutesConfig() }, get currentRoute(): Route | undefined { return getCurrentRoute() }, get currentRoutePath(): string { return getCurrentRoutePath() }, get currentRouteParams(): Record<string, unknown> | undefined { return getCurrentRouteParams() }, get currentRouteConfig(): RouteConfig { return getCurrentRouteConfigByRoutePath() }, get history(): Route[] { return getHistory() }, push, replace, go, back, forward } export type Router = typeof router
the_stack
import aceEvent, { AceEvent } from "@wowts/ace_event-3.0"; import { LuaArray, LuaObj, ipairs, kpairs, lualength, pairs, tonumber, type, wipe, } from "@wowts/lua"; import { huge as INFINITY } from "@wowts/math"; import { find, len, lower, match, sub } from "@wowts/string"; import { concat, insert, sort } from "@wowts/table"; import { AceModule } from "@wowts/tsaddon"; import { C_Item, Enum, GetInventorySlotInfo, GetItemCooldown, GetItemStats, GetTime, GetWeaponEnchantInfo, InventorySlotName, ItemLocation, ItemLocationMixin, } from "@wowts/wow-mock"; import { OvaleClass } from "../Ovale"; import { AstFunctionNode, NamedParametersOf } from "../engine/ast"; import { ConditionFunction, ConditionResult, OvaleConditionClass, ParameterInfo, returnBoolean, returnConstant, returnValueBetween, } from "../engine/condition"; import { OvaleDataClass } from "../engine/data"; import { DebugTools, Tracer } from "../engine/debug"; import { KeyCheck } from "../tools/tools"; import { OptionUiAll } from "../ui/acegui-helpers"; // To allow iteration over InventorySlotNames. export type InventorySlotNameMap = { [key in InventorySlotName]?: boolean }; export const inventorySlotNames: InventorySlotNameMap = { AMMOSLOT: true, BACKSLOT: true, CHESTSLOT: true, FEETSLOT: true, FINGER0SLOT: true, FINGER1SLOT: true, HANDSSLOT: true, HEADSLOT: true, LEGSSLOT: true, MAINHANDSLOT: true, NECKSLOT: true, // (removed in retail) RANGEDSLOT: true, SECONDARYHANDSLOT: true, SHIRTSLOT: true, SHOULDERSLOT: true, TABARDSLOT: true, TRINKET0SLOT: true, TRINKET1SLOT: true, WAISTSLOT: true, WRISTSLOT: true, }; // Bijection between InventorySlotName and InventorySlotID. const slotIdByName: LuaObj<number> = {}; const slotNameById: LuaArray<InventorySlotName> = {}; // Slot names used in Ovale scripts. export type SlotName = | "ammoslot" | "backslot" | "chestslot" | "feetslot" | "finger0slot" | "finger1slot" | "handsslot" | "headslot" | "legsslot" | "mainhandslot" | "neckslot" | "offhandslot" | "secondaryhandslot" | "shirtslot" | "shoulderslot" | "tabardslot" | "trinket0slot" | "trinket1slot" | "waistslot" | "wristslot"; const checkSlotName: KeyCheck<SlotName> = { ammoslot: true, backslot: true, chestslot: true, feetslot: true, finger0slot: true, finger1slot: true, handsslot: true, headslot: true, legsslot: true, mainhandslot: true, neckslot: true, offhandslot: true, secondaryhandslot: true, shirtslot: true, shoulderslot: true, tabardslot: true, trinket0slot: true, trinket1slot: true, waistslot: true, wristslot: true, }; // Map Ovale slot names to InventorySlotName. const slotNameByName: LuaObj<InventorySlotName> = { ammoslot: "AMMOSLOT", backslot: "BACKSLOT", chestslot: "CHESTSLOT", feetslot: "FEETSLOT", finger0slot: "FINGER0SLOT", finger1slot: "FINGER1SLOT", handsslot: "HANDSSLOT", headslot: "HEADSLOT", legsslot: "LEGSSLOT", mainhandslot: "MAINHANDSLOT", neckslot: "NECKSLOT", offhandslot: "SECONDARYHANDSLOT", secondaryhandslot: "SECONDARYHANDSLOT", shirtslot: "SHIRTSLOT", shoulderslot: "SHOULDERSLOT", tabardslot: "TABARDSLOT", trinket0slot: "TRINKET0SLOT", trinket1slot: "TRINKET1SLOT", waistslot: "WAISTSLOT", wristslot: "WRISTSLOT", }; // Map InventorySlotName to Ovale slot names. type OvaleSlotNameMap = { [key in InventorySlotName]?: SlotName }; const ovaleSlotNameByName: OvaleSlotNameMap = {}; interface ItemInfo { exists: boolean; guid: string; pending?: number; id?: number; link?: string; location?: ItemLocationMixin; name?: string; quality?: number; // Enum.ItemQuality type?: number; // Enum.InventoryType // The properties below are populated by parseItemLink(). gem: LuaArray<number>; bonus: LuaArray<number>; modifier: LuaArray<number>; } function resetItemInfo(item: ItemInfo) { item.exists = false; item.guid = ""; delete item.pending; delete item.link; delete item.location; delete item.name; delete item.quality; delete item.type; delete item.id; wipe(item.gem); wipe(item.bonus); wipe(item.modifier); } export class OvaleEquipmentClass { mainHandDPS = 0; offHandDPS = 0; // armorSetCount = {}; private equippedItem: LuaObj<ItemInfo> = {}; private equippedItemBySharedCooldown: LuaObj<number> = {}; private isEquippedItemById: LuaObj<boolean> = {}; private debugOptions: LuaObj<OptionUiAll> = { itemsequipped: { name: "Items equipped", type: "group", args: { itemsequipped: { name: "Items equipped", type: "input", multiline: 25, width: "full", get: (info: LuaArray<string>) => { return this.debugEquipment(); }, }, }, }, }; private module: AceModule & AceEvent; private tracer: Tracer; constructor( private ovale: OvaleClass, ovaleDebug: DebugTools, private data: OvaleDataClass ) { this.module = ovale.createModule( "OvaleEquipment", this.handleInitialize, this.handleDisable, aceEvent ); this.tracer = ovaleDebug.create("OvaleEquipment"); for (const [k, v] of pairs(this.debugOptions)) { ovaleDebug.defaultOptions.args[k] = v; } for (const [slot] of kpairs(inventorySlotNames)) { ovaleSlotNameByName[slot] = lower(slot) as SlotName; const [slotId] = GetInventorySlotInfo(slot); slotIdByName[slot] = slotId; slotNameById[slotId] = slot; this.equippedItem[slot] = { exists: false, guid: "", gem: {}, bonus: {}, modifier: {}, }; } } private handleInitialize = () => { this.module.RegisterEvent( "ITEM_DATA_LOAD_RESULT", this.handleItemDataLoadResult ); this.module.RegisterEvent( "PLAYER_ENTERING_WORLD", this.handlePlayerEnteringWorld ); this.module.RegisterEvent( "PLAYER_EQUIPMENT_CHANGED", this.handlePlayerEquipmentChanged ); }; private handleDisable = () => { this.module.UnregisterEvent("ITEM_DATA_LOAD_RESULT"); this.module.UnregisterEvent("PLAYER_ENTERING_WORLD"); this.module.UnregisterEvent("PLAYER_EQUIPMENT_CHANGED"); }; private handleItemDataLoadResult = ( event: string, itemId: number, success: boolean ) => { if (success && this.isEquippedItemById[itemId]) { for (const [slot, item] of pairs(this.equippedItem)) { if (item.pending) { const slotId = slotIdByName[slot]; const location = ItemLocation.CreateFromEquipmentSlot(slotId); if (location.IsValid() && item.pending == itemId) { this.finishUpdateForSlot( slot as InventorySlotName, itemId, location ); } } } } }; private handlePlayerEnteringWorld = (event: string) => { for (const [slot] of kpairs(inventorySlotNames)) { this.queueUpdateForSlot(slot); } }; private handlePlayerEquipmentChanged = ( event: string, slotId: number, hasCurrent: boolean ) => { const slot = slotNameById[slotId]; this.queueUpdateForSlot(slot); }; // Armor sets are retiring after Legion; for now, return 0 getArmorSetCount(name: string) { /* let count = this.armorSetCount[name]; if (!count) { const className = Ovale.playerClass; if (armorSetName[className] && armorSetName[className][name]) { name = armorSetName[className][name]; count = this.armorSetCount[name]; } } */ return 0; } getEquippedItemId(slot: SlotName): number | undefined { const invSlot = slotNameByName[slot]; const item = this.equippedItem[invSlot]; return (item && item.exists && item.id) || undefined; } getEquippedItemIdBySharedCooldown( sharedCooldown: string ): number | undefined { return this.equippedItemBySharedCooldown[sharedCooldown]; } getEquippedItemLocation(slot: SlotName): ItemLocationMixin | undefined { const invSlot = slotNameByName[slot]; const item = this.equippedItem[invSlot]; if (item && item.exists) { if (item.location && item.location.IsValid()) { return item.location; } } return undefined; } getEquippedItemQuality(slot: SlotName): number | undefined { const invSlot = slotNameByName[slot]; const item = this.equippedItem[invSlot]; return (item && item.exists && item.quality) || undefined; } getEquippedItemBonusIds(slot: SlotName): LuaArray<number> { // Returns the array of bonus IDs for the slot. const invSlot = slotNameByName[slot]; const item = this.equippedItem[invSlot]; return (item && item.bonus) || {}; } hasRangedWeapon() { const item = this.equippedItem["MAINHANDSLOT"]; if (item.exists && item.type != undefined) { return ( item.type == Enum.InventoryType.IndexRangedType || item.type == Enum.InventoryType.IndexRangedrightType ); } return false; } private parseItemLink = (link: string, item: ItemInfo) => { let [s] = match(link, "item:([%-?%d:]+)"); const pattern = "[^:]*:"; let [i, j] = find(s, pattern); let eos = len(s); let numBonus = 0; let numModifiers = 0; let index = 0; while (i) { const token = tonumber(sub(s, i, j - 1)) || 0; index = index + 1; if (index == 1) { item.id = token; } else if (3 <= index && index <= 5) { if (token != 0) { const gem = item.gem || {}; insert(gem, token); item.gem = gem; } } else if (index == 13) { numBonus = token; } else if (index > 13 && index <= 13 + numBonus) { const bonus = item.bonus || {}; insert(bonus, token); item.bonus = bonus; } else if (index == 13 + numBonus + 1) { numModifiers = token; } else if ( index > 13 + numBonus + 1 && index <= 13 + numBonus + 1 + numModifiers ) { const modifier = item.modifier || {}; insert(modifier, token); item.modifier = modifier; } if (j < eos) { s = sub(s, j + 1); [i, j] = find(s, pattern); } else { break; } } // Ignore the last token since we don't need it for Ovale. }; private queueUpdateForSlot = (slot: InventorySlotName) => { const slotId = slotIdByName[slot]; const location = ItemLocation.CreateFromEquipmentSlot(slotId); const item = this.equippedItem[slot]; if (location.IsValid()) { const itemId = C_Item.GetItemID(location); this.isEquippedItemById[itemId] = true; const link = C_Item.GetItemLink(location); if (link) { // Item link is available, so data is already loaded. this.finishUpdateForSlot(slot, itemId, location); } else { // Save pending itemID to be checked in event handler. item.pending = itemId; C_Item.RequestLoadItemData(location); this.tracer.debug(`Slot ${slot}, item ${itemId}: queued`); } } else { this.tracer.debug(`Slot ${slot}: empty`); resetItemInfo(item); } }; private finishUpdateForSlot = ( slot: InventorySlotName, itemId: number, location: ItemLocationMixin ) => { this.tracer.debug(`Slot ${slot}, item ${itemId}: finished`); const item = this.equippedItem[slot]; if (location.IsValid()) { const prevGUID = item.guid; const prevItemId = item.id; if (prevItemId != undefined) { delete this.isEquippedItemById[prevItemId]; } resetItemInfo(item); item.exists = true; item.guid = C_Item.GetItemGUID(location); item.id = itemId; item.location = location; item.name = C_Item.GetItemName(location); item.quality = C_Item.GetItemQuality(location); item.type = C_Item.GetItemInventoryType(location); const link = C_Item.GetItemLink(location); if (link) { item.link = link; this.parseItemLink(link, item); if (slot == "MAINHANDSLOT" || slot == "SECONDARYHANDSLOT") { const stats = GetItemStats(link); if (stats != undefined) { const dps = stats["ITEM_MOD_DAMAGE_PER_SECOND_SHORT"] || 0; if (slot == "MAINHANDSLOT") { this.mainHandDPS = dps; } else if (slot == "SECONDARYHANDSLOT") { this.offHandDPS = dps; } } } } this.isEquippedItemById[itemId] = true; const info = this.data.itemInfo[itemId]; if (info != undefined && info.shared_cd != undefined) { this.equippedItemBySharedCooldown[info.shared_cd] = itemId; } if (prevGUID != item.guid) { //this.UpdateArmorSetCount(); this.ovale.needRefresh(); const slotName = ovaleSlotNameByName[slot]; this.module.SendMessage("Ovale_EquipmentChanged", slotName); } } else { resetItemInfo(item); } }; private debugEquipment = () => { const output: LuaArray<string> = {}; const array: LuaArray<string> = {}; insert(output, "Equipped Items:"); for (const [id] of kpairs(this.isEquippedItemById)) { insert(array, ` ${id}`); } sort(array); for (const [, v] of ipairs(array)) { insert(output, v); } insert(output, ""); wipe(array); for (const [slot, item] of pairs(this.equippedItem)) { const shortSlot = lower(sub(slot, 1, -5)); if (item.exists) { let s = `${shortSlot}: ${item.id}`; if (lualength(item.gem) > 0) { s = s + " gem["; for (const [, v] of ipairs(item.gem)) { s = s + ` ${v}`; } s = s + "]"; } if (lualength(item.bonus) > 0) { s = s + " bonus["; for (const [, v] of ipairs(item.bonus)) { s = s + ` ${v}`; } s = s + "]"; } if (lualength(item.modifier) > 0) { s = s + " mod["; for (const [, v] of ipairs(item.modifier)) { s = s + ` ${v}`; } s = s + "]"; } insert(array, s); } else { insert(array, `${shortSlot}: empty`); } } sort(array); for (const [, v] of ipairs(array)) { insert(output, v); } insert(output, ""); insert(output, `Main-hand DPS = ${this.mainHandDPS}`); insert(output, `Off-hand DPS = ${this.offHandDPS}`); return concat(output, "\n"); }; registerConditions(ovaleCondition: OvaleConditionClass) { ovaleCondition.registerCondition( "hasequippeditem", false, this.hasItemEquipped ); ovaleCondition.registerCondition("hasshield", false, this.hasShield); ovaleCondition.registerCondition("hastrinket", false, this.hasTrinket); ovaleCondition.registerCondition("hasweapon", false, this.hasWeapon); const slotParameter: ParameterInfo<SlotName> = { type: "string", name: "slot", checkTokens: checkSlotName, optional: true, }; const itemParameter: ParameterInfo<number> = { name: "item", type: "number", optional: true, isItem: true, }; ovaleCondition.register( "itemcooldown", this.itemCooldown, { type: "number" }, itemParameter, slotParameter, { name: "shared", type: "string", optional: true } ); ovaleCondition.register( "itemrppm", this.itemRppm, { type: "number" }, { type: "number", name: "item", optional: true }, { type: "string", name: "slot", checkTokens: checkSlotName, optional: true, } ); ovaleCondition.register( "itemcooldownduration", this.itemCooldownDuration, { type: "number" }, itemParameter, slotParameter ); ovaleCondition.registerCondition( "weaponenchantexpires", false, this.weaponEnchantExpires ); ovaleCondition.registerCondition( "weaponenchantpresent", false, this.weaponEnchantPresent ); ovaleCondition.register( "iteminslot", this.itemInSlot, { type: "number" }, { type: "string", optional: false, name: "slot", checkTokens: checkSlotName, } ); } /** Test if the player has a particular item equipped. @name HasEquippedItem @paramsig boolean @param item Item to be checked whether it is equipped. */ private hasItemEquipped = ( positionalParams: LuaArray<any>, namedParams: NamedParametersOf<AstFunctionNode>, atTime: number ) => { const itemId = positionalParams[1]; let boolean = false; if (type(itemId) == "number") { boolean = this.isEquippedItemById[itemId]; } else if (this.data.itemList[itemId] != undefined) { for (const [, id] of pairs(this.data.itemList[itemId])) { boolean = this.isEquippedItemById[id]; if (boolean) break; } } return returnBoolean(boolean); }; /** Test if the player has a shield equipped. @name HasShield @paramsig boolean @return A boolean value. @usage if HasShield() Spell(shield_wall) */ private hasShield = ( positionalParams: LuaArray<any>, namedParams: NamedParametersOf<AstFunctionNode>, atTime: number ) => { const item = this.equippedItem["SECONDARYHANDSLOT"]; const boolean = item.exists && item.type == Enum.InventoryType.IndexShieldType; return returnBoolean(boolean); }; /** Test if the player has a particular trinket equipped. @name HasTrinket @paramsig boolean @param id The item ID of the trinket or the name of an item list. @usage ItemList(rune_of_reorigination 94532 95802 96546) if HasTrinket(rune_of_reorigination) and BuffPresent(rune_of_reorigination_buff) Spell(rake) */ private hasTrinket = ( positionalParams: LuaArray<any>, namedParams: NamedParametersOf<AstFunctionNode>, atTime: number ) => { const itemId = positionalParams[1]; let boolean = false; if (type(itemId) == "number") { // Check only in the trinket slots. boolean = (this.equippedItem["TRINKET0SLOT"].exists && this.equippedItem["TRINKET0SLOT"].id == itemId) || (this.equippedItem["TRINKET1SLOT"].exists && this.equippedItem["TRINKET1SLOT"].id == itemId); } else if (this.data.itemList[itemId] != undefined) { for (const [, id] of pairs(this.data.itemList[itemId])) { boolean = (this.equippedItem["TRINKET0SLOT"].exists && this.equippedItem["TRINKET0SLOT"].id == id) || (this.equippedItem["TRINKET1SLOT"].exists && this.equippedItem["TRINKET1SLOT"].id == id); if (boolean) break; } } return returnBoolean(boolean); }; private hasWeapon: ConditionFunction = ( positionalParameter, namedParameter, atTime ) => { const slot = positionalParameter[1] as SlotName; const handedness = positionalParameter[2]; const invSlot = slotNameByName[slot]; const invType = (handedness == "1h" && Enum.InventoryType.IndexWeaponType) || Enum.InventoryType.Index2HweaponType; const item = this.equippedItem[invSlot]; if (item.exists && item.type) { return returnBoolean(item.type == invType); } return returnBoolean(false); }; /** Get the cooldown time in seconds of an item, e.g., trinket. @name ItemCooldown @paramsig number or boolean @param id The item ID or the equipped slot name. @return The number of seconds. @usage if not ItemCooldown(ancient_petrified_seed) > 0 Spell(berserk_cat) if not ItemCooldown(Trinket0Slot) > 0 Spell(berserk_cat) */ private itemCooldown = ( atTime: number, itemId: number | undefined, slot: SlotName | undefined, sharedCooldown: string | undefined ) => { if (sharedCooldown) { itemId = this.getEquippedItemIdBySharedCooldown(sharedCooldown); } if (slot != undefined) { itemId = this.getEquippedItemId(slot); } if (itemId) { const [start, duration] = GetItemCooldown(itemId); if (start > 0 && duration > 0) { const ending = start + duration; return returnValueBetween(start, ending, duration, start, -1); } } return returnConstant(0); }; private itemCooldownDuration = ( atTime: number, itemId: number | undefined, slot: SlotName | undefined ) => { if (slot !== undefined) { itemId = this.getEquippedItemId(slot); } if (!itemId) return returnConstant(0); let [, duration] = GetItemCooldown(itemId); if (duration <= 0) { duration = (this.data.getItemInfoProperty( itemId, atTime, "cd" ) as number) || 0; } return returnConstant(duration); }; private itemInSlot = (atTime: number, slot: SlotName) => { const itemId = this.getEquippedItemId(slot); return returnConstant(itemId); }; /** Get the number of seconds since the enchantment has expired */ private weaponEnchantExpires: ConditionFunction = ( positionalParams ): ConditionResult => { const expectedEnchantmentId = positionalParams[1]; const hand = positionalParams[2]; let [ hasMainHandEnchant, mainHandExpiration, enchantmentId, hasOffHandEnchant, offHandExpiration, ] = GetWeaponEnchantInfo(); const now = GetTime(); if (hand == "main" || hand === undefined) { if (hasMainHandEnchant && expectedEnchantmentId === enchantmentId) { mainHandExpiration = mainHandExpiration / 1000; return [now + mainHandExpiration, INFINITY]; } } else if (hand == "offhand" || hand == "off") { if (hasOffHandEnchant) { offHandExpiration = offHandExpiration / 1000; return [now + offHandExpiration, INFINITY]; } } return [0, INFINITY]; }; /** Get the number of seconds since the enchantment has expired */ private weaponEnchantPresent: ConditionFunction = (positionalParams) => { const expectedEnchantmentId = positionalParams[1]; const hand = positionalParams[2]; let [ hasMainHandEnchant, mainHandExpiration, enchantmentId, hasOffHandEnchant, offHandExpiration, ] = GetWeaponEnchantInfo(); const now = GetTime(); if (hand == "main" || hand === undefined) { if (hasMainHandEnchant && expectedEnchantmentId === enchantmentId) { mainHandExpiration = mainHandExpiration / 1000; return [0, now + mainHandExpiration]; } } else if (hand == "offhand" || hand == "off") { if (hasOffHandEnchant) { offHandExpiration = offHandExpiration / 1000; return [0, now + offHandExpiration]; } } return []; }; private itemRppm = ( atTime: number, itemId: number | undefined, slot: SlotName | undefined ): ConditionResult => { if (slot) { itemId = this.getEquippedItemId(slot); } if (itemId) { const rppm = this.data.getItemInfoProperty(itemId, atTime, "rppm"); return returnConstant(rppm); } return []; }; }
the_stack
import { computed } from "@ember/object"; import { ComputedPropertyMarker } from "./-private/types"; /** * A computed property transforms an objects function into a property. * By default the function backing the computed property will only be called once and the result * will be cached. You can specify various properties that your computed property is dependent on. * This will force the cached result to be recomputed if the dependencies are modified. */ export default class ComputedProperty<Get, Set = Get> { /** * Call on a computed property to set it into non-cached mode. When in this * mode the computed property will not automatically cache the return value. */ volatile(): this; /** * Call on a computed property to set it into read-only mode. When in this * mode the computed property will throw an error when set. */ readOnly(): this; /** * Sets the dependent keys on this computed property. Pass any number of * arguments containing key paths that this computed property depends on. */ property(...path: string[]): this; /** * In some cases, you may want to annotate computed properties with additional * metadata about how they function or what values they operate on. For example, * computed property functions may close over variables that are then no longer * available for introspection. */ meta(meta: {}): this; meta(): {}; } // Computed property definitions also act as property decorators, including those // returned from "macros" in third-party code. We additionally include a marker // interface that we use in `UnwrapComputedProperty{G,S}etters`. export default interface ComputedProperty<Get, Set = Get> extends PropertyDecorator, ComputedPropertyMarker<Get, Set> {} /** * Creates a new property that is an alias for another property * on an object. Calls to `get` or `set` this property behave as * though they were called on the original property. */ export function alias( dependentKey: string ): ComputedProperty<any>; /** * A computed property that performs a logical `and` on the * original values for the provided dependent properties. */ export function and( ...dependentKeys: string[] ): ComputedProperty<boolean>; /** * A computed property that converts the provided dependent property * into a boolean value. */ export function bool( dependentKey: string ): ComputedProperty<boolean>; /** * A computed property that returns the array of values * for the provided dependent properties. */ export function collect( ...dependentKeys: string[] ): ComputedProperty<any[]>; /** * Creates a new property that is an alias for another property * on an object. Calls to `get` or `set` this property behave as * though they were called on the original property, but also * print a deprecation warning. */ export function deprecatingAlias( dependentKey: string, options: { id: string; until: string } ): ComputedProperty<any>; /** * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options */ export function deprecatingAlias( dependentKey: string, options?: { id?: string | undefined; until?: string | undefined } ): ComputedProperty<any>; /** * A computed property that returns true if the value of the dependent * property is null, an empty string, empty array, or empty function. */ export function empty( dependentKey: string ): ComputedProperty<boolean>; /** * A computed property that returns true if the provided dependent property * is equal to the given value. */ export function equal( dependentKey: string, value: any ): ComputedProperty<boolean>; /** * Expands `pattern`, invoking `callback` for each expansion. */ export function expandProperties( pattern: string, callback: (expanded: string) => void ): void; /** * Filters the array by the callback. */ export function filter( dependentKey: string, callback: (value: any, index: number, array: any[]) => boolean ): ComputedProperty<any[]>; /** * Filters the array by the callback and an array of additional dependent keys. */ export function filter( dependentKey: string, additionalDependentKeys: string[], callback: (value: any, index: number, array: any[]) => boolean ): ComputedProperty<any[]>; /** * Filters the array by the property and value */ export function filterBy( dependentKey: string, propertyKey: string, value?: any ): ComputedProperty<any[]>; /** * A computed property that returns true if the provided dependent property * is greater than the provided value. */ export function gt( dependentKey: string, value: number ): ComputedProperty<boolean>; /** * A computed property that returns true if the provided dependent property * is greater than or equal to the provided value. */ export function gte( dependentKey: string, value: number ): ComputedProperty<boolean>; /** * A computed property which returns a new array with all the elements * two or more dependent arrays have in common. */ export function intersect( ...propertyKeys: string[] ): ComputedProperty<any[]>; /** * A computed property that returns true if the provided dependent property * is less than the provided value. */ export function lt( dependentKey: string, value: number ): ComputedProperty<boolean>; /** * A computed property that returns true if the provided dependent property * is less than or equal to the provided value. */ export function lte( dependentKey: string, value: number ): ComputedProperty<boolean>; /** * Returns an array mapped via the callback */ export function map<U>( dependentKey: string, callback: (value: any, index: number, array: any[]) => U ): ComputedProperty<U[]>; /** * Returns an array mapped to the specified key. */ export function mapBy( dependentKey: string, propertyKey: string ): ComputedProperty<any[]>; /** * A computed property which matches the original value for the * dependent property against a given RegExp, returning `true` * if the value matches the RegExp and `false` if it does not. */ export function match( dependentKey: string, regexp: RegExp ): ComputedProperty<boolean>; /** * A computed property that calculates the maximum value in the * dependent array. This will return `-Infinity` when the dependent * array is empty. */ export function max( dependentKey: string ): ComputedProperty<number>; /** * A computed property that calculates the minimum value in the * dependent array. This will return `Infinity` when the dependent * array is empty. */ export function min( dependentKey: string ): ComputedProperty<number>; /** * A computed property that returns true if the value of the dependent * property is null or undefined. This avoids errors from JSLint complaining * about use of ==, which can be technically confusing. */ export function none( dependentKey: string ): ComputedProperty<boolean>; /** * A computed property that returns the inverse boolean value * of the original value for the dependent property. */ export function not( dependentKey: string ): ComputedProperty<boolean>; /** * A computed property that returns true if the value of the dependent * property is NOT null, an empty string, empty array, or empty function. */ export function notEmpty( dependentKey: string ): ComputedProperty<boolean>; /** * Where `computed.alias` aliases `get` and `set`, and allows for bidirectional * data flow, `computed.oneWay` only provides an aliased `get`. The `set` will * not mutate the upstream property, rather causes the current property to * become the value set. This causes the downstream property to permanently * diverge from the upstream property. */ export function oneWay( dependentKey: string ): ComputedProperty<any>; /** * A computed property which performs a logical `or` on the * original values for the provided dependent properties. */ export function or( ...dependentKeys: string[] ): ComputedProperty<boolean>; /** * Where `computed.oneWay` provides oneWay bindings, `computed.readOnly` provides * a readOnly one way binding. Very often when using `computed.oneWay` one does * not also want changes to propagate back up, as they will replace the value. */ export function readOnly( dependentKey: string ): ComputedProperty<any>; /** * This is a more semantically meaningful alias of `computed.oneWay`, * whose name is somewhat ambiguous as to which direction the data flows. */ export function reads( dependentKey: string ): ComputedProperty<any>; /** * A computed property which returns a new array with all the * properties from the first dependent array that are not in the second * dependent array. */ export function setDiff( setAProperty: string, setBProperty: string ): ComputedProperty<any[]>; /** * A computed property which returns a new array with all the * properties from the first dependent array sorted based on a property * or sort function. * If used with an array of sort properties, it must receive exactly two arguments: * the key of the array to sort, and the key of the array of sort properties. * Alternatively the key of the array to sort, and a the sort function may be used. */ export function sort( itemsKey: string, sortDefinition: string | ((itemA: any, itemB: any) => number) ): ComputedProperty<any[]>; /** * A computed property which returns a new array with all the * properties from the first dependent array sorted based on a property * or sort function. * It may recieve three arguments: the key of the array to sort, an array of dependent keys * for the computed property, and the sort function. */ export function sort( itemsKey: string, dependentKeys: string[], sortDefinition: string | ((itemA: any, itemB: any) => number) ): ComputedProperty<any[]>; /** * A computed property that returns the sum of the values * in the dependent array. */ export function sum( dependentKey: string ): ComputedProperty<number>; /** * A computed property which returns a new array with all the unique * elements from one or more dependent arrays. */ export function uniq( propertyKey: string ): ComputedProperty<any[]>; /** * A computed property which returns a new array with all the unique * elements from one or more dependent arrays. */ export function union( ...propertyKeys: string[] ): ComputedProperty<any[]>; /** * A computed property which returns a new array with all the unique * elements from an array, with uniqueness determined by specific key. */ export function uniqBy( dependentKey: string, propertyKey: string ): ComputedProperty<any[]>;
the_stack
import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; import { FormBuilder } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { SFComponent, SFRadioWidgetSchema, SFDateWidgetSchema, SFSliderWidgetSchema, SFSelectWidgetSchema, SFTransferWidgetSchema, SFTreeSelectWidgetSchema, SFUploadWidgetSchema, SFSchema, } from '@delon/form'; import { _HttpClient } from '@delon/theme'; import { NzDrawerRef } from 'ng-zorro-antd/drawer'; import { NzMessageService } from 'ng-zorro-antd/message'; import { map } from 'rxjs/operators'; @Component({ selector: 'app-dynamicformview', templateUrl: './dynamicformview.component.html', styleUrls: ['./dynamicformview.component.less'], }) export class DynamicformviewComponent implements OnInit { @ViewChild('sf', { static: false }) sf: SFComponent; @Input() _id: Number = -1; @Output() onsubmit = new EventEmitter(); options: {}; AllControlType: any = []; AllSuportType: any = []; SuportType: any = []; get id() { return this._id; } set id(val) { this._id = val; this.CreatForm(val); } constructor( private _router: ActivatedRoute, private router: Router, private _formBuilder: FormBuilder, private _httpClient: _HttpClient, private fb: FormBuilder, private msg: NzMessageService, private drawerRef: NzDrawerRef<string>, private cd: ChangeDetectorRef, ) {} private CreatForm(id) { this._httpClient.get('api/DynamicFormInfo/GetFormFieldValue?FormId=' + this.id + '&BizId=0').subscribe( (x) => { var properties = {}; x.data = x.data.map((x) => { return { Creator: x.creator, FieldCode: x.fieldCode, FieldCreateDate: x.fieldCreateDate, FieldEditDate: x.fieldEditDate, FieldI18nKey: x.fieldI18nKey, FieldId: x.fieldId, FieldMaxLength: x.fieldMaxLength, FieldName: x.fieldName, FieldPattern: x.fieldPattern, FieldPocoTypeName: x.fieldPocoTypeName, FieldStatus: x.fieldStatus, FieldUIElement: x.fieldUIElement, FieldUIElementSchema: x.fieldUIElementSchema, FieldUnit: x.fieldUnit, FieldValue: x.fieldValue, FieldValueDataSource: x.fieldValueDataSource, FieldValueLocalDataSource: x.fieldValueLocalDataSource, FieldValueType: x.fieldValueType, FieldValueTypeName: x.fieldValueTypeName, FormId: x.formId, IsRequired: x.isRequired, }; }); for (let a of x.data) { var Schame = JSON.parse(a.FieldUIElementSchema); switch (a.FieldUIElement) { case 1: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, // exclusiveMinimum: Schame.exclusiveMinimum, // exclusiveMaximum: Schame.exclusiveMaximum, maximum: Schame.maximum, minimum: Schame.minimum, ui: { widgetWidth: Schame.ui.widgetWidth, }, default: a.FieldValue, }; break; case 2: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, maxLength: Schame.maxLength, pattern: Schame.pattern, ui: { addOnAfter: Schame.ui.addOnAfter, placeholder: Schame.ui.placeholder, }, default: a.FieldValue, }; break; case 3: break; case 4: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, ui: { widget: 'md', options: { toolbar: ['bold', 'italic', 'heading', '|', 'quote'], }, }, default: a.FieldValue, }; break; case 5: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, ui: { checkedChildren: Schame.ui.checkedChildren, unCheckedChildren: Schame.ui.unCheckedChildren, }, default: a.FieldValue, }; break; case 6: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue ? JSON.parse(a.FieldValue) : '', ui: { widget: 'checkbox', span: Schame.ui.span, styleType: Schame.ui.styleType, checkAll: Schame.ui.checkAll, asyncData: () => this._httpClient.get(a.FieldValueDataSource).pipe( map((x) => { return x.data; }), ), // this._httpClient.get(a.FieldValueDataSource).pipe( // map((x) => { // return x.data.map((y) => { // return { // value: y[Schame.IotSharp.key], // label: y[Schame.IotSharp.value], // }; // }); // }), // ), }, }; break; case 7: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue, ui: { checkedChildren: Schame.ui.checkedChildren, unCheckedChildren: Schame.ui.unCheckedChildren, }, }; break; case 8: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue, ui: { widget: 'radio', styleType: Schame.ui.styleType, buttonStyle: Schame.ui.buttonStyle, asyncData: () => this._httpClient.get(a.FieldValueDataSource).pipe( map((x) => { return x.data; }), ), // this._httpClient.get(a.FieldValueDataSource).pipe( // map((x) => { // return x.data.map((y) => { // return { // value: y[Schame.IotSharp.key], // label: y[Schame.IotSharp.value], // }; // }); // }), // ), } as SFRadioWidgetSchema, }; break; case 9: switch (Schame.IotSharp.format) { case 'date-time': properties[a.FieldCode] = { type: 'string', format: 'date-time', default: '2015-3-1 11:11:11', displayFormat: 'yyyy-MM-dd HH:mm:ss', title: a.FieldName, }; break; case 'date': properties[a.FieldCode] = { type: 'string', title: a.FieldName, default: a.FieldValue, format: 'date', }; break; case 'month': properties[a.FieldCode] = { title: a.FieldName, default: a.FieldValue, type: 'string', format: 'month', }; break; case 'yyyy': properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue, ui: { widget: 'date', format: Schame.IotSharp.format, mode: 'year', } as SFDateWidgetSchema, }; break; case 'week': properties[a.FieldCode] = { type: 'string', format: 'week', title: a.FieldName, default: a.FieldValue, }; break; case 'range': var dpv = []; try { dpv = JSON.parse(a.FieldValue); } catch (error) {} properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: dpv, ui: { widget: 'date', mode: 'range', } as SFDateWidgetSchema, }; break; case 'Inline': properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue, ui: { widget: 'date', inline: true, } as SFDateWidgetSchema, }; break; } break; case 10: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue, ui: { widget: 'time', placeholder: Schame.ui.placeholder, format: Schame.ui.format, utcEpoch: Schame.ui.utcEpoch, allowEmpty: Schame.ui.allowEmpty, use12Hours: Schame.ui.use12Hours, }, }; break; case 11: if (!Schame.ui) { Schame.ui = {}; } else { } properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, minimum: Schame.minimum, maximum: Schame.maximum, multipleOf: Schame.multipleOf, default: a.FieldValue ? JSON.parse(a.FieldValue) : '', ui: { widget: 'slider', range: Schame.ui.range, } as SFSliderWidgetSchema, }; break; case 12: if (Schame.IotSharp && Schame.IotSharp.allowsearch) { properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue, ui: { widget: 'select', serverSearch: true, searchDebounceTime: 300, searchLoadingText: '搜索中...', onSearch: (q) => { return this._httpClient .get(a.FieldValueDataSource + '?q=' + q) .pipe( map((x) => { return x.data; }), ) .toPromise(); // this._httpClient.get(a.FieldValueDataSource).pipe( // map((x) => { // return x.data.map((y) => { // return { value: y[Schame.IotSharp.key], label: y[Schame.IotSharp.value] }; // }); // }), // ); }, } as SFSelectWidgetSchema, }; } else { properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue, ui: { widget: 'select', asyncData: () => this._httpClient.get(a.FieldValueDataSource).pipe( map((x) => { return x.data; }), ), // this._httpClient.get(a.FieldValueDataSource).pipe( // map((x) => { // return x.data.map((y) => { // return { value: y[Schame.IotSharp.key], label: y[Schame.IotSharp.value] }; // }); // }), // ), } as SFSelectWidgetSchema, }; } break; case 13: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue ? JSON.parse(a.FieldValue) : '', ui: { widget: 'cascader', titles: ['未拥有', '已拥有'], asyncData: (node, index) => { return this._httpClient .get(a.FieldValueDataSource) .toPromise() .then((res) => { node.children = res; }); }, } as unknown as SFTransferWidgetSchema, }; break; case 14: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue ? JSON.parse(a.FieldValue) : '', ui: { widget: 'tree-select', checkable: true, asyncData: () => this._httpClient.get(a.FieldValueDataSource).pipe( map((x) => { return x; }), ), //暂时取消异步支持,值可以绑定,但显示 // expandChange: (e) => { // if (e.eventName === 'expand') { // return this._httpClient.get<SFSchemaEnumType>(a.FieldValueDataSource + '?id=' + e.node.key).pipe( // map((x) => { // return { title: x[Schame.IotSharp.value], value: x[Schame.IotSharp.key] }; // }), // ); // } // return of([]); // } , } as SFTreeSelectWidgetSchema, }; break; case 15: properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue ? JSON.parse(a.FieldValue) : '', ui: { widget: 'transfer', asyncData: () => this._httpClient.get(a.FieldValueDataSource).pipe( map((x) => { return x.data; }), ), // this._httpClient.get(a.FieldValueDataSource).pipe( // map((x) => { // return x.data.map((y) => { // return { value: y[Schame.IotSharp.key], title: y[Schame.IotSharp.value] }; // }); // }), // ), } as SFTransferWidgetSchema, }; break; case 16: if (a.FieldValue && a.FieldValue !== '[]') { let filelist = JSON.parse(JSON.parse(a.FieldValue)); if (filelist.length > 0) { let _filelist = filelist.map((x) => { return { name: x.fileName, url: x.url }; }); properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue, ui: { widget: 'upload', action: Schame.ui.action ? Schame.ui.action : 'api/common/attachment/upLoaderFile', format: Schame.ui.format, text: Schame.ui.text, fileSize: Schame.ui.fileSize, multiple: Schame.ui.multiple, fileType: Schame.ui.fileType, fileList: _filelist, } as SFUploadWidgetSchema, }; } } else { properties[a.FieldCode] = { type: a.FieldValueTypeName, title: a.FieldName, default: a.FieldValue, ui: { widget: 'upload', action: Schame.ui.action ? Schame.ui.action : 'api/common/attachment/upLoaderFile', format: Schame.ui.format, text: Schame.ui.text, fileSize: Schame.ui.fileSize, multiple: Schame.ui.multiple, fileType: Schame.ui.fileType, } as SFUploadWidgetSchema, }; } break; case 17: if (!Schame.ui) { Schame.ui = { autosize: {}, }; } properties[a.FieldCode] = { type: 'string', title: a.FieldName, maxLength: Schame.maxLength, default: a.FieldValue, ui: { borderless: Schame.ui?.borderless ?? false, placeholder: Schame.ui?.placeholder, widget: 'textarea', autosize: { minRows: Schame.ui?.autosize.minRows ?? 2, maxRows: Schame.ui?.autosize.maxRows ?? 4, }, }, }; console.log(properties[a.FieldCode]); break; case 18: properties[a.FieldCode] = { type: 'string', title: a.FieldName, default: a.FieldValue, ui: { widget: 'ueditor', }, }; break; case 19: //Schame.IotSharp.key properties[a.FieldCode] = { type: 'number', title: a.FieldName, maximum: Schame.maximum, multipleOf: Schame.multipleOf, default: a.FieldValue, ui: { widget: 'rate', }, }; break; } } this.schema.properties = properties; this.sf.refreshSchema(); this.cd.detectChanges(); }, (y) => {}, () => {}, ); } ngOnInit(): void {} schema: SFSchema = { properties: {}, }; submit(value: any) { this.onsubmit.emit(value); return; this._httpClient.post('api/dynamicforminfo/saveparams', { form: value, id: this.id }).subscribe( (x) => {}, (y) => {}, () => {}, ); } // this.AllSuportType.filter(c=>c.value===) // this.http.get('api/common/dictionaryservice/gettargettype?id=' + type + '&format=' + format).subscribe( // (x) => { // this.AllSuportType = x.data; // }, // (y) => {}, // () => {}, // ); }
the_stack
import { DebugSession, InitializedEvent, Thread, Scope, Source, OutputEvent, TerminatedEvent, StoppedEvent, Breakpoint, BreakpointEvent, StackFrame, } from "vscode-debugadapter"; import { DebugProtocol } from "vscode-debugprotocol/lib/debugProtocol"; import { window, Uri, WorkspaceFolder } from "vscode"; import * as fs from "fs-extra"; import * as path from "path"; import { Subject } from "await-notify"; import { GrammarDebugger, GrammarBreakPoint } from "../backend/GrammarDebugger"; import { AntlrParseTreeProvider } from "./ParseTreeProvider"; import { AntlrFacade, ParseTreeNode, ParseTreeNodeType } from "../backend/facade"; import { Token, CommonToken } from "antlr4ts"; /** * Interface that reflects the arguments as specified in package.json. */ export interface LaunchRequestArguments extends DebugProtocol.LaunchRequestArguments { input: string; startRule: string; grammar: string; actionFile: string; stopOnEntry?: boolean; trace?: boolean; printParseTree?: boolean; visualParseTree?: boolean; } export interface DebuggerConsumer { debugger: GrammarDebugger; refresh(): void; // A full reload, e.g. after a grammar change. debuggerStopped(uri: Uri): void; // Called after each stop of the debugger (step, pause, breakpoint). } enum VarRef { Globals = 1000, ParseTree = 1002, Context = 2000, Tokens = 3000, SingleToken = 10000, } export class AntlrDebugSession extends DebugSession { private static THREAD_ID = 1; private debugger: GrammarDebugger | undefined; private parseTreeProvider: AntlrParseTreeProvider; private configurationDone = new Subject(); private showTextualParseTree = false; private showGraphicalParseTree = false; private testInput = ""; // Some variables, which are updated between each scope/var request. private tokens: Token[]; private variables: Array<[string, string]>; /** * Creates a new debug adapter that is used for one debug session. * We configure the default implementation of a debug adapter here. * * @param folder The current workspace folder for resolving file paths. * @param backend Our extension backend. * @param consumers A list of consumers that need a notification on certain events during debug. */ public constructor( private folder: WorkspaceFolder | undefined, private backend: AntlrFacade, private consumers: DebuggerConsumer[]) { super(); this.setDebuggerLinesStartAt1(true); this.setDebuggerColumnsStartAt1(false); this.parseTreeProvider = consumers[0] as AntlrParseTreeProvider; } public shutdown(): void { // Nothing to do for now. } protected initializeRequest(response: DebugProtocol.InitializeResponse, args: DebugProtocol.InitializeRequestArguments): void { response.body = response.body || {}; response.body.supportsConfigurationDoneRequest = true; response.body.supportsStepInTargetsRequest = true; this.sendResponse(response); } protected configurationDoneRequest(response: DebugProtocol.ConfigurationDoneResponse, args: DebugProtocol.ConfigurationDoneArguments): void { super.configurationDoneRequest(response, args); this.configurationDone.notify(); } protected launchRequest(response: DebugProtocol.LaunchResponse, args: LaunchRequestArguments): void { if (!args.input) { this.sendErrorResponse(response, { id: 1, format: "Could not launch debug session: no test input file specified", }); return; } if (!path.isAbsolute(args.input) && this.folder) { args.input = path.join(this.folder.uri.fsPath, args.input); } if (!fs.existsSync(args.input)) { this.sendErrorResponse(response, { id: 1, format: "Could not launch debug session: test input file not found.", }); return; } if (args.actionFile) { if (!path.isAbsolute(args.actionFile) && this.folder) { args.actionFile = path.join(this.folder.uri.fsPath, args.actionFile); } if (!fs.existsSync(args.actionFile)) { void window.showInformationMessage( "Cannot find file for semantic predicate evaluation. No evaluation will take place.", ); } } if (!args.grammar) { this.sendErrorResponse(response, { id: 1, format: "Could not launch debug session: no grammar file specified (use the ${file} macro for the " + "current editor).", }); return; } if (path.extname(args.grammar) !== ".g4") { this.sendErrorResponse(response, { id: 1, format: "Could not launch debug session: " + args.grammar + " is not a grammar file", }); return; } if (!path.isAbsolute(args.grammar) && this.folder) { args.grammar = path.join(this.folder.uri.fsPath, args.grammar); } if (!fs.existsSync(args.grammar)) { this.sendErrorResponse(response, { id: 1, format: "Could not launch debug session: cannot find grammar file.", }); return; } if (this.backend.hasErrors(args.grammar)) { this.sendErrorResponse(response, { id: 1, format: "Could not launch debug session: the grammar contains issues.", }); return; } try { this.setup(args.grammar, args.actionFile); for (const consumer of this.consumers) { consumer.debugger = this.debugger!; consumer.refresh(); } this.sendEvent(new InitializedEvent()); // Now we can accept breakpoints. } catch (e) { this.sendErrorResponse(response, { id: 1, format: "Could not prepare debug session:\n\n" + e }); return; } // Need to wait here for the configuration to be done, which happens after break points are set. // This in turn is triggered by sending the InitializedEvent above. this.configurationDone.wait(1000).then(() => { this.showTextualParseTree = args.printParseTree || false; this.showGraphicalParseTree = args.visualParseTree || false; this.testInput = args.input; try { const testInput = fs.readFileSync(args.input, { encoding: "utf8" }); const startRuleIndex = args.startRule ? this.debugger!.ruleIndexFromName(args.startRule) : 0; if (startRuleIndex < 0) { this.sendErrorResponse(response, { id: 2, format: "Error while launching debug session: start rule \"" + args.startRule + "\" not found", }); return; } this.debugger!.start(startRuleIndex, testInput, args.noDebug ? true : false); if (this.showGraphicalParseTree) { this.parseTreeProvider.showWebview(Uri.file(args.grammar), { title: "Parse Tree: " + path.basename(args.grammar) }); } } catch (e) { this.sendErrorResponse(response, { id: 3, format: "Could not launch debug session:\n\n" + e }); return; } this.sendResponse(response); }); } protected setBreakPointsRequest(response: DebugProtocol.SetBreakpointsResponse, args: DebugProtocol.SetBreakpointsArguments): void { this.debugger!.clearBreakPoints(); if (args.breakpoints && args.source.path) { const actualBreakpoints = args.breakpoints.map((sourceBreakPoint) => { const { validated, line, id } = this.debugger!.addBreakPoint(args.source.path!, this.convertDebuggerLineToClient(sourceBreakPoint.line)); const targetBreakPoint = <DebugProtocol.Breakpoint>new Breakpoint(validated, this.convertClientLineToDebugger(line)); targetBreakPoint.id = id; return targetBreakPoint; }); response.body = { breakpoints: actualBreakpoints, }; } this.sendResponse(response); } protected threadsRequest(response: DebugProtocol.ThreadsResponse): void { // We have no threads, so return a dummy entry. response.body = { threads: [ new Thread(AntlrDebugSession.THREAD_ID, "Interpreter"), ], }; this.sendResponse(response); } protected stackTraceRequest(response: DebugProtocol.StackTraceResponse, args: DebugProtocol.StackTraceArguments): void { const startFrame = typeof args.startFrame === "number" ? args.startFrame : 0; const maxLevels = typeof args.levels === "number" ? args.levels : 1000; const stack = this.debugger!.currentStackTrace; const frames: StackFrame[] = []; for (let i = startFrame; i < stack.length; ++i) { const entry = stack[i]; let frame: StackFrame; if (entry.next[0]) { frame = new StackFrame(i, entry.name, this.createSource(entry.source), this.convertDebuggerLineToClient(entry.next[0].start.row), this.convertDebuggerColumnToClient(entry.next[0].start.column), ); } else { frame = new StackFrame(i, entry.name + " <missing next>", this.createSource(entry.source), this.convertDebuggerLineToClient(1), this.convertDebuggerColumnToClient(0), ); } frames.push(frame); if (frames.length > maxLevels) { break; } } response.body = { stackFrames: frames, totalFrames: stack.length, }; this.sendResponse(response); } protected scopesRequest(response: DebugProtocol.ScopesResponse, args: DebugProtocol.ScopesArguments): void { // Cache a few values that stay the same during a single request for scopes and variables. this.tokens = this.debugger!.tokenList; this.variables = this.debugger!.getVariables(args.frameId); const scopes: Scope[] = []; scopes.push(new Scope("Globals", VarRef.Globals, true)); //scopes.push(new Scope(this.debugger.getStackInfo(args.frameId), VarRef.Context, false)); response.body = { scopes, }; this.sendResponse(response); } protected variablesRequest(response: DebugProtocol.VariablesResponse, args: DebugProtocol.VariablesArguments): void { const variables: DebugProtocol.Variable[] = []; switch (args.variablesReference) { case VarRef.Globals: { variables.push({ name: "Test Input", type: "string", value: this.testInput, variablesReference: 0, }); variables.push({ name: "Input Size", type: "number", value: this.debugger!.inputSize.toString(), variablesReference: 0, }); variables.push({ name: "Error Count", type: "number", value: this.debugger!.errorCount.toString(), variablesReference: 0, }); variables.push({ name: "Input Tokens", value: (this.tokens.length - this.debugger!.currentTokenIndex).toString(), variablesReference: VarRef.Tokens, indexedVariables: this.tokens.length - this.debugger!.currentTokenIndex, }); break; } case VarRef.Context: { // Context related break; } case VarRef.Tokens: { const start = this.debugger!.currentTokenIndex + (args.start ? args.start : 0); const length = args.count ? args.count : this.tokens.length; for (let i = 0; i < length; ++i) { const index = start + i; variables.push({ name: index + ": " + this.debugger!.tokenTypeName(this.tokens[index] as CommonToken), type: "Token", value: "", variablesReference: VarRef.Tokens + index, presentationHint: { kind: "class", attributes: ["readonly"] }, }); } break; } default: { if (args.variablesReference >= VarRef.Tokens) { const tokenIndex = args.variablesReference % VarRef.Tokens; if (tokenIndex >= 0 && tokenIndex < this.tokens.length) { const token = this.tokens[tokenIndex]; variables.push({ name: "text", type: "string", value: token.text ? token.text : "", variablesReference: 0, }); variables.push({ name: "type", type: "number", value: token.type + "", variablesReference: 0, }); variables.push({ name: "line", type: "number", value: token.line + "", variablesReference: 0, }); variables.push({ name: "offset", type: "number", value: token.charPositionInLine + "", variablesReference: 0, }); variables.push({ name: "channel", type: "number", value: token.channel + "", variablesReference: 0, }); variables.push({ name: "tokenIndex", type: "number", value: token.tokenIndex + "", variablesReference: 0, }); variables.push({ name: "startIndex", type: "number", value: token.startIndex + "", variablesReference: 0, }); variables.push({ name: "stopIndex", type: "number", value: token.stopIndex + "", variablesReference: 0, }); } } break; } } response.body = { variables, }; this.sendResponse(response); } protected pauseRequest(response: DebugProtocol.PauseResponse, args: DebugProtocol.PauseArguments): void { this.debugger!.pause(); this.sendResponse(response); } protected continueRequest(response: DebugProtocol.ContinueResponse, args: DebugProtocol.ContinueArguments): void { this.debugger!.continue(); this.sendResponse(response); } protected nextRequest(response: DebugProtocol.NextResponse, args: DebugProtocol.NextArguments): void { this.debugger!.stepOver(); this.sendResponse(response); } protected stepInRequest(response: DebugProtocol.StepInResponse, args: DebugProtocol.StepInArguments): void { this.debugger!.stepIn(); this.sendResponse(response); } protected stepOutRequest(response: DebugProtocol.StepOutResponse, args: DebugProtocol.StepOutArguments): void { this.debugger!.stepOut(); this.sendResponse(response); } protected evaluateRequest(response: DebugProtocol.EvaluateResponse, args: DebugProtocol.EvaluateArguments): void { response.body = { result: "evaluation not supported", variablesReference: 0, }; this.sendResponse(response); } private setup(grammar: string, actionFile: string) { const basePath = path.dirname(grammar); this.debugger = this.backend.createDebugger(grammar, actionFile, path.join(basePath, ".antlr")); if (!this.debugger) { throw Error("Debugger creation failed. There are grammar errors."); } if (!this.debugger.isValid) { throw Error("Debugger creation failed. You are either trying to debug an unsupported file type or " + "no interpreter data has been generated yet for the given grammar."); } this.debugger.on("stopOnStep", () => { this.notifyConsumers(Uri.file(grammar)); this.sendEvent(new StoppedEvent("step", AntlrDebugSession.THREAD_ID)); }); this.debugger.on("stopOnPause", () => { this.notifyConsumers(Uri.file(grammar)); this.sendEvent(new StoppedEvent("pause", AntlrDebugSession.THREAD_ID)); }); this.debugger.on("stopOnBreakpoint", () => { this.notifyConsumers(Uri.file(grammar)); this.sendEvent(new StoppedEvent("breakpoint", AntlrDebugSession.THREAD_ID)); }); this.debugger.on("stopOnException", () => { this.notifyConsumers(Uri.file(grammar)); this.sendEvent(new StoppedEvent("exception", AntlrDebugSession.THREAD_ID)); }); this.debugger.on("breakpointValidated", (bp: GrammarBreakPoint) => { const breakpoint: DebugProtocol.Breakpoint = { verified: bp.validated, id: bp.id, }; this.sendEvent(new BreakpointEvent("changed", breakpoint)); }); this.debugger.on("output", (...args: any[]) => { const isError: boolean = args[4]; const column: number = args[3]; const line: number = args[2]; const filePath: string = args[1]; const text: string = args[0]; const e: DebugProtocol.OutputEvent = new OutputEvent(`${text}\n`); e.body.source = filePath ? this.createSource(filePath) : undefined; e.body.line = line; e.body.column = column; e.body.category = isError ? "stderr" : "stdout"; this.sendEvent(e); }); this.debugger.on("end", () => { this.notifyConsumers(Uri.file(grammar)); if (this.showTextualParseTree) { let text = ""; if (!this.tokens) { this.tokens = this.debugger!.tokenList; } for (const token of this.tokens) { text += token.toString() + "\n"; } this.sendEvent(new OutputEvent("Tokens:\n" + text + "\n")); const tree = this.debugger!.currentParseTree; if (tree) { const treeText = this.parseNodeToString(tree); this.sendEvent(new OutputEvent("Parse Tree:\n" + treeText + "\n")); } else { this.sendEvent(new OutputEvent("No Parse Tree\n")); } } if (this.showGraphicalParseTree) { this.parseTreeProvider.showWebview(Uri.file(grammar), { title: "Parse Tree: " + path.basename(grammar), }); } this.sendEvent(new TerminatedEvent()); }); } //---- helpers private createSource(filePath: string): Source { return new Source(path.basename(filePath), this.convertDebuggerPathToClient(filePath), undefined, undefined, "antlr-data"); } private parseNodeToString(node: ParseTreeNode, level = 0): string { let result = " ".repeat(level); switch (node.type) { case ParseTreeNodeType.Rule: { const name = this.debugger!.ruleNameFromIndex(node.ruleIndex!); result += name ? name : "<unknown rule>"; if (node.children.length > 0) { result += " (\n"; for (const child of node.children) { result += this.parseNodeToString(child, level + 1); } result += " ".repeat(level) + ")\n"; } break; } case ParseTreeNodeType.Error: { result += " <Error>"; if (node.symbol) { result += "\"" + node.symbol.text + "\"\n"; } break; } case ParseTreeNodeType.Terminal: { result += "\"" + node.symbol!.text + "\"\n"; break; } default: break; } return result; } private notifyConsumers(uri: Uri) { for (const consumer of this.consumers) { consumer.debuggerStopped(uri); } } private escapeText(input: string): string { let result = ""; for (const c of input) { switch (c) { case "\n": { result += "\\n"; break; } case "\r": { result += "\\r"; break; } case "\t": { result += "\\t"; break; } default: { result += c; break; } } } return result; } }
the_stack
import tape from 'tape' import { Account, Address, BN, MAX_INTEGER } from 'ethereumjs-util' import { Block } from '@ethereumjs/block' import Common, { Chain, Hardfork } from '@ethereumjs/common' import { Transaction, TransactionFactory, FeeMarketEIP1559Transaction } from '@ethereumjs/tx' import VM from '../../src' import { createAccount, getTransaction } from './utils' const TRANSACTION_TYPES = [ { type: 0, name: 'legacy tx', }, { type: 1, name: 'EIP2930 tx', }, { type: 2, name: 'EIP1559 tx', }, ] const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London }) common.setMaxListeners(100) tape('runTx() -> successful API parameter usage', async (t) => { async function simpleRun(vm: VM, msg: string, st: tape.Test) { for (const txType of TRANSACTION_TYPES) { const tx = getTransaction(vm._common, txType.type, true) const caller = tx.getSenderAddress() const acc = createAccount() await vm.stateManager.putAccount(caller, acc) const res = await vm.runTx({ tx }) st.true(res.gasUsed.gt(new BN(0)), `${msg} (${txType.name})`) } } t.test('simple run (unmodified options)', async (st) => { let common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.London }) let vm = new VM({ common }) await simpleRun(vm, 'mainnet (PoW), london HF, default SM - should run without errors', st) common = new Common({ chain: Chain.Rinkeby, hardfork: Hardfork.London }) vm = new VM({ common }) await simpleRun(vm, 'rinkeby (PoA), london HF, default SM - should run without errors', st) st.end() }) t.test('should use passed in blockGasUsed to generate tx receipt', async (t) => { const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Istanbul }) const vm = new VM({ common }) const tx = getTransaction(vm._common, 0, true) const caller = tx.getSenderAddress() const acc = createAccount() await vm.stateManager.putAccount(caller, acc) const blockGasUsed = new BN(1000) const res = await vm.runTx({ tx, blockGasUsed }) t.ok( new BN(res.receipt.gasUsed).eq(blockGasUsed.add(res.gasUsed)), 'receipt.gasUsed should equal block gas used + tx gas used' ) t.end() }) t.test('Legacy Transaction with HF set to pre-Berlin', async (t) => { const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Istanbul }) const vm = new VM({ common }) const tx = getTransaction(vm._common, 0, true) const caller = tx.getSenderAddress() const acc = createAccount() await vm.stateManager.putAccount(caller, acc) const res = await vm.runTx({ tx }) t.true( res.gasUsed.gt(new BN(0)), `mainnet (PoW), istanbul HF, default SM - should run without errors (${TRANSACTION_TYPES[0].name})` ) t.end() }) t.test( 'custom block (block option), disabled block gas limit validation (skipBlockGasLimitValidation: true)', async (t) => { for (const txType of TRANSACTION_TYPES) { const vm = new VM({ common }) const privateKey = Buffer.from( 'e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex' ) const address = Address.fromPrivateKey(privateKey) const initialBalance = new BN(10).pow(new BN(18)) const account = await vm.stateManager.getAccount(address) await vm.stateManager.putAccount( address, Account.fromAccountData({ ...account, balance: initialBalance }) ) const transferCost = 21000 const unsignedTx = TransactionFactory.fromTxData( { to: address, gasLimit: transferCost, gasPrice: 100, nonce: 0, type: txType.type, maxPriorityFeePerGas: 50, maxFeePerGas: 50, }, { common } ) const tx = unsignedTx.sign(privateKey) const coinbase = Buffer.from('00000000000000000000000000000000000000ff', 'hex') const block = Block.fromBlockData( { header: { gasLimit: transferCost - 1, coinbase, baseFeePerGas: 7, }, }, { common } ) const result = await vm.runTx({ tx, block, skipBlockGasLimitValidation: true, }) const coinbaseAccount = await vm.stateManager.getAccount(new Address(coinbase)) // calculate expected coinbase balance const baseFee = block.header.baseFeePerGas! const inclusionFeePerGas = tx instanceof FeeMarketEIP1559Transaction ? BN.min(tx.maxPriorityFeePerGas, tx.maxFeePerGas.sub(baseFee)) : tx.gasPrice.sub(baseFee) const expectedCoinbaseBalance = common.isActivatedEIP(1559) ? result.gasUsed.mul(inclusionFeePerGas) : result.amountSpent t.ok( coinbaseAccount.balance.eq(expectedCoinbaseBalance), `should use custom block (${txType.name})` ) t.equals( result.execResult.exceptionError, undefined, `should run ${txType.name} without errors` ) } t.end() } ) }) tape('runTx() -> API parameter usage/data errors', (t) => { t.test('Typed Transaction with HF set to pre-Berlin', async (t) => { const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Istanbul }) const vm = new VM({ common }) const tx = getTransaction( new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Berlin }), 1, true ) const caller = tx.getSenderAddress() const acc = createAccount() await vm.stateManager.putAccount(caller, acc) try { await vm.runTx({ tx }) // TODO uncomment: // t.fail('should throw error') } catch (e: any) { t.ok( e.message.includes('(EIP-2718) not activated'), `should fail for ${TRANSACTION_TYPES[1].name}` ) } t.end() }) t.test('simple run (reportAccessList option)', async (t) => { const vm = new VM({ common }) const tx = getTransaction(vm._common, 0, true) const caller = tx.getSenderAddress() const acc = createAccount() await vm.stateManager.putAccount(caller, acc) const res = await vm.runTx({ tx, reportAccessList: true }) t.true( res.gasUsed.gt(new BN(0)), `mainnet (PoW), istanbul HF, default SM - should run without errors (${TRANSACTION_TYPES[0].name})` ) t.deepEqual(res.accessList, []) t.end() }) t.test('run without signature', async (t) => { for (const txType of TRANSACTION_TYPES) { const vm = new VM({ common }) const tx = getTransaction(vm._common, txType.type, false) try { await vm.runTx({ tx }) t.fail('should throw error') } catch (e: any) { t.ok(e.message.includes('not signed'), `should fail for ${txType.name}`) } } t.end() }) t.test('run with insufficient funds', async (t) => { for (const txType of TRANSACTION_TYPES) { const vm = new VM({ common }) const tx = getTransaction(vm._common, txType.type, true) try { await vm.runTx({ tx }) } catch (e: any) { t.ok(e.message.toLowerCase().includes('enough funds'), `should fail for ${txType.name}`) } } // EIP-1559 // Fail if signer.balance < gas_limit * max_fee_per_gas const vm = new VM({ common }) let tx = getTransaction(vm._common, 2, true) as FeeMarketEIP1559Transaction const address = tx.getSenderAddress() tx = Object.create(tx) const maxCost = tx.gasLimit.mul(tx.maxFeePerGas) await vm.stateManager.putAccount(address, createAccount(new BN(0), maxCost.subn(1))) try { await vm.runTx({ tx }) t.fail('should throw error') } catch (e: any) { t.ok(e.message.toLowerCase().includes('max cost'), `should fail if max cost exceeds balance`) } // set sufficient balance await vm.stateManager.putAccount(address, createAccount(new BN(0), maxCost)) const res = await vm.runTx({ tx }) t.ok(res, 'should pass if balance is sufficient') t.end() }) t.test('run with insufficient eip1559 funds', async (t) => { const vm = new VM({ common }) const tx = getTransaction(common, 2, true, '0x', false) const address = tx.getSenderAddress() const account = await vm.stateManager.getAccount(address) account.balance = new BN(9000000) // This is the maxFeePerGas multiplied with the gasLimit of 90000 await vm.stateManager.putAccount(address, account) await vm.runTx({ tx }) account.balance = new BN(9000000) await vm.stateManager.putAccount(address, account) const tx2 = getTransaction(common, 2, true, '0x64', false) // Send 100 wei; now balance < maxFeePerGas*gasLimit + callvalue try { await vm.runTx({ tx: tx2 }) t.fail('cannot reach this') } catch (e: any) { t.pass('succesfully threw on insufficient balance for transaction') } t.end() }) t.test('should throw on wrong nonces', async (t) => { const vm = new VM({ common }) const tx = getTransaction(common, 2, true, '0x', false) const address = tx.getSenderAddress() const account = await vm.stateManager.getAccount(address) account.balance = new BN(9000000) // This is the maxFeePerGas multiplied with the gasLimit of 90000 account.nonce = new BN(1) await vm.stateManager.putAccount(address, account) try { await vm.runTx({ tx }) t.fail('cannot reach this') } catch (e: any) { t.pass('succesfully threw on wrong nonces') } t.end() }) t.test("run with maxBaseFee less than block's baseFee", async (t) => { // EIP-1559 // Fail if transaction.maxFeePerGas < block.baseFeePerGas for (const txType of TRANSACTION_TYPES) { const vm = new VM({ common }) const tx = getTransaction(vm._common, txType.type, true) const block = Block.fromBlockData({ header: { baseFeePerGas: 100000 } }, { common }) try { await vm.runTx({ tx, block }) t.fail('should fail') } catch (e: any) { t.ok( e.message.includes("is less than the block's baseFeePerGas"), 'should fail with appropriate error' ) } } t.end() }) }) tape('runTx() -> runtime behavior', async (t) => { t.test('storage cache', async (t) => { for (const txType of TRANSACTION_TYPES) { const common = new Common({ chain: Chain.Mainnet, hardfork: Hardfork.Berlin }) const vm = new VM({ common }) const privateKey = Buffer.from( 'e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex' ) /* Code which is deployed here: PUSH1 01 PUSH1 00 SSTORE INVALID */ const code = Buffer.from('6001600055FE', 'hex') const address = new Address(Buffer.from('00000000000000000000000000000000000000ff', 'hex')) await vm.stateManager.putContractCode(address, code) await vm.stateManager.putContractStorage( address, Buffer.from('00'.repeat(32), 'hex'), Buffer.from('00'.repeat(31) + '01', 'hex') ) const txParams: any = { nonce: '0x00', gasPrice: 1, gasLimit: 100000, to: address, } if (txType.type === 1) { txParams['chainId'] = common.chainIdBN() txParams['accessList'] = [] txParams['type'] = txType.type } const tx = TransactionFactory.fromTxData(txParams, { common }).sign(privateKey) await vm.stateManager.putAccount(tx.getSenderAddress(), createAccount()) await vm.runTx({ tx }) // this tx will fail, but we have to ensure that the cache is cleared t.equal( (<any>vm.stateManager)._originalStorageCache.size, 0, `should clear storage cache after every ${txType.name}` ) } t.end() }) }) tape('runTx() -> runtime errors', async (t) => { t.test('account balance overflows (call)', async (t) => { for (const txType of TRANSACTION_TYPES) { const vm = new VM({ common }) const tx = getTransaction(vm._common, txType.type, true, '0x01') const caller = tx.getSenderAddress() const from = createAccount() await vm.stateManager.putAccount(caller, from) const to = createAccount(new BN(0), MAX_INTEGER) await vm.stateManager.putAccount(tx.to!, to) const res = await vm.runTx({ tx }) t.equal( res.execResult!.exceptionError!.error, 'value overflow', `result should have 'value overflow' error set (${txType.name})` ) t.equal( (<any>vm.stateManager)._checkpointCount, 0, `checkpoint count should be 0 (${txType.name})` ) } t.end() }) t.test('account balance overflows (create)', async (t) => { for (const txType of TRANSACTION_TYPES) { const vm = new VM({ common }) const tx = getTransaction(vm._common, txType.type, true, '0x01', true) const caller = tx.getSenderAddress() const from = createAccount() await vm.stateManager.putAccount(caller, from) const contractAddress = new Address( Buffer.from('61de9dc6f6cff1df2809480882cfd3c2364b28f7', 'hex') ) const to = createAccount(new BN(0), MAX_INTEGER) await vm.stateManager.putAccount(contractAddress, to) const res = await vm.runTx({ tx }) t.equal( res.execResult!.exceptionError!.error, 'value overflow', `result should have 'value overflow' error set (${txType.name})` ) t.equal( (<any>vm.stateManager)._checkpointCount, 0, `checkpoint count should be 0 (${txType.name})` ) } t.end() }) }) // TODO: complete on result values and add more usage scenario test cases tape('runTx() -> API return values', async (t) => { t.test('simple run, common return values', async (t) => { for (const txType of TRANSACTION_TYPES) { const vm = new VM({ common }) const tx = getTransaction(vm._common, txType.type, true) const caller = tx.getSenderAddress() const acc = createAccount() await vm.stateManager.putAccount(caller, acc) const res = await vm.runTx({ tx }) t.true(res.execResult.gasUsed.eqn(0), `execution result -> gasUsed -> 0 (${txType.name})`) t.equal( res.execResult.exceptionError, undefined, `execution result -> exception error -> undefined (${txType.name})` ) t.deepEqual( res.execResult.returnValue, Buffer.from([]), `execution result -> return value -> empty Buffer (${txType.name})` ) t.true( res.execResult.gasRefund!.eqn(0), `execution result -> gasRefund -> 0 (${txType.name})` ) } t.end() }) t.test('simple run, runTx default return values', async (t) => { for (const txType of TRANSACTION_TYPES) { const vm = new VM({ common }) const tx = getTransaction(vm._common, txType.type, true) const caller = tx.getSenderAddress() const acc = createAccount() await vm.stateManager.putAccount(caller, acc) const res = await vm.runTx({ tx }) t.deepEqual( res.gasUsed, tx.getBaseFee(), `runTx result -> gasUsed -> tx.getBaseFee() (${txType.name})` ) if (tx instanceof FeeMarketEIP1559Transaction) { const baseFee = new BN(7) const inclusionFeePerGas = BN.min(tx.maxPriorityFeePerGas, tx.maxFeePerGas.sub(baseFee)) const gasPrice = inclusionFeePerGas.add(baseFee) t.deepEqual( res.amountSpent, res.gasUsed.mul(gasPrice), `runTx result -> amountSpent -> gasUsed * gasPrice (${txType.name})` ) } else { t.deepEqual( res.amountSpent, res.gasUsed.mul((<Transaction>tx).gasPrice), `runTx result -> amountSpent -> gasUsed * gasPrice (${txType.name})` ) } t.deepEqual( res.bloom.bitvector, Buffer.from('00'.repeat(256), 'hex'), `runTx result -> bloom.bitvector -> should be empty (${txType.name})` ) t.deepEqual( res.receipt.gasUsed, res.gasUsed.toArrayLike(Buffer), `runTx result -> receipt.gasUsed -> result.gasUsed as Buffer (${txType.name})` ) t.deepEqual( res.receipt.bitvector, res.bloom.bitvector, `runTx result -> receipt.bitvector -> result.bloom.bitvector (${txType.name})` ) t.deepEqual( res.receipt.logs, [], `runTx result -> receipt.logs -> empty array (${txType.name})` ) } t.end() }) })
the_stack
import type { ReactiveController, ReactiveControllerHost } from 'lit'; import type { ComponentDocument, Data, FetchMoreParams, MaybeTDN, MaybeVariables, Variables, } from '@apollo-elements/core/types'; import type { ApolloError, ApolloQueryResult, DocumentNode, ObservableQuery, QueryOptions, SubscribeToMoreOptions, SubscriptionOptions, WatchQueryOptions, } from '@apollo/client/core'; import { NetworkStatus } from '@apollo/client/core'; import { ApolloController, ApolloControllerOptions } from './apollo-controller.js'; import { bound } from './lib/bound.js'; export interface ApolloQueryControllerOptions<D, V> extends ApolloControllerOptions<D, V>, Partial<WatchQueryOptions<Variables<D, V>, Data<D>>> { variables?: Variables<D, V>; noAutoSubscribe?: boolean; shouldSubscribe?: (options?: Partial<SubscriptionOptions<Variables<D, V>, Data<D>>>) => boolean; onData?: (data: Data<D>) => void; onError?: (error: Error) => void; } export class ApolloQueryController<D extends MaybeTDN = MaybeTDN, V = MaybeVariables<D>> extends ApolloController<D, V> implements ReactiveController { private observableQuery?: ObservableQuery<Data<D>, Variables<D, V>>; private pollingInterval?: number; /** @summary Options to customize the query and to interface with the controller. */ declare options: ApolloQueryControllerOptions<D, V>; /** * `networkStatus` is useful if you want to display a different loading indicator (or no indicator at all) * depending on your network status as it provides a more detailed view into the state of a network request * on your component than `loading` does. `networkStatus` is an enum with different number values between 1 and 8. * These number values each represent a different network state. * * 1. `loading`: The query has never been run before and the request is now pending. A query will still have this network status even if a result was returned from the cache, but a query was dispatched anyway. * 2. `setVariables`: If a query’s variables change and a network request was fired then the network status will be setVariables until the result of that query comes back. React users will see this when options.variables changes on their queries. * 3. `fetchMore`: Indicates that fetchMore was called on this query and that the network request created is currently in flight. * 4. `refetch`: It means that refetch was called on a query and the refetch request is currently in flight. * 5. Unused. * 6. `poll`: Indicates that a polling query is currently in flight. So for example if you are polling a query every 10 seconds then the network status will switch to poll every 10 seconds whenever a poll request has been sent but not resolved. * 7. `ready`: No request is in flight for this query, and no errors happened. Everything is OK. * 8. `error`: No request is in flight for this query, but one or more errors were detected. * * If the network status is less then 7 then it is equivalent to `loading` being true. In fact you could * replace all of your `loading` checks with `networkStatus < 7` and you would not see a difference. * It is recommended that you use `loading`, however. */ networkStatus = NetworkStatus.ready; /** * If data was read from the cache with missing fields, * partial will be true. Otherwise, partial will be falsy. * * @summary True when the query returned partial data. */ partial = false; #hasDisconnected = false; #lastQueryDocument?: DocumentNode; /** @summary A GraphQL document containing a single query. */ get query(): ComponentDocument<D> | null { return this.document; } set query(document: ComponentDocument<D> | null) { this.document = document; } /** @summary Flags an element that's ready and able to auto-subscribe */ public get canAutoSubscribe(): boolean { return ( !!this.client && !!this.document && !this.options.noAutoSubscribe && this.shouldSubscribe() ); } constructor( host: ReactiveControllerHost, query?: ComponentDocument<D> | null, options?: ApolloQueryControllerOptions<D, V> ) { super(host, options); this.init(query ?? null);/* c8 ignore next */ } /** @summary initializes or reinitializes the query */ override hostConnected(): void { super.hostConnected(); if (this.#hasDisconnected && this.observableQuery) { /* c8 ignore next */ this.observableQuery.reobserve(); this.#hasDisconnected = false; } else this.documentChanged(this.query); } override hostDisconnected(): void { this.#hasDisconnected = true; super.hostDisconnected(); } private shouldSubscribe(opts?: Partial<SubscriptionOptions<Variables<D, V>, Data<D>>>): boolean { return this.options.shouldSubscribe?.(opts) ?? true;/* c8 ignore next */ } /** * Determines whether the element is able to automatically subscribe */ private canSubscribe( options?: Partial<SubscriptionOptions<Variables<D, V> | null, Data<D>>> ): boolean { /* c8 ignore next 4 */ return ( !(this.options.noAutoSubscribe ?? false) && !!this.client && !!(options?.query ?? this.document) ); } /** * Creates an instance of ObservableQuery with the options provided by the element. * - `context` Context to be passed to link execution chain * - `errorPolicy` Specifies the ErrorPolicy to be used for this query * - `fetchPolicy` Specifies the FetchPolicy to be used for this query * - `fetchResults` Whether or not to fetch results * - `metadata` Arbitrary metadata stored in the store with this query. Designed for debugging, developer tools, etc. * - `notifyOnNetworkStatusChange` Whether or not updates to the network status should trigger next on the observer of this query * - `pollInterval` The time interval (in milliseconds) on which this query should be refetched from the server. * - `query` A GraphQL document that consists of a single query to be sent down to the server. * - `variables` A map going from variable name to variable value, where the variables are used within the GraphQL query. */ @bound private watchQuery( params?: Partial<WatchQueryOptions<Variables<D, V>, Data<D>>> ): ObservableQuery<Data<D>, Variables<D, V>> { if (!this.client) throw new TypeError('No Apollo client. See https://apolloelements.dev/guides/getting-started/apollo-client/'); /* c8 ignore next */ // covered return this.client.watchQuery({ // It's better to let Apollo client throw this error // eslint-disable-next-line @typescript-eslint/no-non-null-assertion query: this.query!, variables: this.variables ?? undefined, context: this.options.context, errorPolicy: this.options.errorPolicy, fetchPolicy: this.options.fetchPolicy, notifyOnNetworkStatusChange: this.options.notifyOnNetworkStatusChange, partialRefetch: this.options.partialRefetch, pollInterval: this.options.pollInterval, returnPartialData: this.options.returnPartialData, nextFetchPolicy: this.options.nextFetchPolicy, ...params, }) as ObservableQuery<Data<D>, Variables<D, V>>; } private nextData(result: ApolloQueryResult<Data<D>>): void { this.emitter.dispatchEvent(new CustomEvent('apollo-query-result', { detail: result })); this.data = result.data; this.error = result.error ?? null;/* c8 ignore next */ this.errors = result.errors ?? []; this.loading = result.loading ?? false;/* c8 ignore next */ this.networkStatus = result.networkStatus; this.partial = result.partial ?? false; this.options.onData?.(result.data);/* c8 ignore next */ this.notify('data', 'error', 'errors', 'loading', 'networkStatus', 'partial'); } private nextError(error: ApolloError): void { this.emitter.dispatchEvent(new CustomEvent('apollo-error', { detail: error })); this.error = error; this.loading = false; this.options.onError?.(error);/* c8 ignore next */ this.notify('error', 'loading'); } protected override clientChanged(): void { if (this.canSubscribe() && this.shouldSubscribe())/* c8 ignore next */ this.subscribe();/* c8 ignore next */ } protected override documentChanged(doc?: ComponentDocument<D> | null): void { const query = doc ?? undefined;/* c8 ignore next */ if (doc === this.#lastQueryDocument) return;/* c8 ignore next */ if (this.canSubscribe({ query }) && this.shouldSubscribe({ query }))/* c8 ignore next */ this.subscribe({ query }); /* c8 ignore next */ // covered } protected override variablesChanged(variables?: Variables<D, V>): void { if (this.observableQuery) this.refetch(variables);/* c8 ignore next */ else if (this.canSubscribe({ variables }) && this.shouldSubscribe({ variables }))/* c8 ignore next */ this.subscribe({ variables });/* c8 ignore next */ } protected override optionsChanged(options: ApolloQueryControllerOptions<D, V>): void { this.observableQuery?.setOptions?.(options); } /** * Exposes the [`ObservableQuery#refetch`](https://www.apollographql.com/docs/react/api/apollo-client.html#ObservableQuery.refetch) method. * * @param variables The new set of variables. If there are missing variables, the previous values of those variables will be used. */ @bound public async refetch(variables?: Variables<D, V>): Promise<ApolloQueryResult<Data<D>>> { if (!this.observableQuery) throw new Error('Cannot refetch without an ObservableQuery'); /* c8 ignore next */ // covered return this.observableQuery.refetch(variables as Variables<D, V>); } /** * Resets the observableQuery and subscribes. * @param params options for controlling how the subscription subscribes */ @bound public subscribe( params?: Partial<WatchQueryOptions<Variables<D, V>, Data<D>>> ): ZenObservable.Subscription { if (this.observableQuery) this.observableQuery.stopPolling(); /* c8 ignore next */ // covered this.observableQuery = this.watchQuery({ // It's better to let Apollo client throw this error // eslint-disable-next-line @typescript-eslint/no-non-null-assertion query: this.query!, variables: this.variables ?? undefined, context: this.options.context, errorPolicy: this.options.errorPolicy, fetchPolicy: this.options.fetchPolicy, notifyOnNetworkStatusChange: this.options.notifyOnNetworkStatusChange, partialRefetch: this.options.partialRefetch, pollInterval: this.options.pollInterval, refetchWritePolicy: this.options.refetchWritePolicy, returnPartialData: this.options.returnPartialData, ...params, }); this.#lastQueryDocument = params?.query ?? this.query ?? undefined;/* c8 ignore next */ this.loading = true; this.notify('loading'); return this.observableQuery?.subscribe({ next: this.nextData.bind(this), error: this.nextError.bind(this), }); } /** * Lets you pass a GraphQL subscription and updateQuery function * to subscribe to more updates for your query. * * The `updateQuery` parameter is a function that takes the previous query data, * then a `{ subscriptionData: TSubscriptionResult }` object, * and returns an object with updated query data based on the new results. */ @bound public subscribeToMore<TSubscriptionVariables, TSubscriptionData>( options: SubscribeToMoreOptions<Data<D>, TSubscriptionVariables, TSubscriptionData> ): (() => void) | void { return this.observableQuery?.subscribeToMore(options); } /** * @summary Executes a Query once and updates the with the result */ @bound public async executeQuery( params?: Partial<QueryOptions<Variables<D, V>, Data<D>>> ): Promise<ApolloQueryResult<Data<D>>> { try { if (!this.client) throw new TypeError('No Apollo client. See https://apolloelements.dev/guides/getting-started/apollo-client/'); /* c8 ignore next */ // covered this.loading = true; this.notify('loading'); const result = await this.client.query<Data<D>, Variables<D, V>>({ // It's better to let Apollo client throw this error, if needs be // eslint-disable-next-line @typescript-eslint/no-non-null-assertion query: this.query!, variables: this.variables!, context: this.options.context, errorPolicy: this.options.errorPolicy, fetchPolicy: this.options.fetchPolicy === 'cache-and-network' ? undefined/* c8 ignore next */ : this.options.fetchPolicy, notifyOnNetworkStatusChange: this.options.notifyOnNetworkStatusChange, partialRefetch: this.options.partialRefetch, returnPartialData: this.options.returnPartialData, ...params, }); if (result) // NB: not sure why, but sometimes this returns undefined this.nextData(result); return result;/* c8 ignore next */ } catch (error) { this.nextError(error); throw error; } } /** * Exposes the `ObservableQuery#fetchMore` method. * https://www.apollographql.com/docs/react/api/core/ObservableQuery/#ObservableQuery.fetchMore * * The optional `updateQuery` parameter is a function that takes the previous query data, * then a `{ subscriptionData: TSubscriptionResult }` object, * and returns an object with updated query data based on the new results. * * The optional `variables` parameter is an optional new variables object. */ @bound public async fetchMore( params?: Partial<FetchMoreParams<D, V>> ): Promise<ApolloQueryResult<Data<D>>> { this.loading = true; this.notify('loading'); const options = { // It's better to let Apollo client throw this error // eslint-disable-next-line @typescript-eslint/no-non-null-assertion query: this.query!, context: this.options.context, variables: this.variables, ...params, }; return ( this.observableQuery ??= this.watchQuery( options as WatchQueryOptions<Variables<D, V>, Data<D>> ) ).fetchMore({ ...options, variables: (options.variables as Variables<D, V>) ?? undefined, /* c8 ignore next */ }).then(x => { this.loading = false; this.notify('loading'); return x; }); } /** * @summary Start polling this query * @param ms milliseconds to wait between fetches */ @bound public startPolling(ms: number): void { this.pollingInterval = window.setInterval(() => { this.refetch(); }, ms); } /** * @summary Stop polling this query */ @bound public stopPolling(): void { clearInterval(this.pollingInterval); } }
the_stack
export declare function jitsuClient(opts: JitsuOptions): JitsuClient export type JitsuClient = { /** * Sends a third-party event (event intercepted from third-party system, such as analytics.js or GA). Should * not be called directly * @param typeName event name of event * @param _3pData third-party payload. The structure depend on * @param type event-type * @return promise that is resolved after executed. * However, if beacon API is used (see TrackerOption.use_beacon) promise will be resolved immediately */ _send3p: (typeName: EventSrc, _3pPayload: any, type?: string) => Promise<void> /** * Sends a track event to server * @param name event name * @param payload event payload * @return Promise, see _send3p documentation */ track: (typeName: string, payload?: EventPayload) => Promise<void> // /** // * Similar to track(), but send unstructured payload to EventNative processing pipeline. No // * additional detection (user-agent, url and so on will be done). No payload structure is enforced // * @param payload // */ rawTrack: (payload: any) => void /** * Sets a user data * @param userData user data (as map id_type --> value, such as "email": "a@bcd.com" * @param doNotSendEvent if true (false by default), separate "id" event won't be sent to server * @return Promise, see _send3p documentation */ id: (userData: UserProps, doNotSendEvent?: boolean) => Promise<void> /** * Initializes tracker. Must be called * @param initialization options */ init: (opts: JitsuOptions) => void /** * Explicit call for intercepting Segment's analytics. * @param analytics window.analytics object */ interceptAnalytics: (analytics: any) => void /** * Sets a permanent properties that will be persisted across sessions. On every track() call those properties * will be merged with `payload` parameter * @param properties properties * @param opts options. * eventType - apply permanent properties to only certain event type (applied to all types by default) * persist - persist properties across sessions (in cookies). True by default */ set(properties: Record<string, any>, opts?: { eventType?: string, persist?: boolean }); /** * User */ unset(propertyName: string, opts: { eventType?: string, persist?: boolean }); } /** * Type of jitsu function which is exported to window.jitsu when tracker is embedded from server */ export type JitsuFunction = (action: 'track' | 'id' | 'set', eventType: string, payload?: EventPayload) => void; /** * User identification method: * - cookie (based on cookie) * - ls (localstorage) * Currently only 'cookie' is supported */ export type IdMethod = 'cookie' | 'ls' /** * Policy configuration affects cookies storage and IP handling. * - strict: Jitsu doesn't store cookies and replaces last octet in IP address (10.10.10.10 -> 10.10.10.1) * - keep: Jitsu uses cookies for user identification and saves full IP * - comply: Jitsu checks customer country and tries to comply with Regulation laws (such as GDPR, UK's GDPR (PECR) and California's GDPR (CCPA) */ export type Policy = 'strict' | 'keep' | 'comply' /** * Configuration options of Jitsu */ export type JitsuOptions = { /** * If Jitsu should work in compatibility mode. If set to true: * - event_type will be set to 'eventn' instead of 'jitsu' * - EventCtx should be written in eventn_ctx node as opposed to to event root */ compat_mode?: boolean /** * If beacon API (https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API) should be used instead of * XMLHttpRequest. * * Warning: beacon API might be unstable (https://volument.com/blog/sendbeacon-is-broken). Please, * do not use it unless absolutely necessary */ use_beacon_api?: boolean /** * Cookie domain that will be used to identify * users. If not set, location.hostname will be used */ cookie_domain?: string /** * Tracking host (where API calls will be sent). If not set, * we'd try to do the best to "guess" it. Last resort is t.jitsu.com. * * Though this parameter is not required, it's highly recommended to set is explicitly */ tracking_host?: string /** * Name of id cookie. __eventn_id by default */ cookie_name?: string /** * API key. It's highly recommended to explicitely set it. Otherwise, the code will work * in some cases (where server is configured with exactly one client key) */ key: string /** * If google analytics events should be intercepted. Read more about event interception * at https://docs.eventnative.org/sending-data/javascript-reference/events-interception * * @default false */ ga_hook?: boolean /** * If google analytics events should be intercepted. Read more about event interception * at https://docs.eventnative.org/sending-data/javascript-reference/events-interception * * @default false */ segment_hook?: boolean /** * If URL of API server call should be randomize to by-pass adblockers * * @default false */ randomize_url?: boolean /** * If Jitsu should capture third-party cookies: either array * of cookies name or false if the features should be disabled * * @default GA/Segment/Fb cookies: ['_ga': '_fbp', '_ym_uid', 'ajs_user_id', 'ajs_anonymous_id'] */ capture_3rd_party_cookies?: string[] | false; /** * See comment on IdMethod. Currently only 'cookie' and 'cookie-less' are supported */ id_method?: IdMethod /** * Privacy policy configuration makes all policies strict to comply with the cookies law. If set to 'strict' * ip_policy = 'strict' and cookie_policy = 'strict' will be set. * Currently only 'strict' is supported */ privacy_policy?: 'strict' /** * IP policy see Policy */ ip_policy?: Policy /** * Cookie policy see Policy */ cookie_policy?: Policy /** * Log level. 'WARN' if not set */ log_level?: 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'NONE'; //NOTE: If any property is added here, please make sure it's added to browser.ts jitsuProps as well }; /** * User properties (ids). */ export interface UserProps { anonymous_id?: string //anonymous is (cookie or ls based), id?: string //user id (non anonymous). If not set, first known id (from propName below) will be used email?: string //user id (non anonymous). If not set, first known id (from propName below) will be used [propName: string]: any //any other forms of ids } /** * Ids for third-party tracking systems */ export type ThirdpartyIds = { [id: string]: string } export type Conversion = { //The purpose of this set is mainly to minic GA's set of parameters //(see https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters) transaction_id?: string | number //id of transaction affiliation?: string | number //affiliation id revenue?: number //revenue shipping_cost?: number //shipping cost tax?: number //tax cost } /** * Event context. Data that is present in any event type. EventContext is assembled automatically */ export type EventCtx = { event_id: string //unique event id or empty string for generating id on the backend side user: UserProps //user properties ids?: ThirdpartyIds //user ids from external systems user_agent: string //user utc_time: string //current UTC time in ISO 8601 local_tz_offset: number //local timezone offset (in minutes) referer: string //document referer url: string //current url page_title: string //page title //see UTM_TYPES for all supported utm tags doc_path: string //document path doc_host: string //document host doc_search: string //document search string screen_resolution: string //screen resolution vp_size: string //viewport size user_language: string //user language doc_encoding: string utm: Record<string, string> //utm tags (without utm prefix, e.g key will be "source", not utm_source. See click_id: Record<string, string> //all external click ids (passed through URL). See CLICK_IDS for supported all supported click ids [propName: string]: any //context is extendable, any extra properties can be added here } /** * Optional data that can be added to each event. Consist from optional fields, */ export type EventPayload = { conversion?: Conversion //Conversion data if events indicates a conversion src_payload?: any, //Third-party payload if event is intercepted from third-party source [propName: string]: any //payload is extendable, any extra properties can be added here } export type Transport = (url: string, jsonPayload: string) => Promise<void> /** * Type of event source */ export type EventSrc = 'jitsu' | //event came directly from Jitsu 'eventn' | //same as jitsu but for 'compat' mode, see 'ga' | //event is intercepted from GA '3rdparty' | //event is intercepted from 3rdparty source 'ajs'; //event is intercepted from analytics.js /** * Basic information about the event */ export type EventBasics = { source_ip?: string //IP address. Do not set this field on a client side, it will be rewritten on the server anon_ip?: string //First 3 octets of an IP address. Same as IP - will be set on a server api_key: string //JS api key src: EventSrc //Event source event_type: string //event type } /** * Event object. A final object which is send to server */ export type Event = EventBasics & EventPayload & EventCtx; /** * Event object, if tracker works in compatibility mode */ export type EventCompat = EventBasics & { eventn_ctx: EventCtx } & EventPayload;
the_stack
import * as Models from "./Models" export interface AccountChangePasswordResponse { /** * New token */ token: string, /** * New secret */ secret: string } export interface AccountGetActiveOffersResponse { /** * Total number */ count: number, /** * */ items: Models.AccountOffer[] } export type AccountGetAppPermissionsResponse = number export interface AccountGetBannedResponse { /** * Total number */ count: number, /** * */ items: number[], /** * */ profiles: Models.UsersUserMin[], /** * */ groups: Models.GroupsGroup[] } export type AccountGetCountersResponse = Models.AccountAccountCounters export type AccountGetInfoResponse = Models.AccountInfo export type AccountGetProfileInfoResponse = Models.AccountUserSettings export type AccountGetPushSettingsResponse = Models.AccountPushSettings export interface AccountSaveProfileInfoResponse { /** * 1 if changes has been processed */ changed: Models.BaseBoolInt, /** * */ name_request: Models.AccountNameRequest } export type AdsAddOfficeUsersResponse = boolean export type AdsCheckLinkResponse = Models.AdsLinkStatus export type AdsCreateAdsResponse = number[] export type AdsCreateCampaignsResponse = number[] export type AdsCreateClientsResponse = number[] export interface AdsCreateTargetGroupResponse { /** * Group ID */ id: number, /** * Pixel code */ pixel: string } export type AdsDeleteAdsResponse = number[] export type AdsDeleteCampaignsResponse = number export type AdsDeleteClientsResponse = number export type AdsGetAccountsResponse = Models.AdsAccount[] export type AdsGetAdsLayoutResponse = Models.AdsAdLayout[] export type AdsGetAdsTargetingResponse = Models.AdsTargSettings[] export type AdsGetAdsResponse = Models.AdsAd[] export type AdsGetBudgetResponse = number export type AdsGetCampaignsResponse = Models.AdsCampaign[] export interface AdsGetCategoriesResponse { /** * Old categories */ v1: Models.AdsCategory[], /** * Actual categories */ v2: Models.AdsCategory[] } export type AdsGetClientsResponse = Models.AdsClient[] export type AdsGetDemographicsResponse = Models.AdsDemoStats[] export type AdsGetFloodStatsResponse = Models.AdsFloodStats export interface AdsGetLookalikeRequestsResponse { /** * Total count of found lookalike requests */ count: number, /** * found lookalike requests */ items: Models.AdsLookalikeRequest[] } export interface AdsGetMusiciansResponse { /** * Musicians */ items: Models.AdsMusician[] } export type AdsGetOfficeUsersResponse = Models.AdsUsers[] export type AdsGetPostsReachResponse = Models.AdsPromotedPostReach[] export type AdsGetRejectionReasonResponse = Models.AdsRejectReason export type AdsGetStatisticsResponse = Models.AdsStats[] export type AdsGetSuggestionsCitiesResponse = Models.AdsTargSuggestionsCities[] export type AdsGetSuggestionsRegionsResponse = Models.AdsTargSuggestionsRegions[] export type AdsGetSuggestionsResponse = Models.AdsTargSuggestions[] export type AdsGetSuggestionsSchoolsResponse = Models.AdsTargSuggestionsSchools[] export type AdsGetTargetGroupsResponse = Models.AdsTargetGroup[] export type AdsGetTargetingStatsResponse = Models.AdsTargStats export type AdsGetUploadURLResponse = string export type AdsGetVideoUploadURLResponse = string export type AdsImportTargetContactsResponse = number export type AdsRemoveOfficeUsersResponse = boolean export type AdsUpdateAdsResponse = number[] export type AdsUpdateCampaignsResponse = number export type AdsUpdateClientsResponse = number export type AdsUpdateOfficeUsersResponse = Models.AdsUpdateOfficeUsersResult[] export interface AdswebGetAdCategoriesResponse { /** * */ categories: Models.AdswebGetAdCategoriesResponseCategoriesCategory[] } export interface AdswebGetAdUnitCodeResponse { /** * */ html: string } export interface AdswebGetAdUnitsResponse { /** * */ count: number, /** * */ ad_units: Models.AdswebGetAdUnitsResponseAdUnitsAdUnit[] } export interface AdswebGetFraudHistoryResponse { /** * */ count: number, /** * */ entries: Models.AdswebGetFraudHistoryResponseEntriesEntry[] } export interface AdswebGetSitesResponse { /** * */ count: number, /** * */ sites: Models.AdswebGetSitesResponseSitesSite[] } export interface AdswebGetStatisticsResponse { /** * */ next_page_id: string, /** * */ items: Models.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 } export type AppWidgetsGetAppImagesResponse = Models.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 } export type AppWidgetsGetGroupImagesResponse = Models.AppWidgetsPhotos export type AppWidgetsGetImagesByIdResponse = Models.AppWidgetsPhoto[] export type AppWidgetsSaveAppImageResponse = Models.AppWidgetsPhoto export type AppWidgetsSaveGroupImageResponse = Models.AppWidgetsPhoto export interface AppsGetCatalogResponse { /** * Total number */ count: number, /** * */ items: Models.AppsApp[], /** * */ profiles: Models.UsersUserMin[] } export interface AppsGetFriendsListResponse { /** * Total number */ count: number, /** * */ items: Models.UsersUserFull[] } export interface AppsGetLeaderboardExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.AppsLeaderboard[], /** * */ profiles: Models.UsersUserMin[] } export interface AppsGetLeaderboardResponse { /** * Total number */ count: number, /** * */ items: Models.AppsLeaderboard[] } export interface AppsGetScopesResponse { /** * Total number */ count: number, /** * */ items: Models.AppsScope[] } export type AppsGetScoreResponse = number export interface AppsGetResponse { /** * Total number of applications */ count: number, /** * List of applications */ items: Models.AppsApp[] } export type AppsSendRequestResponse = number export interface AuthRestoreResponse { /** * 1 if success */ success: number, /** * Parameter needed to grant access by code */ sid: string } export type BaseBoolResponse = Models.BaseBoolInt export type BaseGetUploadServerResponse = Models.BaseUploadServer export type BaseOkResponse = number export type BoardAddTopicResponse = number export type BoardCreateCommentResponse = number export interface BoardGetCommentsExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.BoardTopicComment[], /** * */ poll: Models.BoardTopicPoll, /** * */ profiles: Models.UsersUser[], /** * */ groups: Models.GroupsGroup[] } export interface BoardGetCommentsResponse { /** * Total number */ count: number, /** * */ items: Models.BoardTopicComment[], /** * */ poll: Models.BoardTopicPoll } export interface BoardGetTopicsExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.BoardTopic[], /** * */ default_order: Models.BoardDefaultOrder, /** * Information whether current user can add topic */ can_add_topics: Models.BaseBoolInt, /** * */ profiles: Models.UsersUserMin[] } export interface BoardGetTopicsResponse { /** * Total number */ count: number, /** * */ items: Models.BoardTopic[], /** * */ default_order: Models.BoardDefaultOrder, /** * Information whether current user can add topic */ can_add_topics: Models.BaseBoolInt } export interface DatabaseGetChairsResponse { /** * Total number */ count: number, /** * */ items: Models.BaseObject[] } export type DatabaseGetCitiesByIdResponse = Models.BaseObject[] export interface DatabaseGetCitiesResponse { /** * Total number */ count: number, /** * */ items: Models.DatabaseCity[] } export type DatabaseGetCountriesByIdResponse = Models.BaseCountry[] export interface DatabaseGetCountriesResponse { /** * Total number */ count: number, /** * */ items: Models.BaseCountry[] } export interface DatabaseGetFacultiesResponse { /** * Total number */ count: number, /** * */ items: Models.DatabaseFaculty[] } export type DatabaseGetMetroStationsByIdResponse = Models.DatabaseStation[] export interface DatabaseGetMetroStationsResponse { /** * Total number */ count: number, /** * */ items: Models.DatabaseStation[] } export interface DatabaseGetRegionsResponse { /** * Total number */ count: number, /** * */ items: Models.DatabaseRegion[] } export type DatabaseGetSchoolClassesResponse = any[][] export interface DatabaseGetSchoolsResponse { /** * Total number */ count: number, /** * */ items: Models.DatabaseSchool[] } export interface DatabaseGetUniversitiesResponse { /** * Total number */ count: number, /** * */ items: Models.DatabaseUniversity[] } export type DocsAddResponse = number export type DocsGetByIdResponse = Models.DocsDoc[] export interface DocsGetTypesResponse { /** * Total number */ count: number, /** * */ items: Models.DocsDocTypes[] } export type DocsGetUploadServer = Models.BaseUploadServer export interface DocsGetResponse { /** * Total number */ count: number, /** * */ items: Models.DocsDoc[] } export interface DocsSaveResponse { /** * */ type: Models.DocsDocAttachmentType, /** * */ audio_message: Models.MessagesAudioMessage, /** * */ doc: Models.DocsDoc, /** * */ graffiti: Models.MessagesGraffiti } export interface DocsSearchResponse { /** * Total number */ count: number, /** * */ items: Models.DocsDoc[] } export type DonutGetSubscriptionResponse = Models.DonutDonatorSubscriptionInfo export interface DonutGetSubscriptionsResponse { /** * */ subscriptions: Models.DonutDonatorSubscriptionInfo[], /** * */ count: number, /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export interface DownloadedGamesPaidStatusResponse { /** * Game has been paid */ is_paid: boolean } export type FaveAddTagResponse = Models.FaveTag export interface FaveGetPagesResponse { /** * */ count: number, /** * */ items: Models.FavePage[] } export interface FaveGetTagsResponse { /** * */ count: number, /** * */ items: Models.FaveTag[] } export interface FaveGetExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.FaveBookmark[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroup[] } export interface FaveGetResponse { /** * Total number */ count: number, /** * */ items: Models.FaveBookmark[] } export interface FriendsAddListResponse { /** * List ID */ list_id: number } export type FriendsAddResponse = number export type FriendsAreFriendsExtendedResponse = Models.FriendsFriendExtendedStatus[] export type FriendsAreFriendsResponse = Models.FriendsFriendStatus[] export interface FriendsDeleteResponse { /** * */ success: number, /** * Returns 1 if friend has been deleted */ friend_deleted: number, /** * Returns 1 if out request has been canceled */ out_request_deleted: number, /** * Returns 1 if incoming request has been declined */ in_request_deleted: number, /** * Returns 1 if suggestion has been declined */ suggestion_deleted: number } export type FriendsGetAppUsersResponse = number[] export type FriendsGetByPhonesResponse = Models.FriendsUserXtrPhone[] export interface FriendsGetListsResponse { /** * Total number of friends lists */ count: number, /** * */ items: Models.FriendsFriendsList[] } export type FriendsGetMutualResponse = number[] export type FriendsGetMutualTargetUidsResponse = Models.FriendsMutualFriend[] export interface FriendsGetOnlineOnlineMobileResponse { /** * */ online: number[], /** * */ online_mobile: number[] } export type FriendsGetOnlineResponse = number[] export type FriendsGetRecentResponse = number[] export interface FriendsGetRequestsExtendedResponse { /** * Total requests number */ count: number, /** * */ items: Models.FriendsRequestsXtrMessage[] } export interface FriendsGetRequestsNeedMutualResponse { /** * Total requests number */ count: number, /** * */ items: Models.FriendsRequests[] } export interface FriendsGetRequestsResponse { /** * Total requests number */ count: number, /** * */ items: number[], /** * Total unread requests number */ count_unread: number } export interface FriendsGetSuggestionsResponse { /** * Total results number */ count: number, /** * */ items: Models.UsersUserFull[] } export interface FriendsGetFieldsResponse { /** * Total friends number */ count: number, /** * */ items: Models.FriendsUserXtrLists[] } export interface FriendsGetResponse { /** * Total friends number */ count: number, /** * */ items: number[] } export interface FriendsSearchResponse { /** * Total number */ count: number, /** * */ items: Models.UsersUserFull[] } export interface GiftsGetResponse { /** * Total number */ count: number, /** * */ items: Models.GiftsGift[] } export type GroupsAddAddressResponse = Models.GroupsAddress export interface GroupsAddCallbackServerResponse { /** * */ server_id: number } export type GroupsAddLinkResponse = Models.GroupsGroupLink export type GroupsCreateResponse = Models.GroupsGroup export type GroupsEditAddressResponse = Models.GroupsAddress export interface GroupsGetAddressesResponse { /** * Total count of addresses */ count: number, /** * */ items: Models.GroupsAddress[] } export interface GroupsGetBannedResponse { /** * Total users number */ count: number, /** * */ items: Models.GroupsBannedItem[] } export type GroupsGetByIdLegacyResponse = Models.GroupsGroupFull[] export interface GroupsGetByIdResponse { /** * */ groups: Models.GroupsGroupFull[], /** * */ profiles: Models.GroupsProfileItem[] } export interface GroupsGetCallbackConfirmationCodeResponse { /** * Confirmation code */ code: string } export interface GroupsGetCallbackServersResponse { /** * */ count: number, /** * */ items: Models.GroupsCallbackServer[] } export type GroupsGetCallbackSettingsResponse = Models.GroupsCallbackSettings export interface GroupsGetCatalogInfoExtendedResponse { /** * Information whether catalog is enabled for current user */ enabled: number, /** * */ categories: Models.GroupsGroupCategoryFull[] } export interface GroupsGetCatalogInfoResponse { /** * Information whether catalog is enabled for current user */ enabled: number, /** * */ categories: Models.GroupsGroupCategory[] } export interface GroupsGetCatalogResponse { /** * Total communities number */ count: number, /** * */ items: Models.GroupsGroup[] } export interface GroupsGetInvitedUsersResponse { /** * Total communities number */ count: number, /** * */ items: Models.UsersUserFull[] } export interface GroupsGetInvitesExtendedResponse { /** * Total communities number */ count: number, /** * */ items: Models.GroupsGroupFull[], /** * */ profiles: Models.UsersUserMin[], /** * */ groups: Models.GroupsGroupFull[] } export interface GroupsGetInvitesResponse { /** * Total communities number */ count: number, /** * */ items: Models.GroupsGroupFull[] } export type GroupsGetLongPollServerResponse = Models.GroupsLongPollServer export type GroupsGetLongPollSettingsResponse = Models.GroupsLongPollSettings export interface GroupsGetMembersFieldsResponse { /** * Total members number */ count: number, /** * */ items: Models.GroupsUserXtrRole[] } export interface GroupsGetMembersFilterResponse { /** * Total members number */ count: number, /** * */ items: Models.GroupsMemberRole[] } export interface GroupsGetMembersResponse { /** * Total members number */ count: number, /** * */ items: number[] } export interface GroupsGetRequestsFieldsResponse { /** * Total communities number */ count: number, /** * */ items: Models.UsersUserFull[] } export interface GroupsGetRequestsResponse { /** * Total communities number */ count: number, /** * */ items: number[] } export type GroupsGetSettingsResponse = any export type GroupsGetTagListResponse = Models.GroupsGroupTag[] export interface GroupsGetTokenPermissionsResponse { /** * */ mask: number, /** * */ permissions: Models.GroupsTokenPermissionSetting[] } export interface GroupsGetExtendedResponse { /** * Total communities number */ count: number, /** * */ items: Models.GroupsGroupFull[] } export interface GroupsGetResponse { /** * Total communities number */ count: number, /** * */ items: number[] } export interface GroupsIsMemberExtendedResponse { /** * Information whether user is a member of the group */ member: Models.BaseBoolInt, /** * Information whether user has been invited to the group */ invitation: Models.BaseBoolInt, /** * Information whether user can be invited */ can_invite: Models.BaseBoolInt, /** * Information whether user's invite to the group can be recalled */ can_recall: Models.BaseBoolInt, /** * Information whether user has sent request to the group */ request: Models.BaseBoolInt } export type GroupsIsMemberResponse = Models.BaseBoolInt export type GroupsIsMemberUserIdsExtendedResponse = Models.GroupsMemberStatusFull[] export type GroupsIsMemberUserIdsResponse = Models.GroupsMemberStatus[] export interface GroupsSearchResponse { /** * Total communities number */ count: number, /** * */ items: Models.GroupsGroup[] } export interface LikesAddResponse { /** * Total likes number */ likes: number } export interface LikesDeleteResponse { /** * Total likes number */ likes: number } export interface LikesGetListExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.UsersUserMin[] } export interface LikesGetListResponse { /** * Total number */ count: number, /** * */ items: number[] } export interface LikesIsLikedResponse { /** * Information whether user liked the object */ liked: Models.BaseBoolInt, /** * Information whether user reposted the object */ copied: Models.BaseBoolInt } export interface MarketAddAlbumResponse { /** * Album ID */ market_album_id: number } export interface MarketAddResponse { /** * Item ID */ market_item_id: number } export type MarketCreateCommentResponse = number export type MarketDeleteCommentResponse = Models.BaseBoolInt export interface MarketGetAlbumByIdResponse { /** * Total number */ count: number, /** * */ items: Models.MarketMarketAlbum[] } export interface MarketGetAlbumsResponse { /** * Total number */ count: number, /** * */ items: Models.MarketMarketAlbum[] } export interface MarketGetByIdExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.MarketMarketItemFull[] } export interface MarketGetByIdResponse { /** * Total number */ count: number, /** * */ items: Models.MarketMarketItem[] } export interface MarketGetCategoriesNewResponse { /** * */ items: Models.MarketMarketCategoryTree[] } export interface MarketGetCategoriesResponse { /** * Total number */ count: number, /** * */ items: Models.MarketMarketCategory[] } export interface MarketGetCommentsResponse { /** * Total number */ count: number, /** * */ items: Models.WallWallComment[] } export interface MarketGetGroupOrdersResponse { /** * Total number */ count: number, /** * */ items: Models.MarketOrder[] } export interface MarketGetOrderByIdResponse { /** * */ order: Models.MarketOrder } export interface MarketGetOrderItemsResponse { /** * Total number */ count: number, /** * */ items: Models.MarketOrderItem[] } export interface MarketGetOrdersExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.MarketOrder[], /** * */ groups: Models.GroupsGroupFull[] } export interface MarketGetOrdersResponse { /** * Total number */ count: number, /** * */ items: Models.MarketOrder[] } export interface MarketGetExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.MarketMarketItemFull[] } export interface MarketGetResponse { /** * Total number */ count: number, /** * */ items: Models.MarketMarketItem[] } export type MarketRestoreCommentResponse = Models.BaseBoolInt export interface MarketSearchExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.MarketMarketItemFull[] } export interface MarketSearchResponse { /** * Total number */ count: number, /** * */ items: Models.MarketMarketItem[] } export type MessagesCreateChatResponse = number export interface MessagesDeleteChatPhotoResponse { /** * Service message ID */ message_id: number, /** * */ chat: Models.MessagesChat } export interface MessagesDeleteConversationResponse { /** * Id of the last message, that was deleted */ last_deleted_id: number } export interface MessagesDeleteResponse { } export type MessagesEditResponse = Models.BaseBoolInt export interface MessagesGetByConversationMessageIdResponse { /** * Total number */ count: number, /** * */ items: Models.MessagesMessage[] } export interface MessagesGetByIdExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.MessagesMessage[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export interface MessagesGetByIdResponse { /** * Total number */ count: number, /** * */ items: Models.MessagesMessage[] } export interface MessagesGetChatPreviewResponse { /** * */ preview: Models.MessagesChatPreview, /** * */ profiles: Models.UsersUserFull[] } export type MessagesGetChatChatIdsFieldsResponse = Models.MessagesChatFull[] export type MessagesGetChatChatIdsResponse = Models.MessagesChat[] export type MessagesGetChatFieldsResponse = Models.MessagesChatFull export type MessagesGetChatResponse = Models.MessagesChat export interface MessagesGetConversationMembersResponse { /** * Chat members count */ count: number, /** * */ items: Models.MessagesConversationMember[], /** * */ chat_restrictions: Models.MessagesChatRestrictions, /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export interface MessagesGetConversationsByIdExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.MessagesConversation[], /** * */ profiles: Models.UsersUser[] } export interface MessagesGetConversationsByIdResponse { /** * Total number */ count: number, /** * */ items: Models.MessagesConversation[] } export interface MessagesGetConversationsResponse { /** * Total number */ count: number, /** * Unread dialogs number */ unread_count: number, /** * */ items: Models.MessagesConversationWithMessage[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export interface MessagesGetHistoryAttachmentsResponse { /** * */ items: Models.MessagesHistoryAttachment[], /** * Value for pagination */ next_from: string } export interface MessagesGetHistoryExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.MessagesMessage[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[], /** * */ conversations: Models.MessagesConversation[] } export interface MessagesGetHistoryResponse { /** * Total number */ count: number, /** * */ items: Models.MessagesMessage[] } export interface MessagesGetImportantMessagesExtendedResponse { /** * */ messages: Models.MessagesMessagesArray, /** * */ profiles: Models.UsersUser[], /** * */ groups: Models.GroupsGroup[], /** * */ conversations: Models.MessagesConversation[] } export interface MessagesGetImportantMessagesResponse { /** * */ messages: Models.MessagesMessagesArray, /** * */ profiles: Models.UsersUser[], /** * */ groups: Models.GroupsGroup[], /** * */ conversations: Models.MessagesConversation[] } export interface MessagesGetIntentUsersResponse { /** * */ count: number, /** * */ items: number[], /** * */ profiles: Models.UsersUserFull[] } export interface MessagesGetInviteLinkResponse { /** * */ link: string } export type MessagesGetLastActivityResponse = Models.MessagesLastActivity export interface MessagesGetLongPollHistoryResponse { /** * */ history: number[][], /** * */ messages: Models.MessagesLongpollMessages, /** * */ credentials: Models.MessagesLongpollParams, /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroup[], /** * */ chats: Models.MessagesChat[], /** * Persistence timestamp */ new_pts: number, /** * */ from_pts: number, /** * Has more */ more: boolean, /** * */ conversations: Models.MessagesConversation[] } export type MessagesGetLongPollServerResponse = Models.MessagesLongpollParams export interface MessagesIsMessagesFromGroupAllowedResponse { /** * */ is_allowed: Models.BaseBoolInt } export interface MessagesJoinChatByInviteLinkResponse { /** * */ chat_id: number } export type MessagesMarkAsImportantResponse = number[] export type MessagesPinResponse = Models.MessagesPinnedMessage export interface MessagesSearchConversationsResponse { /** * Total results number */ count: number, /** * */ items: Models.MessagesConversation[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export interface MessagesSearchExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.MessagesMessage[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[], /** * */ conversations: Models.MessagesConversation[] } export interface MessagesSearchResponse { /** * Total number */ count: number, /** * */ items: Models.MessagesMessage[] } export type MessagesSendResponse = number export type MessagesSendUserIdsResponse = any export interface MessagesSetChatPhotoResponse { /** * Service message ID */ message_id: number, /** * */ chat: Models.MessagesChat } export interface NewsfeedGetBannedExtendedResponse { /** * */ groups: Models.UsersUserFull[], /** * */ profiles: Models.GroupsGroupFull[] } export interface NewsfeedGetBannedResponse { /** * */ groups: number[], /** * */ members: number[] } export interface NewsfeedGetCommentsResponse { /** * */ items: Models.NewsfeedNewsfeedItem[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[], /** * New from value */ next_from: string } export interface NewsfeedGetListsExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.NewsfeedListFull[] } export interface NewsfeedGetListsResponse { /** * Total number */ count: number, /** * */ items: Models.NewsfeedList[] } export interface NewsfeedGetMentionsResponse { /** * Total number */ count: number, /** * */ items: Models.WallWallpostToId[] } export interface NewsfeedGetRecommendedResponse { /** * */ items: Models.NewsfeedNewsfeedItem[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[], /** * New offset value */ new_offset: string, /** * Next from value */ next_from: string } export interface NewsfeedGetSuggestedSourcesResponse { /** * Total number */ count: number, /** * */ items: Models.UsersSubscriptionsItem[] } export interface NewsfeedGetResponse { /** * */ items: Models.NewsfeedNewsfeedItem[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[], /** * New from value */ next_from: string } export type NewsfeedSaveListResponse = number export interface NewsfeedSearchExtendedResponse { /** * */ items: Models.WallWallpostFull[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[], /** * */ suggested_queries: string[], /** * */ next_from: string, /** * Filtered number */ count: number, /** * Total number */ total_count: number } export interface NewsfeedSearchResponse { /** * */ items: Models.WallWallpostFull[], /** * */ suggested_queries: string[], /** * */ next_from: string, /** * Filtered number */ count: number, /** * Total number */ total_count: number } export type NotesAddResponse = number export type NotesCreateCommentResponse = number export type NotesGetByIdResponse = Models.NotesNote export interface NotesGetCommentsResponse { /** * Total number */ count: number, /** * */ items: Models.NotesNoteComment[] } export interface NotesGetResponse { /** * Total number */ count: number, /** * */ items: Models.NotesNote[] } export interface NotificationsGetResponse { /** * Total number */ count: number, /** * */ items: Models.NotificationsNotificationItem[], /** * */ profiles: Models.UsersUser[], /** * */ groups: Models.GroupsGroup[], /** * Time when user has been checked notifications last time */ last_viewed: number, /** * */ photos: Models.PhotosPhoto[], /** * */ videos: Models.VideoVideo[], /** * */ apps: Models.AppsApp[], /** * */ next_from: string, /** * */ ttl: number } export type NotificationsMarkAsViewedResponse = Models.BaseBoolInt export type NotificationsSendMessageResponse = Models.NotificationsSendMessageItem[] export type OrdersCancelSubscriptionResponse = Models.BaseBoolInt export type OrdersChangeStateResponse = string export type OrdersGetAmountResponse = Models.OrdersAmount export type OrdersGetByIdResponse = Models.OrdersOrder[] export type OrdersGetUserSubscriptionByIdResponse = Models.OrdersSubscription export interface OrdersGetUserSubscriptionsResponse { /** * Total number */ count: number, /** * */ items: Models.OrdersSubscription[] } export type OrdersGetResponse = Models.OrdersOrder[] export type OrdersUpdateSubscriptionResponse = Models.BaseBoolInt export type PagesGetHistoryResponse = Models.PagesWikipageHistory[] export type PagesGetTitlesResponse = Models.PagesWikipage[] export type PagesGetVersionResponse = Models.PagesWikipageFull export type PagesGetResponse = Models.PagesWikipageFull export type PagesParseWikiResponse = string export type PagesSaveAccessResponse = number export type PagesSaveResponse = number export type PhotosCopyResponse = number export type PhotosCreateAlbumResponse = Models.PhotosPhotoAlbumFull export type PhotosCreateCommentResponse = number export type PhotosDeleteCommentResponse = Models.BaseBoolInt export type PhotosGetAlbumsCountResponse = number export interface PhotosGetAlbumsResponse { /** * Total number */ count: number, /** * */ items: Models.PhotosPhotoAlbumFull[] } export interface PhotosGetAllCommentsResponse { /** * Total number */ count: number, /** * */ items: Models.PhotosCommentXtrPid[] } export interface PhotosGetAllExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.PhotosPhotoFullXtrRealOffset[], /** * Information whether next page is presented */ more: Models.BaseBoolInt } export interface PhotosGetAllResponse { /** * Total number */ count: number, /** * */ items: Models.PhotosPhotoXtrRealOffset[], /** * Information whether next page is presented */ more: Models.BaseBoolInt } export type PhotosGetByIdExtendedResponse = Models.PhotosPhotoFull[] export type PhotosGetByIdResponse = Models.PhotosPhoto[] export interface PhotosGetCommentsExtendedResponse { /** * Total number */ count: number, /** * Real offset of the comments */ real_offset: number, /** * */ items: Models.WallWallComment[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export interface PhotosGetCommentsResponse { /** * Total number */ count: number, /** * Real offset of the comments */ real_offset: number, /** * */ items: Models.WallWallComment[] } export type PhotosGetMarketUploadServerResponse = Models.BaseUploadServer export type PhotosGetMessagesUploadServerResponse = Models.PhotosPhotoUpload export interface PhotosGetNewTagsResponse { /** * Total number */ count: number, /** * */ items: Models.PhotosPhotoXtrTagInfo[] } export type PhotosGetTagsResponse = Models.PhotosPhotoTag[] export type PhotosGetUploadServerResponse = Models.PhotosPhotoUpload export interface PhotosGetUserPhotosExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.PhotosPhotoFull[] } export interface PhotosGetUserPhotosResponse { /** * Total number */ count: number, /** * */ items: Models.PhotosPhoto[] } export type PhotosGetWallUploadServerResponse = Models.PhotosPhotoUpload export interface PhotosGetExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.PhotosPhotoFull[] } export interface PhotosGetResponse { /** * Total number */ count: number, /** * */ items: Models.PhotosPhoto[] } export type PhotosPutTagResponse = number export type PhotosRestoreCommentResponse = Models.BaseBoolInt export type PhotosSaveMarketAlbumPhotoResponse = Models.PhotosPhoto[] export type PhotosSaveMarketPhotoResponse = Models.PhotosPhoto[] export type PhotosSaveMessagesPhotoResponse = Models.PhotosPhoto[] export type PhotosSaveOwnerCoverPhotoResponse = Models.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 } export type PhotosSaveWallPhotoResponse = Models.PhotosPhoto[] export type PhotosSaveResponse = Models.PhotosPhoto[] export interface PhotosSearchResponse { /** * Total number */ count: number, /** * */ items: Models.PhotosPhoto[] } export type PollsAddVoteResponse = Models.BaseBoolInt export type PollsCreateResponse = Models.PollsPoll export type PollsDeleteVoteResponse = Models.BaseBoolInt export type PollsGetByIdResponse = Models.PollsPoll export type PollsGetVotersResponse = Models.PollsVoters[] export interface PrettyCardsCreateResponse { /** * Owner ID of created pretty card */ owner_id: number, /** * Card ID of created pretty card */ card_id: string } 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 } export interface PrettyCardsEditResponse { /** * Owner ID of edited pretty card */ owner_id: number, /** * Card ID of edited pretty card */ card_id: string } export type PrettyCardsGetByIdResponse = Models.PrettyCardsPrettyCard[] export type PrettyCardsGetUploadURLResponse = string export interface PrettyCardsGetResponse { /** * Total number */ count: number, /** * */ items: Models.PrettyCardsPrettyCard[] } export interface SearchGetHintsResponse { /** * */ count: number, /** * */ items: Models.SearchHint[], /** * */ suggested_queries: string[] } export type SecureCheckTokenResponse = Models.SecureTokenChecked export type SecureGetAppBalanceResponse = number export type SecureGetSMSHistoryResponse = Models.SecureSmsNotification[] export type SecureGetTransactionsHistoryResponse = Models.SecureTransaction[] export type SecureGetUserLevelResponse = Models.SecureLevel[] export type SecureGiveEventStickerResponse = any export type SecureSendNotificationResponse = number[] export type StatsGetPostReachResponse = Models.StatsWallpostStat[] export type StatsGetResponse = Models.StatsPeriod[] export type StatusGetResponse = Models.StatusStatus export type StorageGetKeysResponse = string[] export type StorageGetResponse = Models.StorageValue[] export interface StoriesGetBannedExtendedResponse { /** * Stories count */ count: number, /** * */ items: number[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export interface StoriesGetBannedResponse { /** * Stories count */ count: number, /** * */ items: number[] } export interface StoriesGetByIdExtendedResponse { /** * Stories count */ count: number, /** * */ items: Models.StoriesStory[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export interface StoriesGetByIdResponse { /** * Stories count */ count: number, /** * */ items: Models.StoriesStory[] } export interface StoriesGetPhotoUploadServerResponse { /** * Upload URL */ upload_url: string, /** * Users ID who can to see story. */ user_ids: number[] } export type StoriesGetStatsResponse = Models.StoriesStoryStats export interface StoriesGetVideoUploadServerResponse { /** * Upload URL */ upload_url: string, /** * Users ID who can to see story. */ user_ids: number[] } export interface StoriesGetViewersExtendedV5115Response { /** * Viewers count */ count: number, /** * */ items: Models.StoriesViewersItem[], /** * */ hidden_reason: string } export interface StoriesGetViewersExtendedResponse { /** * Viewers count */ count: number, /** * */ items: Models.UsersUserFull[] } export interface StoriesGetV5113Response { /** * */ count: number, /** * */ items: Models.StoriesFeedItem[], /** * */ profiles: Models.UsersUser[], /** * */ groups: Models.GroupsGroup[], /** * */ need_upload_screen: boolean } export interface StoriesGetResponse { /** * Stories count */ count: number, /** * */ items: Models.StoriesStory[][], /** * */ promo_data: Models.StoriesPromoBlock, /** * */ profiles: Models.UsersUser[], /** * */ groups: Models.GroupsGroup[], /** * */ need_upload_screen: boolean } export interface StoriesSaveResponse { /** * */ count: number, /** * */ items: Models.StoriesStory[] } export interface StoriesUploadResponse { /** * A string hash that is used in the stories.save method */ upload_result: string } export interface StreamingGetServerUrlResponse { /** * Server host */ endpoint: string, /** * Access key */ key: string } export interface UsersGetFollowersFieldsResponse { /** * Total number of available results */ count: number, /** * */ items: Models.UsersUserFull[] } export interface UsersGetFollowersResponse { /** * Total friends number */ count: number, /** * */ items: number[] } export interface UsersGetSubscriptionsExtendedResponse { /** * Total number of available results */ count: number, /** * */ items: Models.UsersSubscriptionsItem[] } export interface UsersGetSubscriptionsResponse { /** * */ users: Models.UsersUsersArray, /** * */ groups: Models.GroupsGroupsArray } export type UsersGetResponse = Models.UsersUserXtrCounters[] export interface UsersSearchResponse { /** * Total number of available results */ count: number, /** * */ items: Models.UsersUserFull[] } export type UtilsCheckLinkResponse = Models.UtilsLinkChecked export interface UtilsGetLastShortenedLinksResponse { /** * Total number of available results */ count: number, /** * */ items: Models.UtilsLastShortenedLink[] } export type UtilsGetLinkStatsExtendedResponse = Models.UtilsLinkStatsExtended export type UtilsGetLinkStatsResponse = Models.UtilsLinkStats export type UtilsGetServerTimeResponse = number export type UtilsGetShortLinkResponse = Models.UtilsShortLink export type UtilsResolveScreenNameResponse = Models.UtilsDomainResolved export interface VideoAddAlbumResponse { /** * Created album ID */ album_id: number } export type VideoCreateCommentResponse = number export type VideoGetAlbumByIdResponse = Models.VideoVideoAlbumFull export interface VideoGetAlbumsByVideoExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.VideoVideoAlbumFull[] } export type VideoGetAlbumsByVideoResponse = number[] export interface VideoGetAlbumsExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.VideoVideoAlbumFull[] } export interface VideoGetAlbumsResponse { /** * Total number */ count: number, /** * */ items: Models.VideoVideoAlbumFull[] } export interface VideoGetCommentsExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.WallWallComment[], /** * */ profiles: Models.UsersUserMin[], /** * */ groups: Models.GroupsGroupFull[] } export interface VideoGetCommentsResponse { /** * Total number */ count: number, /** * */ items: Models.WallWallComment[] } export interface VideoGetExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.VideoVideoFull[], /** * */ profiles: Models.UsersUserMin[], /** * */ groups: Models.GroupsGroupFull[] } export interface VideoGetResponse { /** * Total number */ count: number, /** * */ items: Models.VideoVideo[] } export type VideoRestoreCommentResponse = Models.BaseBoolInt export type VideoSaveResponse = Models.VideoSaveResult export interface VideoSearchExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.VideoVideo[], /** * */ profiles: Models.UsersUserMin[], /** * */ groups: Models.GroupsGroupFull[] } export interface VideoSearchResponse { /** * Total number */ count: number, /** * */ items: Models.VideoVideo[] } export interface WallCreateCommentResponse { /** * Created comment ID */ comment_id: number } export interface WallEditResponse { /** * Edited post ID */ post_id: number } export interface WallGetByIdExtendedResponse { /** * */ items: Models.WallWallpostFull[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export type WallGetByIdLegacyResponse = Models.WallWallpostFull[] export interface WallGetByIdResponse { /** * */ items: Models.WallWallpostFull[] } export interface WallGetCommentExtendedResponse { /** * */ items: Models.WallWallComment[], /** * */ profiles: Models.UsersUser[], /** * */ groups: Models.GroupsGroup[] } export interface WallGetCommentResponse { /** * */ items: Models.WallWallComment[] } export interface WallGetCommentsExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.WallWallComment[], /** * */ show_reply_button: boolean, /** * Information whether current user can comment the post */ can_post: boolean, /** * Information whether groups can comment the post */ groups_can_post: boolean, /** * Count of replies of current level */ current_level_count: number, /** * */ profiles: Models.UsersUser[], /** * */ groups: Models.GroupsGroup[] } export interface WallGetCommentsResponse { /** * Total number */ count: number, /** * */ items: Models.WallWallComment[], /** * Information whether current user can comment the post */ can_post: boolean, /** * Information whether groups can comment the post */ groups_can_post: boolean, /** * Count of replies of current level */ current_level_count: number } export interface WallGetRepostsResponse { /** * */ items: Models.WallWallpostFull[], /** * */ profiles: Models.UsersUser[], /** * */ groups: Models.GroupsGroup[] } export interface WallGetExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.WallWallpostFull[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export interface WallGetResponse { /** * Total number */ count: number, /** * */ items: Models.WallWallpostFull[] } export interface WallPostAdsStealthResponse { /** * Created post ID */ post_id: number } export interface WallPostResponse { /** * Created post ID */ post_id: number } export interface WallRepostResponse { /** * */ success: number, /** * 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 } export interface WallSearchExtendedResponse { /** * Total number */ count: number, /** * */ items: Models.WallWallpostFull[], /** * */ profiles: Models.UsersUserFull[], /** * */ groups: Models.GroupsGroupFull[] } export interface WallSearchResponse { /** * Total number */ count: number, /** * */ items: Models.WallWallpostFull[] } export interface WidgetsGetCommentsResponse { /** * Total number */ count: number, /** * */ posts: Models.WidgetsWidgetComment[] } export interface WidgetsGetPagesResponse { /** * Total number */ count: number, /** * */ pages: Models.WidgetsWidgetPage[] }
the_stack
import INTERNAL_PROPS from '../../processing/dom/internal-properties'; import * as sharedUrlUtils from '../../utils/url'; import * as destLocation from './destination-location'; import urlResolver from './url-resolver'; import settings from '../settings'; import { ResourceType } from '../../typings/url'; import globalContextInfo from './global-context-info'; import { getLocation, sameOriginCheck } from './destination-location'; import { Credentials } from '../../utils/url'; const HASH_RE = /#[\S\s]*$/; const SUPPORTED_WEB_SOCKET_PROTOCOL_RE = /^wss?:/i; const SCOPE_RE = /\/[^/]*$/; // NOTE: The window.location equals 'about:blank' in iframes without src // therefore we need to find a window with src to get the proxy settings export const DEFAULT_PROXY_SETTINGS = (function () { /*eslint-disable no-restricted-properties*/ let locationWindow = globalContextInfo.isInWorker ? { location: parseUrl(self.location.origin), parent: null } : window; let proxyLocation = locationWindow.location; while (!proxyLocation.hostname) { locationWindow = locationWindow.parent; proxyLocation = locationWindow.location; } return { hostname: proxyLocation.hostname, port: proxyLocation.port.toString(), protocol: proxyLocation.protocol }; /*eslint-enable no-restricted-properties*/ })(); export const REQUEST_DESCRIPTOR_VALUES_SEPARATOR = sharedUrlUtils.REQUEST_DESCRIPTOR_VALUES_SEPARATOR; function getCharsetFromDocument (parsedResourceType: ResourceType): string | null { if (!parsedResourceType.isScript && !parsedResourceType.isServiceWorker) return null; return self.document && document[INTERNAL_PROPS.documentCharset] || null; } export let getProxyUrl = function (url: string, opts?): string { url = sharedUrlUtils.getURLString(url); const resourceType = opts && opts.resourceType; const parsedResourceType = sharedUrlUtils.parseResourceType(resourceType); if (!parsedResourceType.isWebSocket && !isSupportedProtocol(url) && !isSpecialPage(url)) return url; // NOTE: Resolves relative URLs. let resolvedUrl = destLocation.resolveUrl(url, opts && opts.doc); if (parsedResourceType.isWebSocket && !isValidWebSocketUrl(resolvedUrl) || !sharedUrlUtils.isValidUrl(resolvedUrl)) return url; /*eslint-disable no-restricted-properties*/ const proxyHostname = opts && opts.proxyHostname || DEFAULT_PROXY_SETTINGS.hostname; const proxyPort = opts && opts.proxyPort || DEFAULT_PROXY_SETTINGS.port; const proxyServerProtocol = opts && opts.proxyProtocol || DEFAULT_PROXY_SETTINGS.protocol; /*eslint-enable no-restricted-properties*/ const proxyProtocol = parsedResourceType.isWebSocket ? proxyServerProtocol.replace('http', 'ws') : proxyServerProtocol; const sessionId = opts && opts.sessionId || settings.get().sessionId; const windowId = opts && opts.windowId || settings.get().windowId; const credentials = opts && opts.credentials; let charset = opts && opts.charset; let reqOrigin = opts && opts.reqOrigin; const crossDomainPort = getCrossDomainProxyPort(proxyPort); // NOTE: If the relative URL contains no slash (e.g. 'img123'), the resolver will keep // the original proxy information, so that we can return such URL as is. // TODO: Implement the isProxyURL function. const parsedProxyUrl = sharedUrlUtils.parseProxyUrl(resolvedUrl); /*eslint-disable no-restricted-properties*/ const isValidProxyUrl = !!parsedProxyUrl && parsedProxyUrl.proxy.hostname === proxyHostname && (parsedProxyUrl.proxy.port === proxyPort || parsedProxyUrl.proxy.port === crossDomainPort); /*eslint-enable no-restricted-properties*/ if (isValidProxyUrl) { if (resourceType && parsedProxyUrl.resourceType === resourceType) return resolvedUrl; // NOTE: Need to change the proxy URL resource type. const destUrl = sharedUrlUtils.formatUrl(parsedProxyUrl.destResourceInfo); return getProxyUrl(destUrl, { proxyProtocol, proxyHostname, proxyPort, sessionId, resourceType, charset, reqOrigin, credentials }); } const parsedUrl = sharedUrlUtils.parseUrl(resolvedUrl); if (!parsedUrl.protocol) // eslint-disable-line no-restricted-properties return url; charset = charset || getCharsetFromDocument(parsedResourceType); // NOTE: It seems that the relative URL had the leading slash or dots, so that the proxy info path part was // removed by the resolver and we have an origin URL with the incorrect host and protocol. /*eslint-disable no-restricted-properties*/ if (parsedUrl.protocol === proxyServerProtocol && parsedUrl.hostname === proxyHostname && parsedUrl.port === proxyPort) { const parsedDestLocation = destLocation.getParsed(); parsedUrl.protocol = parsedDestLocation.protocol; parsedUrl.host = parsedDestLocation.host; parsedUrl.hostname = parsedDestLocation.hostname; parsedUrl.port = parsedDestLocation.port || ''; resolvedUrl = sharedUrlUtils.formatUrl(parsedUrl); } /*eslint-enable no-restricted-properties*/ if (parsedResourceType.isWebSocket) { // eslint-disable-next-line no-restricted-properties parsedUrl.protocol = parsedUrl.protocol.replace('ws', 'http'); resolvedUrl = sharedUrlUtils.formatUrl(parsedUrl); reqOrigin = reqOrigin || destLocation.getOriginHeader(); } return sharedUrlUtils.getProxyUrl(resolvedUrl, { proxyProtocol, proxyHostname, proxyPort, sessionId, resourceType, charset, reqOrigin, windowId, credentials }); } export function overrideGetProxyUrl (func: typeof getProxyUrl): void { getProxyUrl = func; } export function getNavigationUrl (url: string, win) { // NOTE: For the 'about:blank' page, we perform url proxing only for the top window, 'location' object and links. // For images and iframes, we keep urls as they were. // See details in https://github.com/DevExpress/testcafe-hammerhead/issues/339 let destinationLocation = null; const isIframe = win.top !== win; const winLocation = win.location.toString(); if (isIframe) destinationLocation = winLocation; else { const parsedProxyUrl = parseProxyUrl(winLocation); destinationLocation = parsedProxyUrl && parsedProxyUrl.destUrl; } if (isSpecialPage(destinationLocation) && sharedUrlUtils.isRelativeUrl(url)) return ''; url = sharedUrlUtils.prepareUrl(url); return getProxyUrl(url); } export let getCrossDomainIframeProxyUrl = function (url: string) { return getProxyUrl(url, { proxyPort: settings.get().crossDomainProxyPort, resourceType: sharedUrlUtils.getResourceTypeString({ isIframe: true }) }); } export function overrideGetCrossDomainIframeProxyUrl (func: typeof getCrossDomainIframeProxyUrl): void { getCrossDomainIframeProxyUrl = func; } export function getPageProxyUrl (url: string, windowId: string): string { const parsedProxyUrl = parseProxyUrl(url); let resourceType = null; if (parsedProxyUrl) { url = parsedProxyUrl.destUrl; resourceType = parsedProxyUrl.resourceType; } if (resourceType) { const parsedResourceType = parseResourceType(resourceType); parsedResourceType.isIframe = false; resourceType = stringifyResourceType(parsedResourceType); } const isCrossDomainUrl = !destLocation.sameOriginCheck(destLocation.getLocation(), url); const proxyPort = isCrossDomainUrl ? settings.get().crossDomainProxyPort : location.port.toString(); // eslint-disable-line no-restricted-properties return getProxyUrl(url, { windowId, proxyPort, resourceType }); } export function getCrossDomainProxyPort (proxyPort: string) { return settings.get().crossDomainProxyPort === proxyPort // eslint-disable-next-line no-restricted-properties ? location.port.toString() : settings.get().crossDomainProxyPort; } export let resolveUrlAsDest = function (url: string) { return sharedUrlUtils.resolveUrlAsDest(url, getProxyUrl); } export function overrideResolveUrlAsDest (func: typeof resolveUrlAsDest): void { resolveUrlAsDest = func; } export function formatUrl (parsedUrl) { return sharedUrlUtils.formatUrl(parsedUrl); } export let parseProxyUrl = function (proxyUrl: string) { return sharedUrlUtils.parseProxyUrl(proxyUrl); } export function overrideParseProxyUrl (func: typeof parseProxyUrl) { parseProxyUrl = func; } export function parseUrl (url: string | URL) { return sharedUrlUtils.parseUrl(url); } export let convertToProxyUrl = function (url: string, resourceType, charset, isCrossDomain = false) { return getProxyUrl(url, { resourceType, charset, // eslint-disable-next-line no-restricted-properties proxyPort: isCrossDomain ? settings.get().crossDomainProxyPort : DEFAULT_PROXY_SETTINGS.port }); } export function overrideConvertToProxyUrl (func: typeof convertToProxyUrl): void { convertToProxyUrl = func; } export function changeDestUrlPart (proxyUrl: string, nativePropSetter, value, resourceType) { const parsed = sharedUrlUtils.parseProxyUrl(proxyUrl); if (parsed) { const sessionId = parsed.sessionId; const proxy = parsed.proxy; const destUrl = urlResolver.changeUrlPart(parsed.destUrl, nativePropSetter, value, document); return getProxyUrl(destUrl, { /*eslint-disable no-restricted-properties*/ proxyHostname: proxy.hostname, proxyPort: proxy.port, /*eslint-enable no-restricted-properties*/ sessionId, resourceType }); } return proxyUrl; } export function isValidWebSocketUrl (url) { const resolvedUrl = resolveUrlAsDest(url); return SUPPORTED_WEB_SOCKET_PROTOCOL_RE.test(resolvedUrl); } export function isSubDomain (domain, subDomain): boolean { return sharedUrlUtils.isSubDomain(domain, subDomain); } export function isSupportedProtocol (url: string): boolean { return sharedUrlUtils.isSupportedProtocol(url); } export function isSpecialPage (url: string): boolean { return sharedUrlUtils.isSpecialPage(url); } export function parseResourceType (resourceType: string): ResourceType { return sharedUrlUtils.parseResourceType(resourceType); } export function stringifyResourceType (resourceType: ResourceType): string { return sharedUrlUtils.getResourceTypeString(resourceType); } export function isChangedOnlyHash (currentUrl: string, newUrl: string): boolean { // NOTE: we compare proxied urls because urls passed into the function may be proxied, non-proxied // or relative. The getProxyUrl function solves all the corresponding problems. return getProxyUrl(currentUrl).replace(HASH_RE, '') === getProxyUrl(newUrl).replace(HASH_RE, ''); } export function getDestinationUrl (proxyUrl: any) { const parsedProxyUrl = parseProxyUrl(proxyUrl); return parsedProxyUrl ? parsedProxyUrl.destUrl : proxyUrl; } export function getScope (url: string): string | null { if (!isSupportedProtocol(url)) return null; const parsedUrl = parseUrl(resolveUrlAsDest(url)); if (!parsedUrl) return null; // NOTE: Delete query and hash parts. These parts are not related to the scope (GH-2524) const partAfterHostWithoutQueryAndHash = sharedUrlUtils.getPathname(parsedUrl.partAfterHost); return partAfterHostWithoutQueryAndHash.replace(SCOPE_RE, '/') || '/'; } export function getAjaxProxyUrl (url: string, credentials: Credentials) { const isCrossDomain = !sameOriginCheck(getLocation(), url); const opts = { resourceType: stringifyResourceType({ isAjax: true }), credentials } as any; if (isCrossDomain) { opts.proxyPort = settings.get().crossDomainProxyPort; opts.reqOrigin = destLocation.getOriginHeader(); } return getProxyUrl(url, opts); }
the_stack
export namespace Numbers { // Default Application export interface Application {} // Class /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * This provides the base rich text class for all iWork applications. */ export interface RichText { /** * The color of the font. Expressed as an RGB value consisting of a list of three color values from 0 to 65535. ex: Blue = {0, 0, 65535}. */ color(): any; /** * The name of the font. Can be the PostScript name, such as: “TimesNewRomanPS-ItalicMT”, or display name: “Times New Roman Italic”. TIP: Use the Font Book application get the information about a typeface. */ font(): string; /** * The size of the font. */ size(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * One of some text's characters. */ export interface Character {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * One of some text's paragraphs. */ export interface Paragraph {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * One of some text's words. */ export interface Word {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A container for iWork items */ export interface IWorkContainer {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An item which supports formatting */ export interface IWorkItem { /** * The height of the iWork item. */ height(): number; /** * Whether the object is locked. */ locked(): boolean; /** * The iWork container containing this iWork item. */ parent(): any; /** * The horizontal and vertical coordinates of the top left point of the iWork item. */ position(): any; /** * The width of the iWork item. */ width(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An audio clip */ export interface AudioClip { /** * The name of the audio file. */ fileName(): any; /** * The volume setting for the audio clip, from 0 (none) to 100 (full volume). */ clipVolume(): number; /** * If or how the audio clip repeats. */ repetitionMethod(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A shape container */ export interface Shape { /** * The background, if any, for the shape. */ backgroundFillType(): any; /** * The text contained within the shape. */ objectText(): any; /** * Is the iWork item displaying a reflection? */ reflectionShowing(): boolean; /** * The percentage of reflection of the iWork item, from 0 (none) to 100 (full). */ reflectionValue(): number; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; /** * The opacity of the object, in percent. */ opacity(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A chart */ export interface Chart {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An image container */ export interface Image { /** * Text associated with the image, read aloud by VoiceOver. */ description(): string; /** * The image file. */ file(): any; /** * The name of the image file. */ fileName(): any; /** * The opacity of the object, in percent. */ opacity(): number; /** * Is the iWork item displaying a reflection? */ reflectionShowing(): boolean; /** * The percentage of reflection of the iWork item, from 0 (none) to 100 (full). */ reflectionValue(): number; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A group container */ export interface Group { /** * The height of the iWork item. */ height(): number; /** * The iWork container containing this iWork item. */ parent(): any; /** * The horizontal and vertical coordinates of the top left point of the iWork item. */ position(): any; /** * The width of the iWork item. */ width(): number; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A line */ export interface Line { /** * A list of two numbers indicating the horizontal and vertical position of the line ending point. */ endPoint(): any; /** * Is the iWork item displaying a reflection? */ reflectionShowing(): boolean; /** * The percentage of reflection of the iWork item, from 0 (none) to 100 (full). */ reflectionValue(): number; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; /** * A list of two numbers indicating the horizontal and vertical position of the line starting point. */ startPoint(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A movie container */ export interface Movie { /** * The name of the movie file. */ fileName(): any; /** * The volume setting for the movie, from 0 (none) to 100 (full volume). */ movieVolume(): number; /** * The opacity of the object, in percent. */ opacity(): number; /** * Is the iWork item displaying a reflection? */ reflectionShowing(): boolean; /** * The percentage of reflection of the iWork item, from 0 (none) to 100 (full). */ reflectionValue(): number; /** * If or how the movie repeats. */ repetitionMethod(): any; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A table */ export interface Table { /** * The item's name. */ name(): string; /** * The range describing every cell in the table. */ cellRange(): any; /** * The cells currently selected in the table. */ selectionRange(): any; /** * The number of rows in the table. */ rowCount(): number; /** * The number of columns in the table. */ columnCount(): number; /** * The number of header rows in the table. */ headerRowCount(): number; /** * The number of header columns in the table. */ headerColumnCount(): number; /** * The number of footer rows in the table. */ footerRowCount(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A text container */ export interface TextItem { /** * The background, if any, for the text item. */ backgroundFillType(): any; /** * The text contained within the text item. */ objectText(): any; /** * The opacity of the object, in percent. */ opacity(): number; /** * Is the iWork item displaying a reflection? */ reflectionShowing(): boolean; /** * The percentage of reflection of the iWork item, from 0 (none) to 100 (full). */ reflectionValue(): number; /** * The rotation of the iWork item, in degrees from 0 to 359. */ rotation(): number; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A range of cells in a table */ export interface Range { /** * The font of the range's cells. */ fontName(): string; /** * The font size of the range's cells. */ fontSize(): any; /** * The format of the range's cells. */ format(): any; /** * The horizontal alignment of content in the range's cells. */ alignment(): any; /** * The range's coordinates. */ name(): string; /** * The text color of the range's cells. */ textColor(): any; /** * Whether text should wrap in the range's cells. */ textWrap(): boolean; /** * The background color of the range's cells. */ backgroundColor(): any; /** * The vertical alignment of content in the range's cells. */ verticalAlignment(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A cell in a table */ export interface Cell { /** * The cell's column. */ column(): any; /** * The cell's row. */ row(): any; /** * The actual value in the cell, or missing value if the cell is empty. */ value(): any; /** * The formatted value in the cell, or missing value if the cell is empty. */ formattedValue(): string; /** * The formula in the cell, as text, e.g. =SUM(40+2). If the cell does not contain a formula, returns missing value. To set the value of a cell to a formula as text, use the value property. */ formula(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A row of cells in a table */ export interface Row { /** * The row's index in the table (e.g., the second row has address 2). */ address(): number; /** * The height of the row. */ height(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A column of cells in a table */ export interface Column { /** * The column's index in the table (e.g., the second column has address 2). */ address(): number; /** * The width of the column. */ width(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A sheet in a document */ export interface Sheet { /** * The sheet's name. */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A styled document layout. */ export interface Template { /** * The identifier used by the application. */ id(): string; /** * The localized name displayed to the user. */ name(): string; } // CLass Extension /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The Numbers application. */ export interface Application {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The Numbers document. */ export interface Document { /** * Document ID. */ id(): string; /** * The template assigned to the document. */ documentTemplate(): any; /** * The active sheet. */ activeSheet(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface Table { /** * Whether the table is currently filtered. */ filtered(): boolean; /** * Whether header rows are frozen. */ headerRowsFrozen(): boolean; /** * Whether header columns are frozen. */ headerColumnsFrozen(): boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface Range {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface Row {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface Column {} // Records /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ExportOptions { /** * Whether to exclude a summary worksheet in Excel workbook. */ excludeSummaryWorksheet(): boolean; /** * Password. */ password(): string; /** * Password hint. */ passwordHint(): string; /** * Image quality. */ imageQuality(): any; } // Function options /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SetOptionalParameter { /** * The new value. */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MakeOptionalParameter { /** * The class of the new object. */ new: any; /** * The location at which to insert the object. */ at?: any; /** * The initial contents of the object. */ withData?: any; /** * The initial values for properties of the object. */ withProperties?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SortOptionalParameter { /** * The column to sort by. */ by: any; direction?: any; /** * Limit the sort to the specified rows. */ inRows?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ExportOptionalParameter { /** * the destination file */ to: any; /** * The format to use. */ as: any; /** * Optional export settings. */ withProperties?: any; } } export interface Numbers extends Numbers.Application { // Functions /** * Sets the value of the specified object(s). * @param directParameter undefined * @param option * */ set(directParameter: any, option?: Numbers.SetOptionalParameter): void; /** * Delete an object. * @param directParameter undefined * */ delete(directParameter: any, ): void; /** * Create a new object. * @param option * @return The new object. */ make(option?: Numbers.MakeOptionalParameter): any; /** * Clear the contents of a specified range of cells, including formatting and style. * @param directParameter undefined * */ clear(directParameter: Numbers.Range, ): void; /** * Merge a specified range of cells. * @param directParameter undefined * */ merge(directParameter: Numbers.Range, ): void; /** * Sort the rows of the table. * @param directParameter undefined * @param option * */ sort(directParameter: Numbers.Table, option?: Numbers.SortOptionalParameter): void; /** * Unmerge all merged cells in a specified range. * @param directParameter undefined * */ unmerge(directParameter: Numbers.Range, ): void; /** * Transpose the rows and columns of the table. * @param directParameter undefined * */ transpose(directParameter: Numbers.Table, ): void; /** * Export a document to another file * @param directParameter The document to export * @param option * */ export(directParameter: Numbers.Document, option?: Numbers.ExportOptionalParameter): void; /** * Add a column to the table after a specified range of cells. * @param directParameter undefined * @return A reference to the new column */ addColumnAfter(directParameter: Numbers.Range, ): any; /** * Add a column to the table before a specified range of cells. * @param directParameter undefined * @return A reference to the new column */ addColumnBefore(directParameter: Numbers.Range, ): any; /** * Add a row to the table below a specified range of cells. * @param directParameter undefined * @return A reference to the new row */ addRowAbove(directParameter: Numbers.Range, ): any; /** * Add a row to the table below a specified range of cells. * @param directParameter undefined * @return A reference to the new row */ addRowBelow(directParameter: Numbers.Range, ): any; /** * Remove specified rows or columns from a table. * @param directParameter undefined * */ remove(directParameter: Numbers.Range, ): void; }
the_stack
import utils = require('../lib/utils'); import { Compiler } from '../actions/Compiler'; import FileUtil = require('../lib/FileUtil'); import path = require('path'); import ts = require("../lib/typescript-plus/lib/typescript"); const ANY = 'any'; declare var global: any; class CompileEgretEngine implements egret.Command { private compiler: Compiler; public execute(): number { var code = 0; var options = egret.args; var manifest = egret.manifest; var penddings: egret.EgretModule[] = []; var currentPlatform: string, currentConfig: string; global.registerClass = manifest.registerClass; var outputDir = this.getModuleOutputPath(); this.compiler = new Compiler(); global.registerClass = manifest.registerClass; var configurations: egret.CompileConfiguration[] = [ { name: "debug", declaration: true }, { name: "release", minify: true } ]; let excludeList = [ FileUtil.escapePath(path.join(outputDir, "egretia-sdk")), FileUtil.escapePath(path.join(outputDir, "egret-facebook")), FileUtil.escapePath(path.join(outputDir, "promise")), FileUtil.escapePath(path.join(outputDir, "resourcemanager")), FileUtil.escapePath(path.join(outputDir, "assetsmanager")), FileUtil.escapePath(path.join(outputDir, "egret3d")), FileUtil.escapePath(path.join(outputDir, "egret-wasm")), FileUtil.escapePath(path.join(outputDir, "eui-wasm")), FileUtil.escapePath(path.join(outputDir, "dragonBones-wasm")), FileUtil.escapePath(path.join(outputDir, "game-wasm")), FileUtil.escapePath(path.join(outputDir, "wasm_libs")), FileUtil.escapePath(path.join(outputDir, "media")), FileUtil.escapePath(path.join(outputDir, "nest")), FileUtil.escapePath(path.join(outputDir, "res")), FileUtil.escapePath(path.join(outputDir, "dragonBones")) ]; utils.clean(outputDir, excludeList); for (let m of manifest.modules) { preduceSwanModule(m); listModuleFiles(m); for (let config of configurations) { for (let platform of manifest.platforms) { code = this.buildModule(m, platform, config); if (code != 0) { delSwanTemp(m); return code; } } } // break; delSwanTemp(m); } // this.hideInternalMethods(); return code; } private buildModule(m: egret.EgretModule, platform: egret.target.Info, configuration: egret.CompileConfiguration) { var name = m.name; var fileName = name; var options = egret.args; if (platform.name != ANY) { fileName += "." + platform.name; } if (configuration.minify) { fileName += ".min"; } var depends = m.dependencies.map(name => this.getModuleOutputPath(name, name + '.d.ts')); if (platform.name != ANY) { depends.push(this.getModuleOutputPath(m.name, name + '.d.ts')); } var outDir = this.getModuleOutputPath(null, null, m.outFile); var declareFile = this.getModuleOutputPath(m.name, fileName + ".d.ts", m.outFile); var singleFile = this.getModuleOutputPath(m.name, fileName + ".js", m.outFile); //var modFile = this.getModuleOutputPath(m.name, fileName + ".mod.js", m.outFile); var moduleRoot = FileUtil.joinPath(egret.root, m.root); if (!m.root) { return 0; } var tss: string[] = []; m.files.forEach((file) => { var path: string = null; var sourcePlatform: string = null, sourceConfig: string = null; if (typeof (file) == 'string') { path = file; } else { path = file.path; sourcePlatform = file.platform; sourceConfig = file.debug === true ? "debug" : file.debug === false ? "release" : null; } var platformOK = sourcePlatform == null && platform.name == ANY || sourcePlatform == platform.name; var configOK = sourceConfig == null || sourceConfig == configuration.name; if (platformOK && configOK) { tss.push(path); } }); if (tss.length == 0) return 0; tss = depends.concat(tss); var dts = platform.declaration && configuration.declaration; let tsconfig = path.join(egret.root, 'src/egret/'); let isPublish = configuration.name != "debug" let compileOptions: ts.CompilerOptions = this.compiler.parseTsconfig(tsconfig, isPublish).options; // com //make 使用引擎的配置,必须用下面的参数 compileOptions.declaration = dts; compileOptions.out = singleFile; compileOptions.emitReflection = true; var result = this.compiler.compile(compileOptions, tss); if (result.exitStatus != 0) { result.messages.forEach(m => console.log(m)); return result.exitStatus; } if (configuration.minify) { utils.minify(singleFile, singleFile); } return 0; } private getModuleOutputPath(m?: string, filePath: string = "", outFile: string = "build/") { var path = FileUtil.joinPath(egret.root, outFile); if (m) path += m + '/'; path += filePath; return path; } // private hideInternalMethods() { // return; // var tempDts: string[] = []; // global.ignoreDollar = true; // this.dtsFiles.forEach(d => { // var dts = d[0], depends = d[1]; // var tempDtsName = dts.replace(/\.d\.ts/, 'd.ts'); // var singleFile = dts.replace(/\.d\.ts/, 'd.js'); // FileUtil.copy(dts, tempDtsName); // var tss = depends.concat(tempDtsName); // var result = this.compiler.compile({ // args: egret.args, // def: true, // out: singleFile, // files: tss, // outDir: null // }); // if (result.messages && result.messages.length) { // result.messages.forEach(m => console.log(m)); // } // FileUtil.remove(singleFile); // FileUtil.remove(tempDtsName); // tempDts.push(tempDtsName.replace(/\.ts$/, '.d.ts')); // }); // this.dtsFiles.forEach(d => { // FileUtil.remove(d[0]); // }); // tempDts.forEach(d => { // var dts = d.replace(/d\.d\.ts$/, '.d.ts'); // FileUtil.copy(d, dts); // FileUtil.remove(d); // }) // global.ignoreDollar = false; // } } function listModuleFiles(m: egret.EgretModule) { var tsFiles = []; if (m.noOtherTs !== true) tsFiles = FileUtil.search(FileUtil.joinPath(egret.root, m.root), "ts"); var specFiles = {}; m.files.forEach((f, i) => { var fileName = typeof (f) == 'string' ? f : f.path; fileName = FileUtil.joinPath(m.root, fileName); fileName = FileUtil.joinPath(egret.root, fileName); if (f['path']) f['path'] = fileName; else m.files[i] = fileName; specFiles[fileName] = true; }); tsFiles.forEach(f => { if (!specFiles[f]) m.files.push(f); }); } function delSwanTemp(m) { if (m.name != "eui" || !m.sourceRoot) { return; } var pathBefore = FileUtil.joinPath(egret.root, m.root); FileUtil.remove(pathBefore); } function preduceSwanModule(m: egret.EgretModule) { if (m.name != "eui" || !m.sourceRoot) { return; } var replaces = [ ["Egret 2.4"], ["egret."], ["IEventEmitter", "IEventDispatcher"], ["EventEmitter", "EventDispatcher"], [".on(", ".addEventListener("], [".removeListener(", ".removeEventListener("], [".emit(", ".dispatchEvent("], [".emitWith(", ".dispatchEventWith("], [".hasListener(", ".hasEventListener("], [".emitTouchEvent(", ".dispatchTouchEvent("], [".BitmapData", ".Texture"], [".Sprite", ".DisplayObjectContainer"], [".TextInput", ".TextField"], [".ImageLoader", ".URLLoader"], [".HttpRequest", ".URLLoader"], ]; var tsFiles = []; if (m.noOtherTs !== true) tsFiles = FileUtil.search(FileUtil.joinPath(egret.root, m.sourceRoot), "ts"); var pathBefore = FileUtil.joinPath(egret.root, m.sourceRoot); for (var i = 0; i < tsFiles.length; i++) { var content = FileUtil.read(tsFiles[i]); var saveFile = FileUtil.joinPath(egret.root, m.root); var currenFile = tsFiles[i]; var resultFile = currenFile.slice(pathBefore.length, currenFile.length); saveFile += resultFile; for (var r = 0; r < replaces.length; r++) { if (!replaces[r]) { console.log("r = ", r); } content = replaceAll(content, replaces[r][0], replaces[r][1]); } FileUtil.save(saveFile, content); } } function replaceAll(content, search, replace) { var slen = search.length; var rlen = replace.length; for (var i = 0; i < content.length; i++) { if (content.slice(i, i + slen) == search) { content = content.slice(0, i) + replace + content.slice(i + slen, content.length); i += rlen - slen; } } return content; } function changeDefine(content, current, change) { var cuIF = "//if " + current; var chIF = "//if " + change; for (var i = 0; i < content.length; i++) { if (content.slice(i, i + cuIF.length) == cuIF) { content = content.slice(0, i) + "/*" + content.slice(i, content.length); i += 2; for (; i < content.length; i++) { if (content.slice(i, i + 9) == "//endif*/") { i++; break; } } } else if (content.slice(i, i + chIF.length) == chIF) { var before = content.slice(0, i - 2); var end = content.slice(i, content.length); content = before + end; i += 2; for (; i < content.length; i++) { if (content.slice(i, i + 9) == "//endif*/") { i++; break; } } } } return content; } export = CompileEgretEngine;
the_stack
import { TSError, isString, isEmpty, matchWildcard, } from '@terascope/utils'; import * as p from 'xlucene-parser'; import * as i from '@terascope/types'; import { UtilsTranslateQueryOptions } from './interfaces'; type WildCardQueryResults = i.WildcardQuery | i.MultiMatchQuery | i.QueryStringQuery; type TermQueryResults = | i.TermQuery | i.MatchQuery | i.MatchPhraseQuery | i.MultiMatchQuery type RangeQueryResults = | i.RangeQuery | i.MultiMatchQuery | undefined export function translateQuery( parser: p.Parser, options: UtilsTranslateQueryOptions ): i.ElasticsearchDSLResult { const { logger, type_config: typeConfig, variables } = options; let sort: i.AnyQuerySort|i.AnyQuerySort[]|undefined; function buildAnyQuery(node: p.Node): i.AnyQuery | undefined { // if no field and is wildcard if ( p.isWildcard(node) && !node.field && p.getFieldValue(node.value, variables) === '*' ) { return { bool: { filter: [], }, }; } if (p.isGroupLike(node)) { return buildBoolQuery(node); } if (p.isNegation(node)) { return buildNegationQuery(node); } if (p.isExists(node)) { return buildExistsQuery(node); } if (p.isTermType(node)) { const query = buildTermLevelQuery(node); if (query) return query; } const error = new TSError(`Unexpected problem when translating xlucene query ${parser.query}`, { context: { node, ast: parser.ast, }, }); logger.error(error); } function buildTermLevelQuery(node: p.TermLikeNode): i.AnyQuery | i.BoolQuery | undefined { if (p.isWildcardField(node)) { if (isEmpty(typeConfig)) { throw new Error( `Configuration for type_config needs to be provided with fields related to ${node.field}` ); } const should = Object.keys(typeConfig) .filter((field) => matchWildcard(node.field as string, field)) .map((field) => Object.assign({}, node, { field })) .map((newNode) => buildTermLevelQuery(newNode)) as i.AnyQuery[]; return { bool: { should } }; } if (p.isTerm(node)) { return buildTermQuery(node); } if (p.isRegexp(node)) { return buildRegExprQuery(node); } if (p.isWildcard(node)) { return buildWildcardQuery(node); } if (p.isRange(node)) { return buildRangeQuery(node); } if (p.isFunctionNode(node)) { const instance = p.initFunction({ node, variables, type_config: typeConfig }); const { query, sort: sortQuery } = instance.toElasticsearchQuery( getTermField(node), options ); // TODO: review how sort works in this module if (sortQuery != null) { if (!sort) { sort = sortQuery; } else if (Array.isArray(sort)) { sort.push(sortQuery); } else { sort = [sort, sortQuery]; } } return query; } } function buildMultiMatchQuery(node: p.TermLikeNode, query: string): i.MultiMatchQuery { const multiMatchQuery: i.MultiMatchQuery = { multi_match: { query, }, }; logger.trace('built multi-match query', { node, multiMatchQuery }); return multiMatchQuery; } function buildRangeQuery(node: p.Range): RangeQueryResults { if (isMultiMatch(node)) { if (!node.right) { return; } const leftValue = p.getFieldValue(node.left.value, variables); const query = `${node.left.operator}${leftValue}`; return buildMultiMatchQuery(node, query); } const field = getTermField(node); const rangeQuery: i.RangeQuery = { range: { [field]: p.parseRange(node, variables, true), }, }; logger.trace('built range query', { node, rangeQuery }); return rangeQuery; } function buildTermQuery(node: p.Term): TermQueryResults|undefined { const value = p.getFieldValue(node.value, variables, true); if (value == null) return; if (isMultiMatch(node)) { const query = `${value}`; return buildMultiMatchQuery(node, query); } const field = getTermField(node); if (isString(value) || node.analyzed) { const matchQuery: i.MatchQuery = { match: { [field]: { operator: 'and', query: value, }, }, }; logger.trace('built match query', { node, matchQuery }); return matchQuery; } const termQuery: i.TermQuery = { term: { [field]: value, }, }; logger.trace('built term query', { node, termQuery }); return termQuery; } function buildWildcardQuery(node: p.Wildcard): WildCardQueryResults|undefined { const value = p.getFieldValue(node.value, variables, true); if (value == null) return; if (isMultiMatch(node)) { const query = `${value}`; return buildMultiMatchQuery(node, query); } const field = getTermField(node); if (node.analyzed) { return { query_string: { fields: [field], query: value } }; } const wildcardQuery: i.WildcardQuery = { wildcard: { [field]: value, }, }; logger.trace('built wildcard query', { node, wildcardQuery }); return wildcardQuery; } function buildRegExprQuery( node: p.Regexp ): i.RegExprQuery|i.MultiMatchQuery|i.QueryStringQuery|undefined { const value = p.getFieldValue(node.value, variables, true); if (value == null) return; if (isMultiMatch(node)) { const query = `${value}`; return buildMultiMatchQuery(node, query); } const field = getTermField(node); if (node.analyzed) { return { query_string: { fields: [field], query: `/${value}/` } }; } const regexQuery: i.RegExprQuery = { regexp: { [field]: { value, flags: 'COMPLEMENT|EMPTY|INTERSECTION|INTERVAL' } }, }; logger.trace('built regexp query', { node, regexQuery }); return regexQuery; } function buildExistsQuery(node: p.Exists): i.ExistsQuery { const existsQuery: i.ExistsQuery = { exists: { field: node.field, }, }; logger.trace('built exists query', { node, existsQuery }); return existsQuery; } function buildBoolQuery(node: p.GroupLikeNode): i.BoolQuery|undefined { const should: i.AnyQuery[] = []; for (const conj of node.flow) { const query = buildConjunctionQuery(conj); should.push(...flattenQuery(query, 'should')); } if (!should.length) return; const boolQuery: i.BoolQuery = { bool: { should, }, }; logger.trace('built bool query', { node, boolQuery }); return boolQuery; } function buildConjunctionQuery(conj: p.Conjunction): i.BoolQuery|undefined { const filter: i.AnyQuery[] = []; for (const node of conj.nodes) { const query = buildAnyQuery(node); filter.push(...flattenQuery(query, 'filter')); } if (!filter.length) return; return { bool: { filter, }, }; } function buildNegationQuery(node: p.Negation): i.BoolQuery | undefined { const query = buildAnyQuery(node.node); if (!query) return; const mustNot = flattenQuery(query, 'must_not'); logger.trace('built negation query', mustNot, node); return { bool: { must_not: mustNot, }, }; } let topLevelQuery: i.MatchAllQuery|i.ConstantScoreQuery; if (p.isEmptyNode(parser.ast)) { topLevelQuery = { match_all: {}, }; } else { const anyQuery = buildAnyQuery(parser.ast); const filter = compactFinalQuery(anyQuery); topLevelQuery = { constant_score: { filter, } }; } if (!sort && options.default_geo_field && options.geo_sort_point) { sort = { _geo_distance: { order: options.geo_sort_order, unit: options.geo_sort_unit, [options.default_geo_field]: options.geo_sort_point, } }; } return { query: topLevelQuery, // avoid setting it to undefined ...(sort && { sort }) }; } export function isMultiMatch(node: p.TermLikeNode): boolean { return !node.field || node.field === '*'; } export function getTermField(node: p.TermLikeNode): string { return node.field!; } export function flattenQuery( query: i.AnyQuery | undefined, flattenTo: i.BoolQueryTypes ): i.AnyQuery[] { if (!query) return []; if (isBoolQuery(query) && canFlattenBoolQuery(query, flattenTo)) { return query.bool[flattenTo]!; } return [query]; } /** This prevents double nested queries that do the same thing */ export function canFlattenBoolQuery(query: i.BoolQuery, flattenTo: i.BoolQueryTypes): boolean { const types = Object.keys(query.bool); if (types.length !== 1) return false; return types[0] === flattenTo; } export function isBoolQuery(query: unknown): query is i.BoolQuery { if (!query || typeof query !== 'object') return false; return (query as any).bool != null; } export function compactFinalQuery(query?: i.AnyQuery): i.AnyQuery | i.AnyQuery[] { if (!query) return []; if (isBoolQuery(query) && canFlattenBoolQuery(query, 'filter')) { const filter = query.bool.filter!; if (!filter.length) return query; if (filter.length === 1) { return filter[0]; } return filter; } return query; }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace LuckyStar { namespace FormUser { interface tab_SUMMARY_TAB_Sections { onpremise_account_information: DevKit.Controls.Section; online_account_information: DevKit.Controls.Section; user_information: DevKit.Controls.Section; SOCIAL_PANE_TAB: DevKit.Controls.Section; teams_information: DevKit.Controls.Section; organization_information: DevKit.Controls.Section; queue_selection: DevKit.Controls.Section; queue_information: DevKit.Controls.Section; } interface tab_DETAILS_TAB_Sections { user_information_2: DevKit.Controls.Section; mailing_address: DevKit.Controls.Section; DirectReports: DevKit.Controls.Section; } interface tab_ADMINISTRATION_TAB_Sections { administration: DevKit.Controls.Section; e_mail_configuration: DevKit.Controls.Section; } interface tab_MobileOfflineProfile_TAB_Sections { mobileofflineaccessinfo: DevKit.Controls.Section; } interface tab_SUMMARY_TAB extends DevKit.Controls.ITab { Section: tab_SUMMARY_TAB_Sections; } interface tab_DETAILS_TAB extends DevKit.Controls.ITab { Section: tab_DETAILS_TAB_Sections; } interface tab_ADMINISTRATION_TAB extends DevKit.Controls.ITab { Section: tab_ADMINISTRATION_TAB_Sections; } interface tab_MobileOfflineProfile_TAB extends DevKit.Controls.ITab { Section: tab_MobileOfflineProfile_TAB_Sections; } interface Tabs { SUMMARY_TAB: tab_SUMMARY_TAB; DETAILS_TAB: tab_DETAILS_TAB; ADMINISTRATION_TAB: tab_ADMINISTRATION_TAB; MobileOfflineProfile_TAB: tab_MobileOfflineProfile_TAB; } interface Body { Tab: Tabs; notescontrol: DevKit.Controls.Note; /** Type of user. */ AccessMode: DevKit.Controls.OptionSet; /** Shows the complete primary address. */ Address1_Composite: DevKit.Controls.String; /** Fax number for address 1. */ Address1_Fax: DevKit.Controls.String; /** First telephone number associated with address 1. */ Address1_Telephone1: DevKit.Controls.String; /** Second telephone number associated with address 1. */ Address1_Telephone2: DevKit.Controls.String; /** Third telephone number associated with address 1. */ Address1_Telephone3: DevKit.Controls.String; /** Shows the complete secondary address. */ Address2_Composite: DevKit.Controls.String; /** Unique identifier of the business unit with which the user is associated. */ BusinessUnitId: DevKit.Controls.Lookup; /** License type of user. */ CALType: DevKit.Controls.OptionSet; /** Select the mailbox associated with this user. */ DefaultMailbox: DevKit.Controls.Lookup; /** Active Directory domain of which the user is a member. */ DomainName: DevKit.Controls.String; /** Full name of the user. */ FullName: DevKit.Controls.String; /** Home phone number for the user. */ HomePhone: DevKit.Controls.String; /** Internal email address for the user. */ InternalEMailAddress: DevKit.Controls.String; /** User invitation status. */ InviteStatusCode: DevKit.Controls.OptionSet; /** Mobile alert email address for the user. */ MobileAlertEMail: DevKit.Controls.String; /** Items contained with a particular SystemUser. */ MobileOfflineProfileId: DevKit.Controls.Lookup; /** Mobile phone number for the user. */ MobilePhone: DevKit.Controls.String; /** Unique identifier of the manager of the user. */ ParentSystemUserId: DevKit.Controls.Lookup; /** Personal email address of the user. */ PersonalEMailAddress: DevKit.Controls.String; /** User's position in hierarchical security model. */ PositionId: DevKit.Controls.Lookup; /** Preferred address for the user. */ PreferredAddressCode: DevKit.Controls.OptionSet; /** Preferred phone number for the user. */ PreferredPhoneCode: DevKit.Controls.OptionSet; /** Unique identifier of the default queue for the user. */ QueueId: DevKit.Controls.Lookup; /** Title of the user. */ Title: DevKit.Controls.String; /** Windows Live ID */ WindowsLiveID: DevKit.Controls.String; } interface Footer extends DevKit.Controls.IFooter { /** Information about whether the user is enabled. */ IsDisabled: DevKit.Controls.Boolean; } interface Grid { TeamsSubGrid: DevKit.Controls.Grid; PrivateQueuesSubGrid: DevKit.Controls.Grid; DirectReports: DevKit.Controls.Grid; } } class FormUser extends DevKit.IForm { /** * DynamicsCrm.DevKit form User * @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 User */ Body: LuckyStar.FormUser.Body; /** The Footer section of form User */ Footer: LuckyStar.FormUser.Footer; /** The Grid of form User */ Grid: LuckyStar.FormUser.Grid; } class SystemUserApi { /** * DynamicsCrm.DevKit SystemUserApi * @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; /** Type of user. */ AccessMode: DevKit.WebApi.OptionSetValue; /** Active Directory object GUID for the system user. */ ActiveDirectoryGuid: DevKit.WebApi.GuidValueReadonly; /** Unique identifier for address 1. */ Address1_AddressId: DevKit.WebApi.GuidValue; /** Type of address for address 1, such as billing, shipping, or primary address. */ Address1_AddressTypeCode: DevKit.WebApi.OptionSetValue; /** City name for address 1. */ Address1_City: DevKit.WebApi.StringValue; /** Shows the complete primary address. */ Address1_Composite: DevKit.WebApi.StringValueReadonly; /** Country/region name in address 1. */ Address1_Country: DevKit.WebApi.StringValue; /** County name for address 1. */ Address1_County: DevKit.WebApi.StringValue; /** Fax number for address 1. */ Address1_Fax: DevKit.WebApi.StringValue; /** Latitude for address 1. */ Address1_Latitude: DevKit.WebApi.DoubleValue; /** First line for entering address 1 information. */ Address1_Line1: DevKit.WebApi.StringValue; /** Second line for entering address 1 information. */ Address1_Line2: DevKit.WebApi.StringValue; /** Third line for entering address 1 information. */ Address1_Line3: DevKit.WebApi.StringValue; /** Longitude for address 1. */ Address1_Longitude: DevKit.WebApi.DoubleValue; /** Name to enter for address 1. */ Address1_Name: DevKit.WebApi.StringValue; /** ZIP Code or postal code for address 1. */ Address1_PostalCode: DevKit.WebApi.StringValue; /** Post office box number for address 1. */ Address1_PostOfficeBox: DevKit.WebApi.StringValue; /** Method of shipment for address 1. */ Address1_ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** State or province for address 1. */ Address1_StateOrProvince: DevKit.WebApi.StringValue; /** First telephone number associated with address 1. */ Address1_Telephone1: DevKit.WebApi.StringValue; /** Second telephone number associated with address 1. */ Address1_Telephone2: DevKit.WebApi.StringValue; /** Third telephone number associated with address 1. */ Address1_Telephone3: DevKit.WebApi.StringValue; /** United Parcel Service (UPS) zone for address 1. */ Address1_UPSZone: DevKit.WebApi.StringValue; /** UTC offset for address 1. This is the difference between local time and standard Coordinated Universal Time. */ Address1_UTCOffset: DevKit.WebApi.IntegerValue; /** Unique identifier for address 2. */ Address2_AddressId: DevKit.WebApi.GuidValue; /** Type of address for address 2, such as billing, shipping, or primary address. */ Address2_AddressTypeCode: DevKit.WebApi.OptionSetValue; /** City name for address 2. */ Address2_City: DevKit.WebApi.StringValue; /** Shows the complete secondary address. */ Address2_Composite: DevKit.WebApi.StringValueReadonly; /** Country/region name in address 2. */ Address2_Country: DevKit.WebApi.StringValue; /** County name for address 2. */ Address2_County: DevKit.WebApi.StringValue; /** Fax number for address 2. */ Address2_Fax: DevKit.WebApi.StringValue; /** Latitude for address 2. */ Address2_Latitude: DevKit.WebApi.DoubleValue; /** First line for entering address 2 information. */ Address2_Line1: DevKit.WebApi.StringValue; /** Second line for entering address 2 information. */ Address2_Line2: DevKit.WebApi.StringValue; /** Third line for entering address 2 information. */ Address2_Line3: DevKit.WebApi.StringValue; /** Longitude for address 2. */ Address2_Longitude: DevKit.WebApi.DoubleValue; /** Name to enter for address 2. */ Address2_Name: DevKit.WebApi.StringValue; /** ZIP Code or postal code for address 2. */ Address2_PostalCode: DevKit.WebApi.StringValue; /** Post office box number for address 2. */ Address2_PostOfficeBox: DevKit.WebApi.StringValue; /** Method of shipment for address 2. */ Address2_ShippingMethodCode: DevKit.WebApi.OptionSetValue; /** State or province for address 2. */ Address2_StateOrProvince: DevKit.WebApi.StringValue; /** First telephone number associated with address 2. */ Address2_Telephone1: DevKit.WebApi.StringValue; /** Second telephone number associated with address 2. */ Address2_Telephone2: DevKit.WebApi.StringValue; /** Third telephone number associated with address 2. */ Address2_Telephone3: DevKit.WebApi.StringValue; /** United Parcel Service (UPS) zone for address 2. */ Address2_UPSZone: DevKit.WebApi.StringValue; /** UTC offset for address 2. This is the difference between local time and standard Coordinated Universal Time. */ Address2_UTCOffset: DevKit.WebApi.IntegerValue; /** The identifier for the application. This is used to access data in another application. */ ApplicationId: DevKit.WebApi.GuidValue; /** The URI used as a unique logical identifier for the external app. This can be used to validate the application. */ ApplicationIdUri: DevKit.WebApi.StringValueReadonly; /** This is the application directory object Id. */ AzureActiveDirectoryObjectId: DevKit.WebApi.GuidValueReadonly; /** Unique identifier of the business unit with which the user is associated. */ BusinessUnitId: DevKit.WebApi.LookupValue; /** Fiscal calendar associated with the user. */ CalendarId: DevKit.WebApi.LookupValue; /** License type of user. */ CALType: DevKit.WebApi.OptionSetValue; /** Unique identifier of the user who created the user. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the user was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the systemuser. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Indicates if default outlook filters have been populated. */ DefaultFiltersPopulated: DevKit.WebApi.BooleanValueReadonly; /** Select the mailbox associated with this user. */ DefaultMailbox: DevKit.WebApi.LookupValueReadonly; /** Type a default folder name for the user's OneDrive For Business location. */ DefaultOdbFolderName: DevKit.WebApi.StringValueReadonly; /** Reason for disabling the user. */ DisabledReason: DevKit.WebApi.StringValueReadonly; /** Whether to display the user in service views. */ DisplayInServiceViews: DevKit.WebApi.BooleanValue; /** Active Directory domain of which the user is a member. */ DomainName: DevKit.WebApi.StringValue; /** Shows the status of the primary email address. */ EmailRouterAccessApproval: DevKit.WebApi.OptionSetValue; /** Employee identifier for the user. */ EmployeeId: DevKit.WebApi.StringValue; /** Shows the default image for the record. */ EntityImage: DevKit.WebApi.StringValue; EntityImage_Timestamp: DevKit.WebApi.BigIntValueReadonly; EntityImage_URL: DevKit.WebApi.StringValueReadonly; /** For internal use only. */ EntityImageId: DevKit.WebApi.GuidValueReadonly; /** Exchange rate for the currency associated with the systemuser with respect to the base currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** First name of the user. */ FirstName: DevKit.WebApi.StringValue; /** Full name of the user. */ FullName: DevKit.WebApi.StringValueReadonly; /** Government identifier for the user. */ GovernmentId: DevKit.WebApi.StringValue; /** Home phone number for the user. */ HomePhone: DevKit.WebApi.StringValue; /** For internal use only. */ IdentityId: DevKit.WebApi.IntegerValueReadonly; /** Unique identifier of the data import or data migration that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Incoming email delivery method for the user. */ IncomingEmailDeliveryMethod: DevKit.WebApi.OptionSetValue; /** Internal email address for the user. */ InternalEMailAddress: DevKit.WebApi.StringValue; /** User invitation status. */ InviteStatusCode: DevKit.WebApi.OptionSetValue; /** Information about whether the user is an AD user. */ IsActiveDirectoryUser: DevKit.WebApi.BooleanValueReadonly; /** Information about whether the user is enabled. */ IsDisabled: DevKit.WebApi.BooleanValue; /** Shows the status of approval of the email address by O365 Admin. */ IsEmailAddressApprovedByO365Admin: DevKit.WebApi.BooleanValueReadonly; /** Check if user is an integration user. */ IsIntegrationUser: DevKit.WebApi.BooleanValue; /** Information about whether the user is licensed. */ IsLicensed: DevKit.WebApi.BooleanValue; /** Information about whether the user is synced with the directory. */ IsSyncWithDirectory: DevKit.WebApi.BooleanValue; /** Job title of the user. */ JobTitle: DevKit.WebApi.StringValue; /** Last name of the user. */ LastName: DevKit.WebApi.StringValue; /** Time stamp of the latest update for the user */ LatestUpdateTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Middle name of the user. */ MiddleName: DevKit.WebApi.StringValue; /** Mobile alert email address for the user. */ MobileAlertEMail: DevKit.WebApi.StringValue; /** Items contained with a particular SystemUser. */ MobileOfflineProfileId: DevKit.WebApi.LookupValue; /** Mobile phone number for the user. */ MobilePhone: DevKit.WebApi.StringValue; /** Unique identifier of the user who last modified the user. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the user was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the systemuser. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Nickname of the user. */ NickName: DevKit.WebApi.StringValue; /** Unique identifier of the organization associated with the user. */ OrganizationId: DevKit.WebApi.GuidValueReadonly; /** Outgoing email delivery method for the user. */ OutgoingEmailDeliveryMethod: DevKit.WebApi.OptionSetValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Unique identifier of the manager of the user. */ ParentSystemUserId: DevKit.WebApi.LookupValue; /** For internal use only. */ PassportHi: DevKit.WebApi.IntegerValue; /** For internal use only. */ PassportLo: DevKit.WebApi.IntegerValue; /** Personal email address of the user. */ PersonalEMailAddress: DevKit.WebApi.StringValue; /** URL for the Website on which a photo of the user is located. */ PhotoUrl: DevKit.WebApi.StringValue; /** User's position in hierarchical security model. */ PositionId: DevKit.WebApi.LookupValue; /** Preferred address for the user. */ PreferredAddressCode: DevKit.WebApi.OptionSetValue; /** Preferred email address for the user. */ PreferredEmailCode: DevKit.WebApi.OptionSetValue; /** Preferred phone number for the user. */ PreferredPhoneCode: DevKit.WebApi.OptionSetValue; /** Shows the ID of the process. */ ProcessId: DevKit.WebApi.GuidValue; /** Unique identifier of the default queue for the user. */ QueueId: DevKit.WebApi.LookupValue; /** Salutation for correspondence with the user. */ Salutation: DevKit.WebApi.StringValue; /** Check if user is a setup user. */ SetupUser: DevKit.WebApi.BooleanValue; /** SharePoint Work Email Address */ SharePointEmailAddress: DevKit.WebApi.StringValue; /** Skill set of the user. */ Skills: DevKit.WebApi.StringValue; /** Shows the ID of the stage. */ StageId: DevKit.WebApi.GuidValue; /** Unique identifier for the user. */ SystemUserId: DevKit.WebApi.GuidValue; /** Unique identifier of the territory to which the user is assigned. */ TerritoryId: DevKit.WebApi.LookupValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Title of the user. */ Title: DevKit.WebApi.StringValue; /** Unique identifier of the currency associated with the systemuser. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** For internal use only. */ TraversedPath: DevKit.WebApi.StringValue; /** Shows the type of user license. */ UserLicenseType: DevKit.WebApi.IntegerValue; /** User PUID User Identifiable Information */ UserPuid: DevKit.WebApi.StringValueReadonly; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version number of the user. */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** Windows Live ID */ WindowsLiveID: DevKit.WebApi.StringValue; /** User's Yammer login email address */ YammerEmailAddress: DevKit.WebApi.StringValue; /** User's Yammer ID */ YammerUserId: DevKit.WebApi.StringValue; /** Pronunciation of the first name of the user, written in phonetic hiragana or katakana characters. */ YomiFirstName: DevKit.WebApi.StringValue; /** Pronunciation of the full name of the user, written in phonetic hiragana or katakana characters. */ YomiFullName: DevKit.WebApi.StringValueReadonly; /** Pronunciation of the last name of the user, written in phonetic hiragana or katakana characters. */ YomiLastName: DevKit.WebApi.StringValue; /** Pronunciation of the middle name of the user, written in phonetic hiragana or katakana characters. */ YomiMiddleName: DevKit.WebApi.StringValue; } } declare namespace OptionSet { namespace SystemUser { enum AccessMode { /** 1 */ Administrative, /** 5 */ Delegated_Admin, /** 4 */ Non_interactive, /** 2 */ Read, /** 0 */ Read_Write, /** 3 */ Support_User } enum Address1_AddressTypeCode { /** 1 */ Default_Value } enum Address1_ShippingMethodCode { /** 1 */ Default_Value } enum Address2_AddressTypeCode { /** 1 */ Default_Value } enum Address2_ShippingMethodCode { /** 1 */ Default_Value } enum CALType { /** 1 */ Administrative, /** 2 */ Basic, /** 4 */ Device_Basic, /** 8 */ Device_Enterprise, /** 6 */ Device_Essential, /** 3 */ Device_Professional, /** 7 */ Enterprise, /** 5 */ Essential, /** 11 */ Field_Service, /** 0 */ Professional, /** 12 */ Project_Service, /** 9 */ Sales, /** 10 */ Service } enum EmailRouterAccessApproval { /** 1 */ Approved, /** 0 */ Empty, /** 2 */ Pending_Approval, /** 3 */ Rejected } enum IncomingEmailDeliveryMethod { /** 3 */ Forward_Mailbox, /** 1 */ Microsoft_Dynamics_365_for_Outlook, /** 0 */ None, /** 2 */ Server_Side_Synchronization_or_Email_Router } enum InviteStatusCode { /** 4 */ Invitation_Accepted, /** 3 */ Invitation_Expired, /** 2 */ Invitation_Near_Expired, /** 0 */ Invitation_Not_Sent, /** 5 */ Invitation_Rejected, /** 6 */ Invitation_Revoked, /** 1 */ Invited } enum OutgoingEmailDeliveryMethod { /** 1 */ Microsoft_Dynamics_365_for_Outlook, /** 0 */ None, /** 2 */ Server_Side_Synchronization_or_Email_Router } enum PreferredAddressCode { /** 1 */ Mailing_Address, /** 2 */ Other_Address } enum PreferredEmailCode { /** 1 */ Default_Value } enum PreferredPhoneCode { /** 3 */ Home_Phone, /** 1 */ Main_Phone, /** 4 */ Mobile_Phone, /** 2 */ Other_Phone } 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':['User'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.10.31','JsFormVersion':'v2'}
the_stack
import * as ts from 'typescript' import {resolve, relative} from 'path' import { existsSync, readFileSync, readdirSync, writeFileSync, watchFile, } from 'fs' import {JsonOutput} from './types' import {jsonOutputToAnnotatedFile} from './generateFile' const WATCH_CHANGES = true const WATCH_GENERATED = true const primeTargetDir = 'generated' const debugTargetDir = 'gen2' const currentTargetDir = primeTargetDir /** dir with generated tests */ const OUTPUT_DIR = resolve( __dirname, '..', '..', '..', '__tests__', 'effector', currentTargetDir, ) const TS_CONFIG_PATH = resolve(__dirname, '..', '..', 'tsconfig.json') const tsConfigRaw: any = { compilerOptions: { strictNullChecks: true, module: 'CommonJS', target: 'esnext', jsx: 'react', allowJs: true, strict: true, allowSyntheticDefaultImports: true, moduleResolution: 'node', resolveJsonModule: true, lib: ['esnext', 'es2019'], baseUrl: './', paths: { effector: ['packages/effector/index.d.ts'], }, }, exclude: [], } //JSON.parse(readFileSync(TS_CONFIG_PATH, 'utf8')) const REPO_ROOT = resolve(__dirname, '..', '..', '..', '..', '..') const EFFECTOR_TYPES = resolve(REPO_ROOT, 'packages', 'effector', 'index.d.ts') const EFFECTOR_PACKAGE = resolve( REPO_ROOT, 'packages', 'effector', 'package.json', ) const REPO_NODE_MODULES = resolve(REPO_ROOT, 'node_modules') const JEST_TYPES_DIR = resolve(REPO_ROOT, 'node_modules', '@types', 'jest') const JEST_TYPES_FILE = resolve( REPO_ROOT, 'node_modules', '@types', 'jest', 'index.d.ts', ) const jestTypes = readFileSync(JEST_TYPES_FILE, 'utf8') const tsConfig = (() => { const result: any = {} const config = tsConfigRaw.compilerOptions function getResultValue(field: string, value: any) { switch (field) { case 'module': switch (value) { case 'ESNext': return ts.ModuleKind.ESNext case 'CommonJS': /** WARN option change */ return ts.ModuleKind.ESNext // return ts.ModuleKind.CommonJS default: notImplemented() } case 'target': switch (value) { case 'esnext': return ts.ScriptTarget.ESNext case 'ES5': return ts.ScriptTarget.ES5 default: notImplemented() } case 'moduleResolution': switch (value) { case 'node': return ts.ModuleResolutionKind.NodeJs default: notImplemented() } case 'lib': return value.map((lib: string) => `lib.${lib}.d.ts`) case 'jsx': default: return value } } for (const field in config) { result[field] = getResultValue(field, config[field]) } return result function notImplemented() { throw Error('not implemented') } })() function watchVirtual() { const TEST_FILE = 'virtual.test.ts' const TEST_FILE_PATH = resolve(REPO_ROOT, TEST_FILE) const REAL_JSON = resolve(__dirname, '..', '..', '..', 'jsonOutput.json') const fileList = [ { file: TEST_FILE, path: TEST_FILE_PATH, version: 0, }, { file: 'effector', path: EFFECTOR_TYPES, version: 0, }, ] let annots: { fromLine: number toLine: number group: number caseItem: number }[] = [] let jsonOut: JsonOutput let ouptutContent: string = '' const services = ts.createLanguageService( { getScriptFileNames: () => [TEST_FILE], getScriptVersion(fileName) { const absolutePath = resolve(REPO_ROOT, fileName) const record = fileList.find(e => e.path === absolutePath) if (!record) { return '0' } return record.version.toString() }, getScriptSnapshot(fileNameShort) { const isVirtual = fileNameShort === TEST_FILE const fileName = resolve(REPO_ROOT, fileNameShort) if (!isVirtual && !existsSync(fileName)) { // console.error('no file', fileName) return undefined } let rawContent: string if (isVirtual) { const jsonOutput: JsonOutput = JSON.parse( readFileSync(REAL_JSON, 'utf8'), ) jsonOut = jsonOutput const {file, annotations} = jsonOutputToAnnotatedFile(jsonOutput) annots = annotations rawContent = file ouptutContent = file writeFileSync(resolve(__dirname, '..', '..', 'out.gen.ts'), file) } else { rawContent = readFileSync(fileName, 'utf8') } if (fileNameShort.includes('/lib.')) return ts.ScriptSnapshot.fromString(rawContent) const content = [ // `/// <reference path="../../../../../node_modules/@types/jest/index.d.ts" />`, rawContent // .replace(/'effector'/gm, `'../../../../../packages/effector'`) .replace(/\@ts\-expect\-error/gm, ''), ].join(`\n`) return ts.ScriptSnapshot.fromString(content) }, getCurrentDirectory: () => REPO_ROOT, getCompilationSettings: () => tsConfig, getDefaultLibFileName(options: ts.CompilerOptions) { return ts.getDefaultLibFilePath(options) }, fileExists(path) { if ( path === JEST_TYPES_FILE || path === EFFECTOR_PACKAGE || TEST_FILE_PATH ) return true if (fileList.some(e => e.path === path)) return true // if (path.includes('node_modules') || path.includes('package.json')) // return false return ts.sys.fileExists(path) }, readFile(path, encoding) { if (path === JEST_TYPES_FILE) return jestTypes if (path === TEST_FILE_PATH) return ouptutContent const result = ts.sys.readFile(path, encoding) return result }, readDirectory(path, extension, exclude, include, depth) { console.log('readDirectory', {path, extension, exclude, include, depth}) return ts.sys.readDirectory(path, extension, exclude, include, depth) }, directoryExists(name) { if (name === JEST_TYPES_DIR) return true if (name.includes('node_modules')) return false return ts.sys.directoryExists(name) }, getDirectories(path) { console.log('getDirectories', path) return ts.sys.getDirectories(path) }, // resolveModuleNames, // isKnownTypesPackageName(name) { // console.log('isKnownTypesPackageName', name) // if (name === 'effector') return true // return false // }, }, ts.createDocumentRegistry(), ) logErrors(TEST_FILE_PATH, TEST_FILE) if (WATCH_GENERATED) { watchFile( TEST_FILE_PATH, {persistent: true, interval: 250}, (curr, prev) => { if (+curr.mtime <= +prev.mtime) { return } const item = fileList.find(e => e.path === TEST_FILE_PATH)! try { item.version++ } catch (err) { console.error(err) } logErrors(TEST_FILE_PATH, TEST_FILE) }, ) } function logErrors(fileName: string, fileNameShort: string) { const allDiagnostics = services .getCompilerOptionsDiagnostics() .concat(services.getSyntacticDiagnostics(fileName)) .concat(services.getSemanticDiagnostics(fileName)) allDiagnostics.forEach(diagnostic => { const message = ts.flattenDiagnosticMessageText( diagnostic.messageText, '\n', ) if (message.includes(`Unused '@ts-expect-error' directive.`)) return if (message.includes(`implicitly has an 'any' type`)) return if (diagnostic.file) { /** added lines for library reference */ const CHANGED_FILE_OFFSET = 0 const {line, character} = diagnostic.file.getLineAndCharacterOfPosition( diagnostic.start!, ) const lineReal = line + 1 - CHANGED_FILE_OFFSET const annot = annots.find( ann => ann.fromLine <= lineReal && ann.toLine >= lineReal, )! if (annot) { const result = jsonOut.groups[annot.group].caseItems[annot.caseItem] if (result.pass) { console.warn('unexpected error in case', result) console.log( `TS${diagnostic.code}(${lineReal},${character + 1}): ${message}`, ) } } else { console.log( `TS${diagnostic.code} ${ diagnostic.file.fileName } (${lineReal},${character + 1}): ${message}`, ) } } else { console.log(`TS${diagnostic.code} ${message}`) } // console.log(diagnostic) }) if (allDiagnostics.length === 0) { console.log(`no errors in file ${fileNameShort}`) } } } function createWatcher() { function watch(rootFileNames: string[]) { const servicesHost: ts.LanguageServiceHost = { getScriptFileNames: () => rootFileNames, getScriptVersion(fileName) { const absolutePath = resolve(OUTPUT_DIR, fileName) const record = fileList.find(e => e.path === absolutePath) if (!record) { return '0' } return record.version.toString() }, getScriptSnapshot(fileNameShort) { const fileName = resolve(OUTPUT_DIR, fileNameShort) if (!existsSync(fileName)) { // console.error('no file', fileName) return undefined } const rawContent = readFileSync(fileName, 'utf8') if (fileNameShort.includes('/lib.')) return ts.ScriptSnapshot.fromString(rawContent) const content = [ `/// <reference path="../../../../../node_modules/@types/jest/index.d.ts" />`, rawContent // .replace(/'effector'/gm, `'../../../../../packages/effector'`) .replace(/\@ts\-expect\-error/gm, ''), ].join(`\n`) return ts.ScriptSnapshot.fromString(content) }, getCurrentDirectory: () => OUTPUT_DIR, getCompilationSettings: () => tsConfig, getDefaultLibFileName(options: ts.CompilerOptions) { return ts.getDefaultLibFilePath(options) }, fileExists(path) { if (path === JEST_TYPES_FILE || path === EFFECTOR_PACKAGE) return true if (fileList.some(e => e.path === path)) return true if (path.includes('node_modules') || path.includes('package.json')) return false return ts.sys.fileExists(path) }, readFile(path, encoding) { if (path === JEST_TYPES_FILE) return jestTypes const result = ts.sys.readFile(path, encoding) return result }, readDirectory(path, extension, exclude, include, depth) { console.log('readDirectory', {path, extension, exclude, include, depth}) return ts.sys.readDirectory(path, extension, exclude, include, depth) }, directoryExists(name) { if (name === JEST_TYPES_DIR) return true if (name.includes('node_modules')) return false return ts.sys.directoryExists(name) }, getDirectories(path) { console.log('getDirectories', path) return ts.sys.getDirectories(path) }, // resolveModuleNames, // isKnownTypesPackageName(name) { // console.log('isKnownTypesPackageName', name) // if (name === 'effector') return true // return false // }, } const services = ts.createLanguageService( servicesHost, ts.createDocumentRegistry(), ) rootFileNames.forEach(fileNameShort => { const fileName = resolve(OUTPUT_DIR, fileNameShort) logErrors(fileName, fileNameShort) if (WATCH_CHANGES) { watchFile(fileName, {persistent: true, interval: 250}, (curr, prev) => { if (+curr.mtime <= +prev.mtime) { return } const item = fileList.find(e => e.path === fileName)! try { item.version++ } catch (err) { console.error(err) } logErrors(fileName, fileNameShort) }) } }) function logErrors(fileName: string, fileNameShort: string) { const allDiagnostics = services .getCompilerOptionsDiagnostics() .concat(services.getSyntacticDiagnostics(fileName)) .concat(services.getSemanticDiagnostics(fileName)) allDiagnostics.forEach(diagnostic => { const message = ts.flattenDiagnosticMessageText( diagnostic.messageText, '\n', ) if (message.includes(`Unused '@ts-expect-error' directive.`)) return if (message.includes(`implicitly has an 'any' type`)) return if (diagnostic.file) { /** added lines for library reference */ const CHANGED_FILE_OFFSET = 1 const { line, character, } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!) console.log( `TS${diagnostic.code} ${diagnostic.file.fileName} (${line + 1 - CHANGED_FILE_OFFSET},${character + 1}): ${message}`, ) } else { console.log(`TS${diagnostic.code} ${message}`) } // console.log(diagnostic) }) if (allDiagnostics.length === 0) { console.log(`no errors in file ${fileNameShort}`) } } } const currentDirectoryFiles = readdirSync(OUTPUT_DIR).filter( fileName => fileName.length >= 3 && fileName.substr(fileName.length - 3, 3) === '.ts', ) console.log('currentDirectoryFiles', currentDirectoryFiles) const fileList = currentDirectoryFiles.map(fileNameShort => { const fileName = resolve(OUTPUT_DIR, fileNameShort) // const content = readFileSync(fileName, 'utf8') return { file: fileNameShort, path: fileName, // content, version: 0, } }) fileList.push({ file: 'effector', path: EFFECTOR_TYPES, // content: readFileSync(EFFECTOR_TYPES, 'utf8'), version: 0, }) // Start the watcher watch(currentDirectoryFiles) } // createWatcher() watchVirtual()
the_stack
// ==================================================== // GraphQL fragment: ChannelContentsConnectable // ==================================================== export interface ChannelContentsConnectable_Attachment_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Attachment_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Attachment_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelContentsConnectable_Attachment_connection { __typename: "Connection"; created_at: string | null; user: ChannelContentsConnectable_Attachment_connection_user | null; can: ChannelContentsConnectable_Attachment_connection_can | null; } export interface ChannelContentsConnectable_Attachment_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelContentsConnectable_Attachment_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelContentsConnectable_Attachment_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelContentsConnectable_Attachment { __typename: "Attachment"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelContentsConnectable_Attachment_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelContentsConnectable_Attachment_connection | null; source: ChannelContentsConnectable_Attachment_source | null; counts: ChannelContentsConnectable_Attachment_counts | null; src: string | null; src_1x: string | null; src_2x: string | null; src_3x: string | null; file_extension: string | null; can: ChannelContentsConnectable_Attachment_can | null; } export interface ChannelContentsConnectable_Embed_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Embed_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Embed_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelContentsConnectable_Embed_connection { __typename: "Connection"; created_at: string | null; user: ChannelContentsConnectable_Embed_connection_user | null; can: ChannelContentsConnectable_Embed_connection_can | null; } export interface ChannelContentsConnectable_Embed_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelContentsConnectable_Embed_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelContentsConnectable_Embed_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelContentsConnectable_Embed { __typename: "Embed"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelContentsConnectable_Embed_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelContentsConnectable_Embed_connection | null; source: ChannelContentsConnectable_Embed_source | null; counts: ChannelContentsConnectable_Embed_counts | null; src: string | null; src_1x: string | null; src_2x: string | null; src_3x: string | null; can: ChannelContentsConnectable_Embed_can | null; } export interface ChannelContentsConnectable_Image_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Image_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Image_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelContentsConnectable_Image_connection { __typename: "Connection"; created_at: string | null; user: ChannelContentsConnectable_Image_connection_user | null; can: ChannelContentsConnectable_Image_connection_can | null; } export interface ChannelContentsConnectable_Image_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelContentsConnectable_Image_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelContentsConnectable_Image_original_dimensions { __typename: "Dimensions"; width: number | null; height: number | null; } export interface ChannelContentsConnectable_Image_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelContentsConnectable_Image { __typename: "Image"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelContentsConnectable_Image_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelContentsConnectable_Image_connection | null; source: ChannelContentsConnectable_Image_source | null; counts: ChannelContentsConnectable_Image_counts | null; src: string | null; src_1x: string | null; src_2x: string | null; src_3x: string | null; original_dimensions: ChannelContentsConnectable_Image_original_dimensions | null; can: ChannelContentsConnectable_Image_can | null; find_original_url: string | null; } export interface ChannelContentsConnectable_Link_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Link_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Link_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelContentsConnectable_Link_connection { __typename: "Connection"; created_at: string | null; user: ChannelContentsConnectable_Link_connection_user | null; can: ChannelContentsConnectable_Link_connection_can | null; } export interface ChannelContentsConnectable_Link_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelContentsConnectable_Link_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelContentsConnectable_Link_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelContentsConnectable_Link { __typename: "Link"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelContentsConnectable_Link_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelContentsConnectable_Link_connection | null; source: ChannelContentsConnectable_Link_source | null; counts: ChannelContentsConnectable_Link_counts | null; src: string | null; src_1x: string | null; src_2x: string | null; src_3x: string | null; external_url: string | null; can: ChannelContentsConnectable_Link_can | null; } export interface ChannelContentsConnectable_PendingBlock_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_PendingBlock_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_PendingBlock_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelContentsConnectable_PendingBlock_connection { __typename: "Connection"; created_at: string | null; user: ChannelContentsConnectable_PendingBlock_connection_user | null; can: ChannelContentsConnectable_PendingBlock_connection_can | null; } export interface ChannelContentsConnectable_PendingBlock_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelContentsConnectable_PendingBlock_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelContentsConnectable_PendingBlock_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelContentsConnectable_PendingBlock { __typename: "PendingBlock"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelContentsConnectable_PendingBlock_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelContentsConnectable_PendingBlock_connection | null; source: ChannelContentsConnectable_PendingBlock_source | null; counts: ChannelContentsConnectable_PendingBlock_counts | null; can: ChannelContentsConnectable_PendingBlock_can | null; } export interface ChannelContentsConnectable_Text_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Text_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Text_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelContentsConnectable_Text_connection { __typename: "Connection"; created_at: string | null; user: ChannelContentsConnectable_Text_connection_user | null; can: ChannelContentsConnectable_Text_connection_can | null; } export interface ChannelContentsConnectable_Text_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelContentsConnectable_Text_counts { __typename: "BlockCounts"; comments: number | null; } export interface ChannelContentsConnectable_Text_can { __typename: "BlockCan"; mute: boolean | null; remove: boolean | null; manage: boolean | null; } export interface ChannelContentsConnectable_Text { __typename: "Text"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelContentsConnectable_Text_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelContentsConnectable_Text_connection | null; source: ChannelContentsConnectable_Text_source | null; counts: ChannelContentsConnectable_Text_counts | null; content: string; can: ChannelContentsConnectable_Text_can | null; } export interface ChannelContentsConnectable_Channel_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Channel_connection_user { __typename: "User"; id: number; name: string; } export interface ChannelContentsConnectable_Channel_connection_can { __typename: "ConnectionCan"; destroy: boolean | null; } export interface ChannelContentsConnectable_Channel_connection { __typename: "Connection"; created_at: string | null; user: ChannelContentsConnectable_Channel_connection_user | null; can: ChannelContentsConnectable_Channel_connection_can | null; } export interface ChannelContentsConnectable_Channel_source { __typename: "ConnectableSource"; url: string | null; } export interface ChannelContentsConnectable_Channel_counts { __typename: "ChannelCounts"; contents: number | null; } export interface ChannelContentsConnectable_Channel_owner_Group { __typename: "Group"; id: number; name: string; visibility: string; } export interface ChannelContentsConnectable_Channel_owner_User { __typename: "User"; id: number; name: string; } export type ChannelContentsConnectable_Channel_owner = ChannelContentsConnectable_Channel_owner_Group | ChannelContentsConnectable_Channel_owner_User; export interface ChannelContentsConnectable_Channel_can { __typename: "ChannelCan"; mute: boolean | null; } export interface ChannelContentsConnectable_Channel { __typename: "Channel"; id: number; href: string | null; updated_at: string | null; title: string; user: ChannelContentsConnectable_Channel_user | null; /** * Returns the outer channel if we are inside of one */ connection: ChannelContentsConnectable_Channel_connection | null; source: ChannelContentsConnectable_Channel_source | null; truncatedTitle: string; visibility: string; counts: ChannelContentsConnectable_Channel_counts | null; owner: ChannelContentsConnectable_Channel_owner; label: string; can: ChannelContentsConnectable_Channel_can | null; } export type ChannelContentsConnectable = ChannelContentsConnectable_Attachment | ChannelContentsConnectable_Embed | ChannelContentsConnectable_Image | ChannelContentsConnectable_Link | ChannelContentsConnectable_PendingBlock | ChannelContentsConnectable_Text | ChannelContentsConnectable_Channel;
the_stack
import { expect, test } from '@jest/globals'; import { stringifyResolvedType, stringifyShortResolvedType, stringifyType, Type } from '../src/reflection/type'; import { reflect, typeOf } from '../src/reflection/reflection'; import { deserializeType, serializeType } from '../src/type-serialization'; test('stringifyType basic', () => { expect(stringifyResolvedType(typeOf<string>())).toBe('string'); expect(stringifyResolvedType(typeOf<number>())).toBe('number'); expect(stringifyResolvedType(typeOf<Date>())).toBe('Date'); }); test('stringifyType union', () => { expect(stringifyResolvedType(typeOf<string | number>())).toBe('string | number'); }); test('stringifyType object', () => { expect(stringifyResolvedType(typeOf<{ a: string }>())).toBe('{a: string}'); expect(stringifyResolvedType(typeOf<{ a: string, b: number }>())).toBe('{\n a: string;\n b: number;\n}'); expect(stringifyResolvedType(typeOf<{ a: string, b: number, c: boolean }>())).toBe('{\n a: string;\n b: number;\n c: boolean;\n}'); expect(stringifyResolvedType(typeOf<{ a: string, b: number, c: { d: string } }>())).toBe('{\n a: string;\n b: number;\n c: {d: string};\n}'); expect(stringifyResolvedType(typeOf<{ a: string, b: number, c: { d: string, e: number } }>())).toBe('{\n a: string;\n b: number;\n c: {\n d: string;\n e: number;\n };\n}'); expect(stringifyResolvedType(typeOf<{ a: string, b: number, c: { d: string, e: number, f: boolean } }>())).toBe(`{ a: string; b: number; c: { d: string; e: number; f: boolean; }; }`); }); test('stringifyType array', () => { expect(stringifyResolvedType(typeOf<string[]>())).toBe('Array<string>'); expect(stringifyResolvedType(typeOf<(string | number)[]>())).toBe('Array<string | number>'); expect(stringifyResolvedType(typeOf<(string | number)[][]>())).toBe('Array<Array<string | number>>'); }); test('stringifyType tuple', () => { expect(stringifyResolvedType(typeOf<[string]>())).toBe('[string]'); expect(stringifyResolvedType(typeOf<[string, number]>())).toBe('[string, number]'); expect(stringifyResolvedType(typeOf<[string, number?]>())).toBe('[string, number?]'); expect(stringifyResolvedType(typeOf<[a: string, b: number]>())).toBe('[a: string, b: number]'); expect(stringifyResolvedType(typeOf<[a: string, b?: number]>())).toBe('[a: string, b?: number]'); expect(stringifyResolvedType(typeOf<[string, number[]]>())).toBe('[string, Array<number>]'); expect(stringifyResolvedType(typeOf<[...number[]]>())).toBe('[...number[]]'); expect(stringifyResolvedType(typeOf<[...numbers: number[]]>())).toBe('[...numbers: number[]]'); }); test('stringifyType function', () => { expect(stringifyResolvedType(typeOf<() => void>())).toBe('() => void'); expect(stringifyResolvedType(typeOf<(a: string) => void>())).toBe('(a: string) => void'); expect(stringifyResolvedType(typeOf<(a: string, b: number) => void>())).toBe('(a: string, b: number) => void'); expect(stringifyResolvedType(typeOf<(a: string, b?: number) => void>())).toBe('(a: string, b?: number) => void'); expect(stringifyResolvedType(typeOf<(...a: string[]) => void>())).toBe('(...a: string[]) => void'); }); test('stringifyType index signature', () => { expect(stringifyResolvedType(typeOf<{ [name: string]: boolean }>())).toBe('{[index: string]: boolean}'); expect(stringifyResolvedType(typeOf<{ a: boolean, [name: string]: boolean }>())).toBe(`{ a: boolean; [index: string]: boolean; }`); }); test('stringifyType method signature', () => { expect(stringifyResolvedType(typeOf<{ a(): void }>())).toBe('{a(): void}'); expect(stringifyResolvedType(typeOf<{ a(b: string): void }>())).toBe('{a(b: string): void}'); expect(stringifyResolvedType(typeOf<{ a(b: string): void, b: string }>())).toBe(`{ a(b: string): void; b: string; }`); }); test('stringifyType methods', () => { class A { a(): void { } } class B { a(b: string): void { } } class C { a(b: string): void { } b: string = ''; } expect(stringifyResolvedType(typeOf<A>())).toBe('A {a(): void}'); expect(stringifyResolvedType(typeOf<B>())).toBe('B {a(b: string): void}'); expect(stringifyResolvedType(typeOf<C>())).toBe(`C { a(b: string): void; b: string; }`); expect(stringifyType(typeOf<C>(), { showFullDefinition: true, defaultIsOptional: true })).toBe(`C { a(b: string): void; b?: string; }`); }); test('stringifyType template literal', () => { expect(stringifyType(typeOf<`a${string}`>())).toBe('`a${string}`'); expect(stringifyType(typeOf<`a${number}and${string}`>())).toBe('`a${number}and${string}`'); }); test('stringifyType class generics', () => { class A<T> { a!: T; } expect(stringifyResolvedType(typeOf<A<string>>())).toBe('A {a: string}'); expect(stringifyResolvedType(typeOf<A<string | number>>())).toBe('A {a: string | number}'); expect(stringifyShortResolvedType(typeOf<A<string>>())).toBe('A<string>'); expect(stringifyShortResolvedType(typeOf<A<string | number>>())).toBe('A<string | number>'); }); test('stringifyType recursive', () => { interface User { id: number; /** * @description the user */ admin: User; } expect(stringifyResolvedType(typeOf<User>())).toBe(`User { id: number; admin: User; }`); expect(stringifyType(typeOf<User>(), { showNames: false, showFullDefinition: true, showDescription: true })).toBe(`User { id: number; /* the user */ admin: User; }`); type A<T> = [A<T>]; expect(stringifyResolvedType(typeOf<A<string>>())).toBe('[[* Recursion *]]'); }); test('description interface', () => { interface User { id: number; /** * @description the user * another line? */ username: string; } expect(stringifyType(typeOf<User>(), { showNames: false, showFullDefinition: true, showDescription: true })).toBe(`User { id: number; /* the user * another line? */ username: string; }`); ; const json = serializeType(typeOf<User>()); const back = deserializeType(json); expect(stringifyType(back, { showNames: false, showFullDefinition: true, showDescription: true })).toBe(`User { id: number; /* the user * another line? */ username: string; }`); interface small { /** @description thats the number */ id: number; } expect(stringifyType(typeOf<small>(), { showNames: false, showFullDefinition: true, showDescription: true })).toBe(`small {\n /* thats the number */\n id: number;\n}`); }); test('description class', () => { class User { id!: number; /** * @description the user * another line? */ username?: string; } expect(stringifyType(typeOf<User>(), { showNames: false, showFullDefinition: true, showDescription: true })).toBe(`User { id: number; /* the user * another line? */ username?: string; }`); }); test('stringifyType heritage', () => { class Base { id!: number; } class User extends Base { username!: string; } expect(stringifyResolvedType(typeOf<User>())).toBe(`User { id: number; username: string; }`); const serialized = serializeType(typeOf<User>()); const back = deserializeType(serialized); expect(stringifyResolvedType(back)).toBe(`User { id: number; username: string; }`); }); test('enum', () => { enum MyEnum { a, b, c = 4 } interface User { status: MyEnum; } expect(stringifyResolvedType(typeOf<MyEnum>())).toBe('MyEnum {a: 0, b: 1, c: 4}'); expect(stringifyResolvedType(typeOf<User>())).toBe('User {status: MyEnum {a: 0, b: 1, c: 4}}'); const json = serializeType(typeOf<MyEnum>()); const back = deserializeType(json); expect(stringifyResolvedType(back)).toBe('MyEnum {a: 0, b: 1, c: 4}'); }); test('stringifyType class default', () => { class Config { a?: string; url: string = '0.0.0.0'; } expect(stringifyType(typeOf<Config>(), { showFullDefinition: true, showDefaults: true })).toBe(`Config { a?: string; url: string = "0.0.0.0"; }`); expect(stringifyType(typeOf<Config>(), { showFullDefinition: true, showDefaults: true, defaultValues: { a: 'bar', url: '127.0.0.1' } })).toBe(`Config { a?: string = "bar"; url: string = "127.0.0.1"; }`); }); test('stringifyType interface default', () => { interface Config { a?: string; url: string; } expect(stringifyType(typeOf<Config>(), { showFullDefinition: true, showDefaults: true })).toBe(`Config { a?: string; url: string; }`); expect(stringifyType(typeOf<Config>(), { showFullDefinition: true, showDefaults: true, defaultValues: { a: 'bar', url: '127.0.0.1' } })).toBe(`Config { a?: string = "bar"; url: string = "127.0.0.1"; }`); }); test('stringifyType class deep default', () => { class Config { a?: string; sub?: { url: string }; } expect(stringifyType(typeOf<Config>(), { showFullDefinition: true, showDefaults: true })).toBe(`Config { a?: string; sub?: {url: string}; }`); expect(stringifyType(typeOf<Config>(), { showFullDefinition: true, showDefaults: true, defaultValues: { sub: { url: '127.0.0.1' } } })).toBe(`Config { a?: string; sub?: {url: string = "127.0.0.1"}; }`); }); test('stringifyType interface deep default', () => { interface Config { a?: string; sub: { url: string }; } expect(stringifyType(typeOf<Config>(), { showFullDefinition: true, showDefaults: true })).toBe(`Config { a?: string; sub: {url: string}; }`); expect(stringifyType(typeOf<Config>(), { showFullDefinition: true, showDefaults: true, defaultValues: { sub: { url: '127.0.0.1' } } })).toBe(`Config { a?: string; sub: {url: string = "127.0.0.1"}; }`); }); test('stringifyType object literal inline', () => { expect(stringifyType(typeOf<{ a: string }>())).toBe(`{a: string}`); }); test('stringifyType type', () => { const type = typeOf<Type>(); const s = stringifyType(type, {showFullDefinition: true}); }); test('generic', () => { class Gen<T> { id!: T; } expect(stringifyResolvedType(reflect(Gen))).toBe('Gen {id: T}'); expect(stringifyResolvedType(reflect(Gen, typeOf<number>()))).toBe('Gen {id: number}'); })
the_stack
import { Expr, JsonExpr } from "./Expr"; import { InterpolatedPropertyDefinition } from "./InterpolatedPropertyDefs"; import { BaseTechniqueParams, BasicExtrudedLineTechniqueParams, ExtrudedPolygonTechniqueParams, FillTechniqueParams, isTextureBuffer, LineTechniqueParams, MarkerTechniqueParams, PointTechniqueParams, SegmentsTechniqueParams, ShaderTechniqueParams, SolidLineTechniqueParams, StandardExtrudedLineTechniqueParams, StandardTechniqueParams, TerrainTechniqueParams, TextTechniqueParams, TextureCoordinateType } from "./TechniqueParams"; import { StylePriority } from "./Theme"; /** * Names of the supported texture properties. * @internal */ export const TEXTURE_PROPERTY_KEYS = [ "map", "normalMap", "displacementMap", "roughnessMap", "emissiveMap", "alphaMap", "metalnessMap", "bumpMap" ]; // TODO: Can be removed, when all when interpolators are implemented as {@link Expr}s type RemoveInterpolatedPropDef<T> = T | InterpolatedPropertyDefinition<any> extends T ? Exclude<T, InterpolatedPropertyDefinition<any>> : T; type RemoveJsonExpr<T> = T | JsonExpr extends T ? Exclude<T, JsonExpr> : T; /** * Make runtime representation of technique attributes from JSON-compatible typings. * * Translates * - InterpolatedPropertyDefinition -> InterpolatedProperty * - JsonExpr -> Expr */ export type MakeTechniqueAttrs<T> = { [P in keyof T]: T[P] | JsonExpr extends T[P] ? RemoveInterpolatedPropDef<RemoveJsonExpr<T[P]>> | Expr : T[P]; }; /** * Possible techniques that can be used to draw a geometry on the map. */ export type Technique = | SquaresTechnique | CirclesTechnique | PoiTechnique | LineMarkerTechnique | LineTechnique | SegmentsTechnique | SolidLineTechnique | FillTechnique | StandardTechnique | TerrainTechnique | BasicExtrudedLineTechnique | StandardExtrudedLineTechnique | ExtrudedPolygonTechnique | ShaderTechnique | TextTechnique | LabelRejectionLineTechnique; /** * Runtime representation of `SquaresStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `PointTechniqueParams`. */ export interface SquaresTechnique extends MakeTechniqueAttrs<PointTechniqueParams> { name: "squares"; } /** * Runtime representation of `CirclesStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `PointTechniqueParams`. */ export interface CirclesTechnique extends MakeTechniqueAttrs<PointTechniqueParams> { name: "circles"; } /** * Runtime representation of `PoiStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `MarkerTechniqueParams`. */ export interface PoiTechnique extends MakeTechniqueAttrs<MarkerTechniqueParams> { name: "labeled-icon"; } /** * Runtime representation of `LineMarkerStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `MarkerTechniqueParams`. */ export interface LineMarkerTechnique extends MakeTechniqueAttrs<MarkerTechniqueParams> { name: "line-marker"; } /** * Runtime representation of `SegmentsStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `SegmentsTechniqueParams`. */ export interface SegmentsTechnique extends MakeTechniqueAttrs<SegmentsTechniqueParams> { name: "segments"; } /** * Runtime representation of `BasicExtrudedLineStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `BasicExtrudedLineTechniqueParams`. */ export interface BasicExtrudedLineTechnique extends MakeTechniqueAttrs<BasicExtrudedLineTechniqueParams> { name: "extruded-line"; } /** * Runtime representation of `StandardExtrudedLineStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `StandardExtrudedLineTechniqueParams`. */ export interface StandardExtrudedLineTechnique extends MakeTechniqueAttrs<StandardExtrudedLineTechniqueParams> { name: "extruded-line"; } /** * Runtime representation of `SolidLineStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `SolidLineTechniqueParams`. */ export interface SolidLineTechnique extends MakeTechniqueAttrs<SolidLineTechniqueParams> { name: "solid-line" | "dashed-line"; } /** * Runtime representation of `LineStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `LineTechniqueParams`. */ export interface LineTechnique extends MakeTechniqueAttrs<LineTechniqueParams> { name: "line"; } /** * Runtime representation of `FillStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `FillTechniqueParams`. */ export interface FillTechnique extends MakeTechniqueAttrs<FillTechniqueParams> { name: "fill"; } /** * Technique used to render a mesh geometry. * For technique parameters see `StandardTechniqueParams`. */ export interface StandardTechnique extends MakeTechniqueAttrs<StandardTechniqueParams> { name: "standard"; } /** * Runtime representation of `ExtrudedPolygonStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `ExtrudedPolygonTechniqueParams`. */ export interface ExtrudedPolygonTechnique extends MakeTechniqueAttrs<ExtrudedPolygonTechniqueParams> { name: "extruded-polygon"; } /** * Runtime representation of `TextStyle` as parsed by `StyleSetEvaluator`. * For technique parameters see `TextTechniqueParams`. */ export interface TextTechnique extends MakeTechniqueAttrs<TextTechniqueParams> { name: "text"; } /** * Special technique for user-defined shaders. * For technique parameters see `ShaderTechniqueParams`. */ export interface ShaderTechnique extends MakeTechniqueAttrs<ShaderTechniqueParams> { name: "shader"; } /** * Technique used to render a terrain geometry with textures. * For technique parameters see `TerrainTechniqueParams`. */ export interface TerrainTechnique extends MakeTechniqueAttrs<TerrainTechniqueParams> { name: "terrain"; } /** * Technique to avoid label rendering on top of certain line geometries. * For technique parameters see `BaseTechniqueParams`. */ export interface LabelRejectionLineTechnique extends MakeTechniqueAttrs<BaseTechniqueParams> { name: "label-rejection-line"; } /** * Names of the properties controlling transparency. * @internal */ export const TRANSPARENCY_PROPERTY_KEYS = ["opacity", "transparent"]; /** * Additional params used for optimized usage of `Techniques`. */ export interface IndexedTechniqueParams { /** * Optimization: Index into table in `StyleSetEvaluator` or in `DecodedTile`. * @hidden */ _index: number; /** * Optimization: Unique `Technique` index of `Style` from which technique was derived. * @hidden */ _styleSetIndex: number; /** * The styleSet associated to this `Technique`. * @hidden */ _styleSet?: string; /** * The category used to assign render orders to objects created using this `Technique`. * @hidden */ _category?: string; /** * The category used to assign render orders to secondary objects * created using this `Technique`. * @hidden */ _secondaryCategory?: string; /** * `true` if any of the properties of this technique needs to access * the feature's state. * * @hidden */ _usesFeatureState?: boolean; /** * Last computed state derived from [[Technique.kind]]. */ _kindState?: boolean; } /** * For efficiency, `StyleSetEvaluator` returns `Techniques` additional params as defined in * `IndexedTechniqueParams`. */ export type IndexedTechnique = Technique & IndexedTechniqueParams; /** * Type guard to check if an object is an instance of `CirclesTechnique`. */ export function isCirclesTechnique(technique: Technique): technique is CirclesTechnique { return technique.name === "circles"; } /** * Type guard to check if an object is an instance of `SquaresTechnique`. */ export function isSquaresTechnique(technique: Technique): technique is SquaresTechnique { return technique.name === "squares"; } /** * Type guard to check if an object is an instance of `PoiTechnique`. */ export function isPoiTechnique(technique: Technique): technique is PoiTechnique { return technique.name === "labeled-icon"; } /** * Type guard to check if an object is an instance of `LineMarkerTechnique`. */ export function isLineMarkerTechnique(technique: Technique): technique is LineMarkerTechnique { return technique.name === "line-marker"; } /** * Type guard to check if an object is an instance of `LineTechnique`. */ export function isLineTechnique(technique: Technique): technique is LineTechnique { return technique.name === "line"; } /** * Type guard to check if an object is an instance of `SolidLineTechnique`. */ export function isSolidLineTechnique(technique: Technique): technique is SolidLineTechnique { return technique.name === "solid-line" || technique.name === "dashed-line"; } /** * Type guard to check if an object is an instance of `SolidLineTechnique` and is a kind that * has special dashes. * @note Lines with special dashes need line caps to render properly. */ export function isSpecialDashesLineTechnique( technique: Technique ): technique is SolidLineTechnique { return ( (technique.name === "solid-line" || technique.name === "dashed-line") && technique.dashes !== undefined && technique.dashes !== "Square" ); } /** * Type guard to check if an object is an instance of `SegmentsTechnique`. */ export function isSegmentsTechnique(technique: Technique): technique is SegmentsTechnique { return technique.name === "segments"; } /** * Type guard to check if an object is an instance of `BasicExtrudedLineTechnique` * or `StandardExtrudedLineTechnique`. */ export function isExtrudedLineTechnique( technique: Technique ): technique is BasicExtrudedLineTechnique | StandardExtrudedLineTechnique { return technique.name === "extruded-line"; } /** * Type guard to check if an object is an instance of `BasicExtrudedLineTechnique`. */ export function isBasicExtrudedLineTechnique( technique: Technique ): technique is BasicExtrudedLineTechnique { return isExtrudedLineTechnique(technique) && technique.shading === "basic"; } /** * Type guard to check if an object is an instance of `StandardExtrudedLineTechnique`. */ export function isStandardExtrudedLineTechnique( technique: Technique ): technique is StandardExtrudedLineTechnique { return isExtrudedLineTechnique(technique) && technique.shading === "standard"; } /** * Type guard to check if an object is an instance of `FillTechnique`. */ export function isFillTechnique(technique: Technique): technique is FillTechnique { return technique.name === "fill"; } /** * Type guard to check if an object is an instance of `ExtrudedPolygonTechnique`. */ export function isExtrudedPolygonTechnique( technique: Technique ): technique is ExtrudedPolygonTechnique { return technique.name === "extruded-polygon"; } /** * Type guard to check if an object is an instance of `StandardTechnique`. */ export function isStandardTechnique(technique: Technique): technique is StandardTechnique { return technique.name === "standard"; } /** * Type guard to check if an object is an instance of `TerrainTechnique`. */ export function isTerrainTechnique(technique: Technique): technique is TerrainTechnique { return technique.name === "terrain"; } /** * Type guard to check if an object is an instance of `TextTechnique`. */ export function isTextTechnique(technique: Technique): technique is TextTechnique { return technique.name === "text"; } /** * Type guard to check if an object is an instance of `ShaderTechnique`. */ export function isShaderTechnique(technique: Technique): technique is ShaderTechnique { return technique.name === "shader"; } export function isLabelRejectionLineTechnique( technique: Technique ): technique is LabelRejectionLineTechnique { return technique.name === "label-rejection-line"; } /** * Check if vertex normals should be generated for this technique (if no normals are in the data). * @param technique - Technique to check. */ export function needsVertexNormals(technique: Technique): boolean { return ( isExtrudedPolygonTechnique(technique) || isFillTechnique(technique) || isStandardTechnique(technique) || isTerrainTechnique(technique) || isStandardExtrudedLineTechnique(technique) ); } /** * Type guard to check if an object is an instance of a technique with textures. */ export function supportsTextures( technique: Technique ): technique is FillTechnique | StandardTechnique | ExtrudedPolygonTechnique | TerrainTechnique { return ( isFillTechnique(technique) || isStandardTechnique(technique) || isExtrudedPolygonTechnique(technique) || isTerrainTechnique(technique) ); } /** * Get the texture coordinate type if the technique supports it. */ export function textureCoordinateType(technique: Technique): TextureCoordinateType | undefined { return supportsTextures(technique) || isShaderTechnique(technique) ? technique.textureCoordinateType : undefined; } /** * Add all the buffers of the technique to the transfer list. */ export function addBuffersToTransferList(technique: Technique, transferList: ArrayBuffer[]) { if ( isStandardTechnique(technique) || isExtrudedPolygonTechnique(technique) || isTerrainTechnique(technique) ) { for (const texturePropertyKey of TEXTURE_PROPERTY_KEYS) { const textureProperty = (technique as any)[texturePropertyKey]; if (isTextureBuffer(textureProperty)) { if (textureProperty.buffer instanceof ArrayBuffer) { transferList.push(textureProperty.buffer); } } } } } /** * Compose full texture name for given image name with technique specified. * Some techniques allows to add prefix/postfix to icons names specified, this * function uses technique information to create fully qualified texture name. * @param imageName - base name of the marker icon. * @param technique - the technique describing POI or line marker. * @returns fully qualified texture name for loading from atlas (without extension). */ export function composeTechniqueTextureName( imageName: string, technique: PoiTechnique | LineMarkerTechnique ): string { let textureName = imageName; if (typeof technique.imageTexturePrefix === "string") { textureName = technique.imageTexturePrefix + textureName; } if (typeof technique.imageTexturePostfix === "string") { textureName = textureName + technique.imageTexturePostfix; } return textureName; } /** * Sets a technique's render order (or priority for screen-space techniques) depending on its * category and the priorities specified in a given theme. * @param technique- The technique whose render order or priority will be set. * @param theme - The theme from which the category priorities will be taken. */ export function setTechniqueRenderOrderOrPriority( technique: IndexedTechnique, priorities: StylePriority[], labelPriorities: string[] ) { if ( isTextTechnique(technique) || isPoiTechnique(technique) || isLineMarkerTechnique(technique) ) { // for screen-space techniques the `category` is used to assign // priorities. if (labelPriorities && typeof technique._category === "string") { // override the `priority` when the technique uses `category`. const priority = labelPriorities.indexOf(technique._category); if (priority !== -1) { technique.priority = labelPriorities.length - priority; } } } else if (priorities && technique._styleSet !== undefined) { // Compute the render order based on the style category and styleSet. const computeRenderOrder = (category: string): number | undefined => { const priority = priorities?.findIndex( entry => entry.group === technique._styleSet && entry.category === category ); return priority !== undefined && priority !== -1 ? (priority + 1) * 10 : undefined; }; if (typeof technique._category === "string") { // override the renderOrder when the technique is using categories. const renderOrder = computeRenderOrder(technique._category); if (renderOrder !== undefined) { technique.renderOrder = renderOrder; } } if (typeof technique._secondaryCategory === "string") { // override the secondaryRenderOrder when the technique is using categories. const secondaryRenderOrder = computeRenderOrder(technique._secondaryCategory); if (secondaryRenderOrder !== undefined) { (technique as any).secondaryRenderOrder = secondaryRenderOrder; } } } }
the_stack
import {bind, each, indexOf, curry, extend, normalizeCssArray, isFunction} from 'zrender/src/core/util'; import * as graphic from '../../util/graphic'; import {getECData} from '../../util/innerStore'; import { isHighDownDispatcher, setAsHighDownDispatcher, setDefaultStateProxy, enableHoverFocus, Z2_EMPHASIS_LIFT } from '../../util/states'; import DataDiffer from '../../data/DataDiffer'; import * as helper from '../helper/treeHelper'; import Breadcrumb from './Breadcrumb'; import RoamController, { RoamEventParams } from '../../component/helper/RoamController'; import BoundingRect, { RectLike } from 'zrender/src/core/BoundingRect'; import * as matrix from 'zrender/src/core/matrix'; import * as animationUtil from '../../util/animation'; import makeStyleMapper from '../../model/mixin/makeStyleMapper'; import ChartView from '../../view/Chart'; import Tree, { TreeNode } from '../../data/Tree'; import TreemapSeriesModel, { TreemapSeriesNodeItemOption } from './TreemapSeries'; import GlobalModel from '../../model/Global'; import ExtensionAPI from '../../core/ExtensionAPI'; import Model from '../../model/Model'; import { LayoutRect } from '../../util/layout'; import { TreemapLayoutNode } from './treemapLayout'; import Element from 'zrender/src/Element'; import Displayable from 'zrender/src/graphic/Displayable'; import { makeInner, convertOptionIdName } from '../../util/model'; import { PathStyleProps, PathProps } from 'zrender/src/graphic/Path'; import { TreeSeriesNodeItemOption } from '../tree/TreeSeries'; import { TreemapRootToNodePayload, TreemapMovePayload, TreemapRenderPayload, TreemapZoomToNodePayload } from './treemapAction'; import { ColorString, ECElement } from '../../util/types'; import { windowOpen } from '../../util/format'; import { TextStyleProps } from 'zrender/src/graphic/Text'; import { setLabelStyle, getLabelStatesModels } from '../../label/labelStyle'; const Group = graphic.Group; const Rect = graphic.Rect; const DRAG_THRESHOLD = 3; const PATH_LABEL_NOAMAL = 'label'; const PATH_UPPERLABEL_NORMAL = 'upperLabel'; // Should larger than emphasis states lift z const Z2_BASE = Z2_EMPHASIS_LIFT * 10; // Should bigger than every z2. const Z2_BG = Z2_EMPHASIS_LIFT * 2; const Z2_CONTENT = Z2_EMPHASIS_LIFT * 3; const getStateItemStyle = makeStyleMapper([ ['fill', 'color'], // `borderColor` and `borderWidth` has been occupied, // so use `stroke` to indicate the stroke of the rect. ['stroke', 'strokeColor'], ['lineWidth', 'strokeWidth'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'] // Option decal is in `DecalObject` but style.decal is in `PatternObject`. // So do not transfer decal directly. ]); const getItemStyleNormal = function (model: Model<TreemapSeriesNodeItemOption['itemStyle']>): PathStyleProps { // Normal style props should include emphasis style props. const itemStyle = getStateItemStyle(model) as PathStyleProps; // Clear styles set by emphasis. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null; return itemStyle; }; interface RenderElementStorage { nodeGroup: graphic.Group[] background: graphic.Rect[] content: graphic.Rect[] } type LastCfgStorage = { [key in keyof RenderElementStorage]: LastCfg[] // nodeGroup: { // old: Pick<graphic.Group, 'position'>[] // fadein: boolean // }[] // background: { // old: Pick<graphic.Rect, 'shape'> // fadein: boolean // }[] // content: { // old: Pick<graphic.Rect, 'shape'> // fadein: boolean // }[] }; interface FoundTargetInfo { node: TreeNode offsetX?: number offsetY?: number } interface RenderResult { lastsForAnimation: LastCfgStorage willInvisibleEls?: graphic.Rect[] willDeleteEls: RenderElementStorage renderFinally: () => void } interface ReRoot { rootNodeGroup: graphic.Group direction: 'drillDown' | 'rollUp' } interface LastCfg { oldX?: number oldY?: number oldShape?: graphic.Rect['shape'] fadein: boolean } const inner = makeInner<{ nodeWidth: number nodeHeight: number willDelete: boolean }, Element>(); class TreemapView extends ChartView { static type = 'treemap'; type = TreemapView.type; private _containerGroup: graphic.Group; private _breadcrumb: Breadcrumb; private _controller: RoamController; private _oldTree: Tree; private _state: 'ready' | 'animating' = 'ready'; private _storage = createStorage() as RenderElementStorage; seriesModel: TreemapSeriesModel; api: ExtensionAPI; ecModel: GlobalModel; /** * @override */ render( seriesModel: TreemapSeriesModel, ecModel: GlobalModel, api: ExtensionAPI, payload: TreemapZoomToNodePayload | TreemapRenderPayload | TreemapMovePayload | TreemapRootToNodePayload ) { const models = ecModel.findComponents({ mainType: 'series', subType: 'treemap', query: payload }); if (indexOf(models, seriesModel) < 0) { return; } this.seriesModel = seriesModel; this.api = api; this.ecModel = ecModel; const types = ['treemapZoomToNode', 'treemapRootToNode']; const targetInfo = helper .retrieveTargetInfo(payload, types, seriesModel); const payloadType = payload && payload.type; const layoutInfo = seriesModel.layoutInfo; const isInit = !this._oldTree; const thisStorage = this._storage; // Mark new root when action is treemapRootToNode. const reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage) ? { rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()], direction: (payload as TreemapRootToNodePayload).direction } : null; const containerGroup = this._giveContainerGroup(layoutInfo); const hasAnimation = seriesModel.get('animation'); const renderResult = this._doRender(containerGroup, seriesModel, reRoot); ( hasAnimation && !isInit && ( !payloadType || payloadType === 'treemapZoomToNode' || payloadType === 'treemapRootToNode' ) ) ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot) : renderResult.renderFinally(); this._resetController(api); this._renderBreadcrumb(seriesModel, api, targetInfo); } private _giveContainerGroup(layoutInfo: LayoutRect) { let containerGroup = this._containerGroup; if (!containerGroup) { // FIXME // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。 containerGroup = this._containerGroup = new Group(); this._initEvents(containerGroup); this.group.add(containerGroup); } containerGroup.x = layoutInfo.x; containerGroup.y = layoutInfo.y; return containerGroup; } private _doRender(containerGroup: graphic.Group, seriesModel: TreemapSeriesModel, reRoot: ReRoot): RenderResult { const thisTree = seriesModel.getData().tree; const oldTree = this._oldTree; // Clear last shape records. const lastsForAnimation = createStorage() as LastCfgStorage; const thisStorage = createStorage() as RenderElementStorage; const oldStorage = this._storage; const willInvisibleEls: RenderResult['willInvisibleEls'] = []; function doRenderNode(thisNode: TreeNode, oldNode: TreeNode, parentGroup: graphic.Group, depth: number) { return renderNode( seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth ); } // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow), // the oldTree is actually losted, so we can not find all of the old graphic // elements from tree. So we use this stragegy: make element storage, move // from old storage to new storage, clear old storage. dualTravel( thisTree.root ? [thisTree.root] : [], (oldTree && oldTree.root) ? [oldTree.root] : [], containerGroup, thisTree === oldTree || !oldTree, 0 ); // Process all removing. const willDeleteEls = clearStorage(oldStorage) as RenderElementStorage; this._oldTree = thisTree; this._storage = thisStorage; return { lastsForAnimation, willDeleteEls, renderFinally }; function dualTravel( thisViewChildren: TreemapLayoutNode[], oldViewChildren: TreemapLayoutNode[], parentGroup: graphic.Group, sameTree: boolean, depth: number ) { // When 'render' is triggered by action, // 'this' and 'old' may be the same tree, // we use rawIndex in that case. if (sameTree) { oldViewChildren = thisViewChildren; each(thisViewChildren, function (child, index) { !child.isRemoved() && processNode(index, index); }); } // Diff hierarchically (diff only in each subtree, but not whole). // because, consistency of view is important. else { (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey)) .add(processNode) .update(processNode) .remove(curry(processNode, null)) .execute(); } function getKey(node: TreeNode) { // Identify by name or raw index. return node.getId(); } function processNode(newIndex: number, oldIndex?: number) { const thisNode = newIndex != null ? thisViewChildren[newIndex] : null; const oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null; const group = doRenderNode(thisNode, oldNode, parentGroup, depth); group && dualTravel( thisNode && thisNode.viewChildren || [], oldNode && oldNode.viewChildren || [], group, sameTree, depth + 1 ); } } function clearStorage(storage: RenderElementStorage) { const willDeleteEls = createStorage() as RenderElementStorage; storage && each(storage, function (store, storageName) { const delEls = willDeleteEls[storageName]; each(store, function (el) { el && (delEls.push(el as any), inner(el).willDelete = true); }); }); return willDeleteEls; } function renderFinally() { each(willDeleteEls, function (els) { each(els, function (el) { el.parent && el.parent.remove(el); }); }); each(willInvisibleEls, function (el) { el.invisible = true; // Setting invisible is for optimizing, so no need to set dirty, // just mark as invisible. el.dirty(); }); } } private _doAnimation( containerGroup: graphic.Group, renderResult: RenderResult, seriesModel: TreemapSeriesModel, reRoot: ReRoot ) { const durationOption = seriesModel.get('animationDurationUpdate'); const easingOption = seriesModel.get('animationEasing'); // TODO: do not support function until necessary. const duration = (isFunction(durationOption) ? 0 : durationOption) || 0; const easing = (isFunction(easingOption) ? null : easingOption) || 'cubicOut'; const animationWrap = animationUtil.createWrap(); // Make delete animations. each(renderResult.willDeleteEls, function (store, storageName) { each(store, function (el, rawIndex) { if ((el as Displayable).invisible) { return; } const parent = el.parent; // Always has parent, and parent is nodeGroup. let target: PathProps; const innerStore = inner(parent); if (reRoot && reRoot.direction === 'drillDown') { target = parent === reRoot.rootNodeGroup // This is the content element of view root. // Only `content` will enter this branch, because // `background` and `nodeGroup` will not be deleted. ? { shape: { x: 0, y: 0, width: innerStore.nodeWidth, height: innerStore.nodeHeight }, style: { opacity: 0 } } // Others. : {style: {opacity: 0}}; } else { let targetX = 0; let targetY = 0; if (!innerStore.willDelete) { // Let node animate to right-bottom corner, cooperating with fadeout, // which is appropriate for user understanding. // Divided by 2 for reRoot rolling up effect. targetX = innerStore.nodeWidth / 2; targetY = innerStore.nodeHeight / 2; } target = storageName === 'nodeGroup' ? {x: targetX, y: targetY, style: {opacity: 0}} : { shape: {x: targetX, y: targetY, width: 0, height: 0}, style: {opacity: 0} }; } // TODO: do not support delay until necessary. target && animationWrap.add(el, target, duration, 0, easing); }); }); // Make other animations each(this._storage, function (store, storageName) { each(store, function (el, rawIndex) { const last = renderResult.lastsForAnimation[storageName][rawIndex]; const target: PathProps = {}; if (!last) { return; } if (el instanceof graphic.Group) { if (last.oldX != null) { target.x = el.x; target.y = el.y; el.x = last.oldX; el.y = last.oldY; } } else { if (last.oldShape) { target.shape = extend({}, el.shape); el.setShape(last.oldShape); } if (last.fadein) { el.setStyle('opacity', 0); target.style = {opacity: 1}; } // When animation is stopped for succedent animation starting, // el.style.opacity might not be 1 else if (el.style.opacity !== 1) { target.style = {opacity: 1}; } } animationWrap.add(el, target, duration, 0, easing); }); }, this); this._state = 'animating'; animationWrap .finished(bind(function () { this._state = 'ready'; renderResult.renderFinally(); }, this)) .start(); } private _resetController(api: ExtensionAPI) { let controller = this._controller; // Init controller. if (!controller) { controller = this._controller = new RoamController(api.getZr()); controller.enable(this.seriesModel.get('roam')); controller.on('pan', bind(this._onPan, this)); controller.on('zoom', bind(this._onZoom, this)); } const rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight()); controller.setPointerChecker(function (e, x, y) { return rect.contain(x, y); }); } private _clearController() { let controller = this._controller; if (controller) { controller.dispose(); controller = null; } } private _onPan(e: RoamEventParams['pan']) { if (this._state !== 'animating' && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD) ) { // These param must not be cached. const root = this.seriesModel.getData().tree.root; if (!root) { return; } const rootLayout = root.getLayout(); if (!rootLayout) { return; } this.api.dispatchAction({ type: 'treemapMove', from: this.uid, seriesId: this.seriesModel.id, rootRect: { x: rootLayout.x + e.dx, y: rootLayout.y + e.dy, width: rootLayout.width, height: rootLayout.height } } as TreemapMovePayload); } } private _onZoom(e: RoamEventParams['zoom']) { let mouseX = e.originX; let mouseY = e.originY; if (this._state !== 'animating') { // These param must not be cached. const root = this.seriesModel.getData().tree.root; if (!root) { return; } const rootLayout = root.getLayout(); if (!rootLayout) { return; } const rect = new BoundingRect( rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height ); const layoutInfo = this.seriesModel.layoutInfo; // Transform mouse coord from global to containerGroup. mouseX -= layoutInfo.x; mouseY -= layoutInfo.y; // Scale root bounding rect. const m = matrix.create(); matrix.translate(m, m, [-mouseX, -mouseY]); matrix.scale(m, m, [e.scale, e.scale]); matrix.translate(m, m, [mouseX, mouseY]); rect.applyTransform(m); this.api.dispatchAction({ type: 'treemapRender', from: this.uid, seriesId: this.seriesModel.id, rootRect: { x: rect.x, y: rect.y, width: rect.width, height: rect.height } } as TreemapRenderPayload); } } private _initEvents(containerGroup: graphic.Group) { containerGroup.on('click', (e) => { if (this._state !== 'ready') { return; } const nodeClick = this.seriesModel.get('nodeClick', true); if (!nodeClick) { return; } const targetInfo = this.findTarget(e.offsetX, e.offsetY); if (!targetInfo) { return; } const node = targetInfo.node; if (node.getLayout().isLeafRoot) { this._rootToNode(targetInfo); } else { if (nodeClick === 'zoomToNode') { this._zoomToNode(targetInfo); } else if (nodeClick === 'link') { const itemModel = node.hostTree.data.getItemModel<TreeSeriesNodeItemOption>(node.dataIndex); const link = itemModel.get('link', true); const linkTarget = itemModel.get('target', true) || 'blank'; link && windowOpen(link, linkTarget); } } }, this); } private _renderBreadcrumb(seriesModel: TreemapSeriesModel, api: ExtensionAPI, targetInfo: FoundTargetInfo) { if (!targetInfo) { targetInfo = seriesModel.get('leafDepth', true) != null ? {node: seriesModel.getViewRoot()} // FIXME // better way? // Find breadcrumb tail on center of containerGroup. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2); if (!targetInfo) { targetInfo = {node: seriesModel.getData().tree.root}; } } (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group))) .render(seriesModel, api, targetInfo.node, (node) => { if (this._state !== 'animating') { helper.aboveViewRoot(seriesModel.getViewRoot(), node) ? this._rootToNode({node: node}) : this._zoomToNode({node: node}); } }); } /** * @override */ remove() { this._clearController(); this._containerGroup && this._containerGroup.removeAll(); this._storage = createStorage() as RenderElementStorage; this._state = 'ready'; this._breadcrumb && this._breadcrumb.remove(); } dispose() { this._clearController(); } private _zoomToNode(targetInfo: FoundTargetInfo) { this.api.dispatchAction({ type: 'treemapZoomToNode', from: this.uid, seriesId: this.seriesModel.id, targetNode: targetInfo.node }); } private _rootToNode(targetInfo: FoundTargetInfo) { this.api.dispatchAction({ type: 'treemapRootToNode', from: this.uid, seriesId: this.seriesModel.id, targetNode: targetInfo.node }); } /** * @public * @param {number} x Global coord x. * @param {number} y Global coord y. * @return {Object} info If not found, return undefined; * @return {number} info.node Target node. * @return {number} info.offsetX x refer to target node. * @return {number} info.offsetY y refer to target node. */ findTarget(x: number, y: number): FoundTargetInfo { let targetInfo; const viewRoot = this.seriesModel.getViewRoot(); viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) { const bgEl = this._storage.background[node.getRawIndex()]; // If invisible, there might be no element. if (bgEl) { const point = bgEl.transformCoordToLocal(x, y); const shape = bgEl.shape; // For performance consideration, dont use 'getBoundingRect'. if (shape.x <= point[0] && point[0] <= shape.x + shape.width && shape.y <= point[1] && point[1] <= shape.y + shape.height ) { targetInfo = { node: node, offsetX: point[0], offsetY: point[1] }; } else { return false; // Suppress visit subtree. } } }, this); return targetInfo; } } /** * @inner */ function createStorage(): RenderElementStorage | LastCfgStorage { return { nodeGroup: [], background: [], content: [] }; } /** * @inner * @return Return undefined means do not travel further. */ function renderNode( seriesModel: TreemapSeriesModel, thisStorage: RenderElementStorage, oldStorage: RenderElementStorage, reRoot: ReRoot, lastsForAnimation: RenderResult['lastsForAnimation'], willInvisibleEls: RenderResult['willInvisibleEls'], thisNode: TreeNode, oldNode: TreeNode, parentGroup: graphic.Group, depth: number ) { // Whether under viewRoot. if (!thisNode) { // Deleting nodes will be performed finally. This method just find // element from old storage, or create new element, set them to new // storage, and set styles. return; } // ------------------------------------------------------------------- // Start of closure variables available in "Procedures in renderNode". const thisLayout = thisNode.getLayout(); const data = seriesModel.getData(); const nodeModel = thisNode.getModel<TreemapSeriesNodeItemOption>(); // Only for enabling highlight/downplay. Clear firstly. // Because some node will not be rendered. data.setItemGraphicEl(thisNode.dataIndex, null); if (!thisLayout || !thisLayout.isInView) { return; } const thisWidth = thisLayout.width; const thisHeight = thisLayout.height; const borderWidth = thisLayout.borderWidth; const thisInvisible = thisLayout.invisible; const thisRawIndex = thisNode.getRawIndex(); const oldRawIndex = oldNode && oldNode.getRawIndex(); const thisViewChildren = thisNode.viewChildren; const upperHeight = thisLayout.upperHeight; const isParent = thisViewChildren && thisViewChildren.length; const itemStyleNormalModel = nodeModel.getModel('itemStyle'); const itemStyleEmphasisModel = nodeModel.getModel(['emphasis', 'itemStyle']); const itemStyleBlurModel = nodeModel.getModel(['blur', 'itemStyle']); const itemStyleSelectModel = nodeModel.getModel(['select', 'itemStyle']); const borderRadius = itemStyleNormalModel.get('borderRadius') || 0; // End of closure ariables available in "Procedures in renderNode". // ----------------------------------------------------------------- // Node group const group = giveGraphic('nodeGroup', Group); if (!group) { return; } parentGroup.add(group); // x,y are not set when el is above view root. group.x = thisLayout.x || 0; group.y = thisLayout.y || 0; group.markRedraw(); inner(group).nodeWidth = thisWidth; inner(group).nodeHeight = thisHeight; if (thisLayout.isAboveViewRoot) { return group; } // Background const bg = giveGraphic('background', Rect, depth, Z2_BG); bg && renderBackground(group, bg, isParent && thisLayout.upperLabelHeight); const focus = nodeModel.get(['emphasis', 'focus']); const blurScope = nodeModel.get(['emphasis', 'blurScope']); const focusOrIndices = focus === 'ancestor' ? thisNode.getAncestorsIndices() : focus === 'descendant' ? thisNode.getDescendantIndices() : focus; // No children, render content. if (isParent) { // Because of the implementation about "traverse" in graphic hover style, we // can not set hover listener on the "group" of non-leaf node. Otherwise the // hover event from the descendents will be listenered. if (isHighDownDispatcher(group)) { setAsHighDownDispatcher(group, false); } if (bg) { setAsHighDownDispatcher(bg, true); // Only for enabling highlight/downplay. data.setItemGraphicEl(thisNode.dataIndex, bg); enableHoverFocus(bg, focusOrIndices, blurScope); } } else { const content = giveGraphic('content', Rect, depth, Z2_CONTENT); content && renderContent(group, content); (bg as ECElement).disableMorphing = true; if (bg && isHighDownDispatcher(bg)) { setAsHighDownDispatcher(bg, false); } setAsHighDownDispatcher(group, true); // Only for enabling highlight/downplay. data.setItemGraphicEl(thisNode.dataIndex, group); enableHoverFocus(group, focusOrIndices, blurScope); } return group; // ---------------------------- // | Procedures in renderNode | // ---------------------------- function renderBackground(group: graphic.Group, bg: graphic.Rect, useUpperLabel: boolean) { const ecData = getECData(bg); // For tooltip. ecData.dataIndex = thisNode.dataIndex; ecData.seriesIndex = seriesModel.seriesIndex; bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight, r: borderRadius}); if (thisInvisible) { // If invisible, do not set visual, otherwise the element will // change immediately before animation. We think it is OK to // remain its origin color when moving out of the view window. processInvisible(bg); } else { bg.invisible = false; const style = thisNode.getVisual('style') as PathStyleProps; const visualBorderColor = style.stroke; const normalStyle = getItemStyleNormal(itemStyleNormalModel); normalStyle.fill = visualBorderColor; const emphasisStyle = getStateItemStyle(itemStyleEmphasisModel); emphasisStyle.fill = itemStyleEmphasisModel.get('borderColor'); const blurStyle = getStateItemStyle(itemStyleBlurModel); blurStyle.fill = itemStyleBlurModel.get('borderColor'); const selectStyle = getStateItemStyle(itemStyleSelectModel); selectStyle.fill = itemStyleSelectModel.get('borderColor'); if (useUpperLabel) { const upperLabelWidth = thisWidth - 2 * borderWidth; prepareText( // PENDING: convert ZRColor to ColorString for text. bg, visualBorderColor as ColorString, style.opacity, {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight} ); } // For old bg. else { bg.removeTextContent(); } bg.setStyle(normalStyle); bg.ensureState('emphasis').style = emphasisStyle; bg.ensureState('blur').style = blurStyle; bg.ensureState('select').style = selectStyle; setDefaultStateProxy(bg); } group.add(bg); } function renderContent(group: graphic.Group, content: graphic.Rect) { const ecData = getECData(content); // For tooltip. ecData.dataIndex = thisNode.dataIndex; ecData.seriesIndex = seriesModel.seriesIndex; const contentWidth = Math.max(thisWidth - 2 * borderWidth, 0); const contentHeight = Math.max(thisHeight - 2 * borderWidth, 0); content.culling = true; content.setShape({ x: borderWidth, y: borderWidth, width: contentWidth, height: contentHeight, r: borderRadius }); if (thisInvisible) { // If invisible, do not set visual, otherwise the element will // change immediately before animation. We think it is OK to // remain its origin color when moving out of the view window. processInvisible(content); } else { content.invisible = false; const nodeStyle = thisNode.getVisual('style') as PathStyleProps; const visualColor = nodeStyle.fill; const normalStyle = getItemStyleNormal(itemStyleNormalModel); normalStyle.fill = visualColor; normalStyle.decal = nodeStyle.decal; const emphasisStyle = getStateItemStyle(itemStyleEmphasisModel); const blurStyle = getStateItemStyle(itemStyleBlurModel); const selectStyle = getStateItemStyle(itemStyleSelectModel); // PENDING: convert ZRColor to ColorString for text. prepareText(content, visualColor as ColorString, nodeStyle.opacity, null); content.setStyle(normalStyle); content.ensureState('emphasis').style = emphasisStyle; content.ensureState('blur').style = blurStyle; content.ensureState('select').style = selectStyle; setDefaultStateProxy(content); } group.add(content); } function processInvisible(element: graphic.Rect) { // Delay invisible setting utill animation finished, // avoid element vanish suddenly before animation. !element.invisible && willInvisibleEls.push(element); } function prepareText( rectEl: graphic.Rect, visualColor: ColorString, visualOpacity: number, // Can be null/undefined upperLabelRect: RectLike ) { const normalLabelModel = nodeModel.getModel( upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL ); const defaultText = convertOptionIdName(nodeModel.get('name'), null); const isShow = normalLabelModel.getShallow('show'); setLabelStyle( rectEl, getLabelStatesModels(nodeModel, upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL), { defaultText: isShow ? defaultText : null, inheritColor: visualColor, defaultOpacity: visualOpacity, labelFetcher: seriesModel, labelDataIndex: thisNode.dataIndex } ); const textEl = rectEl.getTextContent(); if (!textEl) { return; } const textStyle = textEl.style; const textPadding = normalizeCssArray(textStyle.padding || 0); if (upperLabelRect) { rectEl.setTextConfig({ layoutRect: upperLabelRect }); (textEl as ECElement).disableLabelLayout = true; } textEl.beforeUpdate = function () { const width = Math.max( (upperLabelRect ? upperLabelRect.width : rectEl.shape.width) - textPadding[1] - textPadding[3], 0 ); const height = Math.max( (upperLabelRect ? upperLabelRect.height : rectEl.shape.height) - textPadding[0] - textPadding[2], 0 ); if (textStyle.width !== width || textStyle.height !== height) { textEl.setStyle({ width, height }); } }; textStyle.truncateMinChar = 2; textStyle.lineOverflow = 'truncate'; addDrillDownIcon(textStyle, upperLabelRect, thisLayout); const textEmphasisState = textEl.getState('emphasis'); addDrillDownIcon(textEmphasisState ? textEmphasisState.style : null, upperLabelRect, thisLayout); } function addDrillDownIcon(style: TextStyleProps, upperLabelRect: RectLike, thisLayout: any) { const text = style ? style.text : null; if (!upperLabelRect && thisLayout.isLeafRoot && text != null) { const iconChar = seriesModel.get('drillDownIcon', true); style.text = iconChar ? iconChar + ' ' + text : text; } } function giveGraphic<T extends graphic.Group | graphic.Rect>( storageName: keyof RenderElementStorage, Ctor: {new(): T}, depth?: number, z?: number ): T { let element = oldRawIndex != null && oldStorage[storageName][oldRawIndex]; const lasts = lastsForAnimation[storageName]; if (element) { // Remove from oldStorage oldStorage[storageName][oldRawIndex] = null; prepareAnimationWhenHasOld(lasts, element); } // If invisible and no old element, do not create new element (for optimizing). else if (!thisInvisible) { element = new Ctor(); if (element instanceof Displayable) { element.z2 = calculateZ2(depth, z); } prepareAnimationWhenNoOld(lasts, element); } // Set to thisStorage return (thisStorage[storageName][thisRawIndex] = element) as T; } function prepareAnimationWhenHasOld(lasts: LastCfg[], element: graphic.Group | graphic.Rect) { const lastCfg = lasts[thisRawIndex] = {} as LastCfg; if (element instanceof Group) { lastCfg.oldX = element.x; lastCfg.oldY = element.y; } else { lastCfg.oldShape = extend({}, element.shape); } } // If a element is new, we need to find the animation start point carefully, // otherwise it will looks strange when 'zoomToNode'. function prepareAnimationWhenNoOld(lasts: LastCfg[], element: graphic.Group | graphic.Rect) { const lastCfg = lasts[thisRawIndex] = {} as LastCfg; const parentNode = thisNode.parentNode; const isGroup = element instanceof graphic.Group; if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) { let parentOldX = 0; let parentOldY = 0; // New nodes appear from right-bottom corner in 'zoomToNode' animation. // For convenience, get old bounding rect from background. const parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()]; if (!reRoot && parentOldBg && parentOldBg.oldShape) { parentOldX = parentOldBg.oldShape.width; parentOldY = parentOldBg.oldShape.height; } // When no parent old shape found, its parent is new too, // so we can just use {x:0, y:0}. if (isGroup) { lastCfg.oldX = 0; lastCfg.oldY = parentOldY; } else { lastCfg.oldShape = {x: parentOldX, y: parentOldY, width: 0, height: 0}; } } // Fade in, user can be aware that these nodes are new. lastCfg.fadein = !isGroup; } } // We can not set all backgroud with the same z, Because the behaviour of // drill down and roll up differ background creation sequence from tree // hierarchy sequence, which cause that lowser background element overlap // upper ones. So we calculate z based on depth. // Moreover, we try to shrink down z interval to [0, 1] to avoid that // treemap with large z overlaps other components. function calculateZ2(depth: number, z2InLevel: number) { return depth * Z2_BASE + z2InLevel; } export default TreemapView;
the_stack
import fs from "fs"; import * as _ from "lodash"; import { Stores } from "../../schema/stores"; import { Params } from "../../server/params"; import { ReplicatedError } from "../../server/errors"; import { Context } from "../../context"; import { Exec, KubeConfig, AppsV1Api, CoreV1Api, V1beta1Eviction, V1Node, V1OwnerReference, V1Pod, V1Status, } from "@kubernetes/client-node"; import { logger } from "../../server/logger"; import { Etcd3 } from "etcd3"; import * as yaml from "js-yaml"; export function KurlMutations(stores: Stores, params: Params) { return { async drainNode(root: any, { name }, context: Context): Promise<boolean> { context.requireSingleTenantSession(); await drain(name); return false; }, async deleteNode(root: any, { name }, context: Context): Promise<boolean> { context.requireSingleTenantSession(); await purge(name); return false; }, } } export interface drainResult { waitAndRetry: boolean; misconfiguredPolicyDisruptionBudget: boolean; } async function drain(name: string) { const kc = new KubeConfig(); kc.loadFromDefault(); const coreV1Client: CoreV1Api = kc.makeApiClient(CoreV1Api); // cordon the node let { response, body: node } = await coreV1Client.readNode(name); if (response.statusCode !== 200) { throw new ReplicatedError("Node not found"); } if (!node.spec) { throw new ReplicatedError("Node spec not found"); } node.spec.unschedulable = true; ({ response, body: node } = await coreV1Client.replaceNode(name, node)); if (response.statusCode !== 200) { throw new ReplicatedError(`Cordon node: ${response.statusCode}`); } // list and evict pods let waitAndRetry = false; let misconfiguredPolicyDisruptionBudget = false; const labelSelectors = [ // Defer draining self and pods that provide cluster services to other pods "app notin (rook-ceph-mon,rook-ceph-osd,rook-ceph-operator,kotsadm-api),k8s-app!=kube-dns", // Drain Rook pods "app in (rook-ceph-mon,rook-ceph-osd,rook-ceph-operator)", // Drain dns pod "k8s-app=kube-dns", // Drain self "app=kotsadm-api", ]; for (let i = 0; i < labelSelectors.length; i++) { const labelSelector = labelSelectors[i]; const fieldSelector = `spec.nodeName=${name}`; const { response, body: pods } = await coreV1Client.listPodForAllNamespaces(undefined, undefined, fieldSelector, labelSelector); if (response.statusCode !== 200) { throw new Error(`List pods response status: ${response.statusCode}`); } logger.debug(`Found ${pods.items.length} pods matching labelSelector ${labelSelector}`); for (let j = 0; j < pods.items.length; j++) { const pod = pods.items[j]; if (shouldDrain(pod)) { const result = await evict(coreV1Client, pod); waitAndRetry = waitAndRetry || result.waitAndRetry; misconfiguredPolicyDisruptionBudget = misconfiguredPolicyDisruptionBudget || result.misconfiguredPolicyDisruptionBudget; } } } return { waitAndRetry, misconfiguredPolicyDisruptionBudget }; } async function evict(coreV1Client: CoreV1Api, pod: V1Pod): Promise<drainResult> { const name = _.get(pod, "metadata.name", ""); const namespace = _.get(pod, "metadata.namespace", ""); const eviction: V1beta1Eviction = { apiVersion: "policy/v1beta1", kind: "Eviction", metadata: { name, namespace, }, }; logger.info(`Evicting pod ${name} in namespace ${namespace} from node ${_.get(pod, "spec.nodeName")}`); const result = { waitAndRetry: false, misconfiguredPolicyDisruptionBudget: false }; const { response } = await coreV1Client.createNamespacedPodEviction(name, namespace, eviction); switch (response.statusCode) { case 200: // fallthrough case 201: return result; case 429: logger.warn(`Failed to delete pod ${name}: 429: PodDisruptionBudget is preventing deletion`); result.waitAndRetry = true; return result; case 500: // Misconfigured, e.g. included in multiple budgets logger.error(`Failed to evict pod ${name}: 500: possible PodDisruptionBudget misconfiguration`); result.misconfiguredPolicyDisruptionBudget = true; return result; default: throw new Error(`Unexpected response code ${response.statusCode}`); } } function shouldDrain(pod: V1Pod): boolean { // completed pods always ok to drain if (isFinished(pod)) { return true; } if (isMirror(pod)) { logger.info(`Skipping drain of mirror pod ${_.get(pod, "metadata.name")} in namespace ${_.get(pod, "metadata.namespace")}`); return false; } // TODO if orphaned it's ok to delete the pod if (isDaemonSetPod(pod)) { logger.info(`Skipping drain of DaemonSet pod ${_.get(pod, "metadata.name")} in namespace ${_.get(pod, "metadata.namespace")}`); return false; } return true; } function isFinished(pod: V1Pod): boolean { const phase = _.get(pod, "status.phase"); // https://github.com/kubernetes/api/blob/5524a3672fbb1d8e9528811576c859dbedffeed7/core/v1/types.go#L2414 const succeeded = "Succeeded"; const failed = "Failed"; return phase === succeeded || phase === failed; } function isMirror(pod: V1Pod): boolean { const mirrorAnnotation = "kubernetes.io/config.mirror"; const annotations = pod.metadata && pod.metadata.annotations; return annotations ? _.has(annotations, mirrorAnnotation) : false; } function isDaemonSetPod(pod: V1Pod): boolean { return _.some(_.get(pod, "metadata.ownerReferences", []), (ownerRef: V1OwnerReference) => { return ownerRef.controller && ownerRef.kind === "DaemonSet"; }); } async function purge(name: string) { const kc = new KubeConfig(); kc.loadFromDefault(); const coreV1Client: CoreV1Api = kc.makeApiClient(CoreV1Api); const appsV1Client: AppsV1Api = kc.makeApiClient(AppsV1Api); const exec: Exec = new Exec(kc); let { response, body: node } = await coreV1Client.readNode(name); if (response.statusCode !== 200) { throw new ReplicatedError(`get node ${name} response: ${response.statusCode}`); } ({ response } = await coreV1Client.deleteNode(name)); if (response.statusCode !== 200) { throw new Error(`Delete node returned status code ${response.statusCode}`); } await purgeOSD(coreV1Client, appsV1Client, exec, name); const isMaster = _.has(node.metadata!.labels!, "node-role.kubernetes.io/master"); if (isMaster) { logger.debug(`Node ${name} is a master: running etcd and kubeadm endpoints purge steps`); await purgeMaster(coreV1Client, node); } else { logger.debug(`Node ${name} is not a master: skipping etcd and kubeadm endpoints purge steps`); } } async function purgeMaster(coreV1Client: CoreV1Api, node: V1Node) { const remainingMasterIPs: Array<string> = []; let purgedMasterIP = ""; // 1. Remove the purged endpoint from kubeadm's list of API endpoints in the kubeadm-config // ConfigMap in the kube-system namespace. Keep the list of all master IPs for step 2. const configMapName = "kubeadm-config"; const configMapNS = "kube-system"; const configMapKey = "ClusterStatus"; const { response: cmResponse, body: kubeadmCM } = await coreV1Client.readNamespacedConfigMap(configMapName, configMapNS); if (cmResponse.statusCode !== 200) { throw new Error(`Get kubeadm-config map from kube-system namespace: ${cmResponse.statusCode}`); } const clusterStatus = yaml.safeLoad(kubeadmCM.data![configMapKey]); _.each(clusterStatus.apiEndpoints, (obj, nodeName) => { if (nodeName === node.metadata!.name) { purgedMasterIP = obj.advertiseAddress; } else { remainingMasterIPs.push(obj.advertiseAddress); } }); delete(clusterStatus.apiEndpoints[node.metadata!.name!]); kubeadmCM.data![configMapKey] = yaml.safeDump(clusterStatus); const { response: cmReplaceResp } = await coreV1Client.replaceNamespacedConfigMap(configMapName, configMapNS, kubeadmCM); if (!purgedMasterIP) { logger.warn(`Failed to find IP of deleted master node from kubeadm-config: skipping etcd peer removal step`); return; } if (!remainingMasterIPs.length) { logger.error(`Cannot remove etcd peer: no remaining etcd endpoints available to connect to`); return; } // 2. Use the credentials from the mounted etcd client cert secret to connect to the remaining // etcd members and tell them to forget the purged member. const etcd = new Etcd3({ credentials: { rootCertificate: fs.readFileSync("/etc/kubernetes/pki/etcd/ca.crt"), privateKey: fs.readFileSync("/etc/kubernetes/pki/etcd/client.key"), certChain: fs.readFileSync("/etc/kubernetes/pki/etcd/client.crt"), }, hosts: _.map(remainingMasterIPs, (ip) => `https://${ip}:2379`), }); const peerURL = `https://${purgedMasterIP}:2380`; const { members } = await etcd.cluster.memberList(); const purgedMember = _.find(members, (member) => { return _.includes(member.peerURLs, peerURL); }); if (!purgedMember) { logger.info(`Purged node was not a member of etcd cluster`); return; } logger.info(`Removing etcd member ${purgedMember.ID} ${purgedMember.name}`); await etcd.cluster.memberRemove({ ID: purgedMember.ID }); } async function purgeOSD(coreV1Client: CoreV1Api, appsV1Client: AppsV1Api, exec: Exec, nodeName: string): Promise<void> { const namespace = "rook-ceph"; // 1. Find the Deployment for the OSD on the purged node and lookup its osd ID from labels // before deleting it. const osdLabelSelector = "app=rook-ceph-osd"; let { response, body: deployments } = await appsV1Client.listNamespacedDeployment(namespace, undefined, undefined, undefined, undefined, osdLabelSelector); if (response.statusCode === 404) { return; } if (response.statusCode !== 200) { throw new Error(`List osd deployments in rook-ceph namespace returned status code ${response.statusCode}`); } let osdID = ""; for (let i = 0; i < deployments.items.length; i++) { const deploy = deployments.items[i]; const hostname = deploy.spec!.template!.spec!.nodeSelector!["kubernetes.io/hostname"] if (hostname === nodeName) { osdID = deploy.metadata!.labels!["ceph-osd-id"]; logger.info(`Deleting OSD deployment on host ${nodeName}`); ({ response } = await appsV1Client.deleteNamespacedDeployment(deploy.metadata!.name!, namespace, undefined, undefined, undefined, undefined, "Background")); if (response.statusCode !== 200) { throw new Error(`Got response status code ${response.statusCode}`); } break; } } if (osdID === "") { logger.info("Failed to find ceph osd id for node"); return; } logger.info(`Purging ceph OSD with id ${osdID}`); // 2. Using the osd ID discovered in step 1, exec into the Rook operator pod and run the ceph // command to purge the OSD const operatorLabelSelector = "app=rook-ceph-operator"; let { response: resp, body: pods } = await coreV1Client.listNamespacedPod(namespace, undefined, undefined, undefined, undefined, operatorLabelSelector); if (resp.statusCode !== 200) { throw new Error(`List operator pod in rook-ceph namespace returned status code ${resp.statusCode}`); } if (pods.items.length !== 1) { logger.warn(`Found ${pods.items.length} rook operator pods: skipping osd purge command`); return; } const pod = pods.items[0]; await new Promise((resolve, reject) => { exec.exec( "rook-ceph", pod.metadata!.name!, "rook-ceph-operator", ["ceph", "osd", "purge", osdID, "--force"], process.stdout, process.stderr, null, false, (v1Status: V1Status) => { if (v1Status.status === "Failure") { reject(new Error(v1Status.message)); return; } resolve(); }, ); }) }
the_stack
import { expect } from "chai"; import * as faker from "faker"; import { enablePatches } from "immer"; import * as sinon from "sinon"; import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend"; import { ChildNodeSpecificationTypes, RuleTypes } from "@itwin/presentation-common"; import { IPresentationTreeDataProvider, PresentationTreeNodeLoaderProps, usePresentationTreeNodeLoader } from "@itwin/presentation-components"; import { Presentation } from "@itwin/presentation-frontend"; import { PrimitiveValue } from "@itwin/appui-abstract"; import { AbstractTreeNodeLoader, DelayLoadedTreeNodeItem, MutableTreeModelNode, PagedTreeNodeLoader, Subscription, TreeModelNode, TreeModelRootNode, TreeModelSource, } from "@itwin/components-react"; import { renderHook } from "@testing-library/react-hooks"; import { initialize, terminate } from "../IntegrationTests"; describe("Update", () => { let imodel: IModelConnection; before(async () => { enablePatches(); await initialize(); const testIModelName: string = "assets/datasets/Properties_60InstancesWithUrl2.ibim"; imodel = await SnapshotConnection.openFile(testIModelName); expect(imodel).is.not.null; }); after(async () => { await imodel.close(); await terminate(); }); afterEach(() => { sinon.restore(); }); describe("detection", () => { let defaultProps: Omit<PresentationTreeNodeLoaderProps, "ruleset">; beforeEach(() => { defaultProps = { imodel, pagingSize: 100, enableHierarchyAutoUpdate: true, }; }); describe("on ruleset modification", () => { it("detects custom node change", async () => { const initialRuleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_NODE", label: "test-1", }], }], }); const hierarchy = await verifyHierarchy({ ...defaultProps, ruleset: initialRuleset.id }, ["test-1"]); await Presentation.presentation.rulesets().modify( initialRuleset, { rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_NODE", label: "test-2", }], }], }, ); await hierarchy.verifyChange(["test-2"]); }); it("detects ECInstance node change", async () => { const initialRuleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "Generic", classNames: ["PhysicalObject"] }, groupByClass: false, groupByLabel: false, }], }], }); const hierarchy = await verifyHierarchy( { ...defaultProps, ruleset: initialRuleset.id }, ["Physical Object [0-38]", "Physical Object [0-39]"], ); await Presentation.presentation.rulesets().modify(initialRuleset, { rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "Generic", classNames: ["PhysicalObject"] }, instanceFilter: `this.ECInstanceId = ${parseInt("0x75", 16)}`, groupByClass: false, groupByLabel: false, }], }], }); await hierarchy.verifyChange(["Physical Object [0-39]"]); }); it("detects ECClass grouping node change", async () => { const initialRuleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "Generic", classNames: ["PhysicalObject"] }, instanceFilter: `this.ECInstanceId = ${parseInt("0x74", 16)}`, groupByClass: true, groupByLabel: false, }], }], }); const hierarchy = await verifyHierarchy( { ...defaultProps, ruleset: initialRuleset.id }, [{ ["Physical Object"]: ["Physical Object [0-38]"] }], ); await Presentation.presentation.rulesets().modify(initialRuleset, { rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "Generic", classNames: ["PhysicalObject"] }, instanceFilter: `this.ECInstanceId = ${parseInt("0x75", 16)}`, groupByClass: true, groupByLabel: false, }], }], }); await hierarchy.verifyChange([{ ["Physical Object"]: ["Physical Object [0-39]"] }]); }); }); describe("on ruleset variables' modification", () => { it("detects a change in rule condition", async () => { const ruleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [{ ruleType: RuleTypes.RootNodes, subConditions: [ { condition: `GetVariableBoolValue("use_first")`, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_NODE_1", label: "test-1", }], }, { condition: `GetVariableBoolValue("use_second")`, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_NODE_2", label: "test-2", }], }, ], }], }); await Presentation.presentation.vars(ruleset.id).setBool("use_first", false); await Presentation.presentation.vars(ruleset.id).setBool("use_second", false); const hierarchy = await verifyHierarchy({ ...defaultProps, ruleset: ruleset.id }, []); await Presentation.presentation.vars(ruleset.id).setBool("use_first", true); await hierarchy.verifyChange(["test-1"]); await Presentation.presentation.vars(ruleset.id).setBool("use_second", true); await hierarchy.verifyChange(["test-1", "test-2"]); await Presentation.presentation.vars(ruleset.id).setBool("use_first", false); await hierarchy.verifyChange(["test-2"]); }); it("detects a change in instance filter", async () => { const ruleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "Generic", classNames: ["PhysicalObject"] }, instanceFilter: `GetVariableBoolValue("show_nodes")`, groupByClass: false, groupByLabel: false, }], }], }); await Presentation.presentation.vars(ruleset.id).setBool("show_nodes", false); const hierarchy = await verifyHierarchy({ ...defaultProps, ruleset: ruleset.id }, []); await Presentation.presentation.vars(ruleset.id).setBool("show_nodes", true); await hierarchy.verifyChange(["Physical Object [0-38]", "Physical Object [0-39]"]); await Presentation.presentation.vars(ruleset.id).setBool("show_nodes", false); await hierarchy.verifyChange([]); }); it("detects a change in customization rule's condition", async () => { const ruleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [ { ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "Generic", classNames: ["PhysicalObject"] }, groupByClass: false, groupByLabel: false, }], }, { ruleType: RuleTypes.StyleOverride, condition: `GetVariableBoolValue("should_customize")`, foreColor: `"Red"`, }, ], }); const hierarchy = await verifyHierarchy( { ...defaultProps, ruleset: ruleset.id }, ["Physical Object [0-38]", "Physical Object [0-39]"], ); await Presentation.presentation.vars(ruleset.id).setBool("should_customize", true); await hierarchy.verifyChange([ { label: "Physical Object [0-38]", color: 0xFF0000 }, { label: "Physical Object [0-39]", color: 0xFF0000 }, ]); }); it("detects a change in customization rule's value", async () => { const ruleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [ { ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "Generic", classNames: ["PhysicalObject"] }, groupByClass: false, groupByLabel: false, }], }, { ruleType: RuleTypes.StyleOverride, condition: `ThisNode.IsOfClass("PhysicalObject", "Generic")`, foreColor: `GetVariableStringValue("custom_color")`, }, ], }); const hierarchy = await verifyHierarchy( { ...defaultProps, ruleset: ruleset.id }, ["Physical Object [0-38]", "Physical Object [0-39]"], ); await Presentation.presentation.vars(ruleset.id).setString("custom_color", "Red"); await hierarchy.verifyChange([ { label: "Physical Object [0-38]", color: 0xFF0000 }, { label: "Physical Object [0-39]", color: 0xFF0000 }, ]); await Presentation.presentation.vars(ruleset.id).setString("custom_color", "Blue"); await hierarchy.verifyChange([ { label: "Physical Object [0-38]", color: 0x0000FF }, { label: "Physical Object [0-39]", color: 0x0000FF }, ]); }); it("detects changes of root and expanded nodes", async () => { const ruleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [ { ruleType: RuleTypes.RootNodes, specifications: [ { specType: ChildNodeSpecificationTypes.CustomNode, type: "T_ROOT_1", label: "root-1", hasChildren: "Unknown", }, { specType: ChildNodeSpecificationTypes.CustomNode, type: "T_ROOT_2", label: "root-2", hasChildren: "Unknown", }, ], }, { ruleType: RuleTypes.ChildNodes, condition: `ParentNode.Type = "T_ROOT_1" ANDALSO GetVariableBoolValue("show_children")`, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_CHILD_1", label: "child-1", }], }, { ruleType: RuleTypes.ChildNodes, condition: `ParentNode.Type = "T_ROOT_2" ANDALSO GetVariableBoolValue("show_children")`, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_CHILD_2", label: "child-2", }], }, ], }); await Presentation.presentation.vars(ruleset.id).setBool("show_children", true); const hierarchy = await verifyHierarchy( { ...defaultProps, ruleset: ruleset.id }, [{ ["root-1"]: ["child-1"] }, { ["root-2"]: ["child-2"] }], ); hierarchy.getModelSource().modifyModel((model) => { // expand only the `root-1` node (model.getNode(undefined, 0) as MutableTreeModelNode).isExpanded = true; }); await Presentation.presentation.vars(ruleset.id).setBool("show_children", false); await hierarchy.verifyChange(["root-1", "root-2"]); }); }); describe("partial update", () => { it("handles node insertion", async () => { const ruleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_NODE", label: "test-1" }], }], }); const hierarchy = await verifyHierarchy({ ...defaultProps, ruleset: ruleset.id }, ["test-1"]); await Presentation.presentation.rulesets().modify( ruleset, { rules: [{ ruleType: RuleTypes.RootNodes, specifications: [ { specType: ChildNodeSpecificationTypes.CustomNode, type: "T_NODE", label: "test-1" }, { specType: ChildNodeSpecificationTypes.CustomNode, type: "T_NODE", label: "test-2" }, ], }], }, ); await hierarchy.verifyChange(["test-1", "test-2"]); }); it("handles node update", async () => { const ruleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_NODE", label: "test-1" }], }], }); const hierarchy = await verifyHierarchy({ ...defaultProps, ruleset: ruleset.id }, ["test-1"]); await Presentation.presentation.rulesets().modify( ruleset, { rules: [{ ruleType: RuleTypes.RootNodes, specifications: [ { specType: ChildNodeSpecificationTypes.CustomNode, type: "T_NODE", label: "test-updated" }, ], }], }, ); await hierarchy.verifyChange(["test-updated"]); }); it("handles node removal", async () => { const ruleset = await Presentation.presentation.rulesets().add({ id: faker.random.uuid(), rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_NODE", label: "test-1" }], }], }); const hierarchy = await verifyHierarchy({ ...defaultProps, ruleset: ruleset.id }, ["test-1"]); await Presentation.presentation.rulesets().modify( ruleset, { rules: [{ ruleType: RuleTypes.RootNodes, specifications: [], }], }, ); await hierarchy.verifyChange([]); }); }); interface VerifiedHierarchy { getModelSource(): TreeModelSource; verifyChange: (expectedTree: TreeHierarchy[]) => Promise<void>; } type TreeHierarchy = string | { [label: string]: TreeHierarchy[]; } | { label: string; children?: TreeHierarchy[]; expanded?: true; color?: number; }; async function verifyHierarchy( props: PresentationTreeNodeLoaderProps, expectedTree: TreeHierarchy[], ): Promise<VerifiedHierarchy> { const { result, waitForNextUpdate } = renderHook( (hookProps: PresentationTreeNodeLoaderProps) => usePresentationTreeNodeLoader(hookProps).nodeLoader, { initialProps: props }, ); await expectTree(result.current, expectedTree); return new class implements VerifiedHierarchy { public getModelSource(): TreeModelSource { return result.current.modelSource; } public async verifyChange(expectedUpdatedTree: TreeHierarchy[]): Promise<void> { await waitForNextUpdate({ timeout: 9999999 }); await expectTree(result.current, expectedUpdatedTree); } }(); } async function expectTree( nodeLoader: PagedTreeNodeLoader<IPresentationTreeDataProvider>, expectedHierarchy: TreeHierarchy[], ): Promise<void> { await loadHierarchy(nodeLoader); const model = nodeLoader.modelSource.getModel(); const actualHierarchy = buildActualHierarchy(undefined); expect(actualHierarchy).to.deep.equal(expectedHierarchy); function buildActualHierarchy(parentId: string | undefined): TreeHierarchy[] { const result: TreeHierarchy[] = []; for (const childId of model.getChildren(parentId) ?? []) { const node = model.getNode(childId) as TreeModelNode; const label = (node.label.value as PrimitiveValue).displayValue!; const children = buildActualHierarchy(childId); const additionalProperties: Partial<TreeHierarchy> = {}; if (node.isExpanded) { additionalProperties.expanded = true; } if (node.item.style?.colorOverrides?.color !== undefined) { additionalProperties.color = node.item.style.colorOverrides.color; } if (Object.keys(additionalProperties).length > 0) { result.push({ label, ...additionalProperties, ...(children.length > 0 && { children }) }); } else if (children.length > 0) { result.push({ [label]: children }); } else { result.push(label); } } return result; } } async function loadHierarchy(loader: AbstractTreeNodeLoader): Promise<void> { await loadChildren(loader.modelSource.getModel().getRootNode()); async function loadChildren(parent: TreeModelNode | TreeModelRootNode): Promise<void> { const numChildren = await getChildrenCount(parent); for (let i = 0; i < numChildren; ++i) { await waitForCompletion(loader.loadNode(parent, i).subscribe()); } const children = loader.modelSource.getModel().getChildren(parent.id); if (children === undefined) { return; } for (const sparseValue of children.iterateValues()) { const child = loader.modelSource.getModel().getNode(sparseValue[0]); if (child && (child.item as DelayLoadedTreeNodeItem).hasChildren) { await loadChildren(child); } } } async function getChildrenCount(parent: TreeModelNode | TreeModelRootNode): Promise<number> { await waitForCompletion(loader.loadNode(parent, 0).subscribe()); const treeModel = loader.modelSource.getModel(); const node = parent.id ? treeModel.getNode(parent.id) : treeModel.getRootNode(); return node!.numChildren!; } async function waitForCompletion(subscription: Subscription): Promise<void> { return new Promise((resolve) => subscription.add(resolve)); } } }); });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Services } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { SearchManagementClient } from "../searchManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { SearchService, ServicesListByResourceGroupNextOptionalParams, ServicesListByResourceGroupOptionalParams, ServicesListBySubscriptionNextOptionalParams, ServicesListBySubscriptionOptionalParams, ServicesCreateOrUpdateOptionalParams, ServicesCreateOrUpdateResponse, SearchServiceUpdate, ServicesUpdateOptionalParams, ServicesUpdateResponse, ServicesGetOptionalParams, ServicesGetResponse, ServicesDeleteOptionalParams, ServicesListByResourceGroupResponse, ServicesListBySubscriptionResponse, ServicesCheckNameAvailabilityOptionalParams, ServicesCheckNameAvailabilityResponse, ServicesListByResourceGroupNextResponse, ServicesListBySubscriptionNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Services operations. */ export class ServicesImpl implements Services { private readonly client: SearchManagementClient; /** * Initialize a new instance of the class Services class. * @param client Reference to the service client */ constructor(client: SearchManagementClient) { this.client = client; } /** * Gets a list of all search services in the given resource group. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: ServicesListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<SearchService> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: ServicesListByResourceGroupOptionalParams ): AsyncIterableIterator<SearchService[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: ServicesListByResourceGroupOptionalParams ): AsyncIterableIterator<SearchService> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Gets a list of all search services in the given subscription. * @param options The options parameters. */ public listBySubscription( options?: ServicesListBySubscriptionOptionalParams ): PagedAsyncIterableIterator<SearchService> { const iter = this.listBySubscriptionPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listBySubscriptionPagingPage(options); } }; } private async *listBySubscriptionPagingPage( options?: ServicesListBySubscriptionOptionalParams ): AsyncIterableIterator<SearchService[]> { let result = await this._listBySubscription(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listBySubscriptionNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listBySubscriptionPagingAll( options?: ServicesListBySubscriptionOptionalParams ): AsyncIterableIterator<SearchService> { for await (const page of this.listBySubscriptionPagingPage(options)) { yield* page; } } /** * Creates or updates a search service in the given resource group. If the search service already * exists, all properties will be updated with the given values. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service to create or update. Search * service names must only contain lowercase letters, digits or dashes, cannot use dash as the first * two or last one characters, cannot contain consecutive dashes, and must be between 2 and 60 * characters in length. Search service names must be globally unique since they are part of the * service URI (https://<name>.search.windows.net). You cannot change the service name after the * service is created. * @param service The definition of the search service to create or update. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, searchServiceName: string, service: SearchService, options?: ServicesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<ServicesCreateOrUpdateResponse>, ServicesCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ServicesCreateOrUpdateResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, searchServiceName, service, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Creates or updates a search service in the given resource group. If the search service already * exists, all properties will be updated with the given values. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service to create or update. Search * service names must only contain lowercase letters, digits or dashes, cannot use dash as the first * two or last one characters, cannot contain consecutive dashes, and must be between 2 and 60 * characters in length. Search service names must be globally unique since they are part of the * service URI (https://<name>.search.windows.net). You cannot change the service name after the * service is created. * @param service The definition of the search service to create or update. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, searchServiceName: string, service: SearchService, options?: ServicesCreateOrUpdateOptionalParams ): Promise<ServicesCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, searchServiceName, service, options ); return poller.pollUntilDone(); } /** * Updates an existing search service in the given resource group. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service to update. * @param service The definition of the search service to update. * @param options The options parameters. */ update( resourceGroupName: string, searchServiceName: string, service: SearchServiceUpdate, options?: ServicesUpdateOptionalParams ): Promise<ServicesUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, searchServiceName, service, options }, updateOperationSpec ); } /** * Gets the search service with the given name in the given resource group. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service associated with the * specified resource group. * @param options The options parameters. */ get( resourceGroupName: string, searchServiceName: string, options?: ServicesGetOptionalParams ): Promise<ServicesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, searchServiceName, options }, getOperationSpec ); } /** * Deletes a search service in the given resource group, along with its associated resources. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param searchServiceName The name of the Azure Cognitive Search service associated with the * specified resource group. * @param options The options parameters. */ delete( resourceGroupName: string, searchServiceName: string, options?: ServicesDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, searchServiceName, options }, deleteOperationSpec ); } /** * Gets a list of all search services in the given resource group. * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: ServicesListByResourceGroupOptionalParams ): Promise<ServicesListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * Gets a list of all search services in the given subscription. * @param options The options parameters. */ private _listBySubscription( options?: ServicesListBySubscriptionOptionalParams ): Promise<ServicesListBySubscriptionResponse> { return this.client.sendOperationRequest( { options }, listBySubscriptionOperationSpec ); } /** * Checks whether or not the given search service name is available for use. Search service names must * be globally unique since they are part of the service URI (https://<name>.search.windows.net). * @param name The search service name to validate. Search service names must only contain lowercase * letters, digits or dashes, cannot use dash as the first two or last one characters, cannot contain * consecutive dashes, and must be between 2 and 60 characters in length. * @param options The options parameters. */ checkNameAvailability( name: string, options?: ServicesCheckNameAvailabilityOptionalParams ): Promise<ServicesCheckNameAvailabilityResponse> { return this.client.sendOperationRequest( { name, options }, checkNameAvailabilityOperationSpec ); } /** * ListByResourceGroupNext * @param resourceGroupName The name of the resource group within the current subscription. You can * obtain this value from the Azure Resource Manager API or the portal. * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method. * @param options The options parameters. */ private _listByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: ServicesListByResourceGroupNextOptionalParams ): Promise<ServicesListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } /** * ListBySubscriptionNext * @param nextLink The nextLink from the previous successful call to the ListBySubscription method. * @param options The options parameters. */ private _listBySubscriptionNext( nextLink: string, options?: ServicesListBySubscriptionNextOptionalParams ): Promise<ServicesListBySubscriptionNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listBySubscriptionNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.SearchService }, 201: { bodyMapper: Mappers.SearchService }, 202: { bodyMapper: Mappers.SearchService }, 204: { bodyMapper: Mappers.SearchService }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.service, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.searchServiceName, Parameters.subscriptionId ], headerParameters: [ Parameters.accept, Parameters.clientRequestId, Parameters.contentType ], mediaType: "json", serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.SearchService }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.service1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.searchServiceName, Parameters.subscriptionId ], headerParameters: [ Parameters.accept, Parameters.clientRequestId, Parameters.contentType ], mediaType: "json", serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SearchService }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.searchServiceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.clientRequestId], serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, 404: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.searchServiceName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.clientRequestId], serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SearchServiceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId ], headerParameters: [Parameters.accept, Parameters.clientRequestId], serializer }; const listBySubscriptionOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Search/searchServices", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SearchServiceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept, Parameters.clientRequestId], serializer }; const checkNameAvailabilityOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Search/checkNameAvailability", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.CheckNameAvailabilityOutput }, default: { bodyMapper: Mappers.CloudError } }, requestBody: { parameterPath: { name: ["name"], typeParam: ["typeParam"] }, mapper: { ...Mappers.CheckNameAvailabilityInput, required: true } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [ Parameters.accept, Parameters.clientRequestId, Parameters.contentType ], mediaType: "json", serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SearchServiceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.resourceGroupName, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept, Parameters.clientRequestId], serializer }; const listBySubscriptionNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.SearchServiceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept, Parameters.clientRequestId], serializer };
the_stack
import { Resource, StoredProcedureDefinition, TriggerDefinition, UserDefinedFunctionDefinition } from "@azure/cosmos"; import * as ko from "knockout"; import * as _ from "underscore"; import * as Constants from "../../Common/Constants"; import { bulkCreateDocument } from "../../Common/dataAccess/bulkCreateDocument"; import { createDocument } from "../../Common/dataAccess/createDocument"; import { getCollectionUsageSizeInKB } from "../../Common/dataAccess/getCollectionDataUsageSize"; import { readCollectionOffer } from "../../Common/dataAccess/readCollectionOffer"; import { readStoredProcedures } from "../../Common/dataAccess/readStoredProcedures"; import { readTriggers } from "../../Common/dataAccess/readTriggers"; import { readUserDefinedFunctions } from "../../Common/dataAccess/readUserDefinedFunctions"; import { getErrorMessage, getErrorStack } from "../../Common/ErrorHandlingUtils"; import * as Logger from "../../Common/Logger"; import { fetchPortalNotifications } from "../../Common/PortalNotifications"; import * as DataModels from "../../Contracts/DataModels"; import * as ViewModels from "../../Contracts/ViewModels"; import { UploadDetailsRecord } from "../../Contracts/ViewModels"; import { useTabs } from "../../hooks/useTabs"; import { Action, ActionModifiers } from "../../Shared/Telemetry/TelemetryConstants"; import * as TelemetryProcessor from "../../Shared/Telemetry/TelemetryProcessor"; import { userContext } from "../../UserContext"; import { SqlTriggerResource } from "../../Utils/arm/generatedClients/cosmos/types"; import { isServerlessAccount } from "../../Utils/CapabilityUtils"; import { logConsoleInfo } from "../../Utils/NotificationConsoleUtils"; import Explorer from "../Explorer"; import { useCommandBar } from "../Menus/CommandBar/CommandBarComponentAdapter"; import { CassandraAPIDataClient, CassandraTableKey, CassandraTableKeys } from "../Tables/TableDataClient"; import ConflictsTab from "../Tabs/ConflictsTab"; import DocumentsTab from "../Tabs/DocumentsTab"; import GraphTab from "../Tabs/GraphTab"; import MongoDocumentsTab from "../Tabs/MongoDocumentsTab"; import { NewMongoQueryTab } from "../Tabs/MongoQueryTab/MongoQueryTab"; import { NewMongoShellTab } from "../Tabs/MongoShellTab/MongoShellTab"; import { NewQueryTab } from "../Tabs/QueryTab/QueryTab"; import QueryTablesTab from "../Tabs/QueryTablesTab"; import { CollectionSettingsTabV2 } from "../Tabs/SettingsTabV2"; import { useDatabases } from "../useDatabases"; import { useSelectedNode } from "../useSelectedNode"; import ConflictId from "./ConflictId"; import DocumentId from "./DocumentId"; import StoredProcedure from "./StoredProcedure"; import Trigger from "./Trigger"; import UserDefinedFunction from "./UserDefinedFunction"; export default class Collection implements ViewModels.Collection { public nodeKind: string; public container: Explorer; public self: string; public rid: string; public databaseId: string; public partitionKey: DataModels.PartitionKey; public partitionKeyPropertyHeader: string; public partitionKeyProperty: string; public id: ko.Observable<string>; public defaultTtl: ko.Observable<number>; public indexingPolicy: ko.Observable<DataModels.IndexingPolicy>; public uniqueKeyPolicy: DataModels.UniqueKeyPolicy; public usageSizeInKB: ko.Observable<number>; public offer: ko.Observable<DataModels.Offer>; public conflictResolutionPolicy: ko.Observable<DataModels.ConflictResolutionPolicy>; public changeFeedPolicy: ko.Observable<DataModels.ChangeFeedPolicy>; public partitions: ko.Computed<number>; public throughput: ko.Computed<number>; public rawDataModel: DataModels.Collection; public analyticalStorageTtl: ko.Observable<number>; public schema: DataModels.ISchema; public requestSchema: () => void; public geospatialConfig: ko.Observable<DataModels.GeospatialConfig>; // TODO move this to API customization class public cassandraKeys: CassandraTableKeys; public cassandraSchema: CassandraTableKey[]; public documentIds: ko.ObservableArray<DocumentId>; public children: ko.ObservableArray<ViewModels.TreeNode>; public storedProcedures: ko.Computed<StoredProcedure[]>; public userDefinedFunctions: ko.Computed<UserDefinedFunction[]>; public triggers: ko.Computed<Trigger[]>; public showStoredProcedures: ko.Observable<boolean>; public showTriggers: ko.Observable<boolean>; public showUserDefinedFunctions: ko.Observable<boolean>; public showConflicts: ko.Observable<boolean>; public selectedDocumentContent: ViewModels.Editable<any>; public selectedSubnodeKind: ko.Observable<ViewModels.CollectionTabKind>; public focusedSubnodeKind: ko.Observable<ViewModels.CollectionTabKind>; public isCollectionExpanded: ko.Observable<boolean>; public isStoredProceduresExpanded: ko.Observable<boolean>; public isUserDefinedFunctionsExpanded: ko.Observable<boolean>; public isTriggersExpanded: ko.Observable<boolean>; public documentsFocused: ko.Observable<boolean>; public settingsFocused: ko.Observable<boolean>; public storedProceduresFocused: ko.Observable<boolean>; public userDefinedFunctionsFocused: ko.Observable<boolean>; public triggersFocused: ko.Observable<boolean>; private isOfferRead: boolean; constructor(container: Explorer, databaseId: string, data: DataModels.Collection) { this.nodeKind = "Collection"; this.container = container; this.self = data._self; this.rid = data._rid; this.databaseId = databaseId; this.rawDataModel = data; this.partitionKey = data.partitionKey; this.id = ko.observable(data.id); this.defaultTtl = ko.observable(data.defaultTtl); this.indexingPolicy = ko.observable(data.indexingPolicy); this.usageSizeInKB = ko.observable(); this.offer = ko.observable(); this.conflictResolutionPolicy = ko.observable(data.conflictResolutionPolicy); this.changeFeedPolicy = ko.observable<DataModels.ChangeFeedPolicy>(data.changeFeedPolicy); this.analyticalStorageTtl = ko.observable(data.analyticalStorageTtl); this.schema = data.schema; this.requestSchema = data.requestSchema; this.geospatialConfig = ko.observable(data.geospatialConfig); // TODO fix this to only replace non-excaped single quotes this.partitionKeyProperty = (this.partitionKey && this.partitionKey.paths && this.partitionKey.paths.length && this.partitionKey.paths.length > 0 && this.partitionKey.paths[0].replace(/[/]+/g, ".").substr(1).replace(/[']+/g, "")) || null; this.partitionKeyPropertyHeader = (this.partitionKey && this.partitionKey.paths && this.partitionKey.paths.length > 0 && this.partitionKey.paths[0]) || null; if (userContext.apiType === "Mongo" && this.partitionKeyProperty && ~this.partitionKeyProperty.indexOf(`"`)) { this.partitionKeyProperty = this.partitionKeyProperty.replace(/["]+/g, ""); } // TODO #10738269 : Add this logic in a derived class for Mongo if (userContext.apiType === "Mongo" && this.partitionKeyProperty && this.partitionKeyProperty.indexOf("$v") > -1) { // From $v.shard.$v.key.$v > shard.key this.partitionKeyProperty = this.partitionKeyProperty.replace(/.\$v/g, "").replace(/\$v./g, ""); this.partitionKeyPropertyHeader = "/" + this.partitionKeyProperty; } this.documentIds = ko.observableArray<DocumentId>([]); this.isCollectionExpanded = ko.observable<boolean>(false); this.selectedSubnodeKind = ko.observable<ViewModels.CollectionTabKind>(); this.focusedSubnodeKind = ko.observable<ViewModels.CollectionTabKind>(); this.documentsFocused = ko.observable<boolean>(); this.documentsFocused.subscribe((focus) => { console.log("Focus set on Documents: " + focus); this.focusedSubnodeKind(ViewModels.CollectionTabKind.Documents); }); this.settingsFocused = ko.observable<boolean>(false); this.settingsFocused.subscribe((focus) => { this.focusedSubnodeKind(ViewModels.CollectionTabKind.Settings); }); this.storedProceduresFocused = ko.observable<boolean>(false); this.storedProceduresFocused.subscribe((focus) => { this.focusedSubnodeKind(ViewModels.CollectionTabKind.StoredProcedures); }); this.userDefinedFunctionsFocused = ko.observable<boolean>(false); this.userDefinedFunctionsFocused.subscribe((focus) => { this.focusedSubnodeKind(ViewModels.CollectionTabKind.UserDefinedFunctions); }); this.triggersFocused = ko.observable<boolean>(false); this.triggersFocused.subscribe((focus) => { this.focusedSubnodeKind(ViewModels.CollectionTabKind.Triggers); }); this.children = ko.observableArray<ViewModels.TreeNode>([]); this.children.subscribe(() => { // update the database in zustand store const database = this.getDatabase(); database.collections( database.collections()?.map((collection) => { if (collection.id() === this.id()) { return this; } return collection; }) ); useDatabases.getState().updateDatabase(database); }); this.storedProcedures = ko.computed(() => { return this.children() .filter((node) => node.nodeKind === "StoredProcedure") .map((node) => <StoredProcedure>node); }); this.userDefinedFunctions = ko.computed(() => { return this.children() .filter((node) => node.nodeKind === "UserDefinedFunction") .map((node) => <UserDefinedFunction>node); }); this.triggers = ko.computed(() => { return this.children() .filter((node) => node.nodeKind === "Trigger") .map((node) => <Trigger>node); }); const showScriptsMenus: boolean = userContext.apiType === "SQL" || userContext.apiType === "Gremlin"; this.showStoredProcedures = ko.observable<boolean>(showScriptsMenus); this.showTriggers = ko.observable<boolean>(showScriptsMenus); this.showUserDefinedFunctions = ko.observable<boolean>(showScriptsMenus); this.showConflicts = ko.observable<boolean>( userContext?.databaseAccount?.properties.enableMultipleWriteLocations && data && !!data.conflictResolutionPolicy ); this.isStoredProceduresExpanded = ko.observable<boolean>(false); this.isUserDefinedFunctionsExpanded = ko.observable<boolean>(false); this.isTriggersExpanded = ko.observable<boolean>(false); this.isOfferRead = false; } public expandCollapseCollection() { useSelectedNode.getState().setSelectedNode(this); TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, { description: "Collection node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); if (this.isCollectionExpanded()) { this.collapseCollection(); } else { this.expandCollection(); } useCommandBar.getState().setContextButtons([]); useTabs .getState() .refreshActiveTab( (tab) => tab.collection && tab.collection.databaseId === this.databaseId && tab.collection.id() === this.id() ); } public collapseCollection() { if (!this.isCollectionExpanded()) { return; } this.isCollectionExpanded(false); TelemetryProcessor.trace(Action.CollapseTreeNode, ActionModifiers.Mark, { description: "Collection node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); } public expandCollection(): void { if (this.isCollectionExpanded()) { return; } this.isCollectionExpanded(true); TelemetryProcessor.trace(Action.ExpandTreeNode, ActionModifiers.Mark, { description: "Collection node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); } public onDocumentDBDocumentsClick() { useSelectedNode.getState().setSelectedNode(this); this.selectedSubnodeKind(ViewModels.CollectionTabKind.Documents); TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, { description: "Documents node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); const documentsTabs: DocumentsTab[] = useTabs .getState() .getTabs( ViewModels.CollectionTabKind.Documents, (tab) => tab.collection && tab.collection.databaseId === this.databaseId && tab.collection.id() === this.id() ) as DocumentsTab[]; let documentsTab: DocumentsTab = documentsTabs && documentsTabs[0]; if (documentsTab) { useTabs.getState().activateTab(documentsTab); } else { const startKey: number = TelemetryProcessor.traceStart(Action.Tab, { databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: "Items", }); this.documentIds([]); documentsTab = new DocumentsTab({ partitionKey: this.partitionKey, documentIds: ko.observableArray<DocumentId>([]), tabKind: ViewModels.CollectionTabKind.Documents, title: "Items", collection: this, node: this, tabPath: `${this.databaseId}>${this.id()}>Documents`, onLoadStartKey: startKey, }); useTabs.getState().activateNewTab(documentsTab); } } public onConflictsClick() { useSelectedNode.getState().setSelectedNode(this); this.selectedSubnodeKind(ViewModels.CollectionTabKind.Conflicts); TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, { description: "Conflicts node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); const conflictsTabs: ConflictsTab[] = useTabs .getState() .getTabs( ViewModels.CollectionTabKind.Conflicts, (tab) => tab.collection && tab.collection.databaseId === this.databaseId && tab.collection.id() === this.id() ) as ConflictsTab[]; let conflictsTab: ConflictsTab = conflictsTabs && conflictsTabs[0]; if (conflictsTab) { useTabs.getState().activateTab(conflictsTab); } else { const startKey: number = TelemetryProcessor.traceStart(Action.Tab, { databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: "Conflicts", }); this.documentIds([]); const conflictsTab: ConflictsTab = new ConflictsTab({ partitionKey: this.partitionKey, conflictIds: ko.observableArray<ConflictId>([]), tabKind: ViewModels.CollectionTabKind.Conflicts, title: "Conflicts", collection: this, node: this, tabPath: `${this.databaseId}>${this.id()}>Conflicts`, onLoadStartKey: startKey, }); useTabs.getState().activateNewTab(conflictsTab); } } public onTableEntitiesClick() { useSelectedNode.getState().setSelectedNode(this); this.selectedSubnodeKind(ViewModels.CollectionTabKind.QueryTables); TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, { description: "Entities node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); if (userContext.apiType === "Cassandra" && !this.cassandraKeys) { (<CassandraAPIDataClient>this.container.tableDataClient).getTableKeys(this).then((keys: CassandraTableKeys) => { this.cassandraKeys = keys; }); } const queryTablesTabs: QueryTablesTab[] = useTabs .getState() .getTabs( ViewModels.CollectionTabKind.QueryTables, (tab) => tab.collection && tab.collection.databaseId === this.databaseId && tab.collection.id() === this.id() ) as QueryTablesTab[]; let queryTablesTab: QueryTablesTab = queryTablesTabs && queryTablesTabs[0]; if (queryTablesTab) { useTabs.getState().activateTab(queryTablesTab); } else { this.documentIds([]); let title = `Entities`; if (userContext.apiType === "Cassandra") { title = `Rows`; } const startKey: number = TelemetryProcessor.traceStart(Action.Tab, { databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: title, }); queryTablesTab = new QueryTablesTab({ tabKind: ViewModels.CollectionTabKind.QueryTables, title: title, tabPath: "", collection: this, node: this, onLoadStartKey: startKey, }); useTabs.getState().activateNewTab(queryTablesTab); } } public onGraphDocumentsClick() { useSelectedNode.getState().setSelectedNode(this); this.selectedSubnodeKind(ViewModels.CollectionTabKind.Graph); TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, { description: "Documents node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); const graphTabs: GraphTab[] = useTabs .getState() .getTabs( ViewModels.CollectionTabKind.Graph, (tab) => tab.collection && tab.collection.databaseId === this.databaseId && tab.collection.id() === this.id() ) as GraphTab[]; let graphTab: GraphTab = graphTabs && graphTabs[0]; if (graphTab) { useTabs.getState().activateTab(graphTab); } else { this.documentIds([]); const title = "Graph"; const startKey: number = TelemetryProcessor.traceStart(Action.Tab, { databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: title, }); graphTab = new GraphTab({ account: userContext.databaseAccount, tabKind: ViewModels.CollectionTabKind.Graph, node: this, title: title, tabPath: "", collection: this, masterKey: userContext.masterKey || "", collectionPartitionKeyProperty: this.partitionKeyProperty, collectionId: this.id(), databaseId: this.databaseId, isTabsContentExpanded: this.container.isTabsContentExpanded, onLoadStartKey: startKey, }); useTabs.getState().activateNewTab(graphTab); } } public onMongoDBDocumentsClick = () => { useSelectedNode.getState().setSelectedNode(this); this.selectedSubnodeKind(ViewModels.CollectionTabKind.Documents); TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, { description: "Documents node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); const mongoDocumentsTabs: MongoDocumentsTab[] = useTabs .getState() .getTabs( ViewModels.CollectionTabKind.Documents, (tab) => tab.collection && tab.collection.databaseId === this.databaseId && tab.collection.id() === this.id() ) as MongoDocumentsTab[]; let mongoDocumentsTab: MongoDocumentsTab = mongoDocumentsTabs && mongoDocumentsTabs[0]; if (mongoDocumentsTab) { useTabs.getState().activateTab(mongoDocumentsTab); } else { const startKey: number = TelemetryProcessor.traceStart(Action.Tab, { databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: "Documents", }); this.documentIds([]); mongoDocumentsTab = new MongoDocumentsTab({ partitionKey: this.partitionKey, documentIds: this.documentIds, tabKind: ViewModels.CollectionTabKind.Documents, title: "Documents", tabPath: "", collection: this, node: this, onLoadStartKey: startKey, }); useTabs.getState().activateNewTab(mongoDocumentsTab); } }; public onSchemaAnalyzerClick = async () => { useSelectedNode.getState().setSelectedNode(this); this.selectedSubnodeKind(ViewModels.CollectionTabKind.SchemaAnalyzer); const SchemaAnalyzerTab = await (await import("../Tabs/SchemaAnalyzerTab")).default; TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, { description: "Schema node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); for (const tab of useTabs.getState().openedTabs) { if ( tab instanceof SchemaAnalyzerTab && tab.collection?.databaseId === this.databaseId && tab.collection?.id() === this.id() ) { return useTabs.getState().activateTab(tab); } } const startKey = TelemetryProcessor.traceStart(Action.Tab, { databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: "Schema", }); this.documentIds([]); useTabs.getState().activateNewTab( new SchemaAnalyzerTab({ account: userContext.databaseAccount, masterKey: userContext.masterKey || "", container: this.container, tabKind: ViewModels.CollectionTabKind.SchemaAnalyzer, title: "Schema", tabPath: "", collection: this, node: this, onLoadStartKey: startKey, }) ); }; public onSettingsClick = async (): Promise<void> => { useSelectedNode.getState().setSelectedNode(this); await this.loadOffer(); this.selectedSubnodeKind(ViewModels.CollectionTabKind.Settings); TelemetryProcessor.trace(Action.SelectItem, ActionModifiers.Mark, { description: "Settings node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); const tabTitle = !this.offer() ? "Settings" : "Scale & Settings"; const matchingTabs = useTabs.getState().getTabs(ViewModels.CollectionTabKind.CollectionSettingsV2, (tab) => { return tab.collection && tab.collection.databaseId === this.databaseId && tab.collection.id() === this.id(); }); const traceStartData = { databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: tabTitle, }; const settingsTabOptions: ViewModels.TabOptions = { tabKind: undefined, title: !this.offer() ? "Settings" : "Scale & Settings", tabPath: "", collection: this, node: this, }; let settingsTabV2 = matchingTabs && (matchingTabs[0] as CollectionSettingsTabV2); this.launchSettingsTabV2(settingsTabV2, traceStartData, settingsTabOptions); }; private launchSettingsTabV2 = ( settingsTabV2: CollectionSettingsTabV2, traceStartData: any, settingsTabOptions: ViewModels.TabOptions ): void => { if (!settingsTabV2) { const startKey: number = TelemetryProcessor.traceStart(Action.Tab, traceStartData); settingsTabOptions.onLoadStartKey = startKey; settingsTabOptions.tabKind = ViewModels.CollectionTabKind.CollectionSettingsV2; settingsTabV2 = new CollectionSettingsTabV2(settingsTabOptions); useTabs.getState().activateNewTab(settingsTabV2); } else { useTabs.getState().activateTab(settingsTabV2); } }; public onNewQueryClick(source: any, event: MouseEvent, queryText?: string) { const collection: ViewModels.Collection = source.collection || source; const id = useTabs.getState().getTabs(ViewModels.CollectionTabKind.Query).length + 1; const title = "Query " + id; const startKey: number = TelemetryProcessor.traceStart(Action.Tab, { databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: title, }); useTabs.getState().activateNewTab( new NewQueryTab( { tabKind: ViewModels.CollectionTabKind.Query, title: title, tabPath: "", collection: this, node: this, queryText: queryText, partitionKey: collection.partitionKey, onLoadStartKey: startKey, }, { container: this.container } ) ); } public onNewMongoQueryClick(source: any, event: MouseEvent, queryText?: string) { const collection: ViewModels.Collection = source.collection || source; const id = useTabs.getState().getTabs(ViewModels.CollectionTabKind.Query).length + 1; const title = "Query " + id; const startKey: number = TelemetryProcessor.traceStart(Action.Tab, { databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: title, }); const newMongoQueryTab: NewMongoQueryTab = new NewMongoQueryTab( { tabKind: ViewModels.CollectionTabKind.Query, title: title, tabPath: "", collection: this, node: this, partitionKey: collection.partitionKey, onLoadStartKey: startKey, }, { container: this.container, viewModelcollection: this, } ); useTabs.getState().activateNewTab(newMongoQueryTab); } public onNewGraphClick() { const id: number = useTabs.getState().getTabs(ViewModels.CollectionTabKind.Graph).length + 1; const title: string = "Graph Query " + id; const startKey: number = TelemetryProcessor.traceStart(Action.Tab, { databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.Tab, tabTitle: title, }); const graphTab: GraphTab = new GraphTab({ account: userContext.databaseAccount, tabKind: ViewModels.CollectionTabKind.Graph, node: this, title: title, tabPath: "", collection: this, masterKey: userContext.masterKey || "", collectionPartitionKeyProperty: this.partitionKeyProperty, collectionId: this.id(), databaseId: this.databaseId, isTabsContentExpanded: this.container.isTabsContentExpanded, onLoadStartKey: startKey, }); useTabs.getState().activateNewTab(graphTab); } public onNewMongoShellClick() { const mongoShellTabs = useTabs.getState().getTabs(ViewModels.CollectionTabKind.MongoShell) as NewMongoShellTab[]; let index = 1; if (mongoShellTabs.length > 0) { index = mongoShellTabs[mongoShellTabs.length - 1].index + 1; } const mongoShellTab: NewMongoShellTab = new NewMongoShellTab( { tabKind: ViewModels.CollectionTabKind.MongoShell, title: "Shell " + index, tabPath: "", collection: this, node: this, index: index, }, { container: this.container, } ); useTabs.getState().activateNewTab(mongoShellTab); } public onNewStoredProcedureClick(source: ViewModels.Collection, event: MouseEvent) { StoredProcedure.create(source, event); } public onNewUserDefinedFunctionClick(source: ViewModels.Collection) { UserDefinedFunction.create(source); } public onNewTriggerClick(source: ViewModels.Collection, event: MouseEvent) { Trigger.create(source, event); } public createStoredProcedureNode(data: StoredProcedureDefinition & Resource): StoredProcedure { const node = new StoredProcedure(this.container, this, data); useSelectedNode.getState().setSelectedNode(node); this.children.push(node); return node; } public createUserDefinedFunctionNode(data: UserDefinedFunctionDefinition & Resource): UserDefinedFunction { const node = new UserDefinedFunction(this.container, this, data); useSelectedNode.getState().setSelectedNode(node); this.children.push(node); return node; } public createTriggerNode(data: TriggerDefinition & Resource): Trigger { const node = new Trigger(this.container, this, data); useSelectedNode.getState().setSelectedNode(node); this.children.push(node); return node; } public findStoredProcedureWithId(sprocId: string): StoredProcedure { return _.find(this.storedProcedures(), (storedProcedure: StoredProcedure) => storedProcedure.id() === sprocId); } public findTriggerWithId(triggerId: string): Trigger { return _.find(this.triggers(), (trigger: Trigger) => trigger.id() === triggerId); } public findUserDefinedFunctionWithId(userDefinedFunctionId: string): UserDefinedFunction { return _.find( this.userDefinedFunctions(), (userDefinedFunction: Trigger) => userDefinedFunction.id() === userDefinedFunctionId ); } public expandCollapseStoredProcedures() { this.selectedSubnodeKind(ViewModels.CollectionTabKind.StoredProcedures); if (this.isStoredProceduresExpanded()) { this.collapseStoredProcedures(); } else { this.expandStoredProcedures(); } useTabs .getState() .refreshActiveTab( (tab) => tab.collection && tab.collection.databaseId === this.databaseId && tab.collection.id() === this.id() ); } public expandStoredProcedures() { if (this.isStoredProceduresExpanded()) { return; } this.loadStoredProcedures().then( () => { this.isStoredProceduresExpanded(true); TelemetryProcessor.trace(Action.ExpandTreeNode, ActionModifiers.Mark, { description: "Stored procedures node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); }, (error) => { TelemetryProcessor.trace(Action.ExpandTreeNode, ActionModifiers.Failed, { description: "Stored procedures node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, error: getErrorMessage(error), }); } ); } public collapseStoredProcedures() { if (!this.isStoredProceduresExpanded()) { return; } this.isStoredProceduresExpanded(false); TelemetryProcessor.trace(Action.CollapseTreeNode, ActionModifiers.Mark, { description: "Stored procedures node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); } public expandCollapseUserDefinedFunctions() { this.selectedSubnodeKind(ViewModels.CollectionTabKind.UserDefinedFunctions); if (this.isUserDefinedFunctionsExpanded()) { this.collapseUserDefinedFunctions(); } else { this.expandUserDefinedFunctions(); } useTabs .getState() .refreshActiveTab( (tab) => tab.collection && tab.collection.databaseId === this.databaseId && tab.collection.id() === this.id() ); } public expandUserDefinedFunctions() { if (this.isUserDefinedFunctionsExpanded()) { return; } this.loadUserDefinedFunctions().then( () => { this.isUserDefinedFunctionsExpanded(true); TelemetryProcessor.trace(Action.ExpandTreeNode, ActionModifiers.Mark, { description: "UDF node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); }, (error) => { TelemetryProcessor.trace(Action.ExpandTreeNode, ActionModifiers.Failed, { description: "UDF node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, error: getErrorMessage(error), }); } ); } public collapseUserDefinedFunctions() { if (!this.isUserDefinedFunctionsExpanded()) { return; } this.isUserDefinedFunctionsExpanded(false); TelemetryProcessor.trace(Action.ExpandTreeNode, ActionModifiers.Mark, { description: "UDF node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); } public expandCollapseTriggers() { this.selectedSubnodeKind(ViewModels.CollectionTabKind.Triggers); if (this.isTriggersExpanded()) { this.collapseTriggers(); } else { this.expandTriggers(); } useTabs .getState() .refreshActiveTab( (tab) => tab.collection && tab.collection.databaseId === this.databaseId && tab.collection.id() === this.id() ); } public expandTriggers() { if (this.isTriggersExpanded()) { return; } this.loadTriggers().then( () => { this.isTriggersExpanded(true); TelemetryProcessor.trace(Action.ExpandTreeNode, ActionModifiers.Mark, { description: "Triggers node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); }, (error) => { this.isTriggersExpanded(true); TelemetryProcessor.trace(Action.ExpandTreeNode, ActionModifiers.Mark, { description: "Triggers node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, error: getErrorMessage(error), }); } ); } public collapseTriggers() { if (!this.isTriggersExpanded()) { return; } this.isTriggersExpanded(false); TelemetryProcessor.trace(Action.CollapseTreeNode, ActionModifiers.Mark, { description: "Triggers node", databaseName: this.databaseId, collectionName: this.id(), dataExplorerArea: Constants.Areas.ResourceTree, }); } public loadStoredProcedures(): Promise<any> { return readStoredProcedures(this.databaseId, this.id()).then((storedProcedures) => { const storedProceduresNodes: ViewModels.TreeNode[] = storedProcedures.map( (storedProcedure) => new StoredProcedure(this.container, this, storedProcedure) ); const otherNodes = this.children().filter((node) => node.nodeKind !== "StoredProcedure"); const allNodes = otherNodes.concat(storedProceduresNodes); this.children(allNodes); }); } public loadUserDefinedFunctions(): Promise<any> { return readUserDefinedFunctions(this.databaseId, this.id()).then((userDefinedFunctions) => { const userDefinedFunctionsNodes: ViewModels.TreeNode[] = userDefinedFunctions.map( (udf) => new UserDefinedFunction(this.container, this, udf) ); const otherNodes = this.children().filter((node) => node.nodeKind !== "UserDefinedFunction"); const allNodes = otherNodes.concat(userDefinedFunctionsNodes); this.children(allNodes); }); } public loadTriggers(): Promise<any> { return readTriggers(this.databaseId, this.id()).then((triggers) => { const triggerNodes: ViewModels.TreeNode[] = triggers.map( (trigger: SqlTriggerResource | TriggerDefinition) => new Trigger(this.container, this, trigger) ); const otherNodes = this.children().filter((node) => node.nodeKind !== "Trigger"); const allNodes = otherNodes.concat(triggerNodes); this.children(allNodes); }); } public onDragOver(source: Collection, event: { originalEvent: DragEvent }) { event.originalEvent.stopPropagation(); event.originalEvent.preventDefault(); } public onDrop(source: Collection, event: { originalEvent: DragEvent }) { event.originalEvent.stopPropagation(); event.originalEvent.preventDefault(); this.uploadFiles(event.originalEvent.dataTransfer.files); } public async getPendingThroughputSplitNotification(): Promise<DataModels.Notification> { if (!this.container) { return undefined; } try { const notifications: DataModels.Notification[] = await fetchPortalNotifications(); if (!notifications || notifications.length === 0) { return undefined; } return _.find(notifications, (notification: DataModels.Notification) => { const throughputUpdateRegExp: RegExp = new RegExp("Throughput update (.*) in progress"); return ( notification.kind === "message" && notification.collectionName === this.id() && notification.description && throughputUpdateRegExp.test(notification.description) ); }); } catch (error) { Logger.logError( JSON.stringify({ error: getErrorMessage(error), accountName: userContext?.databaseAccount, databaseName: this.databaseId, collectionName: this.id(), }), "Settings tree node" ); return undefined; } } public async uploadFiles(files: FileList): Promise<{ data: UploadDetailsRecord[] }> { const data = await Promise.all(Array.from(files).map((file) => this.uploadFile(file))); return { data }; } private uploadFile(file: File): Promise<UploadDetailsRecord> { const reader = new FileReader(); const onload = (resolve: (value: UploadDetailsRecord) => void, evt: any): void => { const fileData: string = evt.target.result; this._createDocumentsFromFile(file.name, fileData).then((record) => resolve(record)); }; const onerror = (resolve: (value: UploadDetailsRecord) => void, evt: ProgressEvent): void => { resolve({ fileName: file.name, numSucceeded: 0, numThrottled: 0, numFailed: 1, errors: [(evt as any).error.message], }); }; return new Promise<UploadDetailsRecord>((resolve) => { reader.onload = onload.bind(this, resolve); reader.onerror = onerror.bind(this, resolve); reader.readAsText(file); }); } private async _createDocumentsFromFile(fileName: string, documentContent: string): Promise<UploadDetailsRecord> { const record: UploadDetailsRecord = { fileName: fileName, numSucceeded: 0, numFailed: 0, numThrottled: 0, errors: [], }; try { const parsedContent = JSON.parse(documentContent); if (Array.isArray(parsedContent)) { const chunkSize = 100; // 100 is the max # of bulk operations the SDK currently accepts const chunkedContent = Array.from({ length: Math.ceil(parsedContent.length / chunkSize) }, (_, index) => parsedContent.slice(index * chunkSize, index * chunkSize + chunkSize) ); for (const chunk of chunkedContent) { let retryAttempts = 0; let chunkComplete = false; let documentsToAttempt = chunk; while (retryAttempts < 10 && !chunkComplete) { const responses = await bulkCreateDocument(this, documentsToAttempt); const attemptedDocuments = [...documentsToAttempt]; documentsToAttempt = []; responses.forEach((response, index) => { if (response.statusCode === 201) { record.numSucceeded++; } else if (response.statusCode === 429) { documentsToAttempt.push(attemptedDocuments[index]); } else { record.numFailed++; } }); if (documentsToAttempt.length === 0) { chunkComplete = true; break; } logConsoleInfo( `${documentsToAttempt.length} document creations were throttled. Waiting ${retryAttempts} seconds and retrying throttled documents` ); retryAttempts++; await sleep(retryAttempts); } } } else { await createDocument(this, parsedContent); record.numSucceeded++; } return record; } catch (error) { record.numFailed++; record.errors = [...record.errors, error.message]; return record; } } /** * Top-level method that will open the correct tab type depending on account API */ public openTab(): void { if (userContext.apiType === "Tables") { this.onTableEntitiesClick(); return; } else if (userContext.apiType === "Cassandra") { this.onTableEntitiesClick(); return; } else if (userContext.apiType === "Gremlin") { this.onGraphDocumentsClick(); return; } else if (userContext.apiType === "Mongo") { this.onMongoDBDocumentsClick(); return; } this.onDocumentDBDocumentsClick(); } /** * Get correct collection label depending on account API */ public getLabel(): string { if (userContext.apiType === "Tables") { return "Entities"; } else if (userContext.apiType === "Cassandra") { return "Rows"; } else if (userContext.apiType === "Gremlin") { return "Graph"; } else if (userContext.apiType === "Mongo") { return "Documents"; } return "Items"; } public getDatabase(): ViewModels.Database { return useDatabases.getState().findDatabaseWithId(this.databaseId); } public async loadOffer(): Promise<void> { if (!this.isOfferRead && !isServerlessAccount() && !this.offer()) { const startKey: number = TelemetryProcessor.traceStart(Action.LoadOffers, { databaseName: this.databaseId, collectionName: this.id(), }); const params: DataModels.ReadCollectionOfferParams = { collectionId: this.id(), collectionResourceId: this.self, databaseId: this.databaseId, }; try { this.offer(await readCollectionOffer(params)); this.usageSizeInKB(await getCollectionUsageSizeInKB(this.databaseId, this.id())); this.isOfferRead = true; TelemetryProcessor.traceSuccess( Action.LoadOffers, { databaseName: this.databaseId, collectionName: this.id(), }, startKey ); } catch (error) { TelemetryProcessor.traceFailure( Action.LoadOffers, { databaseName: this.databaseId, collectionName: this.id(), error: getErrorMessage(error), errorStack: getErrorStack(error), }, startKey ); throw error; } } } } function sleep(seconds: number) { return new Promise((resolve) => setTimeout(resolve, seconds * 1000)); }
the_stack
import * as React from "react" import Typography from "@material-ui/core/Typography" import TextField from "@material-ui/core/TextField" import Table from "@material-ui/core/Table" import TableBody from "@material-ui/core/TableBody" import TableCell from "@material-ui/core/TableCell" import TableHead from "@material-ui/core/TableHead" import TableRow from "@material-ui/core/TableRow" import { Url, GAVersion } from "@/constants" import GeneratedURL from "./GeneratedURL" import useStyles from "./useStyles" import useInputs from "./useInputs" import ExternalLink from "../../ExternalLink" import InlineCode from "../../InlineCode" const customCampaigns = ( <ExternalLink href={Url.aboutCustomCampaigns}>Custom Campaigns</ExternalLink> ) interface WebURLBuilderProps { version: GAVersion } export const WebURLBuilder: React.FC<WebURLBuilderProps> = ({ version }) => { const classes = useStyles() const { websiteURL, source, setSource, medium, setMedium, campaign, setCampaign, id, setID, term, setTerm, content, setContent, onWebsiteChange, } = useInputs() return ( <> <Typography variant="body1"> This tool allows you to easily add campaign parameters to URLs so you can measure {customCampaigns} in Google Analytics. </Typography> <Typography variant="h3"> Enter the website URL and campaign information </Typography> <Typography> Fill out all fields marked with an asterisk (*), and the campaign URL will be generated for you. </Typography> <section className={classes.inputs}> <TextField id="website-url" required value={websiteURL || ""} onChange={onWebsiteChange} label="website URL" size="small" variant="outlined" helperText={ <span> The full website URL (e.g.{" "} <span className={classes.bold}>https://www.example.com</span>) </span> } /> <TextField id="campaign-id" value={id || ""} onChange={e => setID(e.target.value)} label="campaign ID" size="small" variant="outlined" helperText={<span>The ads campaign id.</span>} /> <TextField id="campaign-source" required value={source || ""} onChange={e => setSource(e.target.value)} label="campaign source" size="small" variant="outlined" helperText={ <span> The referrer (e.g. <span className={classes.bold}>google</span>,{" "} <span className={classes.bold}>newsletter</span>) </span> } /> <TextField id="campaign-medium" required value={medium || ""} onChange={e => setMedium(e.target.value)} label="campaign medium" size="small" variant="outlined" helperText={ <span> Marketing medium (e.g. <span className={classes.bold}>cpc</span>,{" "} <span className={classes.bold}>banner</span>,{" "} <span className={classes.bold}>email</span>) </span> } /> <TextField id="campaign-name" required={version === GAVersion.UniversalAnalytics} value={campaign || ""} onChange={e => setCampaign(e.target.value)} label="campaign name" size="small" variant="outlined" helperText={ <span> Product, promo code, or slogan (e.g.{" "} <span className={classes.bold}>spring_sale</span>) One of campaign name or campaign id are required. </span> } /> <TextField id="campaign-term" value={term || ""} onChange={e => setTerm(e.target.value)} label="campaign term" size="small" variant="outlined" helperText="Identify the paid keywords" /> <TextField id="campaign-content" value={content || ""} onChange={e => setContent(e.target.value)} label="campaign content" size="small" variant="outlined" helperText="Use to differentiate ads" /> </section> <GeneratedURL version={version} source={source || ""} websiteURL={websiteURL || ""} medium={medium || ""} campaign={campaign || ""} id={id || ""} term={term || ""} content={content || ""} /> <Typography variant="h2"> More information and examples for each parameter </Typography> <Typography variant="body1"> The following table gives a detailed explanation and example of each of the campaign parameters: </Typography> <Table size="small"> <TableHead> <TableRow> <TableCell>Parameter</TableCell> <TableCell>Required</TableCell> <TableCell>Example</TableCell> <TableCell>Description</TableCell> </TableRow> </TableHead> <TableBody> <TableRow> <TableCell className={classes.denseTableCell}> <Typography variant="body1">Campaign ID</Typography> <InlineCode>utm_id</InlineCode> </TableCell> <TableCell> <Typography variant="body1">No</Typography> </TableCell> <TableCell> <Typography variant="body1"> <InlineCode>abc.123</InlineCode> </Typography> </TableCell> <TableCell> <Typography variant="body1"> Used to identify which ads campaign this referral references. Use <InlineCode>utm_id</InlineCode> to identify a specific ads campaign. </Typography> </TableCell> </TableRow> <TableRow> <TableCell className={classes.denseTableCell}> <Typography variant="body1">Campaign Source</Typography> <InlineCode>utm_source</InlineCode> </TableCell> <TableCell> <Typography variant="body1">Yes</Typography> </TableCell> <TableCell> <Typography variant="body1"> <InlineCode>google</InlineCode> </Typography> </TableCell> <TableCell> <Typography variant="body1"> Use <InlineCode>utm_source</InlineCode> to identify a search engine, newsletter name, or other source. </Typography> </TableCell> </TableRow> <TableRow> <TableCell className={classes.denseTableCell}> <Typography variant="body1">Campaign Medium</Typography> <InlineCode>utm_medium</InlineCode> </TableCell> <TableCell> <Typography variant="body1">Yes</Typography> </TableCell> <TableCell> <Typography variant="body1"> <InlineCode>cpc</InlineCode> </Typography> </TableCell> <TableCell> <Typography variant="body1"> Use <InlineCode>utm_medium</InlineCode> to identify a medium such as email or cost-per-click. </Typography> </TableCell> </TableRow> <TableRow> <TableCell className={classes.denseTableCell}> <Typography variant="body1">Campaign Name</Typography> <InlineCode>utm_campaign</InlineCode> </TableCell> <TableCell> <Typography variant="body1">No</Typography> </TableCell> <TableCell> <Typography variant="body1"> <InlineCode>spring_sale</InlineCode> </Typography> </TableCell> <TableCell> <Typography variant="body1"> Used for keyword analysis. Use{" "} <InlineCode>utm_campaign</InlineCode> to identify a specific product promotion or strategic campaign. </Typography> </TableCell> </TableRow> <TableRow> <TableCell className={classes.denseTableCell}> <Typography variant="body1">Campaign Term</Typography> <InlineCode>utm_term</InlineCode> </TableCell> <TableCell> <Typography variant="body1">No</Typography> </TableCell> <TableCell> <Typography variant="body1"> <InlineCode>running+shoes</InlineCode> </Typography> </TableCell> <TableCell> <Typography variant="body1"> Used for paid search. Use <InlineCode>utm_term</InlineCode> to note the keywords for this ad. </Typography> </TableCell> </TableRow> <TableRow> <TableCell className={classes.denseTableCell}> <Typography variant="body1">Campaign Content</Typography> <InlineCode>utm_content</InlineCode> </TableCell> <TableCell> <Typography variant="body1">No</Typography> </TableCell> <TableCell> <Typography variant="body1"> <InlineCode>logolink</InlineCode> </Typography> </TableCell> <TableCell> <Typography variant="body1"> Used for A/B testing and content-targeted ads. Use{" "} <InlineCode>utm_content</InlineCode> to differentiate ads or links that point to the same URL. </Typography> </TableCell> </TableRow> </TableBody> </Table> <Typography variant="h2">Related Resources</Typography> <Typography variant="body1" component="ul"> <li> <ExternalLink href={Url.aboutCampaign}> About Custom Campaigns </ExternalLink> </li> <li> <ExternalLink href={Url.bestPracticesForCreatingCustomCampaigns}> Best Practices for creating Custom Campaigns </ExternalLink> </li> <li> <ExternalLink href={Url.aboutReferralTrafficReport}> About the Refferal Traffic report </ExternalLink> </li> <li> <ExternalLink href={Url.aboutTrafficSourceDimensions}> About traffic source dimensions </ExternalLink> </li> <li> <ExternalLink href={Url.googleAdsAutoTagging}> Google Ads Auto-Tagging </ExternalLink> </li> </Typography> </> ) } export default WebURLBuilder
the_stack
import AutoLayout from '@lume/autolayout/es/AutoLayout.js' import {attribute, autorun, element} from '@lume/element' import {emits} from '@lume/eventful' import {Node, NodeAttributes} from '../core/Node.js' import {Motor} from '../core/Motor.js' import {autoDefineElements} from '../LumeConfig.js' import type {XYZPartialValuesArray} from '../xyz-values/XYZValues.js' export {AutoLayout} type Viewport = { width: any 'min-width': any 'max-width': any height: any 'min-height': any 'max-height': any 'aspect-ratio': number } export type AutoLayoutNodeAttributes = NodeAttributes | 'visualFormat' /** * A Node that lays children out based on an Apple AutoLayout VFL layout * description. */ @element('lume-autolayout-node', autoDefineElements) export class AutoLayoutNode extends Node { static DEFAULT_PARSE_OPTIONS = { extended: true, strict: false, } @attribute @emits('propertychange') visualFormat: string | null = '' /** * Constructor * * @param {Object} [options] options to set. * @param {String|Array} [options.visualFormat] String or array of strings containing VFL. * @param {Object} [options.layoutOptions] Options such as viewport, spacing, etc... TODO make this a reactive property. * @return {AutoLayoutNode} this */ constructor(options: any) { super() // PORTED { this.on('sizechange', this.#layout) this.on('reflow', this.#layout) // } // TODO use Settable.set instead. if (options) { if (options.visualFormat) { this.setVisualFormat(options.visualFormat) } if (options.layoutOptions) { this.setLayoutOptions(options.layoutOptions) } } } connectedCallback() { super.connectedCallback() this._stopFns.push( autorun(() => { this.setVisualFormat(this.visualFormat || '') }), ) } #autoLayoutView?: any | undefined childConnectedCallback(child: Node) { // @prod-prune if (!(child instanceof Node)) throw new Error('Child elements of AutoLayoutNode must be instances of LUME.Node.') super.childConnectedCallback(child) if (!this.#autoLayoutView) return this.#checkNodes() } childDisconnectedCallback(child: Node) { // @prod-prune if (!(child instanceof Node)) throw new Error('Child elements of AutoLayoutNode must be instances of LUME.Node.') super.childDisconnectedCallback(child) if (!this.#autoLayoutView) return const _idToNode = this.#idToNode for (const id in _idToNode) { if (_idToNode[id] === child) { delete _idToNode[id] break } } this.#checkNodes() } /** * Forces a reflow of the layout. * * @return {AutoLayoutNode} this */ reflowLayout() { if (!this.#reflowLayout) { this.#reflowLayout = true Motor.once(() => this.emit('reflow')) // PORTED } return this } /** * Sets the visual-format string. * * @param {String|Array} visualFormat String or array of strings containing VFL. * @param {Object} [parseOptions] Specify to override the parse options for the VFL. * @return {AutoLayoutNode} this */ setVisualFormat(visualFormat: string, parseOptions?: any) { // @ts-ignore: TODO, _visualFormat is not used anywhere, but it works??? this._visualFormat = visualFormat var constraints = AutoLayout.VisualFormat.parse( visualFormat, parseOptions || AutoLayoutNode.DEFAULT_PARSE_OPTIONS, ) this.#metaInfo = AutoLayout.VisualFormat.parseMetaInfo(visualFormat) this.#autoLayoutView = new AutoLayout.View({ constraints: constraints, }) this.#checkNodes() this.reflowLayout() return this } /** * Sets the options such as viewport, spacing, etc... * * @param {Object} options Layout-options to set. * @return {AutoLayoutNode} this */ setLayoutOptions(options: any) { this.#layoutOptions = options || {} this.reflowLayout() return this } /** * Adds a new child to this node. If this method is called with no argument it will * create a new node, however it can also be called with an existing node which it will * append to the node that this method is being called on. Returns the new or passed in node. * * @param {Node|void} child The node to appended or no node to create a new node. * @param {String} id Unique id of the node which matches the id used in the Visual format. * @return {Node} the appended node. */ addToLayout(child: Node, id: string) { // PORTED this.append(child) // PORTED // TODO instead of handling nodes here, we should handle them in // childComposedCallback, to support ShadowDOM. if (id) this.#idToNode[id] = child this.reflowLayout() return child } /** * Removes a child node from another node. The passed in node must be * a child of the node that this method is called upon. * * @param {Node} [child] node to be removed * @param {String} [id] Unique id of the node which matches the id used in the Visual format. */ removeFromLayout(child: Node, id: string) { // PORTED if (child && id) { this.removeChild(child) // PORTED delete this.#idToNode[id] } else if (child) { for (id in this.#idToNode) { if (this.#idToNode[id] === child) { delete this.#idToNode[id] break } } this.removeChild(child) // PORTED } else if (id) { this.removeChild(this.#idToNode[id]) // PORTED delete this.#idToNode[id] } this.reflowLayout() } #layoutOptions: any = {} #idToNode: any = {} #reflowLayout = false #metaInfo?: any #setIntrinsicWidths(widths: any) { for (var key in widths) { var subView = this.#autoLayoutView.subViews[key] var node = this.#idToNode[key] if (subView && node) { subView.intrinsicWidth = node.calculatedSize.x // PORTED } } } #setIntrinsicHeights(heights: any) { for (var key in heights) { var subView = this.#autoLayoutView.subViews[key] var node = this.#idToNode[key] if (subView && node) { subView.intrinsicHeight = node.calculatedSize.y // PORTED } } } #setViewPortSize(size: XYZPartialValuesArray<number>, vp: Viewport) { size = [ vp.width !== undefined && vp.width !== true ? vp.width : Math.max(Math.min(size[0], vp['max-width'] || size[0]), vp['min-width'] || 0), vp.height !== undefined && vp.height !== true ? vp.height : Math.max(Math.min(size[1]! /*TODO no !*/, vp['max-height'] || size[1]), vp['min-height'] || 0), ] if (vp.width === true && vp.height === true) { size[0] = this.#autoLayoutView.fittingWidth size[1] = this.#autoLayoutView.fittingHeight } else if (vp.width === true) { this.#autoLayoutView.setSize(undefined, size[1]) size[0] = this.#autoLayoutView.fittingWidth // TODO ASPECT RATIO? } else if (vp.height === true) { this.#autoLayoutView.setSize(size[0], undefined) size[1] = this.#autoLayoutView.fittingHeight // TODO ASPECT RATIO? } else { size = vp['aspect-ratio'] ? [Math.min(size[0], size[1] * vp['aspect-ratio']), Math.min(size[1], size[0] / vp['aspect-ratio'])] : size this.#autoLayoutView.setSize(size[0], size[1]) } return size } #layout = () => { if (!this.#autoLayoutView) { return } var x var y var size = this.size.toArray() if (this.#layoutOptions.spacing || this.#metaInfo.spacing) { this.#autoLayoutView.setSpacing(this.#layoutOptions.spacing || this.#metaInfo.spacing) } var widths = this.#layoutOptions.widths || this.#metaInfo.widths if (widths) { this.#setIntrinsicWidths(widths) } var heights = this.#layoutOptions.heights || this.#metaInfo.heights if (heights) { this.#setIntrinsicHeights(heights) } if (this.#layoutOptions.viewport || this.#metaInfo.viewport) { var restrainedSize = this.#setViewPortSize(size, this.#layoutOptions.viewport || this.#metaInfo.viewport) x = (size[0] - restrainedSize[0]) / 2 y = (size[1] - restrainedSize[1]) / 2 } else { this.#autoLayoutView.setSize(size[0], size[1]) x = 0 y = 0 } for (var key in this.#autoLayoutView.subViews) { var subView = this.#autoLayoutView.subViews[key] if (key.indexOf('_') !== 0 && subView.type !== 'stack') { var node = this.#idToNode[key] if (node) { this.#updateNode(node, subView, x, y, widths, heights) } } } if (this.#reflowLayout) { this.#reflowLayout = false } } #updateNode(node: Node, subView: any, x: number, y: number, widths: any, heights: any) { // NOTE The following sizeMode, size, and position functions are no-ops, // they only perform type casting for use in TypeScript code. Without // them there will be type errors. node.sizeMode = [ // PORTED // @ts-ignore: TODO, key is not defined from anywhere, but it was working??? widths && widths[key] === true ? 'proportional' : 'literal', // @ts-ignore: TODO, key is not defined from anywhere, but it was working??? heights && heights[key] === true ? 'proportional' : 'literal', ] node.size = [ // PORTED // @ts-ignore: TODO, key is not defined from anywhere, but it was working??? widths && widths[key] === true ? 1 : subView.width, // @ts-ignore: TODO, key is not defined from anywhere, but it was working??? heights && heights[key] === true ? 1 : subView.height, ] node.position = [ // PORTED x + subView.left, y + subView.top, subView.zIndex * 5, ] } #checkNodes() { const subViews = this.#autoLayoutView.subViews const subViewKeys = Object.keys(subViews) const _idToNode = this.#idToNode // If a node is not found for a subview key, see if exists in this's DOM children by className // XXX Should we use a `data-*` attribute instead of a class name? for (var key of subViewKeys) { var subView = subViews[key] if (key.indexOf('_') !== 0 && subView.type !== 'stack') { var node = _idToNode[key] if (!node) { node = this.querySelector('.' + key) if (node && node.parentElement === this) _idToNode[key] = node } } } this.#showOrHideNodes() } #showOrHideNodes() { const subViews = this.#autoLayoutView.subViews const subViewKeys = Object.keys(subViews) const _idToNode = this.#idToNode const nodeIds = Object.keys(_idToNode) // hide the child nodes that are should not be visible for the current subview. for (const id of nodeIds) { if (subViewKeys.includes(id)) _idToNode[id].visible = true else _idToNode[id].visible = false } } } import type {ElementAttributes} from '@lume/element' declare module '@lume/element' { namespace JSX { interface IntrinsicElements { 'lume-autolayout-node': ElementAttributes<AutoLayoutNode, AutoLayoutNodeAttributes> } } } declare global { interface HTMLElementTagNameMap { 'lume-autolayout-node': AutoLayoutNode } }
the_stack
import { generatePrivateKey, getAddressFromPrivateKey, getPubkeyFromPrivateKey, // toChecksumAddress, encrypt, decrypt, EncryptOptions, Keystore, Signature, getAddress, } from '@harmony-js/crypto'; import { isPrivateKey, add0xToString, hexToNumber, AddressSuffix, ChainType, } from '@harmony-js/utils'; import { Transaction, RLPSign } from '@harmony-js/transaction'; import { StakingTransaction } from '@harmony-js/staking'; import { Messenger, RPCMethod } from '@harmony-js/network'; import { Shards } from './types'; import { defaultMessenger } from './utils'; export interface Balance { balance?: string; nonce?: number; shardID?: number; } class Account { /** * static method create account * * @example * ```javascript * const account = new Account(); * console.log(account); * ``` */ static new(): Account { const newAcc = new Account()._new(); return newAcc; } /** * Static Method: add a private key to Account * @param {string} key - private Key * * @example * ```javascript * const account = new Account.add(key_1); * console.log(account); * ``` */ static add(key: string): Account { const newAcc = new Account()._import(key); return newAcc; } /**@hidden */ privateKey?: string; /**@hidden */ publicKey?: string; /**@hidden */ address?: string; /**@hidden */ balance?: string = '0'; /**@hidden */ nonce?: number = 0; /**@hidden */ shardID: number; /**@hidden */ shards: Shards; /**@hidden */ messenger: Messenger; /**@hidden */ encrypted: boolean = false; /** * check sum address * * @example * ```javascript * console.log(account.checksumAddress); * ``` */ get checksumAddress(): string { return this.address ? getAddress(this.address).checksum : ''; } /** * Get bech32 Address * * @example * ```javascript * console.log(account.bech32Address); * ``` */ get bech32Address(): string { return this.address ? getAddress(this.address).bech32 : ''; } /** * get Bech32 TestNet Address * * @example * ```javascript * console.log(account.bech32TestNetAddress); * ``` */ get bech32TestNetAddress(): string { return this.address ? getAddress(this.address).bech32TestNet : ''; } /** * get Shards number with this Account * * @example * ```javascript * console.log(account.getShardsCount); * ``` */ get getShardsCount(): number { return this.shards.size; } /** * Generate an account object * * @param key import an existing privateKey, or create a random one * @param messenger you can setMessage later, or set message on `new` * * @example * ```javascript * // import the Account class * const { Account } = require('@harmony-js/account'); * * // Messenger is optional, by default, we have a defaultMessenger * // If you like to change, you will import related package here. * const { HttpProvider, Messenger } = require('@harmony-js/network'); * const { ChainType, ChainID } = require('@harmony-js/utils'); * * // create a custom messenger * const customMessenger = new Messenger( * new HttpProvider('http://localhost:9500'), * ChainType.Harmony, // if you are connected to Harmony's blockchain * ChainID.HmyLocal, // check if the chainId is correct * ) * * // setMessenger later * const randomAccount = new Account() * randomAccount.setMessenger(customMessenger) * * // or you can set messenger on `new` * const randomAccountWithCustomMessenger = new Account(undefined, customMessenger) * * // NOTED: Key with or without `0x` are accepted, makes no different * // NOTED: DO NOT import `mnemonic phrase` using `Account` class, use `Wallet` instead * const myPrivateKey = '0xe19d05c5452598e24caad4a0d85a49146f7be089515c905ae6a19e8a578a6930' * const myAccountWithMyPrivateKey = new Account(myPrivateKey) * ``` */ constructor(key?: string, messenger: Messenger = defaultMessenger) { this.messenger = messenger; if (!key) { this._new(); } else { this._import(key); } this.shardID = this.messenger.currentShard || 0; this.shards = new Map(); this.shards.set(this.shardID, { address: `${this.bech32Address}${AddressSuffix}0`, balance: this.balance || '0', nonce: this.nonce || 0, }); } async toFile(password: string, options?: EncryptOptions): Promise<string> { if (this.privateKey && isPrivateKey(this.privateKey)) { const file = await encrypt(this.privateKey, password, options); this.privateKey = file; this.encrypted = true; return file; } else { throw new Error('Encryption failed because PrivateKey is not correct'); } } async fromFile(keyStore: string, password: string): Promise<Account> { try { if (typeof password !== 'string') { throw new Error('you must provide password'); } const file: Keystore = JSON.parse(keyStore.toLowerCase()); const decyptedPrivateKey = await decrypt(file, password); if (isPrivateKey(decyptedPrivateKey)) { return this._import(decyptedPrivateKey); } else { throw new Error('decrypted failed'); } } catch (error) { throw error; } } /** * Get the account balance * * @param blockNumber by default, it's `latest` * * @example * ```javascript * account.getBalance().then((value) => { * console.log(value); * }); * ``` */ async getBalance(blockNumber: string = 'latest'): Promise<Balance> { try { if (this.messenger) { const balance = await this.messenger.send( RPCMethod.GetBalance, [this.address, blockNumber], this.messenger.chainPrefix, this.messenger.currentShard || 0, ); const nonce = await this.messenger.send( RPCMethod.GetTransactionCount, [this.address, blockNumber], this.messenger.chainPrefix, this.messenger.currentShard || 0, ); if (balance.isError()) { throw balance.error.message; } if (nonce.isError()) { throw nonce.error.message; } this.balance = hexToNumber(balance.result); this.nonce = Number.parseInt(hexToNumber(nonce.result), 10); this.shardID = this.messenger.currentShard || 0; } else { throw new Error('No Messenger found'); } return { balance: this.balance, nonce: this.nonce, shardID: this.shardID, }; } catch (error) { throw error; } } /** * @function updateShards */ async updateBalances(blockNumber: string = 'latest'): Promise<void> { // this.messenger.setShardingProviders(); const shardProviders = this.messenger.shardProviders; if (shardProviders.size > 1) { for (const [name, val] of shardProviders) { const balanceObject = await this.getShardBalance(val.shardID, blockNumber); await this.shards.set(name === val.shardID ? name : val.shardID, balanceObject); } } else { const currentShard = await this.getShardBalance( this.messenger.currentShard || 0, blockNumber, ); this.shards.set(this.messenger.currentShard || 0, currentShard); } } /** * @function signTransaction */ async signTransaction( transaction: Transaction, updateNonce: boolean = true, encodeMode: string = 'rlp', blockNumber: string = 'latest', ): Promise<Transaction> { if (!this.privateKey || !isPrivateKey(this.privateKey)) { throw new Error(`${this.privateKey} is not found or not correct`); } if (updateNonce) { // await this.updateBalances(blockNumber); const txShardID = transaction.txParams.shardID; const shardNonce = await this.getShardNonce( typeof txShardID === 'string' ? Number.parseInt(txShardID, 10) : txShardID, blockNumber, ); transaction.setParams({ ...transaction.txParams, from: this.messenger.chainPrefix === ChainType.Harmony ? this.bech32Address : this.checksumAddress || '0x', nonce: shardNonce, }); } if (encodeMode === 'rlp') { const [signature, rawTransaction]: [Signature, string] = RLPSign( transaction, this.privateKey, ); return transaction.map((obj: any) => { return { ...obj, signature, rawTransaction, from: this.messenger.chainPrefix === ChainType.Harmony ? this.bech32Address : this.checksumAddress || '0x', }; }); } else { // TODO: if we use other encode method, eg. protobuf, we should implement this return transaction; } } /** * This function is still in development, coming soon! * * @param staking * @param updateNonce * @param encodeMode * @param blockNumber * @param shardID */ async signStaking( staking: StakingTransaction, updateNonce: boolean = true, encodeMode: string = 'rlp', blockNumber: string = 'latest', shardID: number = this.messenger.currentShard, ): Promise<StakingTransaction> { if (!this.privateKey || !isPrivateKey(this.privateKey)) { throw new Error(`${this.privateKey} is not found or not correct`); } if (updateNonce) { // await this.updateBalances(blockNumber); const txShardID = shardID; const shardNonce = await this.getShardNonce( typeof txShardID === 'string' ? Number.parseInt(txShardID, 10) : txShardID, blockNumber, ); staking.setFromAddress( this.messenger.chainPrefix === ChainType.Harmony ? this.bech32Address : this.checksumAddress || '0x', ); staking.setNonce(shardNonce); } if (encodeMode === 'rlp') { const [signature, rawTransaction]: [Signature, string] = staking.rlpSign(this.privateKey); staking.setRawTransaction(rawTransaction); staking.setSignature(signature); staking.setFromAddress( this.messenger.chainPrefix === ChainType.Harmony ? this.bech32Address : this.checksumAddress || '0x', ); return staking; } else { // TODO: if we use other encode method, eg. protobuf, we should implement this return staking; } } /** * @param messenger * * @example * ```javascript * // create a custom messenger * const customMessenger = new Messenger( * new HttpProvider('http://localhost:9500'), * ChainType.Harmony, // if you are connected to Harmony's blockchain * ChainID.HmyLocal, // check if the chainId is correct * ) * * // to create an Account with random privateKey * // and you can setMessenger later * const randomAccount = new Account() * randomAccount.setMessenger(customMessenger) * ``` */ setMessenger(messenger: Messenger) { this.messenger = messenger; } /** * Get account address from shard ID * @param shardID * * @example * ```javascript * console.log(account.getAddressFromShardID(0)); * * > one103q7qe5t2505lypvltkqtddaef5tzfxwsse4z7-0 * ``` */ getAddressFromShardID(shardID: number) { const shardObject = this.shards.get(shardID); if (shardObject) { return shardObject.address; } else { return undefined; } } /** * Get all shards' addresses from the account * * @example * ```javascript * console.log(account.getAddresses()); * ``` */ getAddresses(): string[] { const addressArray: string[] = []; for (const [name, val] of this.shards) { const index: number = typeof name === 'string' ? Number.parseInt(name, 10) : name; addressArray[index] = val.address; } return addressArray; } /** * Get the specific shard's balance * * @param shardID `shardID` is binding with the endpoint, IGNORE it! * @param blockNumber by default, it's `latest` * * @example * ``` * account.getShardBalance().then((value) => { * console.log(value); * }); * ``` */ async getShardBalance(shardID: number, blockNumber: string = 'latest') { const balance = await this.messenger.send( RPCMethod.GetBalance, [this.address, blockNumber], this.messenger.chainPrefix, shardID, ); const nonce = await this.messenger.send( RPCMethod.GetTransactionCount, [this.address, blockNumber], this.messenger.chainPrefix, shardID, ); if (balance.isError()) { throw balance.error.message; } if (nonce.isError()) { throw nonce.error.message; } return { address: `${this.bech32Address}${AddressSuffix}${shardID}`, balance: hexToNumber(balance.result), nonce: Number.parseInt(hexToNumber(nonce.result), 10), }; } /** * Get the specific shard's nonce * * @param shardID `shardID` is binding with the endpoint, IGNORE it! * @param blockNumber by default, it's `latest` * * @example * ``` * account.getShardNonce().then((value) => { * console.log(value); * }); * ``` */ async getShardNonce(shardID: number, blockNumber: string = 'latest') { const nonce = await this.messenger.send( RPCMethod.GetAccountNonce, [this.address, blockNumber], this.messenger.chainPrefix, shardID, ); if (nonce.isError()) { throw nonce.error.message; } return nonce.result; } /** * @function _new private method create Account * @return {Account} Account instance * @ignore */ private _new(): Account { const prv = generatePrivateKey(); if (!isPrivateKey(prv)) { throw new Error('key gen failed'); } return this._import(prv); } /** * @function _import private method import a private Key * @param {string} key - private key * @return {Account} Account instance * @ignore */ private _import(key: string): Account { if (!isPrivateKey(key)) { throw new Error(`${key} is not PrivateKey`); } this.privateKey = add0xToString(key); this.publicKey = getPubkeyFromPrivateKey(this.privateKey); this.address = getAddressFromPrivateKey(this.privateKey); this.shardID = this.messenger.currentShard || 0; this.shards = new Map(); this.shards.set(this.shardID, { address: `${this.bech32Address}${AddressSuffix}0`, balance: this.balance || '0', nonce: this.nonce || 0, }); this.encrypted = false; return this; } } /** * This comment _supports_ [Markdown](https://marked.js.org/) */ export { Account };
the_stack
import { VDomModel, VDomRenderer } from '@jupyterlab/apputils'; import { CodeEditor } from '@jupyterlab/codeeditor'; import { IDocumentWidget } from '@jupyterlab/docregistry'; import { TranslationBundle } from '@jupyterlab/translation'; import { caretDownIcon, caretUpIcon } from '@jupyterlab/ui-components'; import type * as CodeMirror from 'codemirror'; import React, { ReactElement } from 'react'; import * as lsProtocol from 'vscode-languageserver-protocol'; import { CodeDiagnostics as LSPDiagnosticsSettings } from '../../_diagnostics'; import { StatusMessage, WidgetAdapter } from '../../adapters/adapter'; import { DocumentLocator, focus_on } from '../../components/utils'; import { FeatureSettings } from '../../feature'; import { DiagnosticSeverity } from '../../lsp'; import { IEditorPosition } from '../../positioning'; import { CodeMirrorVirtualEditor } from '../../virtual/codemirror_editor'; import { VirtualDocument } from '../../virtual/document'; import { IVirtualEditor } from '../../virtual/editor'; import '../../../style/diagnostics_listing.css'; /** * Diagnostic which is localized at a specific editor (cell) within a notebook * (if used in the context of a FileEditor, then there is just a single editor) */ export interface IEditorDiagnostic { diagnostic: lsProtocol.Diagnostic; editor: CodeMirror.Editor; range: { start: IEditorPosition; end: IEditorPosition; }; } export const DIAGNOSTICS_LISTING_CLASS = 'lsp-diagnostics-listing'; const DIAGNOSTICS_PLACEHOLDER_CLASS = 'lsp-diagnostics-placeholder'; export class DiagnosticsDatabase extends Map< VirtualDocument, IEditorDiagnostic[] > { get all(): Array<IEditorDiagnostic> { return [].concat.apply([], this.values() as any); } } export interface IDiagnosticsRow { data: IEditorDiagnostic; key: string; document: VirtualDocument; /** * Cell number is the ordinal, 1-based cell identifier displayed to the user. */ cell_number?: number; } interface IListingContext { db: DiagnosticsDatabase; editor: IVirtualEditor<CodeEditor.IEditor>; adapter: WidgetAdapter<IDocumentWidget>; } interface IColumnOptions { id: string; label: string; render_cell(data: IDiagnosticsRow, context?: IListingContext): ReactElement; sort(a: IDiagnosticsRow, b: IDiagnosticsRow): number; is_available?(context: IListingContext): boolean; } class Column { public is_visible: boolean; constructor(private options: IColumnOptions) { this.is_visible = true; } render_cell(data: IDiagnosticsRow, context: IListingContext) { return this.options.render_cell(data, context); } sort(a: IDiagnosticsRow, b: IDiagnosticsRow) { return this.options.sort(a, b); } get id(): string { return this.options.id; } is_available(context: IListingContext) { if (this.options.is_available != null) { return this.options.is_available(context); } return true; } render_header(listing: DiagnosticsListing): ReactElement { return ( <SortableTH label={this.options.label} id={this.id} listing={listing} key={this.id} /> ); } } function SortableTH(props: { id: string; label: string; listing: DiagnosticsListing; }): ReactElement { const is_sort_key = props.id === props.listing.sort_key; const sortIcon = !is_sort_key || props.listing.sort_direction === 1 ? caretUpIcon : caretDownIcon; return ( <th key={props.id} onClick={() => props.listing.sort(props.id)} className={is_sort_key ? 'lsp-sorted-header' : undefined} data-id={props.id} > <div> <label>{props.label}</label> <sortIcon.react tag="span" className="lsp-sort-icon" /> </div> </th> ); } export function message_without_code(diagnostic: lsProtocol.Diagnostic) { let message = diagnostic.message; let code_str = '' + diagnostic.code; if ( diagnostic.code != null && diagnostic.code !== '' && message.startsWith(code_str + '') ) { return message.slice(code_str.length).trim(); } return message; } export class DiagnosticsListing extends VDomRenderer<DiagnosticsListing.Model> { sort_key = 'Severity'; sort_direction = 1; private _diagnostics: Map<string, IDiagnosticsRow>; protected trans: TranslationBundle; public columns: Column[]; protected severityTranslations: Record< keyof typeof DiagnosticSeverity, string >; constructor(model: DiagnosticsListing.Model) { super(model); const trans = model.trans; this.trans = trans; this.severityTranslations = { Error: trans.__('Error'), Warning: trans.__('Warning'), Information: trans.__('Information'), Hint: trans.__('Hint') }; this.columns = [ new Column({ id: 'Virtual Document', label: this.trans.__('Virtual Document'), render_cell: (row, context: IListingContext) => ( <td key={0}> <DocumentLocator document={row.document} adapter={context.adapter} trans={this.trans} /> </td> ), sort: (a, b) => a.document.id_path.localeCompare(b.document.id_path), is_available: context => context.db.size > 1 }), new Column({ id: 'Message', label: this.trans.__('Message'), render_cell: row => { let message = message_without_code(row.data.diagnostic); return <td key={1}>{message}</td>; }, sort: (a, b) => a.data.diagnostic.message.localeCompare(b.data.diagnostic.message) }), new Column({ id: 'Code', label: this.trans.__('Code'), render_cell: row => <td key={2}>{row.data.diagnostic.code}</td>, sort: (a, b) => (a.data.diagnostic.code + '').localeCompare( b.data.diagnostic.source + '' ) }), new Column({ id: 'Severity', label: this.trans.__('Severity'), // TODO: use default diagnostic severity render_cell: row => { const severity = DiagnosticSeverity[ row.data.diagnostic.severity || 1 ] as keyof typeof DiagnosticSeverity; return ( <td key={3}>{this.severityTranslations[severity] || severity}</td> ); }, sort: (a, b) => { if (!a.data.diagnostic.severity) { return +1; } if (!b.data.diagnostic.severity) { return -1; } return a.data.diagnostic.severity > b.data.diagnostic.severity ? 1 : -1; } }), new Column({ id: 'Source', label: this.trans.__('Source'), render_cell: row => <td key={4}>{row.data.diagnostic.source}</td>, sort: (a, b) => { if (!a.data.diagnostic.source) { return +1; } if (!b.data.diagnostic.source) { return -1; } return a.data.diagnostic.source.localeCompare( b.data.diagnostic.source ); } }), new Column({ id: 'Cell', label: this.trans.__('Cell'), render_cell: row => <td key={5}>{row.cell_number}</td>, sort: (a, b) => a.cell_number! - b.cell_number! || a.data.range.start.line - b.data.range.start.line || a.data.range.start.ch - b.data.range.start.ch, is_available: context => context.adapter.has_multiple_editors }), new Column({ id: 'Line:Ch', label: this.trans.__('Line:Ch'), render_cell: row => ( <td key={6}> {row.data.range.start.line}:{row.data.range.start.ch} </td> ), sort: (a, b) => a.data.range.start.line - b.data.range.start.line || a.data.range.start.ch - b.data.range.start.ch }) ]; } sort(key: string) { if (key === this.sort_key) { this.sort_direction = this.sort_direction * -1; } else { this.sort_key = key; this.sort_direction = 1; } this.update(); } render() { let diagnostics_db = this.model.diagnostics; const editor = this.model.virtual_editor; const adapter = this.model.adapter; if (diagnostics_db == null || editor == null || !adapter) { return ( <div className={DIAGNOSTICS_PLACEHOLDER_CLASS}> {this.trans.__('Diagnostics are not available')} </div> ); } if (diagnostics_db.size === 0) { return ( <div className={DIAGNOSTICS_PLACEHOLDER_CLASS}> {this.trans.__('No issues detected, great job!')} </div> ); } let by_document = Array.from(diagnostics_db).map( ([virtual_document, diagnostics]) => { if (virtual_document.isDisposed) { return []; } return diagnostics.map((diagnostic_data, i) => { let cell_number: number | null = null; if (adapter.has_multiple_editors) { let { index: cell_id } = editor.find_editor(diagnostic_data.editor); cell_number = cell_id + 1; } return { data: diagnostic_data, key: virtual_document.uri + ',' + i, document: virtual_document, cell_number: cell_number, editor: editor } as IDiagnosticsRow; }); } ); let flattened: IDiagnosticsRow[] = ([] as IDiagnosticsRow[]).concat.apply( [], by_document ); this._diagnostics = new Map(flattened.map(row => [row.key, row])); let sorted_column = this.columns.filter( column => column.id === this.sort_key )[0]; let sorter = sorted_column.sort.bind(sorted_column); let sorted = flattened.sort((a, b) => sorter(a, b) * this.sort_direction); let context: IListingContext = { db: diagnostics_db, editor: editor, adapter: adapter }; let columns_to_display = this.columns.filter( column => column.is_available(context) && column.is_visible ); let elements = sorted.map(row => { let cells = columns_to_display.map(column => column.render_cell(row, context) ); return ( <tr key={row.key} data-key={row.key} onClick={() => { this.jump_to(row); }} > {cells} </tr> ); }); let columns_headers = columns_to_display.map(column => column.render_header(this) ); return ( <table className={DIAGNOSTICS_LISTING_CLASS}> <thead> <tr>{columns_headers}</tr> </thead> <tbody>{elements}</tbody> </table> ); } get_diagnostic(key: string): IDiagnosticsRow | undefined { if (!this._diagnostics.has(key)) { console.warn('Could not find the diagnostics row with key', key); return; } return this._diagnostics.get(key); } jump_to(row: IDiagnosticsRow) { const cm_editor = row.data.editor; focus_on(cm_editor.getWrapperElement()); cm_editor.getDoc().setCursor(row.data.range.start); cm_editor.focus(); } } export namespace DiagnosticsListing { /** * A VDomModel for the LSP of current file editor/notebook. */ export class Model extends VDomModel { diagnostics: DiagnosticsDatabase | null; virtual_editor: CodeMirrorVirtualEditor | null; adapter: WidgetAdapter<any> | null; settings: FeatureSettings<LSPDiagnosticsSettings>; status_message: StatusMessage; trans: TranslationBundle; constructor(translator_bundle: TranslationBundle) { super(); this.trans = translator_bundle; } } }
the_stack
import React, { useState, useEffect, useMemo } from 'react' import { Checkbox, CircularProgress, FormControl, FormControlLabel, Grid, IconButton, Link, Tooltip, Typography, makeStyles, } from '@material-ui/core' import { DataGrid, GridCellParams } from '@mui/x-data-grid' import { ToggleButtonGroup, ToggleButton, ToggleButtonProps, } from '@material-ui/lab' import PluginManager from '@jbrowse/core/PluginManager' import { format } from 'timeago.js' import { ipcRenderer } from 'electron' // icons import DeleteIcon from '@material-ui/icons/Delete' import EditIcon from '@material-ui/icons/Edit' import ViewComfyIcon from '@material-ui/icons/ViewComfy' import ListIcon from '@material-ui/icons/List' import PlaylistAddIcon from '@material-ui/icons/PlaylistAdd' // locals import RenameSessionDialog from './dialogs/RenameSessionDialog' import DeleteSessionDialog from './dialogs/DeleteSessionDialog' import { useLocalStorage, loadPluginManager } from './util' import SessionCard from './SessionCard' const useStyles = makeStyles(theme => ({ pointer: { cursor: 'pointer', }, formControl: { margin: theme.spacing(2), }, header: { margin: theme.spacing(2), }, toggleButton: { '&.Mui-disabled': { pointerEvents: 'auto', }, }, })) interface RecentSessionData { path: string name: string screenshot?: string updated: number } type RecentSessions = RecentSessionData[] function RecentSessionsList({ setError, sessions, setSelectedSessions, setSessionToRename, setPluginManager, }: { setError: (e: unknown) => void setSessionToRename: (arg: RecentSessionData) => void setPluginManager: (pm: PluginManager) => void setSelectedSessions: (arg: RecentSessionData[]) => void sessions: RecentSessionData[] }) { const classes = useStyles() const columns = [ { field: 'rename', minWidth: 40, width: 40, sortable: false, filterable: false, headerName: ' ', renderCell: (params: GridCellParams) => { return ( <IconButton onClick={() => setSessionToRename(params.row as RecentSessionData)} > <Tooltip title="Rename session"> <EditIcon /> </Tooltip> </IconButton> ) }, }, { field: 'name', headerName: 'Session name', flex: 0.7, renderCell: (params: GridCellParams) => { const { value } = params return ( <Link className={classes.pointer} onClick={async () => { try { setPluginManager(await loadPluginManager(params.row.path)) } catch (e) { console.error(e) setError(e) } }} > {value} </Link> ) }, }, { field: 'path', headerName: 'Session path', flex: 0.7, renderCell: (params: GridCellParams) => { const { value } = params return value }, }, { field: 'lastModified', headerName: 'Last modified', renderCell: ({ value }: GridCellParams) => { if (!value) { return null } const lastModified = new Date(value as string) const now = Date.now() const oneDayLength = 24 * 60 * 60 * 1000 if (now - lastModified.getTime() < oneDayLength) { return ( <Tooltip title={lastModified.toLocaleString('en-US')}> <div>{format(lastModified)}</div> </Tooltip> ) } return lastModified.toLocaleString('en-US') }, width: 150, }, ] return ( <div style={{ height: 400, width: '100%' }}> <DataGrid checkboxSelection disableSelectionOnClick onSelectionModelChange={args => { setSelectedSessions( sessions.filter(session => args.includes(session.path)), ) }} rows={sessions.map(session => ({ id: session.path, name: session.name, rename: session.name, delete: session.name, lastModified: session.updated, path: session.path, }))} rowHeight={25} headerHeight={33} columns={columns} /> </div> ) } function RecentSessionsCards({ sessions, setError, setSessionsToDelete, setSessionToRename, setPluginManager, addToQuickstartList, }: { setError: (e: unknown) => void setSessionsToDelete: (e: RecentSessionData[]) => void setSessionToRename: (arg: RecentSessionData) => void setPluginManager: (pm: PluginManager) => void sessions: RecentSessionData[] addToQuickstartList: (arg: RecentSessionData) => void }) { return ( <Grid container spacing={4}> {sessions?.map(session => ( <Grid item key={session.path}> <SessionCard sessionData={session} onClick={async () => { try { const pm = await loadPluginManager(session.path) setPluginManager(pm) } catch (e) { console.error(e) setError(e) } }} onDelete={del => setSessionsToDelete([del])} onRename={setSessionToRename} onAddToQuickstartList={addToQuickstartList} /> </Grid> ))} </Grid> ) } // note: adjust props so disabled button can have a tooltip and not lose styling // https://stackoverflow.com/a/63276424 function ToggleButtonWithTooltip(props: ToggleButtonProps) { const classes = useStyles() const { title = '', children, disabled, onClick, ...other } = props const adjustedButtonProps = { disabled: disabled, component: disabled ? 'div' : undefined, onClick: disabled ? undefined : onClick, } return ( <Tooltip title={title}> <ToggleButton {...other} {...adjustedButtonProps} classes={{ root: classes.toggleButton }} > {children} </ToggleButton> </Tooltip> ) } export default function RecentSessionPanel({ setError, setPluginManager, }: { setError: (e: unknown) => void setPluginManager: (pm: PluginManager) => void }) { const classes = useStyles() const [displayMode, setDisplayMode] = useLocalStorage('displayMode', 'list') const [sessions, setSessions] = useState<RecentSessions>([]) const [sessionToRename, setSessionToRename] = useState<RecentSessionData>() const [updateSessionsList, setUpdateSessionsList] = useState(0) const [selectedSessions, setSelectedSessions] = useState<RecentSessions>() const [sessionsToDelete, setSessionsToDelete] = useState<RecentSessions>() const [showAutosaves, setShowAutosaves] = useLocalStorage( 'showAutosaves', 'false', ) const sortedSessions = useMemo( () => sessions?.sort((a, b) => b.updated - a.updated), [sessions], ) useEffect(() => { ;(async () => { try { const sessions = await ipcRenderer.invoke( 'listSessions', showAutosaves === 'true', ) setSessions(sessions) } catch (e) { console.error(e) setError(e) } })() }, [setError, updateSessionsList, showAutosaves]) if (!sessions) { return ( <CircularProgress style={{ position: 'fixed', top: '50%', left: '50%', marginTop: -25, marginLeft: -25, }} size={50} /> ) } async function addToQuickstartList(arg: RecentSessionData[]) { await Promise.all( arg.map(session => ipcRenderer.invoke('addToQuickstartList', session.path, session.name), ), ) } return ( <div> <RenameSessionDialog sessionToRename={sessionToRename} onClose={() => { setSessionToRename(undefined) setUpdateSessionsList(s => s + 1) }} /> {sessionsToDelete ? ( <DeleteSessionDialog setError={setError} sessionsToDelete={sessionsToDelete} onClose={() => { setSessionsToDelete(undefined) setUpdateSessionsList(s => s + 1) }} /> ) : null} <FormControl className={classes.formControl}> <ToggleButtonGroup exclusive value={displayMode} onChange={(_, newVal) => setDisplayMode(newVal)} > <ToggleButtonWithTooltip value="grid" title="Grid view"> <ViewComfyIcon /> </ToggleButtonWithTooltip> <ToggleButtonWithTooltip value="list" title="List view"> <ListIcon /> </ToggleButtonWithTooltip> </ToggleButtonGroup> </FormControl> <FormControl className={classes.formControl}> <ToggleButtonGroup> <ToggleButtonWithTooltip value="delete" title="Delete sessions" disabled={!selectedSessions?.length} onClick={() => setSessionsToDelete(selectedSessions)} > <DeleteIcon /> </ToggleButtonWithTooltip> <ToggleButtonWithTooltip value="quickstart" title="Add sessions to quickstart list" disabled={!selectedSessions?.length} onClick={() => addToQuickstartList(selectedSessions || [])} > <PlaylistAddIcon /> </ToggleButtonWithTooltip> </ToggleButtonGroup> </FormControl> <FormControlLabel control={ <Checkbox checked={showAutosaves === 'true'} onChange={() => setShowAutosaves(showAutosaves === 'true' ? 'false' : 'true') } /> } label="Show autosaves" /> {sortedSessions.length ? ( displayMode === 'grid' ? ( <RecentSessionsCards addToQuickstartList={entry => addToQuickstartList([entry])} setPluginManager={setPluginManager} sessions={sortedSessions} setError={setError} setSessionsToDelete={setSessionsToDelete} setSessionToRename={setSessionToRename} /> ) : ( <RecentSessionsList setPluginManager={setPluginManager} sessions={sortedSessions} setError={setError} setSelectedSessions={setSelectedSessions} setSessionToRename={setSessionToRename} /> ) ) : ( <Typography>No sessions available</Typography> )} </div> ) }
the_stack
import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ComponentFixture, fakeAsync, inject, TestBed, tick, } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { CdkTreeModule } from '@angular/cdk/tree'; import { TestScheduler } from 'rxjs/testing'; import { getTestScheduler } from 'jasmine-marbles'; import { of as observableOf } from 'rxjs'; import { NgbModal, NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { DynamicFormLayoutService, DynamicFormsCoreModule, DynamicFormValidationService } from '@ng-dynamic-forms/core'; import { DynamicFormsNGBootstrapUIModule } from '@ng-dynamic-forms/ui-ng-bootstrap'; import { TranslateModule } from '@ngx-translate/core'; import { VocabularyOptions } from '../../../../../../core/submission/vocabularies/models/vocabulary-options.model'; import { VocabularyService } from '../../../../../../core/submission/vocabularies/vocabulary.service'; import { VocabularyServiceStub } from '../../../../../testing/vocabulary-service.stub'; import { DsDynamicOneboxComponent } from './dynamic-onebox.component'; import { DynamicOneboxModel } from './dynamic-onebox.model'; import { FormFieldMetadataValueObject } from '../../../models/form-field-metadata-value.model'; import { createTestComponent } from '../../../../../testing/utils.test'; import { AuthorityConfidenceStateDirective } from '../../../../../authority-confidence/authority-confidence-state.directive'; import { ObjNgFor } from '../../../../../utils/object-ngfor.pipe'; import { VocabularyEntry } from '../../../../../../core/submission/vocabularies/models/vocabulary-entry.model'; import { createSuccessfulRemoteDataObject$ } from '../../../../../remote-data.utils'; import { VocabularyTreeviewComponent } from '../../../../../vocabulary-treeview/vocabulary-treeview.component'; import { mockDynamicFormLayoutService, mockDynamicFormValidationService } from '../../../../../testing/dynamic-form-mock-services'; export let ONEBOX_TEST_GROUP; export let ONEBOX_TEST_MODEL_CONFIG; /* tslint:disable:max-classes-per-file */ // Mock class for NgbModalRef export class MockNgbModalRef { componentInstance = { vocabularyOptions: undefined, preloadLevel: undefined, selectedItem: undefined }; result: Promise<any> = new Promise((resolve, reject) => resolve(true)); } function init() { ONEBOX_TEST_GROUP = new FormGroup({ onebox: new FormControl(), }); ONEBOX_TEST_MODEL_CONFIG = { vocabularyOptions: { closed: false, name: 'vocabulary' } as VocabularyOptions, disabled: false, id: 'onebox', label: 'Conference', minChars: 3, name: 'onebox', placeholder: 'Conference', readOnly: false, required: false, repeatable: false, value: undefined }; } describe('DsDynamicOneboxComponent test suite', () => { let scheduler: TestScheduler; let testComp: TestComponent; let oneboxComponent: DsDynamicOneboxComponent; let testFixture: ComponentFixture<TestComponent>; let oneboxCompFixture: ComponentFixture<DsDynamicOneboxComponent>; let vocabularyServiceStub: any; let modalService: any; let html; let modal; const vocabulary = { id: 'vocabulary', name: 'vocabulary', scrollable: true, hierarchical: false, preloadLevel: 0, type: 'vocabulary', _links: { self: { url: 'self' }, entries: { url: 'entries' } } }; const hierarchicalVocabulary = { id: 'hierarchicalVocabulary', name: 'hierarchicalVocabulary', scrollable: true, hierarchical: true, preloadLevel: 2, type: 'vocabulary', _links: { self: { url: 'self' }, entries: { url: 'entries' } } }; // waitForAsync beforeEach beforeEach(() => { vocabularyServiceStub = new VocabularyServiceStub(); modal = jasmine.createSpyObj('modal', { open: jasmine.createSpy('open'), close: jasmine.createSpy('close'), dismiss: jasmine.createSpy('dismiss'), } ); init(); TestBed.configureTestingModule({ imports: [ DynamicFormsCoreModule, DynamicFormsNGBootstrapUIModule, FormsModule, NgbModule, ReactiveFormsModule, TranslateModule.forRoot(), CdkTreeModule ], declarations: [ DsDynamicOneboxComponent, TestComponent, AuthorityConfidenceStateDirective, ObjNgFor, VocabularyTreeviewComponent ], // declare the test component providers: [ ChangeDetectorRef, DsDynamicOneboxComponent, { provide: VocabularyService, useValue: vocabularyServiceStub }, { provide: DynamicFormLayoutService, useValue: mockDynamicFormLayoutService }, { provide: DynamicFormValidationService, useValue: mockDynamicFormValidationService }, { provide: NgbModal, useValue: modal } ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }).compileComponents(); }); describe('', () => { // synchronous beforeEach beforeEach(() => { html = ` <ds-dynamic-onebox [bindId]="bindId" [group]="group" [model]="model" (blur)="onBlur($event)" (change)="onValueChange($event)" (focus)="onFocus($event)"></ds-dynamic-onebox>`; spyOn(vocabularyServiceStub, 'findVocabularyById').and.returnValue(createSuccessfulRemoteDataObject$(vocabulary)); testFixture = createTestComponent(html, TestComponent) as ComponentFixture<TestComponent>; testComp = testFixture.componentInstance; }); afterEach(() => { testFixture.destroy(); }); it('should create DsDynamicOneboxComponent', inject([DsDynamicOneboxComponent], (app: DsDynamicOneboxComponent) => { expect(app).toBeDefined(); })); }); describe('Has not hierarchical vocabulary', () => { beforeEach(() => { spyOn(vocabularyServiceStub, 'findVocabularyById').and.returnValue(createSuccessfulRemoteDataObject$(vocabulary)); }); describe('when init model value is empty', () => { beforeEach(() => { oneboxCompFixture = TestBed.createComponent(DsDynamicOneboxComponent); oneboxComponent = oneboxCompFixture.componentInstance; // FormComponent test instance oneboxComponent.group = ONEBOX_TEST_GROUP; oneboxComponent.model = new DynamicOneboxModel(ONEBOX_TEST_MODEL_CONFIG); oneboxCompFixture.detectChanges(); }); afterEach(() => { oneboxCompFixture.destroy(); oneboxComponent = null; }); it('should init component properly', () => { expect(oneboxComponent.currentValue).not.toBeDefined(); }); it('should search when 3+ characters typed', fakeAsync(() => { spyOn((oneboxComponent as any).vocabularyService, 'getVocabularyEntriesByValue').and.callThrough(); oneboxComponent.search(observableOf('test')).subscribe(); tick(300); oneboxCompFixture.detectChanges(); expect((oneboxComponent as any).vocabularyService.getVocabularyEntriesByValue).toHaveBeenCalled(); })); it('should set model.value on input type when VocabularyOptions.closed is false', () => { const inputDe = oneboxCompFixture.debugElement.query(By.css('input.form-control')); const inputElement = inputDe.nativeElement; inputElement.value = 'test value'; inputElement.dispatchEvent(new Event('input')); expect(oneboxComponent.inputValue).toEqual(new FormFieldMetadataValueObject('test value')); }); it('should not set model.value on input type when VocabularyOptions.closed is true', () => { oneboxComponent.model.vocabularyOptions.closed = true; oneboxCompFixture.detectChanges(); const inputDe = oneboxCompFixture.debugElement.query(By.css('input.form-control')); const inputElement = inputDe.nativeElement; inputElement.value = 'test value'; inputElement.dispatchEvent(new Event('input')); expect(oneboxComponent.model.value).not.toBeDefined(); }); it('should emit blur Event onBlur when popup is closed', () => { spyOn(oneboxComponent.blur, 'emit'); spyOn(oneboxComponent.instance, 'isPopupOpen').and.returnValue(false); oneboxComponent.onBlur(new Event('blur')); expect(oneboxComponent.blur.emit).toHaveBeenCalled(); }); it('should not emit blur Event onBlur when popup is opened', () => { spyOn(oneboxComponent.blur, 'emit'); spyOn(oneboxComponent.instance, 'isPopupOpen').and.returnValue(true); const input = oneboxCompFixture.debugElement.query(By.css('input')); input.nativeElement.blur(); expect(oneboxComponent.blur.emit).not.toHaveBeenCalled(); }); it('should emit change Event onBlur when VocabularyOptions.closed is false and inputValue is changed', () => { oneboxComponent.inputValue = 'test value'; oneboxCompFixture.detectChanges(); spyOn(oneboxComponent.blur, 'emit'); spyOn(oneboxComponent.change, 'emit'); spyOn(oneboxComponent.instance, 'isPopupOpen').and.returnValue(false); oneboxComponent.onBlur(new Event('blur',)); expect(oneboxComponent.change.emit).toHaveBeenCalled(); expect(oneboxComponent.blur.emit).toHaveBeenCalled(); }); it('should not emit change Event onBlur when VocabularyOptions.closed is false and inputValue is not changed', () => { oneboxComponent.inputValue = 'test value'; oneboxComponent.model = new DynamicOneboxModel(ONEBOX_TEST_MODEL_CONFIG); (oneboxComponent.model as any).value = 'test value'; oneboxCompFixture.detectChanges(); spyOn(oneboxComponent.blur, 'emit'); spyOn(oneboxComponent.change, 'emit'); spyOn(oneboxComponent.instance, 'isPopupOpen').and.returnValue(false); oneboxComponent.onBlur(new Event('blur',)); expect(oneboxComponent.change.emit).not.toHaveBeenCalled(); expect(oneboxComponent.blur.emit).toHaveBeenCalled(); }); it('should not emit change Event onBlur when VocabularyOptions.closed is false and inputValue is null', () => { oneboxComponent.inputValue = null; oneboxComponent.model = new DynamicOneboxModel(ONEBOX_TEST_MODEL_CONFIG); (oneboxComponent.model as any).value = 'test value'; oneboxCompFixture.detectChanges(); spyOn(oneboxComponent.blur, 'emit'); spyOn(oneboxComponent.change, 'emit'); spyOn(oneboxComponent.instance, 'isPopupOpen').and.returnValue(false); oneboxComponent.onBlur(new Event('blur',)); expect(oneboxComponent.change.emit).not.toHaveBeenCalled(); expect(oneboxComponent.blur.emit).toHaveBeenCalled(); }); it('should emit focus Event onFocus', () => { spyOn(oneboxComponent.focus, 'emit'); oneboxComponent.onFocus(new Event('focus')); expect(oneboxComponent.focus.emit).toHaveBeenCalled(); }); }); describe('when init model value is not empty', () => { beforeEach(() => { oneboxCompFixture = TestBed.createComponent(DsDynamicOneboxComponent); oneboxComponent = oneboxCompFixture.componentInstance; // FormComponent test instance oneboxComponent.group = ONEBOX_TEST_GROUP; oneboxComponent.model = new DynamicOneboxModel(ONEBOX_TEST_MODEL_CONFIG); const entry = observableOf(Object.assign(new VocabularyEntry(), { authority: null, value: 'test', display: 'testDisplay' })); spyOn((oneboxComponent as any).vocabularyService, 'getVocabularyEntryByValue').and.returnValue(entry); spyOn((oneboxComponent as any).vocabularyService, 'getVocabularyEntryByID').and.returnValue(entry); (oneboxComponent.model as any).value = new FormFieldMetadataValueObject('test', null, null, 'testDisplay'); oneboxCompFixture.detectChanges(); }); afterEach(() => { oneboxCompFixture.destroy(); oneboxComponent = null; }); it('should init component properly', fakeAsync(() => { tick(); expect(oneboxComponent.currentValue).toEqual(new FormFieldMetadataValueObject('test', null, null, 'testDisplay')); expect((oneboxComponent as any).vocabularyService.getVocabularyEntryByValue).toHaveBeenCalled(); })); it('should emit change Event onChange and currentValue is empty', () => { oneboxComponent.currentValue = null; spyOn(oneboxComponent.change, 'emit'); oneboxComponent.onChange(new Event('change')); expect(oneboxComponent.change.emit).toHaveBeenCalled(); expect(oneboxComponent.model.value).toBeNull(); }); }); describe('when init model value is not empty and has authority', () => { beforeEach(() => { oneboxCompFixture = TestBed.createComponent(DsDynamicOneboxComponent); oneboxComponent = oneboxCompFixture.componentInstance; // FormComponent test instance oneboxComponent.group = ONEBOX_TEST_GROUP; oneboxComponent.model = new DynamicOneboxModel(ONEBOX_TEST_MODEL_CONFIG); const entry = observableOf(Object.assign(new VocabularyEntry(), { authority: 'test001', value: 'test001', display: 'test' })); spyOn((oneboxComponent as any).vocabularyService, 'getVocabularyEntryByValue').and.returnValue(entry); spyOn((oneboxComponent as any).vocabularyService, 'getVocabularyEntryByID').and.returnValue(entry); (oneboxComponent.model as any).value = new FormFieldMetadataValueObject('test', null, 'test001'); oneboxCompFixture.detectChanges(); }); afterEach(() => { oneboxCompFixture.destroy(); oneboxComponent = null; }); it('should init component properly', fakeAsync(() => { tick(); expect(oneboxComponent.currentValue).toEqual(new FormFieldMetadataValueObject('test001', null, 'test001', 'test')); expect((oneboxComponent as any).vocabularyService.getVocabularyEntryByID).toHaveBeenCalled(); })); it('should emit change Event onChange and currentValue is empty', () => { oneboxComponent.currentValue = null; spyOn(oneboxComponent.change, 'emit'); oneboxComponent.onChange(new Event('change')); expect(oneboxComponent.change.emit).toHaveBeenCalled(); expect(oneboxComponent.model.value).toBeNull(); }); }); }); describe('Has hierarchical vocabulary', () => { beforeEach(() => { scheduler = getTestScheduler(); spyOn(vocabularyServiceStub, 'findVocabularyById').and.returnValue(createSuccessfulRemoteDataObject$(hierarchicalVocabulary)); oneboxCompFixture = TestBed.createComponent(DsDynamicOneboxComponent); oneboxComponent = oneboxCompFixture.componentInstance; // FormComponent test instance modalService = TestBed.inject(NgbModal); modalService.open.and.returnValue(new MockNgbModalRef()); }); describe('when init model value is empty', () => { beforeEach(() => { oneboxComponent.group = ONEBOX_TEST_GROUP; oneboxComponent.model = new DynamicOneboxModel(ONEBOX_TEST_MODEL_CONFIG); oneboxCompFixture.detectChanges(); }); afterEach(() => { oneboxCompFixture.destroy(); oneboxComponent = null; }); it('should init component properly', fakeAsync(() => { tick(); expect(oneboxComponent.currentValue).not.toBeDefined(); })); it('should open tree properly', (done) => { scheduler.schedule(() => oneboxComponent.openTree(new Event('click'))); scheduler.flush(); expect((oneboxComponent as any).modalService.open).toHaveBeenCalled(); done(); }); }); describe('when init model value is not empty', () => { beforeEach(() => { oneboxComponent.group = ONEBOX_TEST_GROUP; oneboxComponent.model = new DynamicOneboxModel(ONEBOX_TEST_MODEL_CONFIG); const entry = observableOf(Object.assign(new VocabularyEntry(), { authority: null, value: 'test', display: 'testDisplay' })); spyOn((oneboxComponent as any).vocabularyService, 'getVocabularyEntryByValue').and.returnValue(entry); spyOn((oneboxComponent as any).vocabularyService, 'getVocabularyEntryByID').and.returnValue(entry); (oneboxComponent.model as any).value = new FormFieldMetadataValueObject('test', null, null, 'testDisplay'); oneboxCompFixture.detectChanges(); }); afterEach(() => { oneboxCompFixture.destroy(); oneboxComponent = null; }); it('should init component properly', fakeAsync(() => { tick(); expect(oneboxComponent.currentValue).toEqual(new FormFieldMetadataValueObject('test', null, null, 'testDisplay')); expect((oneboxComponent as any).vocabularyService.getVocabularyEntryByValue).toHaveBeenCalled(); })); it('should open tree properly', (done) => { scheduler.schedule(() => oneboxComponent.openTree(new Event('click'))); scheduler.flush(); expect((oneboxComponent as any).modalService.open).toHaveBeenCalled(); done(); }); }); }); }); // declare a test component @Component({ selector: 'ds-test-cmp', template: `` }) class TestComponent { group: FormGroup = ONEBOX_TEST_GROUP; model = new DynamicOneboxModel(ONEBOX_TEST_MODEL_CONFIG); } /* tslint:enable:max-classes-per-file */
the_stack
import * as THREE from 'three' import React, { useEffect, useRef, useContext }from 'react' import * as d3 from 'd3'; import * as _ from 'underscore'; import SideBar from './sidebar'; import {StoreContext} from '../../../store'; const width = window.innerWidth; const height = window.innerHeight; const vizWidth = width; const fov = 100; const near = 50; const far = 5000; // -----------fakeStore----------- if needed to test // const store = [ // { // endpoint: '35.225.31.212', // clusterName: 'standard-cluster-1', // clusterDescription: '', // creationTime: '2019-08-27T23:21:01+00:00', // clusterStatus: 'RUNNING', // nodeCount: 7, // location: 'us-central1-a', // NodePool_0: [ 'default-pool', 'diskSize[Gb]: 100', 'MachineType: g1-small' ], // NodePool_1: [ 'pool-1', 'diskSize[Gb]: 100', 'MachineType: f1-micro' ], // NodePool_2: [ 'pool-2', 'diskSize[Gb]: 100', 'MachineType: f1-micro' ] // }, // { // endpoint: '34.70.204.169', // clusterName: 'weakclust', // clusterDescription: '', // creationTime: '2019-09-11T03:02:01+00:00', // clusterStatus: 'RUNNING', // nodeCount: 1, // location: 'us-central1-a', // NodePool_0: [ 'pool-1', 'diskSize[Gb]: 30', 'MachineType: g1-small' ] // } // ] const Visualizer = () => { let [store, setStore] = useContext(StoreContext); useEffect(() => { if(store.clusters){ const renderer = new THREE.WebGLRenderer(); renderer.setSize( width, height ); ref.current.appendChild(renderer.domElement); let camera = new THREE.PerspectiveCamera( fov, width / height, near, far ); //---------------number of hexagons---------------\\ const pointAmmount = store.clusters.length; // https://upload.wikimedia.org/wikipedia/commons/e/e6/Basic_hexagon.svg // https://fastforwardlabs.github.io/visualization_assets/circle-sprite.png const circleSprite = new THREE.TextureLoader().load(".././src/client/assets/visualizerPage/Basic_hexagon.svg") const testSprite = new THREE.TextureLoader().load('https://fastforwardlabs.github.io/visualization_assets/circle-sprite.png') const colorArray = ['skyblue', 'blue', 'lightblue', 'skyblue', 'blue', 'lightblue', ] const colorArray2 = ['red'] /* Testing to make random elements appear */ const randomPosition = (offset:number, radius?: number ) => { const ptAngle = Math.random() * 2 * Math.PI; const ptRadiusSq = Math.random() * radius * radius; const ptX = Math.sqrt(ptRadiusSq) * Math.cos(ptAngle); const ptY = Math.sqrt(ptRadiusSq) * Math.sin(ptAngle); return [ptX + offset, ptY]; } const pointInfo = []; const pointInfo2 = []; //generating shapes for cluster! for (let i = 0; i < pointAmmount; i++) { const position = [2400*i -2400,1] const group = i; const name = store.clusters[i].clusterName; const clusterStatus = store.clusters[i].clusterStatus; const creationTime = store.clusters[i].creationTime; const location = store.clusters[i].location; const nodeCount = store.clusters[i].nodeCount; const endpoint = store.clusters[i].endpoint const point = { position, name, clusterStatus, creationTime, location, nodeCount, endpoint, group }; pointInfo.push(point); } //for each cluster we must put nodes inside //omfg it works store.clusters.forEach(((cluster,i)=>{ for(let j = 0; j < cluster.nodeCount; j++){ const name2 = `Point` + j; const position = randomPosition(pointInfo[i].position[0], 300); const group = 0; const point2 = {position, name2, group} pointInfo2.push(point2) } })) const generatedPoints = pointInfo; const generatedPoints2 = pointInfo2; const pointsGeometry = new THREE.Geometry(); const pointsGeometry2 = new THREE.Geometry(); const colors = []; const colors2 = []; for (const point of generatedPoints) { const vertex = new THREE.Vector3(point.position[0], point.position[1]) pointsGeometry.vertices.push(vertex); const color = new THREE.Color(colorArray[point.group]); colors.push(color); } for (const point2 of generatedPoints2) { const vertex = new THREE.Vector3(point2.position[0], point2.position[1]) pointsGeometry2.vertices.push(vertex); const color = new THREE.Color(colorArray2[point2.group]); colors2.push(color); } pointsGeometry.colors = colors; pointsGeometry2.colors = colors2; //sizeAttenuation:true makes shakes bigger when zoom const pointsMaterial = new THREE.PointsMaterial({ size: 800, sizeAttenuation: true, vertexColors: THREE.VertexColors, map: circleSprite, transparent: true,}); const pointsMaterial2 = new THREE.PointsMaterial({ size: 100, sizeAttenuation: true, vertexColors: THREE.VertexColors, map: testSprite, transparent: true,}); //this where the shape is created const points = new THREE.Points(pointsGeometry, pointsMaterial); const points2 = new THREE.Points(pointsGeometry2, pointsMaterial2); const scene = new THREE.Scene(); scene.add(points); scene.add(points2) scene.background = new THREE.Color('black'); function toRadians (angle) { return angle * (Math.PI / 180); } const getScaleFromZ = (cameraZPosition) => { const halfFov = fov/2; const halfFovRadians = toRadians(halfFov); const halfFovHeight = Math.tan(halfFovRadians) * cameraZPosition; const fovHeight = halfFovHeight * 2; const scale = height / fovHeight; // Divide visualization height by height derived from field of view return scale; } function getZFromScale(scale) { const halfFov = fov/2; const halfFovRadians = toRadians(halfFov); let scaleHeight = height / scale; let cameraZPosition = scaleHeight / (2 * Math.tan(halfFovRadians)); return cameraZPosition; } function zoomHandler(d3_transform) { let scale = d3_transform.k; let x = -(d3_transform.x - vizWidth / 2) / scale; let y = (d3_transform.y - height / 2) / scale; let z = getZFromScale(scale); camera.position.set(x, y, z); } let zoom = d3.zoom() .scaleExtent([getScaleFromZ(far), getScaleFromZ(near)]) .on('zoom', () => { let d3_transform = d3.event.transform; zoomHandler(d3_transform); }); //d3 White space in the browser const view = d3.select(renderer.domElement); function setUpZoom() { view.call(zoom); const initialScale = getScaleFromZ(far); const initialTransform = d3.zoomIdentity.translate(vizWidth / 2, height / 2).scale(initialScale); zoom.transform(view, initialTransform); camera.position.set(0, 0, far); } setUpZoom(); const animate = function () { requestAnimationFrame(animate); renderer.render(scene, camera); }; animate(); const mouseToThree = (mouseX?: number, mouseY?: number) => { return new THREE.Vector3( mouseX / vizWidth * 2 - 1, - (mouseY / height) * 2 + 1, 1) } function sortIntersectsByDistanceToRay(intersects) { return _.sortBy(intersects, "distanceToRay"); } const hoverContainer = new THREE.Object3D(); const removeHighlights = () => { hoverContainer.remove(...hoverContainer.children); }; const tooltipState: {[k: string]: any} = { display: "none", } const grouptipState:{[k: string]: any} = { display: "none", } const toolTip = divRefOne.current; const pointTip = divRefTwo.current; const groupTip = divRefThree.current; //---------highlight functionality--------// const highlightPoint = (datum) => { removeHighlights(); const geometry = new THREE.Geometry(); geometry.vertices.push(new THREE.Vector3(datum.position[0], datum.position[1], 0)); geometry.colors = [ new THREE.Color(colorArray[datum.group])]; const material = new THREE.PointsMaterial({ size: 500, sizeAttenuation: false, vertexColors: THREE.VertexColors, map: circleSprite, transparent: false }); const point = new THREE.Points(geometry, material); hoverContainer.add(point); }; const updateTooltip = () => { toolTip.style.display = tooltipState.display; toolTip.style.left = tooltipState.left + 'px'; toolTip.style.top = tooltipState.top + 'px'; pointTip.innerText = tooltipState.name; pointTip.style.background = colorArray[tooltipState.group]; pStatus.current.textContent = tooltipState.clusterStatus //+ tooltipState.creationTime + tooltipState.location + tooltipState.nodeCount; pTime.current.textContent = tooltipState.creationTime; pLocation.current.textContent = tooltipState.location; pNode.current.textContent = tooltipState.nodeCount; pendpoint.current.textContent = tooltipState.endpoint; } const updateTooltip2 = () => { groupTip.style.display = grouptipState.display; groupTip.style.left = grouptipState.left + 'px'; groupTip.style.top = grouptipState.top + 'px'; pointTip.innerText = grouptipState.name; pointTip.style.background = colorArray[grouptipState.group]; pStatus.current.textContent = grouptipState.clusterStatus //+ grouptipState.creationTime + grouptipState.location + grouptipState.nodeCount; pTime.current.textContent = grouptipState.creationTime; pLocation.current.textContent = grouptipState.location; pNode.current.textContent = grouptipState.nodeCount; } function showTooltip(mousePosition, datum) { const tooltipWidth = 120; let xOffset = -tooltipWidth / 2; let yOffset = 30; tooltipState.display = "block"; tooltipState.left = mousePosition[0] + xOffset; tooltipState.top = mousePosition[1] + yOffset; tooltipState.name = datum.name; tooltipState.group = datum.group; tooltipState.clusterStatus = datum.clusterStatus; tooltipState.creationTime = datum.creationTime; tooltipState.location = datum.location; tooltipState.nodeCount = datum.nodeCount; tooltipState.endpoint = datum.endpoint updateTooltip(); } function showTooltip2(mousePosition, datum) { grouptipState.display = "block"; grouptipState.left = 0; grouptipState.top = 400; grouptipState.name = datum.name; grouptipState.group = datum.group; grouptipState.clusterStatus = datum.clusterStatus; grouptipState.clusterStatus = datum.clusterStatus; grouptipState.creationTime = datum.creationTime; grouptipState.location = datum.location; grouptipState.nodeCount = datum.nodeCount; updateTooltip2(); } //ray caster makes sure when we hover over shape we get it on dom element const raycaster = new THREE.Raycaster(); //this threshhold is what makes you hover over more than the centre raycaster.params.Points.threshold = 300; const checkCollission = (mousePosition) => { const mouseVector = mouseToThree(...mousePosition); raycaster.setFromCamera(mouseVector, camera); const intersects = raycaster.intersectObject(points); if (intersects[0]) { const sortedCollisions = sortIntersectsByDistanceToRay(intersects); const collision: any = sortedCollisions[0]; const index = collision.index const datum = generatedPoints[index]; showTooltip(mousePosition, datum); highlightPoint(datum); } else { removeHighlights(); hideTooltip(); } } // raycasting helper functions end view.on('mousemove', () => { const [mouseX, mouseY] = d3.mouse(view.node()); const mousePosition = [mouseX, mouseY]; checkCollission(mousePosition); }) // pointsContainer.add(points); view.on('mouseleave', () => { removeHighlights(); }); function hideTooltip() { tooltipState.display = 'none'; updateTooltip(); } } }) const ref = useRef<HTMLDivElement>(null) const divRefOne = useRef<HTMLDivElement>(null) const divRefTwo = useRef<HTMLDivElement>(null) const divRefThree = useRef<HTMLDivElement>(null) const pStatus = useRef<HTMLSpanElement>(null) const pTime = useRef<HTMLSpanElement>(null) const pLocation = useRef<HTMLSpanElement>(null) const pNode = useRef<HTMLSpanElement>(null) const pendpoint = useRef<HTMLSpanElement>(null) return ( <> <SideBar/> <div ref={ref} id="leCanvas"> <div ref={divRefOne} id="tool-tip"> <div ref={divRefTwo} id="point-tip" /> <div> status: <span ref={pStatus}/> </div> <div> Time Created: <span ref={pTime}/> </div> <div> Cluster Location: <span ref={pLocation}/> </div> <div> nodeCount:<span ref={pNode}/> </div> <div> Endpoint: <span ref={pendpoint}/> </div> </div> </div> </> ); }; export default Visualizer;
the_stack
'use strict'; import { EventEmitter } from 'events'; import machina = require('machina'); import { errors, endpoint, AuthenticationProvider } from 'azure-iot-common'; import { Amqp as BaseAmqpClient, AmqpMessage, SenderLink, ReceiverLink, AmqpTransportError, getErrorName } from 'azure-iot-amqp-base'; import { TwinProperties } from 'azure-iot-device'; import * as uuid from 'uuid'; import * as dbg from 'debug'; import rhea = require('rhea'); const debug = dbg('azure-iot-device-amqp:AmqpTwinClient'); const debugErrors = dbg('azure-iot-device-amqp:AmqpTwinClient:Errors'); interface LinkOption { properties: { [key: string]: string; }; rcv_settle_mode: number; snd_settle_mode: number; autoaccept?: boolean; } enum TwinMethod { GET = 'GET', PATCH = 'PATCH', PUT = 'PUT', DELETE = 'DELETE' } /** * @private * @class module:azure-iot-device-amqp.AmqpTwinClient * @classdesc Acts as a client for device-twin traffic * * @param {Object} config configuration object * @fires AmqpTwinClient#error an error has occurred * @fires AmqpTwinClient#desiredPropertyUpdate a desired property has been updated * @throws {ReferenceError} If client parameter is falsy. * */ /* Codes_SRS_NODE_DEVICE_AMQP_TWIN_06_005: [The `AmqpTwinClient` shall inherit from the `EventEmitter` class.] */ export class AmqpTwinClient extends EventEmitter { private _client: BaseAmqpClient; private _authenticationProvider: AuthenticationProvider; private _endpoint: string; private _senderLink: SenderLink; private _receiverLink: ReceiverLink; private _fsm: any; private _pendingTwinRequests: { [key: string]: (err: Error, twinProperties?: any) => void }; private _messageHandler: (message: AmqpMessage) => void; private _errorHandler: (err: Error) => void; constructor(authenticationProvider: AuthenticationProvider, client: any) { super(); this._client = client; this._authenticationProvider = authenticationProvider; this._senderLink = null; this._receiverLink = null; this._pendingTwinRequests = {}; this._messageHandler = (message: AmqpMessage): void => { // // The ONLY time we should see a message on the receiver link without a correlationId is if the message is a desired property delta update. // const correlationId: string = message.correlation_id; if (correlationId) { this._onResponseMessage(message); } else if (message.hasOwnProperty('body')) { this._onDesiredPropertyDelta(message); } else { // // Can't be any message we know what to do with. Just drop it on the floor. // debug('malformed response message received from service: ' + JSON.stringify(message)); } }; this._errorHandler = (err: Error): void => this._fsm.handle('handleLinkError', err); this._fsm = new machina.Fsm({ namespace: 'amqp-twin-client', initialState: 'detached', states: { detached: { _onEnter: (err, detachCallback) => { if (detachCallback) { detachCallback(err); } else { if (err) { this.emit('error', err); } } }, getTwin: (callback) => { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_007: [The `getTwin` method shall attach the sender link if it's not already attached.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_009: [THe `getTwin` method shall attach the receiver link if it's not already attached.]*/ this._fsm.transition('attaching', (err) => { if (err) { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_008: [If attaching the sender link fails, the `getTwin` method shall call its callback with the error that caused the failure.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_010: [If attaching the receiver link fails, the `getTwin` method shall call its callback with the error that caused the failure.]*/ callback(err); } else { this._fsm.handle('getTwin', callback); } }); }, updateTwinReportedProperties: (patch, callback) => { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_015: [The `updateTwinReportedProperties` method shall attach the sender link if it's not already attached.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_017: [THe `updateTwinReportedProperties` method shall attach the receiver link if it's not already attached.]*/ this._fsm.transition('attaching', (err) => { if (err) { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_016: [If attaching the sender link fails, the `updateTwinReportedProperties` method shall call its callback with the error that caused the failure.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_018: [If attaching the receiver link fails, the `updateTwinReportedProperties` method shall call its callback with the error that caused the failure.]*/ callback(err); } else { this._fsm.handle('updateTwinReportedProperties', patch, callback); } }); }, enableTwinDesiredPropertiesUpdates: (callback) => { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_023: [The `enableTwinDesiredPropertiesUpdates` method shall attach the sender link if it's not already attached.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_025: [The `enableTwinDesiredPropertiesUpdates` method shall attach the receiver link if it's not already attached.]*/ this._fsm.transition('attaching', (err) => { if (err) { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_024: [If attaching the sender link fails, the `enableTwinDesiredPropertiesUpdates` method shall call its callback with the error that caused the failure.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_026: [If attaching the receiver link fails, the `enableTwinDesiredPropertiesUpdates` method shall call its callback with the error that caused the failure.]*/ callback(err); } else { this._fsm.handle('enableTwinDesiredPropertiesUpdates', callback); } }); }, /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_031: [The `disableTwinDesiredPropertiesUpdates` method shall call its callback immediately and with no arguments if the links are detached.]*/ disableTwinDesiredPropertiesUpdates: (callback) => callback(), /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_004: [The `detach` method shall call its `callback` immediately if the links are already detached.]*/ detach: (callback) => callback() }, attaching: { _onEnter: (attachCallback) => { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_007: [The `attach` method shall call the `getDeviceCredentials` method on the `authenticationProvider` object passed as an argument to the constructor to retrieve the device id.]*/ this._authenticationProvider.getDeviceCredentials((err, credentials) => { if (err) { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_008: [The `attach` method shall call its callback with an error if the call to `getDeviceCredentials` fails with an error.]*/ this._fsm.transition('detached', err, attachCallback); } else { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_06_007: [The endpoint argument for attachReceiverLink shall be `/device/<deviceId>/twin`.] */ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_18_001: [If a `moduleId` value was set in the device's connection string, the endpoint argument for `attachReceiverLink` shall be `/devices/<deviceId>/modules/<moduleId>/twin`]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_06_009: [The endpoint argument for attachSenderLink shall be `/device/<deviceId>/twin`.] */ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_18_002: [If a `moduleId` value was set in the device's connection string, the endpoint argument for `attachSenderLink` shall be `/device/<deviceId>/modules/<moduleId>/twin`.]*/ if (credentials.moduleId) { this._endpoint = endpoint.moduleTwinPath(credentials.deviceId, credentials.moduleId); } else { this._endpoint = endpoint.deviceTwinPath(credentials.deviceId); } /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_06_006: [When a listener is added for the `response` event, and the `post` event is NOT already subscribed, upstream and downstream links are established via calls to `attachReceiverLink` and `attachSenderLink`.] */ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_06_012: [When a listener is added for the `post` event, and the `response` event is NOT already subscribed, upstream and downstream links are established via calls to `attachReceiverLink` and `attachSenderLine`.] */ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_036: [The same correlationId shall be used for both the sender and receiver links.]*/ const linkCorrelationId: string = uuid.v4().toString(); this._client.attachSenderLink( this._endpoint, this._generateTwinLinkProperties(linkCorrelationId), (senderLinkError?: Error, senderTransportObject?: any): void => { if (senderLinkError) { /* Codes_SRS_NODE_DEVICE_AMQP_TWIN_06_022: [If an error occurs on establishing the upstream or downstream link then the `error` event shall be emitted.] */ this._fsm.transition('detached', senderLinkError, attachCallback); } else { this._senderLink = senderTransportObject; this._senderLink.on('error', this._errorHandler); this._client.attachReceiverLink( this._endpoint, this._generateTwinLinkProperties(linkCorrelationId, true), (receiverLinkError?: Error, receiverTransportObject?: any): void => { if (receiverLinkError) { this._fsm.transition('detached', receiverLinkError, attachCallback); } else { this._receiverLink = receiverTransportObject; this._receiverLink.on('message', this._messageHandler); this._receiverLink.on('error', this._errorHandler); this._fsm.transition('attached', attachCallback); } }); } }); } }); }, handleLinkError: (err, callback) => this._fsm.transition('detaching', err, callback), detach: (callback) => this._fsm.transition('detaching', null, callback), '*': () => this._fsm.deferUntilTransition() }, attached: { _onEnter: (callback) => { callback(); }, handleLinkError: (err) => { this._fsm.transition('detaching', err); }, /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_011: [** The `getTwin` method shall send an `AmqpMessage` using the `SenderLink.send` method with the following annotations and properties: - `operation` annotation set to `GET`. - `resource` annotation set to `undefined` - `correlationId` property set to a uuid - `body` set to ` `.]*/ getTwin: (callback) => this._sendTwinRequest(TwinMethod.GET, undefined, ' ', callback), /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_019: [The `updateTwinReportedProperties` method shall send an `AmqpMessage` using the `SenderLink.send` method with the following annotations and properties: - `operation` annotation set to `PATCH`. - `resource` annotation set to `/properties/reported` - `correlationId` property set to a uuid - `body` set to the stringified patch object.]*/ updateTwinReportedProperties: (patch, callback) => this._sendTwinRequest(TwinMethod.PATCH, '/properties/reported', JSON.stringify(patch), callback), /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_027: [The `enableTwinDesiredPropertiesUpdates` method shall send an `AmqpMessage` using the `SenderLink.send` method with the following annotations and properties: - `operation` annotation set to `PUT`. - `resource` annotation set to `/notifications/twin/properties/desired` - `correlationId` property set to a uuid - `body` set to `undefined`.]*/ enableTwinDesiredPropertiesUpdates: (callback) => this._sendTwinRequest(TwinMethod.PUT, '/notifications/twin/properties/desired', ' ', callback), /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_032: [The `disableTwinDesiredPropertiesUpdates` method shall send an `AmqpMessage` using the `SenderLink.send` method with the following annotations and properties: - `operation` annotation set to `DELETE`. - `resource` annotation set to `/notifications/twin/properties/desired` - `correlationId` property set to a uuid - `body` set to `undefined`.]*/ disableTwinDesiredPropertiesUpdates: (callback) => this._sendTwinRequest(TwinMethod.DELETE, '/notifications/twin/properties/desired', ' ', callback), detach: (callback) => this._fsm.transition('detaching', null, callback) }, detaching: { _onEnter: (err, detachCallback) => { const senderLink = this._senderLink; const receiverLink = this._receiverLink; /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_005: [The `detach` method shall detach the links and call its `callback` with no arguments if the links are successfully detached.]*/ this._client.detachSenderLink(this._endpoint, (detachSenderError: Error, _result?: any) => { senderLink.removeListener('error', this._errorHandler); if (detachSenderError) { debugErrors('we received an error for the detach of the upstream link during the disconnect. Moving on to the downstream link. Error=' + detachSenderError); } this._client.detachReceiverLink(this._endpoint, (detachReceiverError: Error, _result?: any) => { receiverLink.removeListener('message', this._messageHandler); receiverLink.removeListener('error', this._errorHandler); if (detachReceiverError) { debugErrors('we received an error for the detach of the downstream link during the disconnect. Error=' + detachReceiverError); } /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_006: [The `detach` method shall call its `callback` with an `Error` if detaching either of the links fail.]*/ let possibleError = err || detachSenderError || detachReceiverError; this._fsm.transition('detached', possibleError, detachCallback); }); }); }, '*': () => this._fsm.deferUntilTransition() } } }); } getTwin(callback: (err: Error, twin?: TwinProperties) => void): void { this._fsm.handle('getTwin', callback); } updateTwinReportedProperties(patch: any, callback: (err?: Error) => void): void { this._fsm.handle('updateTwinReportedProperties', patch, callback); } enableTwinDesiredPropertiesUpdates(callback: (err?: Error) => void): void { this._fsm.handle('enableTwinDesiredPropertiesUpdates', callback); } disableTwinDesiredPropertiesUpdates(callback: (err?: Error) => void): void { this._fsm.handle('disableTwinDesiredPropertiesUpdates', callback); } /** * Necessary for the client to be able to properly detach twin links * attach() isn't necessary because it's done by the FSM automatically when one of the APIs is called. */ detach(callback: (err?: Error) => void): void { this._fsm.handle('detach', callback); } private _generateTwinLinkProperties( correlationId: string, autoaccept?: boolean): LinkOption { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_06_010: [** The link options argument for attachSenderLink shall be: attach: { properties: { 'com.microsoft:channel-correlation-id' : 'twin:<correlationId>', 'com.microsoft:api-version' : endpoint.apiVersion }, sndSettleMode: 1, rcvSettleMode: 0 } ] */ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_06_008: [The link options argument for attachReceiverLink shall be: attach: { properties: { 'com.microsoft:channel-correlation-id' : 'twin:<correlationId>', 'com.microsoft:api-version' : endpoint.apiVersion }, sndSettleMode: 1, rcvSettleMode: 0 } ] */ // Note that the settle mode hard coded values correspond to the defined constant values in the amqp10 specification. return { properties: { 'com.microsoft:channel-correlation-id' : 'twin:' + correlationId, 'com.microsoft:api-version' : endpoint.apiVersion }, snd_settle_mode: 1, rcv_settle_mode: 0, autoaccept: autoaccept }; } private _onResponseMessage(message: AmqpMessage): void { debug('onResponseMessage: The downstream message is: ' + JSON.stringify(message)); /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_013: [The `getTwin` method shall monitor `Message` objects on the `ReceiverLink.on('message')` handler until a message with the same `correlationId` as the one that was sent is received.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_021: [The `updateTwinReportedProperties` method shall monitor `Message` objects on the `ReceiverLink.on('message')` handler until a message with the same `correlationId` as the one that was sent is received.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_029: [The `enableTwinDesiredPropertiesUpdates` method shall monitor `Message` objects on the `ReceiverLink.on('message')` handler until a message with the same `correlationId` as the one that was sent is received.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_034: [The `disableTwinDesiredPropertiesUpdates` method shall monitor `Message` objects on the `ReceiverLink.on('message')` handler until a message with the same `correlationId` as the one that was sent is received.]*/ if (this._pendingTwinRequests[message.correlation_id]) { const pendingRequestCallback = this._pendingTwinRequests[message.correlation_id]; delete this._pendingTwinRequests[message.correlation_id]; if (!message.message_annotations) { let result = (message.body && message.body.content.length > 0) ? JSON.parse(message.body.content) : undefined; pendingRequestCallback(null, result); } else if (message.message_annotations.status >= 200 && message.message_annotations.status <= 300) { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_014: [The `getTwin` method shall parse the body of the received message and call its callback with a `null` error object and the parsed object as a result.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_022: [The `updateTwinReportedProperties` method shall call its callback with no argument when a response is received]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_030: [The `enableTwinDesiredPropertiesUpdates` method shall call its callback with no argument when a response is received]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_035: [The `disableTwinDesiredPropertiesUpdates` method shall call its callback with no argument when a response is received]*/ let result = (message.body && message.body.content.length > 0) ? JSON.parse(message.body.content) : undefined; pendingRequestCallback(null, result); } else { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_038: [The `getTwin` method shall call its callback with a translated error according to the table described in **SRS_NODE_DEVICE_AMQP_TWIN_16_037** if the `status` message annotation is `> 300`.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_039: [The `updateTwinReportedProperties` method shall call its callback with a translated error according to the table described in **SRS_NODE_DEVICE_AMQP_TWIN_16_037** if the `status` message annotation is `> 300`.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_040: [The `enableTwinDesiredPropertiesUpdates` method shall call its callback with a translated error according to the table described in **SRS_NODE_DEVICE_AMQP_TWIN_16_037** if the status message annotation is `> 300`.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_041: [The `disableTwinDesiredPropertiesUpdates` method shall call its callback with a translated error according to the table described in **SRS_NODE_DEVICE_AMQP_TWIN_16_037** if the status message annotation is `> 300`.]*/ pendingRequestCallback(this._translateErrorResponse(message)); } } else { debug('received a response for an unknown request: ' + JSON.stringify(message)); } } private _onDesiredPropertyDelta(message: AmqpMessage): void { debug('onDesiredPropertyDelta: The message is: ' + JSON.stringify(message)); this.emit('twinDesiredPropertiesUpdate', JSON.parse(message.body.content)); } private _sendTwinRequest(method: TwinMethod, resource: string, body: string, callback: (err?: Error) => void): void { let amqpMessage = new AmqpMessage(); amqpMessage.message_annotations = { operation: method }; if (resource) { amqpMessage.message_annotations.resource = resource; } let correlationId = uuid.v4(); // // Just a reminder here. The correlation id will not be serialized into a amqp uuid encoding (0x98). // The service doesn't require it and leaving it as a string will be just fine. // amqpMessage.correlation_id = correlationId; if (body) { amqpMessage.body = rhea.message.data_section(Buffer.from(body)); } this._pendingTwinRequests[correlationId] = callback; this._senderLink.send(amqpMessage, (err) => { /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_012: [If the `SenderLink.send` call fails, the `getTwin` method shall call its callback with the error that caused the failure.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_020: [If the `SenderLink.send` call fails, the `updateTwinReportedProperties` method shall call its callback with the error that caused the failure.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_028: [If the `SenderLink.send` call fails, the `enableTwinDesiredPropertiesUpdates` method shall call its callback with the error that caused the failure.]*/ /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_033: [If the `SenderLink.send` call fails, the `disableTwinDesiredPropertiesUpdates` method shall call its callback with the error that caused the failure.]*/ if (err) { debugErrors('could not get twin: ' + getErrorName(err)); delete this._pendingTwinRequests[correlationId]; callback(err); } else { debug(method + ' request sent with correlationId: ' + correlationId); } }); } /*Codes_SRS_NODE_DEVICE_AMQP_TWIN_16_037: [The responses containing errors received on the receiver link shall be translated according to the following table: | statusCode | ErrorType | | ---------- | ------------------------| | 400 | FormatError | | 401 | UnauthorizedError | | 403 | InvalidOperationError | | 404 | DeviceNotFoundError | | 429 | ThrottlingError | | 500 | InternalServerError | | 503 | ServiceUnavailableError | | 504 | TimeoutError | | others | TwinRequestError | ]*/ private _translateErrorResponse(amqpMessage: AmqpMessage): Error { let err: AmqpTransportError; let statusCode: number; let errorMessage: string = 'Twin operation failed'; if (amqpMessage.message_annotations) { statusCode = amqpMessage.message_annotations.status; } if (amqpMessage.body) { errorMessage = JSON.parse(amqpMessage.body.content); } switch (statusCode) { case 400: err = new errors.FormatError(errorMessage); break; case 401: err = new errors.UnauthorizedError(errorMessage); break; case 403: err = new errors.InvalidOperationError(errorMessage); break; case 404: err = new errors.DeviceNotFoundError(errorMessage); break; case 429: err = new errors.ThrottlingError(errorMessage); break; case 500: err = new errors.InternalServerError(errorMessage); break; case 503: err = new errors.ServiceUnavailableError(errorMessage); break; case 504: err = new errors.TimeoutError(errorMessage); break; default: err = new errors.TwinRequestError(errorMessage); } err.amqpError = <any>amqpMessage; return err; } }
the_stack
import { AbstractLayout } from '@antv/g6-core'; import { Layout } from '../../layout'; import { LayoutWorker } from '../../layout/worker/layout.worker'; import { LAYOUT_MESSAGE } from '../../layout/worker/layoutConst'; import { gpuDetector } from '../../util/gpu'; import { mix, clone } from '@antv/util'; import { IGraph } from '../../interface/graph'; // eslint-disable-next-line @typescript-eslint/no-implied-eval const mockRaf = (cb: TimerHandler) => setTimeout(cb, 16); const mockCaf = (reqId: number) => clearTimeout(reqId); const helper = { // pollyfill requestAnimationFrame(callback: FrameRequestCallback) { const fn = typeof window !== 'undefined' ? window.requestAnimationFrame || window.webkitRequestAnimationFrame || mockRaf : mockRaf; return fn(callback); }, cancelAnimationFrame(requestId: number) { const fn = typeof window !== 'undefined' ? window.cancelAnimationFrame || window.webkitCancelAnimationFrame || mockCaf : mockCaf; return fn(requestId); }, }; const GPU_LAYOUT_NAMES = ['fruchterman', 'gForce']; const LAYOUT_PIPES_ADJUST_NAMES = ['force', 'grid', 'circular']; export default class LayoutController extends AbstractLayout { public graph: IGraph; public destroyed: boolean; private worker; private workerData; // private data; private isGPU: boolean; // the configurations of the layout // private layoutCfg: any; // LayoutOptions // the type name of the layout // private layoutType: string; // private data: GraphData; // private layoutMethods: typeof Layout; constructor(graph: IGraph) { super(graph); this.graph = graph; this.layoutCfg = graph.get('layout') || {}; this.layoutType = this.getLayoutType(); this.worker = null; this.workerData = {}; this.initLayout(); } // eslint-disable-next-line class-methods-use-this protected initLayout() { // no data before rendering } // get layout worker and create one if not exists private getWorker() { if (this.worker) { return this.worker; } if (typeof Worker === 'undefined') { // 如果当前浏览器不支持 web worker,则不使用 web worker console.warn('Web worker is not supported in current browser.'); this.worker = null; } else { this.worker = LayoutWorker(this.layoutCfg.workerScriptURL); } return this.worker; } // stop layout worker private stopWorker() { const { workerData } = this; if (!this.worker) { return; } this.worker.terminate(); this.worker = null; // 重新开始新的布局之前,先取消之前布局的requestAnimationFrame。 if (workerData.requestId) { helper.cancelAnimationFrame(workerData.requestId); workerData.requestId = null; } if (workerData.requestId2) { helper.cancelAnimationFrame(workerData.requestId2); workerData.requestId2 = null; } } private execLayoutMethod(layoutCfg, order): Promise<void> { return new Promise(async (reslove, reject) => { const { graph } = this; if (graph.get('destroyed')) return; let layoutType = layoutCfg.type; // 每个布局方法都需要注册 layoutCfg.onLayoutEnd = () => { graph.emit('aftersublayout', { type: layoutType }); reslove(); } // 若用户指定开启 gpu,且当前浏览器支持 webgl,且该算法存在 GPU 版本(目前仅支持 fruchterman 和 gForce),使用 gpu 版本的布局 if (layoutType && this.isGPU) { if (!this.hasGPUVersion(layoutType)) { console.warn( `The '${layoutType}' layout does not support GPU calculation for now, it will run in CPU.`, ); } else { layoutType = `${layoutType}-gpu`; } } const isForce = layoutType === 'force' || layoutType === 'g6force' || layoutType === 'gForce'; if (isForce) { const { onTick } = layoutCfg; const tick = () => { if (onTick) { onTick(); } graph.refreshPositions(); }; layoutCfg.tick = tick; } else if (layoutCfg.type === 'comboForce') { layoutCfg.comboTrees = graph.get('comboTrees'); } let enableTick = false; let layoutMethod; try { layoutMethod = new Layout[layoutType](layoutCfg); } catch (e) { console.warn(`The layout method: '${layoutType}' does not exist! Please specify it first.`); reject(); } // 是否需要迭代的方式完成布局。这里是来自布局对象的实例属性,是由布局的定义者在布局类定义的。 enableTick = layoutMethod.enableTick; if (enableTick) { const { onTick } = layoutCfg; const tick = () => { if (onTick) { onTick(); } graph.refreshPositions(); }; layoutMethod.tick = tick; } const layoutData = this.filterLayoutData(this.data, layoutCfg); addLayoutOrder(layoutData, order); layoutMethod.init(layoutData); // 若存在节点没有位置信息,且没有设置 layout,在 initPositions 中 random 给出了所有节点的位置,不需要再次执行 random 布局 // 所有节点都有位置信息,且指定了 layout,则执行布局(代表不是第一次进行布局) graph.emit('beforesublayout', { type: layoutType }); await layoutMethod.execute(); if (layoutMethod.isCustomLayout && layoutCfg.onLayoutEnd) layoutCfg.onLayoutEnd(); this.layoutMethods[order] = layoutMethod; }); } private updateLayoutMethod(layoutMethod, layoutCfg): Promise<void> { return new Promise(async (reslove, reject) => { const { graph } = this; const layoutType = layoutCfg?.type; // 每个布局方法都需要注册 layoutCfg.onLayoutEnd = () => { graph.emit('aftersublayout', { type: layoutType }); reslove(); } const layoutData = this.filterLayoutData(this.data, layoutCfg); layoutMethod.init(layoutData); layoutMethod.updateCfg(layoutCfg); graph.emit('beforesublayout', { type: layoutType }); await layoutMethod.execute(); if (layoutMethod.isCustomLayout && layoutCfg.onLayoutEnd) layoutCfg.onLayoutEnd(); }); } /** * @param {function} success callback * @return {boolean} 是否使用web worker布局 */ public layout(success?: () => void): boolean { const { graph } = this; this.data = this.setDataFromGraph(); const { nodes, hiddenNodes } = this.data; if (!nodes) { return false; } const width = graph.get('width'); const height = graph.get('height'); const layoutCfg: any = {}; Object.assign( layoutCfg, { width, height, center: [width / 2, height / 2], }, this.layoutCfg, ); this.layoutCfg = layoutCfg; this.destoryLayoutMethods(); graph.emit('beforelayout'); this.initPositions(layoutCfg.center, nodes); // init hidden nodes this.initPositions(layoutCfg.center, hiddenNodes); // 防止用户直接用 -gpu 结尾指定布局 let layoutType = layoutCfg.type; if (layoutType && layoutType.split('-')[1] === 'gpu') { layoutType = layoutType.split('-')[0]; layoutCfg.gpuEnabled = true; } // 若用户指定开启 gpu,且当前浏览器支持 webgl,且该算法存在 GPU 版本(目前仅支持 fruchterman 和 gForce),使用 gpu 版本的布局 let enableGPU = false; if (layoutCfg.gpuEnabled) { enableGPU = true; // 打开下面语句将会导致 webworker 报找不到 window if (!gpuDetector().webgl) { console.warn(`Your browser does not support webGL or GPGPU. The layout will run in CPU.`); enableGPU = false; } } this.isGPU = enableGPU; // 在 onAllLayoutEnd 中执行用户自定义 onLayoutEnd,触发 afterlayout、更新节点位置、fitView/fitCenter、触发 afterrender const { onLayoutEnd, layoutEndFormatted, adjust } = layoutCfg; if (!layoutEndFormatted) { layoutCfg.layoutEndFormatted = true; layoutCfg.onAllLayoutEnd = async () => { // 执行用户自定义 onLayoutEnd if (onLayoutEnd) { onLayoutEnd(); } // 更新节点位置 this.refreshLayout(); // 最后再次调整 if (adjust && layoutCfg.pipes) { await this.adjustPipesBox(this.data, adjust); this.refreshLayout(); } // 触发 afterlayout graph.emit('afterlayout'); }; } this.stopWorker(); if (layoutCfg.workerEnabled && this.layoutWithWorker(this.data)) { // 如果启用布局web worker并且浏览器支持web worker,用web worker布局。否则回退到不用web worker布局。 return true; } let start = Promise.resolve(); if (layoutCfg.type) { start = start.then(async () => await this.execLayoutMethod(layoutCfg, 0)); } else if (layoutCfg.pipes) { layoutCfg.pipes.forEach((cfg, index) => { start = start.then(async () => await this.execLayoutMethod(cfg, index)); }); } // 最后统一在外部调用onAllLayoutEnd start.then(() => { if (layoutCfg.onAllLayoutEnd) layoutCfg.onAllLayoutEnd(); // 在执行 execute 后立即执行 success,且在 timeBar 中有 throttle,可以防止 timeBar 监听 afterrender 进行 changeData 后 layout,从而死循环 // 对于 force 一类布局完成后的 fitView 需要用户自己在 onLayoutEnd 中配置 if (success) success(); }).catch((error) => { console.warn('graph layout failed,', error); }); return false; } /** * layout with web worker * @param {object} data graph data * @return {boolean} 是否支持web worker */ private layoutWithWorker(data): boolean { const { layoutCfg, graph } = this; const worker = this.getWorker(); // 每次worker message event handler调用之间的共享数据,会被修改。 const { workerData } = this; if (!worker) { return false; } workerData.requestId = null; workerData.requestId2 = null; workerData.currentTick = null; workerData.currentTickData = null; graph.emit('beforelayout'); let start = Promise.resolve(); if (layoutCfg.type) { start = start.then(() => this.runWebworker(worker, data, layoutCfg)); } else if (layoutCfg.pipes) { for (const cfg of layoutCfg.pipes) { start = start.then(() => this.runWebworker(worker, data, cfg)); } } // 最后统一在外部调用onAllLayoutEnd start.then(() => { if (layoutCfg.onAllLayoutEnd) layoutCfg.onAllLayoutEnd(); }).catch((error) => { console.error('layout failed', error); }); return true; } private runWebworker(worker, allData, layoutCfg): Promise<void> { const { isGPU } = this; const data = this.filterLayoutData(allData, layoutCfg); const { nodes, edges } = data; const offScreenCanvas = document.createElement('canvas'); const gpuWorkerAbility = isGPU && typeof window !== 'undefined' && // eslint-disable-next-line @typescript-eslint/dot-notation window.navigator && !navigator[`gpu`] && // WebGPU 还不支持 OffscreenCanvas 'OffscreenCanvas' in window && 'transferControlToOffscreen' in offScreenCanvas; // NOTE: postMessage的message参数里面不能包含函数,否则postMessage会报错, // 例如:'function could not be cloned'。 // 详情参考:https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm // 所以这里需要把过滤layoutCfg里的函数字段过滤掉。 const filteredLayoutCfg = filterObject(layoutCfg, value => typeof value !== 'function'); if (!gpuWorkerAbility) { worker.postMessage({ type: LAYOUT_MESSAGE.RUN, nodes, edges, layoutCfg: filteredLayoutCfg, }); } else { const offscreen: any = (offScreenCanvas as any).transferControlToOffscreen(); // filteredLayoutCfg.canvas = offscreen; filteredLayoutCfg.type = `${filteredLayoutCfg.type}-gpu`; worker.postMessage( { type: LAYOUT_MESSAGE.GPURUN, nodes, edges, layoutCfg: filteredLayoutCfg, canvas: offscreen, }, [offscreen], ); } return new Promise((reslove, reject) => { worker.onmessage = (event) => { this.handleWorkerMessage(reslove, reject, event, data, layoutCfg); }; }); } // success callback will be called when updating graph positions for the first time. private handleWorkerMessage(reslove, reject, event, data, layoutCfg) { const { graph, workerData } = this; const eventData = event.data; const { type } = eventData; const onTick = () => { if (layoutCfg.onTick) { layoutCfg.onTick(); } }; switch (type) { case LAYOUT_MESSAGE.TICK: workerData.currentTick = eventData.currentTick; workerData.currentTickData = eventData; if (!workerData.requestId) { workerData.requestId = helper.requestAnimationFrame(function requestId() { updateLayoutPosition(data, eventData); graph.refreshPositions(); onTick(); if (eventData.currentTick === eventData.totalTicks) { // 如果是最后一次tick reslove(); } else if (workerData.currentTick === eventData.totalTicks) { // 注意这里workerData.currentTick可能已经不再是前面赋值时候的值了, // 因为在requestAnimationFrame等待时间里,可能产生新的tick。 // 如果当前tick不是最后一次tick,并且所有的tick消息都已发出来了,那么需要用最后一次tick的数据再刷新一次。 workerData.requestId2 = helper.requestAnimationFrame(function requestId2() { updateLayoutPosition(data, workerData.currentTickData); graph.refreshPositions(); workerData.requestId2 = null; onTick(); reslove(); }); } workerData.requestId = null; }); } break; case LAYOUT_MESSAGE.END: // 如果没有tick消息(非力导布局) if (workerData.currentTick == null) { updateLayoutPosition(data, eventData); reslove(); } break; case LAYOUT_MESSAGE.GPUEND: // 如果没有tick消息(非力导布局) if (workerData.currentTick == null) { updateGPUWorkerLayoutPosition(data, eventData); reslove(); } break; case LAYOUT_MESSAGE.ERROR: console.warn('Web-Worker layout error!', eventData.message); reject(); break; default: reject(); break; } } // 更新布局参数 public updateLayoutCfg(cfg) { const { graph, layoutMethods } = this; const layoutCfg = mix({}, this.layoutCfg, cfg); this.layoutCfg = layoutCfg; if (!layoutMethods?.length) { this.layout(); return; } this.data = this.setDataFromGraph(); this.stopWorker(); if (cfg.workerEnabled && this.layoutWithWorker(this.data)) { // 如果启用布局web worker并且浏览器支持web worker,用web worker布局。否则回退到不用web worker布局。 return; } graph.emit('beforelayout'); let start = Promise.resolve(); if (layoutMethods.length === 1) { start = start.then(async () => await this.updateLayoutMethod(layoutMethods[0], layoutCfg)); } else { layoutMethods?.forEach((layoutMethod, index) => { const currentCfg = layoutCfg.pipes[index]; start = start.then(async() => await this.updateLayoutMethod(layoutMethod, currentCfg)); }); } start.then(() => { if (layoutCfg.onAllLayoutEnd) layoutCfg.onAllLayoutEnd(); }).catch((error) => { console.warn('layout failed', error); }); } protected adjustPipesBox(data, adjust: string): Promise<void> { return new Promise((resolve) => { const { nodes } = data; if (!nodes?.length) { resolve(); } if (!LAYOUT_PIPES_ADJUST_NAMES.includes(adjust)) { console.warn(`The adjust type ${adjust} is not supported yet, please assign it with 'force', 'grid', or 'circular'.` ); resolve(); } const layoutCfg = { center: this.layoutCfg.center, nodeSize: (d) => Math.max(d.height, d.width), preventOverlap: true, onLayoutEnd: () => { }, }; // 计算出大单元 const { groupNodes, layoutNodes } = this.getLayoutBBox(nodes); const preNodes = clone(layoutNodes); // 根据大单元坐标的变化,调整这里面每个小单元nodes layoutCfg.onLayoutEnd = () => { layoutNodes?.forEach((ele, index) => { const dx = ele.x - preNodes[index]?.x; const dy = ele.y - preNodes[index]?.y; groupNodes[index]?.forEach((n: any) => { n.x += dx; n.y += dy; }); }); resolve(); } const layoutMethod = new Layout[adjust](layoutCfg); layoutMethod.layout({ nodes: layoutNodes }); }); } public hasGPUVersion(layoutName: string): boolean { return GPU_LAYOUT_NAMES.includes(layoutName); } public destroy() { this.destoryLayoutMethods(); const { worker } = this; if (worker) { worker.terminate(); this.worker = null; } this.destroyed = true; this.graph.set('layout', undefined); this.layoutCfg = undefined; this.layoutType = undefined; this.layoutMethods = undefined; this.graph = null; } } function updateLayoutPosition(data, layoutData) { const { nodes } = data; const { nodes: layoutNodes } = layoutData; const nodeLength = nodes.length; for (let i = 0; i < nodeLength; i++) { const node = nodes[i]; node.x = layoutNodes[i].x; node.y = layoutNodes[i].y; } } function filterObject(collection, callback) { const result = {}; if (collection && typeof collection === 'object') { Object.keys(collection).forEach(key => { if (collection.hasOwnProperty(key) && callback(collection[key])) { result[key] = collection[key]; } }); return result; } return collection; } function updateGPUWorkerLayoutPosition(data, layoutData) { const { nodes } = data; const { vertexEdgeData } = layoutData; const nodeLength = nodes.length; for (let i = 0; i < nodeLength; i++) { const node = nodes[i]; const x = vertexEdgeData[4 * i]; const y = vertexEdgeData[4 * i + 1]; node.x = x; node.y = y; } } function addLayoutOrder(data, order) { if (!data?.nodes?.length) { return; } const { nodes } = data; nodes.forEach(node => { node.layoutOrder = order; }); }
the_stack
import { Injectable, EventEmitter } from '@angular/core'; import { Observable, throwError, of, from } from 'rxjs'; import { map, catchError, switchMap, tap } from 'rxjs/operators'; import * as osmAuth from 'osm-auth'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Storage } from '@ionic/storage'; import { MapService } from './map.service'; import { TagsService } from './tags.service'; import { DataService } from './data.service'; import { AlertService } from './alert.service'; import { ConfigService, User } from './config.service'; import { cloneDeep } from 'lodash'; import bboxPolygon from '@turf/bbox-polygon' import { Platform } from '@ionic/angular'; import { addAttributesToFeature } from '../../../scripts/osmToOsmgo/index.js' @Injectable({ providedIn: 'root' }) export class OsmApiService { oauthParam = { prod: { url: 'https://www.openstreetmap.org', oauth_consumer_key: 'v2oE6nAar9KvIWLZHs4ip5oB7GFzbp6wTfznPNkr', oauth_secret: '1M71flXI86rh4JC3koIlAxn1KSzGksusvA8TgDz7' }, dev: { url: 'https://master.apis.dev.openstreetmap.org', oauth_consumer_key: 'PmNIoIN7dRKXQqmVSi07LAh7okepVRv0VvQAX3pM', oauth_secret: 'NULSrWvYE5nKtwOkSVSYAJ2zBQUJK6AgJo6ZE5Ax', } } auth; eventNewPoint = new EventEmitter(); constructor( private platform: Platform, private http: HttpClient, public mapService: MapService, public tagsService: TagsService, public dataService: DataService, public alertService: AlertService, public configService: ConfigService, private localStorage: Storage ) { } initAuth(){ const landing = `${window.location.origin}/assets/land.html` // land_single.html const windowType = 'newFullPage'; // singlepage, popup, newFullPage this.auth = new osmAuth({ url: this.configService.getIsDevServer() ? this.oauthParam.dev.url : this.oauthParam.prod.url, oauth_consumer_key: this.configService.getIsDevServer() ? this.oauthParam.dev.oauth_consumer_key : this.oauthParam.prod.oauth_consumer_key, oauth_secret: this.configService.getIsDevServer() ? this.oauthParam.dev.oauth_secret : this.oauthParam.prod.oauth_secret, auto: false, // show a login form if the user is not authenticated and landing: landing, windowType: windowType }); } login$(): Observable<any> { return Observable.create( observer => { this.auth.authenticate((e => { observer.next(true) })) } ).pipe( map((res) => { return res; }) ); } isAuthenticated(): boolean { return this.auth.authenticated() } logout() { if (this.configService.user_info.authType == 'oauth'){ this.auth.logout(); } this.localStorage.remove('changeset') this.configService.resetUserInfo(); } // retourne l'URL de l'API (dev ou prod) getUrlApi() { return this.configService.getIsDevServer() ? this.oauthParam.dev.url : this.oauthParam.prod.url; } // DETAIL DE L'UTILISATEUR getUserDetail$(_user?, _password?, basicAuth = false, passwordSaved = true, test = false): Observable<User> { const PATH_API = '/api/0.6/user/details.json' let _observable; if (!basicAuth) { _observable = Observable.create( observer => { this.auth.xhr({ method: 'GET', path: PATH_API, options: { header: { 'Content-Type': 'application/json' } }, }, (err, details) => { if (err) { observer.error({ response: err.response || '??', status: err.status || 0 }); } observer.next(JSON.parse(details)) }); }) } else { const url = this.getUrlApi() + PATH_API; // const headers = new Headers(); let headers = new HttpHeaders(); headers = headers .set('Authorization', `Basic ${btoa(_user + ':' + _password)}`) .set('Content-Type', 'application/json'); _observable = this.http.get(url, { headers: headers}) } return _observable.pipe( map((res: any) => { const x_user = res.user; const uid = x_user['id']; const display_name = x_user['display_name']; const _userInfo: User = { user: _user, password: passwordSaved ?_password : null, uid: uid, display_name: display_name, connected: true, authType: basicAuth ? 'basic' : 'oauth',}; if (!test){ this.configService.setUserInfo(_userInfo); } return _userInfo; }), catchError((error: any) => { return throwError(error); }) ); } // CHANGESET /* Edits can only be added to a changeset as long as it is still open; a changeset can either be closed explicitly (see your editor's documentation), or it closes itself if no edits are added to it for a period of inactivity (currently one hour). The same user can have multiple active changesets at the same time. A changeset has a maximum capacity (currently 50,000 edits) and maximum lifetime (currently 24 hours) */ createOSMChangeSet(comment, password): Observable<any> { const appVersion = `${this.configService.getAppVersion().appName} ${this.configService.getAppVersion().appVersionNumber}`; const content_put = ` <osm> <changeset> <tag k="created_by" v="${appVersion}"/> <tag k="comment" v="${comment}"/> <tag k="source" v="survey"/> </changeset> </osm>`; const PATH_API = `/api/0.6/changeset/create` let _observable; if (this.configService.user_info.authType === 'oauth') { _observable = Observable.create( observer => { this.auth.xhr({ method: 'PUT', path: PATH_API, options: { header: { 'Content-Type': 'text/xml' } }, content: content_put }, (err, details) => { if (err) { observer.error({ response: err.response || '??', status: err.status || 0 }); } observer.next(details) }) } ) } else { const url = this.getUrlApi() + PATH_API; let headers = new HttpHeaders(); headers = headers .set('Authorization', `Basic ${btoa(this.configService.getUserInfo().user + ':' + password)}`) .set('Content-Type', 'text/xml'); _observable = this.http.put(url, content_put, { headers: headers, responseType: 'text' }) } return _observable.pipe( map((res) => { this.configService.setChangeset(res.toString(), Date.now(), Date.now(), comment); return res; }) ); } // determine si le changset est valide, sinon on en crée un nouveau getValidChangset(_comments, password): Observable<any> { // si il n'existe pas if (this.configService.getChangeset().id == null || this.configService.getChangeset().id === '') { return this.createOSMChangeSet(_comments, password); } else if (_comments !== this.configService.getChangeset().comment) { // un commentaire différent => nouveau ChangeSet return this.createOSMChangeSet(_comments, password); } else if ((Date.now() - this.configService.getChangeset().last_changeset_activity) / 1000 > 3540 || // bientot une heure sans activité (Date.now() - this.configService.getChangeset().last_changeset_activity) / 1000 > 86360) { // bientot > 24h return this.createOSMChangeSet(_comments, password); } else { return of(this.configService.getChangeset().id) .pipe( map(CS => CS) ); } } escapeXmlValue(a) { return a .replace(/&/g, '&amp;') .replace(/'/g, "&apos;") .replace(/"/g, '&quot;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') } // GEOJSON => XML osm geojson2OsmCreate(geojson, id_changeset) { const tags_json = geojson.properties.tags; const lng = geojson.geometry.coordinates[0]; const lat = geojson.geometry.coordinates[1]; const node_header = `<node changeset="${id_changeset}" lat="${lat}" lon="${lng}">`; let tags_xml = ''; for (const k in tags_json) { if (k !== '' && tags_json[k] !== '') { // TODO: miss tags_xml += `<tag k="${this.escapeXmlValue(k.trim())}" v="${this.escapeXmlValue(String(tags_json[k]).trim())}"/>`; } } const xml = `<osm> ${node_header} ${tags_xml} </node></osm>`; return (xml); } // convert feature to xml(osm) geojson2OsmUpdate(_feature, id_changeset) { const tags_json = _feature.properties.tags; const type_objet = _feature.properties.type; const version = _feature.properties.meta.version; const id = _feature.properties.id; if (type_objet === 'node') { // c'est un noeud, les coords sont dans le Geojson const lng = _feature.geometry.coordinates[0]; const lat = _feature.geometry.coordinates[1]; const node_header = `<node id="${id}" changeset="${id_changeset}" version="${version}" lat="${lat}" lon="${lng}">`; let tags_xml = ''; for (const k in tags_json) { if (k !== '' && tags_json[k] !== '') { tags_xml += `<tag k="${this.escapeXmlValue(k.trim())}" v="${this.escapeXmlValue(String(tags_json[k]).trim())}"/>`; } } const xml = '<osm>' + node_header + tags_xml + '</node></osm>'; return (xml); } else if (type_objet === 'way') { const way_header = '<way id="' + id + '" changeset="' + id_changeset + '" version="' + version + '">'; let tags_xml = ''; for (const k in tags_json) { if (k !== '' && tags_json[k] !== '') { tags_xml += `<tag k="${this.escapeXmlValue(k.trim())}" v="${this.escapeXmlValue(String(tags_json[k]).trim())}"/>`; } } let nd_ref_xml = ''; for (let i = 0; i < _feature.ndRefs.length; i++) { nd_ref_xml += `<nd ref="${_feature.ndRefs[i]}"/>`; } const xml = `<osm> ${way_header}${nd_ref_xml}${tags_xml}</way></osm>`; return xml; } else if (type_objet === 'relation') { const relation_header = `<relation id="${id}" changeset="${id_changeset}" version="${version}">`; let tags_xml = ''; for (const k in tags_json) { if (k !== '' && tags_json[k] !== '') { tags_xml += `<tag k="${this.escapeXmlValue(k.trim())}" v="${this.escapeXmlValue(String(tags_json[k]).trim())}"/>`; } } let rel_ref_xml = ''; for (let i = 0; i < _feature.relMembers.length; i++) { rel_ref_xml += `<member type="${_feature.relMembers[i].type}" role="${_feature.relMembers[i].role}" ref="${_feature.relMembers[i].ref}"/>`; } const xml = `<osm> ${relation_header} ${tags_xml} ${rel_ref_xml} </relation></osm>`; return xml; } } /// CREATE NODE createOsmNode(_feature) { const feature = cloneDeep(_feature); const d = new Date(); const tmpId = 'tmp_' + d.getTime(); feature.id = 'node/' + tmpId; feature.properties.id = tmpId; feature.properties['meta'] = { timestamp: 0, version: 0, user: '' }; feature.properties.changeType = 'Create'; feature.properties.originalData = null; addAttributesToFeature(feature) this.dataService.addFeatureToGeojsonChanged(this.mapService.getIconStyle(feature)); // refresh changed only return of(_feature); } apiOsmCreateNode(_feature, changesetId, password) { const feature = cloneDeep(_feature); const content_put = this.geojson2OsmCreate(feature, changesetId); const PATH_API = `/api/0.6/node/create` let _observable; if (this.configService.user_info.authType === 'oauth') { _observable = Observable.create( observer => { this.auth.xhr({ method: 'PUT', path: PATH_API, options: { header: { 'Content-Type': 'text/xml' } }, content: content_put }, (err, details) => { if (err) { observer.error({ response: err.response || '??', status: err.status || 0 }); } observer.next(details) }) } ) } else { const url = this.getUrlApi() + '/api/0.6/node/create'; let headers = new HttpHeaders(); headers = headers .set('Authorization', `Basic ${btoa(this.configService.getUserInfo().user + ':' + password)}`); _observable = this.http.put(url, content_put, { headers: headers, responseType: 'text' }) } return _observable.pipe( map(id => { return id; }), catchError(error => { return throwError(error); }) ); } // Update updateOsmElement(_feature, origineData) { const feature = cloneDeep(_feature); addAttributesToFeature(feature) const id = feature.id; if (origineData === 'data_changed') {// il a déjà été modifié == if (feature.properties.changeType) this.dataService.updateFeatureToGeojsonChanged(this.mapService.getIconStyle(feature)); } else { // jamais été modifié, n'exite donc pas dans this.geojsonChanged mais dans le this.geojson feature.properties.changeType = 'Update'; feature.properties.originalData = this.dataService.getFeatureById(feature.properties.id, 'data'); this.dataService.addFeatureToGeojsonChanged(this.mapService.getIconStyle(feature)); this.dataService.deleteFeatureFromGeojson(feature); } return of(id); } apiOsmUpdateOsmElement(_feature, changesetId, password) { const feature = cloneDeep(_feature); const id = feature.id; const content_put = this.geojson2OsmUpdate(feature, changesetId); const PATH_API = `/api/0.6/${id}` let _observable; if (this.configService.user_info.authType === 'oauth') { _observable = Observable.create( observer => { this.auth.xhr({ method: 'PUT', path: PATH_API, options: { header: { 'Content-Type': 'text/xml' } }, content: content_put }, (err, details) => { if (err) { observer.error({ response: err.response || '??', status: err.status || 0 }); } observer.next(details) }) } ) } else { const url = this.getUrlApi() + PATH_API let headers = new HttpHeaders(); headers = headers .set('Authorization', `Basic ${btoa(this.configService.getUserInfo().user + ':' + password)}`) .set('Content-Type', 'text/xml'); _observable = this.http.put(url, content_put, { headers: headers, responseType: 'text' }) } return _observable.pipe( map(data => { this.mapService.eventOsmElementUpdated.emit(feature); return data; }), catchError(error => { return throwError(error); }) ); } // Delete deleteOsmElement(_feature) { const feature = cloneDeep(_feature); addAttributesToFeature(feature) const id = feature.id; if (feature.properties.changeType) { // il a déjà été modifié if (feature.properties.changeType === 'Create') { // il n'est pas sur le serveur, on le supprime des 2 geojson this.dataService.deleteFeatureFromGeojsonChanged(feature); } else if (feature.properties.changeType === 'Update') { // on reprend les données originales this.dataService.updateFeatureToGeojson(feature.properties.originalData); feature.properties.changeType = 'Delete'; this.dataService.updateFeatureToGeojsonChanged(this.mapService.getIconStyle(feature)); } } else { // jamais été modifié, n'exite donc pas dans this.geojsonChanged feature.properties.changeType = 'Delete'; feature.properties.originalData = this.dataService.getFeatureById(feature.properties.id, 'data'); this.dataService.addFeatureToGeojsonChanged(this.mapService.getIconStyle(feature)); this.dataService.deleteFeatureFromGeojson(feature); } return of(id); } apiOsmDeleteOsmElement(_feature, changesetId, password) { const feature = cloneDeep(_feature); const id = feature.id; const content_delete = this.geojson2OsmUpdate(feature, changesetId); const PATH_API = `/api/0.6/${id}` let _observable; if (this.configService.user_info.authType === 'oauth') { _observable = Observable.create( observer => { this.auth.xhr({ method: 'DELETE', path: PATH_API, options: { header: { 'Content-Type': 'text/xml' } }, content: content_delete }, (err, details) => { if (err) { observer.error({ response: err.response || '??', status: err.status || 0 }); } observer.next(details) }) } ) } else { const url = this.getUrlApi() + PATH_API let headers = new HttpHeaders(); headers = headers .set('Authorization', `Basic ${btoa(this.configService.getUserInfo().user + ':' + password)}`); _observable = this.http.request('delete', url, { headers: headers, body: content_delete }) } return _observable.pipe( map(data => { this.mapService.eventOsmElementDeleted.emit(feature); return data; }), catchError(error => { return throwError(error); }) ); } /* Convertit les donnée XML d'OSM en geojson en utilisant osmtogeojson Filtre les données* Convertit les polygones/lignes en point Generation du style dans les properties* Fusion avec les données existantes (ancienne + les données modifiés)* * utilisation du webworker */ formatOsmJsonData$(osmData, oldGeojson, geojsonChanged) { const that = this; const oldBbox = this.dataService.getGeojsonBbox(); const oldBboxFeature = cloneDeep(oldBbox.features[0]); return from( new Promise((resolve, reject) => { const workerFormatData = new Worker('assets/workers/worker-formatOsmData.js'); workerFormatData.postMessage({ tagsConfig: that.tagsService.tags, primaryKeys: that.tagsService.primaryKeys, osmData: osmData, oldGeojson: oldGeojson, oldBboxFeature: oldBboxFeature, geojsonChanged: geojsonChanged }); workerFormatData.onmessage = (formatedData) => { workerFormatData.terminate(); if (formatedData.data) { resolve(formatedData.data); } else { reject(Error('It broke')); } }; }) ); } getDataFromBbox(bbox: any) { const featureBbox = bboxPolygon(bbox); for (let i = 0; i < featureBbox.geometry.coordinates[0].length; i++) { featureBbox.geometry.coordinates[0][i][0] = featureBbox.geometry.coordinates[0][i][0]; featureBbox.geometry.coordinates[0][i][1] = featureBbox.geometry.coordinates[0][i][1]; } const headers = new HttpHeaders() .set('Content-Type', 'text/xml') .set('Accept', 'text/xml'); const url = this.getUrlApi() + `/api/0.6/map?bbox=${bbox.join(',')}`; return this.http.get(url, {headers: headers, responseType: 'text' }) .pipe( switchMap(osmData => this.formatOsmJsonData$(osmData, this.dataService.getGeojson(), this.dataService.getGeojsonChanged())), map((newDataJson => { return newDataJson }), catchError((error: any) => { return throwError(error.error || 'Impossible de télécharger les données (api)'); } )) ); } }
the_stack
import { EventHandler, FocusEvent, KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent, SyntheticEvent, useEffect, useRef, useState, } from "react"; import { isButton } from "ariakit-utils/dom"; import { addGlobalEventListener, isFocusEventOutside, isPortalEvent, isSelfTarget, queueBeforeEvent, } from "ariakit-utils/events"; import { focusIfNeeded, isFocusable } from "ariakit-utils/focus"; import { useEvent, useForkRef, useSafeLayoutEffect, useTagName, } from "ariakit-utils/hooks"; import { queueMicrotask } from "ariakit-utils/misc"; import { isApple, isFirefox, isSafari } from "ariakit-utils/platform"; import { createComponent, createElement, createHook, } from "ariakit-utils/system"; import { As, BivariantCallback, Options, Props } from "ariakit-utils/types"; const isSafariOrFirefoxOnAppleDevice = isApple() && (isSafari() || isFirefox()); const alwaysFocusVisibleInputTypes = [ "text", "search", "url", "tel", "email", "password", "number", "date", "month", "week", "time", "datetime", "datetime-local", ]; function isAlwaysFocusVisible(element: HTMLElement) { const { tagName, readOnly, type } = element as HTMLInputElement; if (tagName === "TEXTAREA" && !readOnly) return true; if (tagName === "SELECT" && !readOnly) return true; if (tagName === "INPUT" && !readOnly) { return alwaysFocusVisibleInputTypes.includes(type); } if (element.isContentEditable) return true; return false; } // See https://github.com/ariakit/ariakit/issues/1257 function isAlwaysFocusVisibleDelayed(element: HTMLElement) { const role = element.getAttribute("role"); if (role === "combobox") return true; return false; } function getLabels(element: HTMLElement | HTMLInputElement) { if ("labels" in element) { return element.labels; } return null; } function isNativeCheckboxOrRadio(element: { tagName: string; type?: string }) { const tagName = element.tagName.toLowerCase(); if (tagName === "input" && element.type) { return element.type === "radio" || element.type === "checkbox"; } return false; } function isNativeTabbable(tagName?: string) { if (!tagName) return true; return ( tagName === "button" || tagName === "input" || tagName === "select" || tagName === "textarea" || tagName === "a" ); } function supportsDisabledAttribute(tagName?: string) { if (!tagName) return true; return ( tagName === "button" || tagName === "input" || tagName === "select" || tagName === "textarea" ); } function getTabIndex( focusable: boolean, trulyDisabled: boolean, nativeTabbable: boolean, supportsDisabled: boolean, tabIndexProp?: number ) { if (!focusable) { return tabIndexProp; } if (trulyDisabled) { if (nativeTabbable && !supportsDisabled) { // Anchor, audio and video tags don't support the `disabled` attribute. // We must pass tabIndex={-1} so they don't receive focus on tab. return -1; } // Elements that support the `disabled` attribute don't need tabIndex. return; } if (nativeTabbable) { // If the element is enabled and it's natively tabbable, we don't need to // specify a tabIndex attribute unless it's explicitly set by the user. return tabIndexProp; } // If the element is enabled and is not natively tabbable, we have to // fallback tabIndex={0}. return tabIndexProp || 0; } function useDisableEvent( onEvent?: EventHandler<SyntheticEvent>, disabled?: boolean ) { return useEvent((event: SyntheticEvent) => { onEvent?.(event); if (event.defaultPrevented) return; if (disabled) { event.stopPropagation(); event.preventDefault(); } }); } // isKeyboardModality should be true by defaault. let isKeyboardModality = true; function onGlobalMouseDown(event: MouseEvent) { const target = event.target as HTMLElement | EventTarget | null; if (target && "hasAttribute" in target) { // If the target element is already focus-visible, we keep the keyboard // modality. if (!target.hasAttribute("data-focus-visible")) { isKeyboardModality = false; } } } function onGlobalKeyDown(event: KeyboardEvent) { if (event.metaKey) return; if (event.ctrlKey) return; isKeyboardModality = true; } /** * A component hook that returns props that can be passed to `Role` or any other * Ariakit component to render an element that can be focused. * @see https://ariakit.org/components/focusable * @example * ```jsx * const props = useFocusable(); * <Role {...props}>Focusable</Role> * ``` */ export const useFocusable = createHook<FocusableOptions>( ({ focusable = true, accessibleWhenDisabled, autoFocus, onFocusVisible, ...props }) => { const ref = useRef<HTMLDivElement>(null); // Add global event listeners to determine whether the user is using a // keyboard to navigate the site or not. useEffect(() => { if (!focusable) return; addGlobalEventListener("mousedown", onGlobalMouseDown, true); addGlobalEventListener("keydown", onGlobalKeyDown, true); }, [focusable]); // Safari and Firefox on Apple devices don't focus on checkboxes or radio // buttons when their labels are clicked. This effect will make sure the // focusable element is focused on label click. if (isSafariOrFirefoxOnAppleDevice) { useEffect(() => { if (!focusable) return; const element = ref.current; if (!element) return; if (!isNativeCheckboxOrRadio(element)) return; const labels = getLabels(element); if (!labels) return; const onMouseUp = () => queueMicrotask(() => element.focus()); labels.forEach((label) => label.addEventListener("mouseup", onMouseUp)); return () => { labels.forEach((label) => label.removeEventListener("mouseup", onMouseUp) ); }; }, [focusable]); } const disabled = focusable && props.disabled; const trulyDisabled = !!disabled && !accessibleWhenDisabled; const [focusVisible, setFocusVisible] = useState(false); // When the focusable element is disabled, it doesn't trigger a blur event // so we can't set focusVisible to false there. Instead, we have to do it // here by checking the element's disabled attribute. useEffect(() => { if (!focusable) return; if (trulyDisabled && focusVisible) { setFocusVisible(false); } }, [focusable, trulyDisabled, focusVisible]); // When an element that has focus becomes hidden, it doesn't trigger a blur // event so we can't set focusVisible to false there. We observe the element // and check if it's still focusable. Otherwise, we set focusVisible to // false. useEffect(() => { if (!focusable) return; if (!focusVisible) return; const element = ref.current; if (!element) return; if (typeof IntersectionObserver === "undefined") return; const observer = new IntersectionObserver(() => { if (!isFocusable(element)) { setFocusVisible(false); } }); observer.observe(element); return () => observer.disconnect(); }, [focusable, focusVisible]); // Disable events when the element is disabled. const onKeyPressCapture = useDisableEvent( props.onKeyPressCapture, disabled ); const onMouseDownCapture = useDisableEvent( props.onMouseDownCapture, disabled ); const onClickCapture = useDisableEvent(props.onClickCapture, disabled); const onMouseDownProp = props.onMouseDown; const onMouseDown = useEvent((event: ReactMouseEvent<HTMLDivElement>) => { onMouseDownProp?.(event); if (event.defaultPrevented) return; if (!focusable) return; const element = event.currentTarget; // Safari and Firefox on MacOS don't focus on buttons on mouse down like // other browsers/platforms. Instead, they focus on the closest focusable // ancestor element, which is ultimately the body element. So we make sure // to give focus to the tabbable element on mouse down so it works // consistently across browsers. if (!isSafariOrFirefoxOnAppleDevice) return; if (isPortalEvent(event)) return; if (!isButton(element) && !isNativeCheckboxOrRadio(element)) return; // We can't focus right away after on mouse down, otherwise it would // prevent drag events from happening. So we queue the focus to the next // animation frame, but always before the next mouseup event. The mouseup // event might happen before the next animation frame on touch devices or // by tapping on a MacBook's trackpad, for example. queueBeforeEvent(element, "mouseup", () => focusIfNeeded(element)); }); const onFocusVisibleProp = onFocusVisible; const onFocusVisibleEvent = useEvent( (event: SyntheticEvent<HTMLDivElement>) => { onFocusVisibleProp?.(event); if (event.defaultPrevented) return; if (!focusable) return; setFocusVisible(true); } ); const onKeyDownCaptureProp = props.onKeyDownCapture; const onKeyDownCapture = useEvent( (event: ReactKeyboardEvent<HTMLDivElement>) => { onKeyDownCaptureProp?.(event); if (!focusable) return; if (event.metaKey) return; if (event.altKey) return; if (event.ctrlKey) return; if (!isSelfTarget(event)) return; if (!focusVisible && !event.defaultPrevented) { // Triggers onFocusVisible when the element has initially received // non-keyboard focus, but then a key has been pressed. onFocusVisibleEvent(event); } } ); const onFocusCaptureProp = props.onFocusCapture; const onFocusCapture = useEvent((event: FocusEvent<HTMLDivElement>) => { onFocusCaptureProp?.(event); if (event.defaultPrevented) return; if (!focusable) return; if (!isSelfTarget(event)) { setFocusVisible(false); return; } if (isKeyboardModality || isAlwaysFocusVisible(event.target)) { onFocusVisibleEvent(event); } // See https://github.com/ariakit/ariakit/issues/1257 else if (isAlwaysFocusVisibleDelayed(event.target)) { queueBeforeEvent(event.target, "focusout", () => onFocusVisibleEvent(event) ); } else { setFocusVisible(false); } }); const onBlurProp = props.onBlur; // Note: Can't use onBlurCapture here otherwise it will not work with // CompositeItem's with the virtualFocus state set to true. const onBlur = useEvent((event: FocusEvent<HTMLDivElement>) => { onBlurProp?.(event); if (!focusable) return; if (isFocusEventOutside(event)) { setFocusVisible(false); } }); // The native autoFocus prop is problematic in many ways. For example, when // an element has the native autofocus attribute, the focus event will be // triggered before React effects (even layout effects) and before refs are // assigned. This means we won't have access to the element's ref or // anything else that's set up by React effects on the onFocus event. So we // don't pass the autoFocus prop to the element and instead manually focus // the element when it's mounted. The order in which this effect runs also // matters. It must be declared here after all the event callbacks above so // the event callback effects run before this one. See // https://twitter.com/diegohaz/status/1408180632933388289 useSafeLayoutEffect(() => { if (!focusable) return; if (autoFocus) { ref.current?.focus(); } }, [focusable, autoFocus]); const tagName = useTagName(ref, props.as); const nativeTabbable = focusable && isNativeTabbable(tagName); const supportsDisabled = focusable && supportsDisabledAttribute(tagName); const style = trulyDisabled ? { pointerEvents: "none" as const, ...props.style } : props.style; props = { "data-focus-visible": focusable && focusVisible ? "" : undefined, "aria-disabled": disabled ? true : undefined, ...props, ref: useForkRef(ref, props.ref), style, tabIndex: getTabIndex( focusable, trulyDisabled, nativeTabbable, supportsDisabled, props.tabIndex ), disabled: supportsDisabled && trulyDisabled ? true : undefined, // TODO: Test Focusable contentEditable. contentEditable: disabled ? undefined : props.contentEditable, onKeyPressCapture, onClickCapture, onMouseDownCapture, onMouseDown, onKeyDownCapture, onFocusCapture, onBlur, }; return props; } ); /** * A component that renders an element that can be focused. * @see https://ariakit.org/components/focusable * @example * ```jsx * <Focusable>Focusable</Focusable> * ``` */ export const Focusable = createComponent<FocusableOptions>((props) => { props = useFocusable(props); return createElement("div", props); }); export type FocusableOptions<T extends As = "div"> = Options<T> & { /** * Determines whether the focusable element is disabled. If the focusable * element doesn't support the native `disabled` attribute, the * `aria-disabled` attribute will be used instead. * @default false */ disabled?: boolean; /** * Automatically focus the element when it is mounted. It works similarly to * the native `autoFocus` prop, but solves an issue where the element is * given focus before React effects can run. * @default false */ autoFocus?: boolean; /** * Whether the element should be focusable. * @default true */ focusable?: boolean; /** * Determines whether the element should be focusable even when it is * disabled. * * This is important when discoverability is a concern. For example: * * > A toolbar in an editor contains a set of special smart paste functions * that are disabled when the clipboard is empty or when the function is not * applicable to the current content of the clipboard. It could be helpful to * keep the disabled buttons focusable if the ability to discover their * functionality is primarily via their presence on the toolbar. * * Learn more on [Focusability of disabled * controls](https://www.w3.org/TR/wai-aria-practices-1.2/#kbd_disabled_controls). */ accessibleWhenDisabled?: boolean; /** * Custom event handler that is called when the element is focused via the * keyboard or when a key is pressed while the element is focused. */ onFocusVisible?: BivariantCallback<(event: SyntheticEvent) => void>; }; export type FocusableProps<T extends As = "div"> = Props<FocusableOptions<T>>;
the_stack
import * as coreHttp from "@azure/core-http"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { StorageClientContext } from "../storageClientContext"; import { DirectoryCreateOptionalParams, DirectoryCreateResponse, DirectoryGetPropertiesOptionalParams, DirectoryGetPropertiesResponse, DirectoryDeleteOptionalParams, DirectoryDeleteResponse, DirectorySetPropertiesOptionalParams, DirectorySetPropertiesResponse, DirectorySetMetadataOptionalParams, DirectorySetMetadataResponse, DirectoryListFilesAndDirectoriesSegmentOptionalParams, DirectoryListFilesAndDirectoriesSegmentResponse, DirectoryListHandlesOptionalParams, DirectoryListHandlesResponse, DirectoryForceCloseHandlesOptionalParams, DirectoryForceCloseHandlesResponse } from "../models"; /** Class representing a Directory. */ export class Directory { private readonly client: StorageClientContext; /** * Initialize a new instance of the class Directory class. * @param client Reference to the service client */ constructor(client: StorageClientContext) { this.client = client; } /** * Creates a new directory under the specified share or parent directory. * @param fileAttributes If specified, the provided file attributes shall be set. Default value: * ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreatedOn Creation time for the file/directory. Default value: Now. * @param fileLastWriteOn Last write time for the file/directory. Default value: Now. * @param options The options parameters. */ create( fileAttributes: string, fileCreatedOn: string, fileLastWriteOn: string, options?: DirectoryCreateOptionalParams ): Promise<DirectoryCreateResponse> { const operationArguments: coreHttp.OperationArguments = { fileAttributes, fileCreatedOn, fileLastWriteOn, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, createOperationSpec ) as Promise<DirectoryCreateResponse>; } /** * Returns all system properties for the specified directory, and can also be used to check the * existence of a directory. The data returned does not include the files in the directory or any * subdirectories. * @param options The options parameters. */ getProperties( options?: DirectoryGetPropertiesOptionalParams ): Promise<DirectoryGetPropertiesResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, getPropertiesOperationSpec ) as Promise<DirectoryGetPropertiesResponse>; } /** * Removes the specified empty directory. Note that the directory must be empty before it can be * deleted. * @param options The options parameters. */ delete( options?: DirectoryDeleteOptionalParams ): Promise<DirectoryDeleteResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, deleteOperationSpec ) as Promise<DirectoryDeleteResponse>; } /** * Sets properties on the directory. * @param fileAttributes If specified, the provided file attributes shall be set. Default value: * ‘Archive’ for file and ‘Directory’ for directory. ‘None’ can also be specified as default. * @param fileCreatedOn Creation time for the file/directory. Default value: Now. * @param fileLastWriteOn Last write time for the file/directory. Default value: Now. * @param options The options parameters. */ setProperties( fileAttributes: string, fileCreatedOn: string, fileLastWriteOn: string, options?: DirectorySetPropertiesOptionalParams ): Promise<DirectorySetPropertiesResponse> { const operationArguments: coreHttp.OperationArguments = { fileAttributes, fileCreatedOn, fileLastWriteOn, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, setPropertiesOperationSpec ) as Promise<DirectorySetPropertiesResponse>; } /** * Updates user defined metadata for the specified directory. * @param options The options parameters. */ setMetadata( options?: DirectorySetMetadataOptionalParams ): Promise<DirectorySetMetadataResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, setMetadataOperationSpec ) as Promise<DirectorySetMetadataResponse>; } /** * Returns a list of files or directories under the specified share or directory. It lists the contents * only for a single level of the directory hierarchy. * @param options The options parameters. */ listFilesAndDirectoriesSegment( options?: DirectoryListFilesAndDirectoriesSegmentOptionalParams ): Promise<DirectoryListFilesAndDirectoriesSegmentResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, listFilesAndDirectoriesSegmentOperationSpec ) as Promise<DirectoryListFilesAndDirectoriesSegmentResponse>; } /** * Lists handles for directory. * @param options The options parameters. */ listHandles( options?: DirectoryListHandlesOptionalParams ): Promise<DirectoryListHandlesResponse> { const operationArguments: coreHttp.OperationArguments = { options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, listHandlesOperationSpec ) as Promise<DirectoryListHandlesResponse>; } /** * Closes all handles open for given directory. * @param handleId Specifies handle ID opened on the file or directory to be closed. Asterisk (‘*’) is * a wildcard that specifies all handles. * @param options The options parameters. */ forceCloseHandles( handleId: string, options?: DirectoryForceCloseHandlesOptionalParams ): Promise<DirectoryForceCloseHandlesResponse> { const operationArguments: coreHttp.OperationArguments = { handleId, options: coreHttp.operationOptionsToRequestOptionsBase(options || {}) }; return this.client.sendOperationRequest( operationArguments, forceCloseHandlesOperationSpec ) as Promise<DirectoryForceCloseHandlesResponse>; } } // Operation Specifications const xmlSerializer = new coreHttp.Serializer(Mappers, /* isXml */ true); const createOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}", httpMethod: "PUT", responses: { 201: { headersMapper: Mappers.DirectoryCreateHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.DirectoryCreateExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.metadata, Parameters.filePermission, Parameters.filePermissionKey1, Parameters.fileAttributes, Parameters.fileCreatedOn, Parameters.fileLastWriteOn ], isXML: true, serializer: xmlSerializer }; const getPropertiesOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}", httpMethod: "GET", responses: { 200: { headersMapper: Mappers.DirectoryGetPropertiesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.DirectoryGetPropertiesExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.shareSnapshot, Parameters.restype2 ], urlParameters: [Parameters.url], headerParameters: [Parameters.version, Parameters.accept1], isXML: true, serializer: xmlSerializer }; const deleteOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}", httpMethod: "DELETE", responses: { 202: { headersMapper: Mappers.DirectoryDeleteHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.DirectoryDeleteExceptionHeaders } }, queryParameters: [Parameters.timeoutInSeconds, Parameters.restype2], urlParameters: [Parameters.url], headerParameters: [Parameters.version, Parameters.accept1], isXML: true, serializer: xmlSerializer }; const setPropertiesOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.DirectorySetPropertiesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.DirectorySetPropertiesExceptionHeaders } }, queryParameters: [ Parameters.comp, Parameters.timeoutInSeconds, Parameters.restype2 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.filePermission, Parameters.filePermissionKey1, Parameters.fileAttributes, Parameters.fileCreatedOn, Parameters.fileLastWriteOn ], isXML: true, serializer: xmlSerializer }; const setMetadataOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.DirectorySetMetadataHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.DirectorySetMetadataExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.comp5, Parameters.restype2 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.metadata ], isXML: true, serializer: xmlSerializer }; const listFilesAndDirectoriesSegmentOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ListFilesAndDirectoriesSegmentResponse, headersMapper: Mappers.DirectoryListFilesAndDirectoriesSegmentHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.DirectoryListFilesAndDirectoriesSegmentExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.comp1, Parameters.prefix, Parameters.marker, Parameters.maxResults, Parameters.shareSnapshot, Parameters.restype2, Parameters.include1 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.includeExtendedInfo ], isXML: true, serializer: xmlSerializer }; const listHandlesOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ListHandlesResponse, headersMapper: Mappers.DirectoryListHandlesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.DirectoryListHandlesExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.marker, Parameters.maxResults, Parameters.shareSnapshot, Parameters.comp9 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.recursive ], isXML: true, serializer: xmlSerializer }; const forceCloseHandlesOperationSpec: coreHttp.OperationSpec = { path: "/{shareName}/{directory}", httpMethod: "PUT", responses: { 200: { headersMapper: Mappers.DirectoryForceCloseHandlesHeaders }, default: { bodyMapper: Mappers.StorageError, headersMapper: Mappers.DirectoryForceCloseHandlesExceptionHeaders } }, queryParameters: [ Parameters.timeoutInSeconds, Parameters.marker, Parameters.shareSnapshot, Parameters.comp10 ], urlParameters: [Parameters.url], headerParameters: [ Parameters.version, Parameters.accept1, Parameters.recursive, Parameters.handleId ], isXML: true, serializer: xmlSerializer };
the_stack
import { Doc, doc, FastPath, ParserOptions, Printer } from "prettier"; import { format, inspect } from "util"; import RESERVED_WORDS from "./reservedWords"; import { getNodeKey, isNodeKey } from "./util"; // Cheap lodash ;) const _ = { keys: Object.keys.bind(Object), identity: <T>(val: T): T => val, isArray: Array.isArray.bind(Array), isNumber: (n: unknown): n is number => typeof n === "number", values: Object.values.bind(Object), filter: <T>(arr: T[], fn: (arg: T) => unknown) => arr.filter(fn), compact: <T>(arr: (T | null | undefined)[]): T[] => arr.filter(_.identity as any), last: <T = any>(arr: T[]): T | undefined => arr[arr.length - 1], invert: <TKey extends string | number, TVal extends string | number>( input: Record<TKey, TVal>, ): Record<TVal, TKey> => { const output = {} as Record<TVal, TKey>; for (const key in input) { output[input[key]] = key; } return output; }, }; function optionsToHash(options) { if (!Array.isArray(options)) { throw new Error("Invalid options - expected array, got " + options); } const result = {}; for (const option of options) { whitelistKeys(option, ["DefElem"]); const elem = option.DefElem; if (!elem) { throw new Error("Invalid option element"); } whitelistKeys(elem, ["defname", "arg", "defaction", "location"]); const { defname, arg, defaction } = elem; if (defaction != null && defaction !== 0) { throw new Error("Expecting defaction = 0"); } if (result[defname]) { throw new Error(`Option '${defname}' defined twice?!`); } result[defname] = arg; } return result; } function getFunctionBodyEscapeSequence(text) { for (let i = 0; i < 1000; i++) { const escape = `$${i === 1 ? "_" : i ? i : ""}$`; if (text.indexOf(escape) < 0) { return escape; } } throw new Error("Could not find an acceptable function escape sequence"); } const { concat, join, hardline, line, softline, group, indent } = doc.builders; const commaLine = concat([",", line]); function whitelistKeys(obj, allowed) { const keys = [...allowed]; if (keys.length === 1 && /^[A-Z]/.test(keys[0])) { keys.push("comments"); keys.push("start"); keys.push("end"); } const extraKeys = Object.keys(obj).filter((key) => keys.indexOf(key) < 0); if (extraKeys.length) { throw new Error( `Key '${extraKeys.join("', '")}' in \`${JSON.stringify( obj, )}\` is not implemented (supported keys: '${keys.join("', '")}')`, ); } } function isContextNode(node) { const nodeKeys = Object.keys(node).filter(isNodeKey); if (nodeKeys.length === 1) { if (nodeKeys[0].substr(-4) === "Stmt") { return true; } // TODO: context could be part way through, e.g. `INSERT INTO foo SELECT col from my_table` - make sure we handle this. } return false; } function getContextNodeFromPath(path) { for (let i = 0, parent = null; (parent = path.getParentNode(i)); i++) { if (isContextNode(parent)) { return parent; } } return null; } const CONSTRAINT_TYPES = [ "NULL", "NOT NULL", "DEFAULT", "CHECK", "PRIMARY KEY", "UNIQUE", "EXCLUDE", "REFERENCES", ]; const compact = (o) => { return _.filter(_.compact(o), (p) => { if (p == null) { return false; } return p.toString().length; }); }; const fail = (type, node) => { throw new Error(format("Unhandled %s node: %s", type, JSON.stringify(node))); }; const parens = (doc) => { return concat(["(", doc, ")"]); }; function deparseNodes(nodes) { return nodes.map((node) => deparse(node)); } function deString(obj) { return obj.String.str; } function deInteger(obj) { return obj.Integer.ival; } function deConst(obj) { whitelistKeys(obj, ["A_Const"]); const { val } = obj.A_Const; const type = getNodeKey(val); if (type === "String") { return deString(val); } else if (type === "Integer") { return deInteger(val); } else { throw new Error("Invalid constant " + JSON.stringify(obj)); } } function list(nodes, separator = ", ") { if (!nodes) { return ""; } return deparseNodes(nodes).join(separator); } function quote(value) { console.warn("DEPRECATED call to `quote` - use `quoteIdent` if appropriate."); if (value == null) { return null; } if (_.isArray(value)) { return value.map((o) => quote(o)); } return '"' + value + '"'; } function isReserved(identString) { return RESERVED_WORDS.indexOf(identString) >= 0; } function quoteIdent(value) { if (value == null) { return null; } if (_.isArray(value)) { return value.map((o) => quoteIdent(o)); } if (value.match(/^[a-z_][a-z0-9_]*$/) && !isReserved(value)) { return value; } return '"' + value + '"'; } // SELECT encode(E'''123\\000\\001', 'base64') function escape(literal) { return "'" + literal.replace(/'/g, "''") + "'"; } function convertTypeName(typeName, size) { switch (typeName) { case "bpchar": if (size != null) { return "char"; } // return `pg_catalog.bpchar` below so that the following is symmetric // SELECT char 'c' = char 'c' AS true return "pg_catalog.bpchar"; case "varchar": return "varchar"; case "numeric": return "numeric"; case "bool": return "boolean"; case "int2": return "smallint"; case "int4": return "int"; case "int8": return "bigint"; case "real": case "float4": return "real"; case "float8": return "pg_catalog.float8"; case "text": // SELECT EXTRACT(CENTURY FROM CURRENT_DATE)>=21 AS True return "pg_catalog.text"; case "date": return "pg_catalog.date"; case "time": return "time"; case "timetz": return "pg_catalog.timetz"; case "timestamp": return "timestamp"; case "timestamptz": return "pg_catalog.timestamptz"; case "interval": return "interval"; case "bit": return "bit"; default: throw new Error(format("Unhandled data type: %s", typeName)); } } function getType(astNames, args) { const names = astNames.map((name) => name.String.str); const mods = (nameDoc, size) => { if (size != null) { return concat([nameDoc, "(", size, ")"]); } return nameDoc; }; // handle the special "char" (in quotes) type if (names[0] === "char") { names[0] = '"char"'; } if (names[0] === "pg_catalog") { if (names.length !== 2) { throw new Error(`Cannot yet understand type '${names.join(".")}'`); } const res = convertTypeName(names[1], args); return mods(res, args); } else { return mods(join(".", names), args); } } function deparse(something: any): any { debugger; throw new Error("No more deparse!"); } const print: Printer["print"] = (path: FastPath, options, print) => { const item = path.getValue(); if (item.Document) { const { statements } = item.Document; return statements.length ? join( hardline, path .map(print, "Document", "statements") .map((stmt) => group(concat([stmt, ";"]))), ) : ""; } if (item == null) { return null; } const type = getNodeKey(item); if (TYPES[type] == null) { throw new Error(type + " is not implemented"); } return path.call((innerPath) => { return TYPES[type](innerPath, options, print); }, type); }; export default print; function deparseFrameOptions(options, refName, startOffset, endOffset) { const FRAMEOPTION_NONDEFAULT = 0x00001; // any specified? const FRAMEOPTION_RANGE = 0x00002; // RANGE behavior const FRAMEOPTION_ROWS = 0x00004; // ROWS behavior const FRAMEOPTION_BETWEEN = 0x00008; // BETWEEN given? const FRAMEOPTION_START_UNBOUNDED_PRECEDING = 0x00010; // start is U. P. const FRAMEOPTION_END_UNBOUNDED_PRECEDING = 0x00020; // (disallowed) const FRAMEOPTION_START_UNBOUNDED_FOLLOWING = 0x00040; // (disallowed) const FRAMEOPTION_END_UNBOUNDED_FOLLOWING = 0x00080; // end is U. F. const FRAMEOPTION_START_CURRENT_ROW = 0x00100; // start is C. R. const FRAMEOPTION_END_CURRENT_ROW = 0x00200; // end is C. R. const FRAMEOPTION_START_VALUE_PRECEDING = 0x00400; // start is V. P. const FRAMEOPTION_END_VALUE_PRECEDING = 0x00800; // end is V. P. const FRAMEOPTION_START_VALUE_FOLLOWING = 0x01000; // start is V. F. const FRAMEOPTION_END_VALUE_FOLLOWING = 0x02000; // end is V. F. if (!(options & FRAMEOPTION_NONDEFAULT)) { return ""; } const output = []; if (refName != null) { output.push(refName); } if (options & FRAMEOPTION_RANGE) { output.push("RANGE"); } if (options & FRAMEOPTION_ROWS) { output.push("ROWS"); } const between = options & FRAMEOPTION_BETWEEN; if (between) { output.push("BETWEEN"); } if (options & FRAMEOPTION_START_UNBOUNDED_PRECEDING) { output.push("UNBOUNDED PRECEDING"); } if (options & FRAMEOPTION_START_UNBOUNDED_FOLLOWING) { output.push("UNBOUNDED FOLLOWING"); } if (options & FRAMEOPTION_START_CURRENT_ROW) { output.push("CURRENT ROW"); } if (options & FRAMEOPTION_START_VALUE_PRECEDING) { output.push(deparse(startOffset) + " PRECEDING"); } if (options & FRAMEOPTION_START_VALUE_FOLLOWING) { output.push(deparse(startOffset) + " FOLLOWING"); } if (between) { output.push("AND"); if (options & FRAMEOPTION_END_UNBOUNDED_PRECEDING) { output.push("UNBOUNDED PRECEDING"); } if (options & FRAMEOPTION_END_UNBOUNDED_FOLLOWING) { output.push("UNBOUNDED FOLLOWING"); } if (options & FRAMEOPTION_END_CURRENT_ROW) { output.push("CURRENT ROW"); } if (options & FRAMEOPTION_END_VALUE_PRECEDING) { output.push(deparse(endOffset) + " PRECEDING"); } if (options & FRAMEOPTION_END_VALUE_FOLLOWING) { output.push(deparse(endOffset) + " FOLLOWING"); } } return output.join(" "); } function deparseInterval(node) { const type = ["interval"]; if (node.arrayBounds != null) { type.push("[]"); } if (node.typmods) { const typmods = node.typmods.map((item) => deparse(item)); let intervals = interval(typmods[0]); // SELECT interval(0) '1 day 01:23:45.6789' if ( node.typmods[0] && node.typmods[0].A_Const && node.typmods[0].A_Const.val.Integer.ival === 32767 && node.typmods[1] && node.typmods[1].A_Const != null ) { intervals = [`(${node.typmods[1].A_Const.val.Integer.ival})`]; } else { intervals = intervals.map((part) => { if (part === "second" && typmods.length === 2) { return "second(" + _.last(typmods) + ")"; } return part; }); } type.push(intervals.join(" to ")); } return type.join(" "); } const TYPES: { [type: string]: ( path: FastPath, options: ParserOptions, print: (path: FastPath) => Doc, ) => Doc; } = { ["RawStmt"](path, options, print) { // RawStmt is mostly useful for getting statement start/end locations return path.call(print, "stmt"); }, ["A_Expr"](path, options, print) { const node = path.getValue(); const output = []; switch (node.kind) { case 0: // AEXPR_OP if (node.lexpr) { output.push(parens(deparse(node.lexpr))); } if (node.name.length > 1) { const schema = deparse(node.name[0]); const operator = deparse(node.name[1]); output.push(`OPERATOR(${schema}.${operator})`); } else { output.push(deparse(node.name[0])); } if (node.rexpr) { output.push(parens(deparse(node.rexpr))); } if (output.length === 2) { return parens(output.join("")); } return parens(output.join(" ")); case 1: // AEXPR_OP_ANY output.push(deparse(node.lexpr)); output.push(format("ANY (%s)", deparse(node.rexpr))); return output.join(` ${deparse(node.name[0])} `); case 2: // AEXPR_OP_ALL output.push(deparse(node.lexpr)); output.push(format("ALL (%s)", deparse(node.rexpr))); return output.join(` ${deparse(node.name[0])} `); case 3: // AEXPR_DISTINCT return format( "%s IS DISTINCT FROM %s", deparse(node.lexpr), deparse(node.rexpr), ); case 4: // AEXPR_NULLIF return format( "NULLIF(%s, %s)", deparse(node.lexpr), deparse(node.rexpr), ); case 5: { // AEXPR_OF const op = node.name[0].String.str === "=" ? "IS OF" : "IS NOT OF"; return format("%s %s (%s)", deparse(node.lexpr), op, list(node.rexpr)); } case 6: { // AEXPR_IN const operator = node.name[0].String.str === "=" ? "IN" : "NOT IN"; return format( "%s %s (%s)", deparse(node.lexpr), operator, list(node.rexpr), ); } case 7: // AEXPR_LIKE output.push(deparse(node.lexpr)); if (node.name[0].String.str === "!~~") { output.push(format("NOT LIKE (%s)", deparse(node.rexpr))); } else { output.push(format("LIKE (%s)", deparse(node.rexpr))); } return output.join(" "); case 8: // AEXPR_ILIKE output.push(deparse(node.lexpr)); if (node.name[0].String.str === "!~~*") { output.push(format("NOT ILIKE (%s)", deparse(node.rexpr))); } else { output.push(format("ILIKE (%s)", deparse(node.rexpr))); } return output.join(" "); case 9: // AEXPR_SIMILAR // SIMILAR TO emits a similar_escape FuncCall node with the first argument output.push(deparse(node.lexpr)); if (deparse(node.rexpr.FuncCall.args[1].Null)) { output.push( format("SIMILAR TO %s", deparse(node.rexpr.FuncCall.args[0])), ); } else { output.push( format( "SIMILAR TO %s ESCAPE %s", deparse(node.rexpr.FuncCall.args[0]), deparse(node.rexpr.FuncCall.args[1]), ), ); } return output.join(" "); case 10: // AEXPR_BETWEEN TODO(zhm) untested output.push(deparse(node.lexpr)); output.push( format( "BETWEEN %s AND %s", deparse(node.rexpr[0]), deparse(node.rexpr[1]), ), ); return output.join(" "); case 11: // AEXPR_NOT_BETWEEN TODO(zhm) untested output.push(deparse(node.lexpr)); output.push( format( "NOT BETWEEN %s AND %s", deparse(node.rexpr[0]), deparse(node.rexpr[1]), ), ); return output.join(" "); default: return fail("A_Expr", node); } }, ["Alias"](path, options, print) { const node = path.getValue(); const name = node.aliasname; const output = ["AS"]; if (node.colnames) { output.push(name + parens(list(node.colnames))); } else { output.push(quoteIdent(name)); } return output.join(" "); }, ["A_ArrayExpr"](path, options, print) { const node = path.getValue(); return format("ARRAY[%s]", list(node.elements)); }, ["A_Const"](path, options, print) { const node = path.getValue(); if (node.val.String) { return escape(node.val.String.str); } return path.call(print, "val"); }, ["A_Indices"](path, options, print) { const node = path.getValue(); if (node.lidx) { return format("[%s:%s]", deparse(node.lidx), deparse(node.uidx)); } return format("[%s]", deparse(node.uidx)); }, ["A_Indirection"](path, options, print) { const node = path.getValue(); const output = [`(${deparse(node.arg)})`]; // TODO(zhm) figure out the actual rules for when a '.' is needed // // select a.b[0] from a; // select (select row(1)).* // select c2[2].f2 from comptable // select c2.a[2].f2[1].f3[0].a1 from comptable for (let i = 0; i < node.indirection.length; i++) { const subnode = node.indirection[i]; if (subnode.String || subnode.A_Star) { const value = subnode.A_Star ? "*" : quote(subnode.String.str); output.push(`.${value}`); } else { output.push(deparse(subnode)); } } return output.join(""); }, ["A_Star"](_path, _options, _print) { return "*"; }, ["BitString"](path, options, print) { const node = path.getValue(); const prefix = node.str[0]; return `${prefix}'${node.str.substring(1)}'`; }, ["BoolExpr"](path, options, print) { const node = path.getValue(); switch (node.boolop) { case 0: return parens(list(node.args, " AND ")); case 1: return parens(list(node.args, " OR ")); case 2: return format("NOT (%s)", deparse(node.args[0])); default: return fail("BoolExpr", node); } }, ["BooleanTest"](path, options, print) { const node = path.getValue(); const output = []; output.push(deparse(node.arg)); const tests = [ "IS TRUE", "IS NOT TRUE", "IS FALSE", "IS NOT FALSE", "IS UNKNOWN", "IS NOT UNKNOWN", ]; output.push(tests[node.booltesttype]); return output.join(" "); }, ["CaseExpr"](path, options, print) { const node = path.getValue(); const output = ["CASE"]; if (node.arg) { output.push(deparse(node.arg)); } for (let i = 0; i < node.args.length; i++) { output.push(deparse(node.args[i])); } if (node.defresult) { output.push("ELSE"); output.push(deparse(node.defresult)); } output.push("END"); return output.join(" "); }, ["CoalesceExpr"](path, options, print) { const node = path.getValue(); return format("COALESCE(%s)", list(node.args)); }, ["CollateClause"](path, options, print) { const node = path.getValue(); const output = []; if (node.arg) { output.push(deparse(node.arg)); } output.push("COLLATE"); if (node.collname) { output.push(quote(deparseNodes(node.collname))); } return output.join(" "); }, ["ColumnDef"](path, options, print) { const node = path.getValue(); const output = [quoteIdent(node.colname)]; output.push(deparse(node.typeName)); if (node.raw_default) { output.push("USING"); output.push(deparse(node.raw_default)); } if (node.constraints) { output.push(list(node.constraints, " ")); } return _.compact(output).join(" "); }, ["ColumnRef"](path, options, print) { const node = path.getValue(); const fields = node.fields.map((field) => { if (field.String) { return quoteIdent(field.String.str); } return deparse(field); }); return fields.join("."); }, ["CommonTableExpr"](path, options, print) { const node = path.getValue(); const output = []; output.push(node.ctename); if (node.aliascolnames) { output.push(format("(%s)", quoteIdent(deparseNodes(node.aliascolnames)))); } output.push(format("AS (%s)", deparse(node.ctequery))); return output.join(" "); }, ["Float"](path, options, print) { const node = path.getValue(); // wrap negative numbers in parens, SELECT (-2147483648)::int4 * (-1)::int4 if (node.str[0] === "-") { return `(${node.str})`; } return node.str; }, ["FuncCall"](path, options, print) { const node = path.getValue(); const output = []; let params = []; if (node.args) { params = node.args.map((item) => { return deparse(item); }); } // COUNT(*) if (node.agg_star) { params.push("*"); } const name = list(node.funcname, "."); const order = []; const withinGroup = node.agg_within_group; if (node.agg_order) { order.push("ORDER BY"); order.push(list(node.agg_order, ", ")); } const call = []; call.push(name + "("); if (node.agg_distinct) { call.push("DISTINCT "); } // prepend variadic before the last parameter // SELECT CONCAT('|', VARIADIC ARRAY['1','2','3']) if (node.func_variadic) { params[params.length - 1] = "VARIADIC " + params[params.length - 1]; } call.push(params.join(", ")); if (order.length && !withinGroup) { call.push(" "); call.push(order.join(" ")); } call.push(")"); output.push(compact(call).join("")); if (order.length && withinGroup) { output.push("WITHIN GROUP"); output.push(parens(order.join(" "))); } if (node.agg_filter != null) { output.push(format("FILTER (WHERE %s)", deparse(node.agg_filter))); } if (node.over != null) { output.push(format("OVER %s", deparse(node.over))); } return output.join(" "); }, ["GroupingFunc"](path, options, print) { const node = path.getValue(); return "GROUPING(" + list(node.args) + ")"; }, ["GroupingSet"](path, options, print) { const node = path.getValue(); switch (node.kind) { case 0: // GROUPING_SET_EMPTY return "()"; case 1: // GROUPING_SET_SIMPLE return fail("GroupingSet", node); case 2: // GROUPING_SET_ROLLUP return "ROLLUP (" + list(node.content) + ")"; case 3: // GROUPING_SET_CUBE return "CUBE (" + list(node.content) + ")"; case 4: // GROUPING_SET_SETS return "GROUPING SETS (" + list(node.content) + ")"; default: return fail("GroupingSet", node); } }, ["Integer"](path, options, print) { const node = path.getValue(); if (node.ival < 0) { return `(${node.ival})`; } return node.ival.toString(); }, ["IntoClause"](path, options, print) { const node = path.getValue(); return deparse(node.rel); }, ["JoinExpr"](path, options, print) { const node = path.getValue(); const output = []; output.push(deparse(node.larg)); if (node.isNatural) { output.push("NATURAL"); } let join = null; switch (true) { case node.jointype === 0 && node.quals != null: join = "INNER JOIN"; break; case node.jointype === 0 && !node.isNatural && !(node.quals != null) && !(node.usingClause != null): join = "CROSS JOIN"; break; case node.jointype === 0: join = "JOIN"; break; case node.jointype === 1: join = "LEFT OUTER JOIN"; break; case node.jointype === 2: join = "FULL OUTER JOIN"; break; case node.jointype === 3: join = "RIGHT OUTER JOIN"; break; default: fail("JoinExpr", node); break; } output.push(join); if (node.rarg) { // wrap nested join expressions in parens to make the following symmetric: // select * from int8_tbl x cross join (int4_tbl x cross join lateral (select x.f1) ss) if (node.rarg.JoinExpr != null && !(node.rarg.JoinExpr.alias != null)) { output.push(`(${deparse(node.rarg)})`); } else { output.push(deparse(node.rarg)); } } if (node.quals) { output.push(`ON ${deparse(node.quals)}`); } if (node.usingClause) { const using = quoteIdent(deparseNodes(node.usingClause)).join(", "); output.push(`USING (${using})`); } const wrapped = node.rarg.JoinExpr != null || node.alias ? "(" + output.join(" ") + ")" : output.join(" "); if (node.alias) { return wrapped + " " + deparse(node.alias); } return wrapped; }, ["LockingClause"](path, options, print) { const node = path.getValue(); const strengths = [ "NONE", // LCS_NONE "FOR KEY SHARE", "FOR SHARE", "FOR NO KEY UPDATE", "FOR UPDATE", ]; const output = []; output.push(strengths[node.strength]); if (node.lockedRels) { output.push("OF"); output.push(list(node.lockedRels)); } return output.join(" "); }, ["MinMaxExpr"](path, options, print) { const node = path.getValue(); const output = []; if (node.op === 0) { output.push("GREATEST"); } else { output.push("LEAST"); } output.push(parens(list(node.args))); return output.join(""); }, ["NamedArgExpr"](path, options, print) { const node = path.getValue(); const output = []; output.push(node.name); output.push(":="); output.push(deparse(node.arg)); return output.join(" "); }, ["Null"](_path, _options, _print) { return "NULL"; }, ["NullTest"](path, options, print) { const node = path.getValue(); const output = [deparse(node.arg)]; if (node.nulltesttype === 0) { output.push("IS NULL"); } else if (node.nulltesttype === 1) { output.push("IS NOT NULL"); } return output.join(" "); }, ["ParamRef"](path, options, print) { const node = path.getValue(); if (node.number >= 0) { return ["$", node.number].join(""); } return "?"; }, ["RangeFunction"](path, options, print) { const node = path.getValue(); const output = []; if (node.lateral) { output.push("LATERAL"); } const funcs = []; for (let i = 0; i < node.functions.length; i++) { const funcCall = node.functions[i]; const call = [deparse(funcCall[0])]; if (funcCall[1] && funcCall[1].length) { call.push(format("AS (%s)", list(funcCall[1]))); } funcs.push(call.join(" ")); } const calls = funcs.join(", "); if (node.is_rowsfrom) { output.push(`ROWS FROM (${calls})`); } else { output.push(calls); } if (node.ordinality) { output.push("WITH ORDINALITY"); } if (node.alias) { output.push(deparse(node.alias)); } if (node.coldeflist) { const defList = list(node.coldeflist); if (!node.alias) { output.push(` AS (${defList})`); } else { output.push(`(${defList})`); } } return output.join(" "); }, ["RangeSubselect"](path, options, print) { const node = path.getValue(); let output = ""; if (node.lateral) { output += "LATERAL "; } output += parens(deparse(node.subquery)); if (node.alias) { return output + " " + deparse(node.alias); } return output; }, ["RangeTableSample"](path, options, print) { const node = path.getValue(); const output = []; output.push(deparse(node.relation)); output.push("TABLESAMPLE"); output.push(deparse(node.method[0])); if (node.args) { output.push(parens(list(node.args))); } if (node.repeatable) { output.push("REPEATABLE(" + deparse(node.repeatable) + ")"); } return output.join(" "); }, ["RangeVar"](path, options, print) { const node = path.getValue(); const output = []; if (node.inhOpt === 0) { output.push("ONLY"); } if (node.relpersistence === "u") { output.push("UNLOGGED"); } if (node.relpersistence === "t") { output.push("TEMPORARY"); } if (node.schemaname != null) { output.push(quoteIdent(node.schemaname)); output.push("."); } output.push(quoteIdent(node.relname)); if (node.alias) { output.push(deparse(node.alias)); } return output.join(" "); }, ["ResTarget"](path, options, print) { const node = path.getValue(); const contextNode = getContextNodeFromPath(path); if (!contextNode) { throw new Error( `Could not find contextNode for ResTarget\n\n${inspect(node, { depth: 6, })}`, ); } const valDoc = path.call(print, "val"); const identDoc = quoteIdent(node.name); if (contextNode.SelectStmt) { if (!valDoc && !identDoc) { throw new Error("Don't know what to SELECT!"); } return concat([ valDoc || "", valDoc && identDoc ? " AS " : "", identDoc || "", ]); } else if (contextNode.UpdateStmt) { return concat([identDoc, " = ", valDoc]); } else if (identDoc && !valDoc) { return identDoc; } return fail("ResTarget", node); }, ["RowExpr"](path, options, print) { const node = path.getValue(); if (node.row_format === 2) { return parens(list(node.args)); } return format("ROW(%s)", list(node.args)); }, ["SelectStmt"](path, options, print) { const node = path.getValue(); const output = []; whitelistKeys(node, [ "withClause", "op", "all", "valuesLists", "larg", "rarg", "distinctClause", "targetList", "intoClause", "fromClause", "whereClause", "groupClause", "havingClause", "windowClause", "sortClause", "limitCount", "limitOffset", "lockingClause", ]); const { withClause, op, all, valuesLists, distinctClause, targetList, intoClause, fromClause, whereClause, groupClause, havingClause, windowClause, sortClause, limitCount, limitOffset, lockingClause, } = node; if (withClause) { output.push(path.call(print, "withClause")); } if (op === 0) { // VALUES select's don't get SELECT if (valuesLists == null) { output.push("SELECT"); } } else { output.push(parens(path.call(print, "larg"))); const sets = ["NONE", "UNION", "INTERSECT", "EXCEPT"]; output.push(sets[op]); if (all) { output.push("ALL"); } output.push(parens(path.call(print, "rarg"))); } if (distinctClause) { if (!distinctClause.length || distinctClause[0] == null) { output.push("DISTINCT"); } else { output.push( concat([ "(", softline, group(join(concat([",", line]), path.map(print, "distinctClause"))), softline, ")", ]), ); } } if (targetList) { output.push(group(join(commaLine, path.map(print, "targetList")))); } if (intoClause) { output.push("INTO"); output.push(indent(path.call(print, "intoClause"))); } if (fromClause) { output.push("FROM"); output.push(indent(join(commaLine, path.map(print, "fromClause")))); } if (whereClause) { output.push("WHERE"); output.push(indent(path.call(print, "whereClause"))); } if (valuesLists) { output.push("VALUES"); output.push( join( commaLine, valuesLists.map((list, index) => { return concat([ "(", join(commaLine, path.map(print, "valuesList", index)), ")", ]); }), ), ); } if (groupClause) { output.push("GROUP BY"); output.push(indent(join(commaLine, path.map(print, "groupClause")))); } if (havingClause) { output.push("HAVING"); output.push(indent(path.call(print, "havingClause"))); } if (windowClause) { output.push("WINDOW"); const windows = []; for (let i = 0; i < windowClause.length; i++) { const w = windowClause[i]; const window = []; if (w.WindowDef.name) { window.push(quoteIdent(w.WindowDef.name) + " AS"); } window.push(parens(path.call(print, "windowClause", i))); windows.push(window.join(" ")); } output.push(windows.join(", ")); } if (sortClause) { output.push("ORDER BY"); output.push(indent(join(commaLine, path.map(print, "sortClause")))); } if (limitCount) { output.push("LIMIT"); output.push(indent(path.call(print, "limitCount"))); } if (limitOffset) { output.push("OFFSET"); output.push(indent(path.call(print, "limitOffset"))); } if (lockingClause) { output.push(join(line, path.map(print, "lockingClause"))); } return join(line, output); }, ["CreateStmt"](path, options, print) { const node = path.getValue(); const output = []; output.push("CREATE TABLE"); output.push(deparse(node.relation)); output.push("("); output.push(list(node.tableElts)); output.push(")"); output.push(";"); return output.join(" "); }, ["ConstraintStmt"](path, options, print) { const node = path.getValue(); const output = []; const constraint = CONSTRAINT_TYPES[node.contype]; if (node.conname) { output.push(`CONSTRAINT ${node.conname} ${constraint}`); } else { output.push(constraint); } return output.join(" "); }, ["ReferenceConstraint"](path, options, print) { const node = path.getValue(); const output = []; if (node.pk_attrs && node.fk_attrs) { output.push("FOREIGN KEY"); output.push("("); output.push(list(node.fk_attrs)); output.push(")"); output.push("REFERENCES"); output.push(deparse(node.pktable)); output.push("("); output.push(list(node.pk_attrs)); output.push(")"); } else if (node.pk_attrs) { output.push(TYPES.ConstraintStmt(node, options, print)); output.push(deparse(node.pktable)); output.push("("); output.push(list(node.pk_attrs)); output.push(")"); } else { output.push(TYPES.ConstraintStmt(node, options, print)); output.push(deparse(node.pktable)); } return output.join(" "); }, ["ExclusionConstraint"](path, options, print) { const node = path.getValue(); const output = []; function getExclusionGroup(node) { const output = []; const a = node.exclusions.map((excl) => { if (excl[0].IndexElem.name) { return excl[0].IndexElem.name; } else if (excl[0].IndexElem.expr) { return deparse(excl[0].IndexElem.expr); } }); const b = node.exclusions.map((excl) => deparse(excl[1][0])); for (let i = 0; i < a.length; i++) { output.push(`${a[i]} WITH ${b[i]}`); i !== a.length - 1 && output.push(","); } return output.join(" "); } if (node.exclusions && node.access_method) { output.push("USING"); output.push(node.access_method); output.push("("); output.push(getExclusionGroup(node)); output.push(")"); } return output.join(" "); }, ["Constraint"](path, options, print) { const node = path.getValue(); const output = []; const constraint = CONSTRAINT_TYPES[node.contype]; if (!constraint) { throw new Error("type not implemented: " + node.contype); } if (constraint === "REFERENCES") { output.push(TYPES.ReferenceConstraint(node, options, print)); } else { output.push(TYPES.ConstraintStmt(node, options, print)); } if (node.keys) { output.push("("); output.push(list(node.keys)); output.push(")"); } if (node.raw_expr) { output.push(deparse(node.raw_expr)); } if (node.fk_del_action) { switch (node.fk_del_action) { case "r": output.push("ON DELETE RESTRICT"); break; case "c": output.push("ON DELETE CASCADE"); break; default: } } if (node.fk_upd_action) { switch (node.fk_upd_action) { case "r": output.push("ON UPDATE RESTRICT"); break; case "c": output.push("ON UPDATE CASCADE"); break; default: } } if (constraint === "EXCLUDE") { output.push(TYPES.ExclusionConstraint(node, options, print)); } return output.join(" "); }, ["FunctionParameter"](path, options, print) { const node = path.getValue(); const output = []; output.push(node.name); output.push(deparse(node.argType)); return output.join(" "); }, ["CreateFunctionStmt"](path, options, print) { const node = path.getValue(); const returns = node.parameters ? node.parameters.filter( ({ FunctionParameter }) => FunctionParameter.mode === 116, ) : []; // var setof = node.parameters.filter( // ({ FunctionParameter }) => FunctionParameter.mode === 109 // ); let volatility, language, functionBody; let functionBodyOptionIndex; node.options.forEach((option, index) => { if (option && option.DefElem) { switch (option.DefElem.defname) { case "as": functionBodyOptionIndex = index; functionBody = deString(option.DefElem.arg[0]); break; case "language": language = deString(option.DefElem.arg); break; case "volatility": volatility = option; break; default: throw new Error( `Did not understand DefElem defname: '${option.DefElem.defname}'`, ); } } }); const functionBodyParser = { plv8: "javascript", plpgsql: "postgresql", sql: "postgresql", plpython: "python", plruby: "ruby", }[language]; // TODO: we need to do this on the result body, not the source body, in case it's been modified. const functionEscape = getFunctionBodyEscapeSequence(functionBody); const args = concat([ "(", group( join( ",", node.parameters ? node.parameters .map((param, index) => { const { FunctionParameter } = param; if (FunctionParameter.mode === 105) { return path.call(print, "parameters", index); } }) .filter((_) => _) : [], ), ), ")", ]); const createFunctionFooDoc = group( concat([ "CREATE ", node.replace ? "OR REPLACE " : "", "FUNCTION ", join(".", node.funcname.map(deString).map(quoteIdent)), softline, args, ]), ); const returnsDoc = concat([ line, "RETURNS ", returns.length ? group( concat([ "TABLE(", group( join( concat([",", line]), node.parameters .map((param, index) => { const { FunctionParameter } = param; if (FunctionParameter.mode === 116) { return path.call(print, "parameters", index); } }) .filter((_) => _), ), ), ")", ]), ) : path.call(print, "returnType"), ]); const languageDoc = concat([line, `LANGUAGE '${language}'`]); const volatilityDoc = volatility ? concat([line, deString(volatility.DefElem.arg).toUpperCase()]) : ""; return group( concat([ group( concat([ group( concat([ createFunctionFooDoc, returnsDoc, languageDoc, volatilityDoc, ]), ), line, "AS ", functionEscape, ]), ), /* * This tells prettier to print * `node['options'][functionBodyOptionIndex]` which is a `DefElem` * containing the function body. If the DefElem is understood by * embed.ts then it'll be parsed in the relevant language, otherwise * it'll be handled by the fallback printer in here (see `DefElem` * below). */ group(path.call(print, "options", functionBodyOptionIndex)), functionEscape, ]), ); }, ["CreateSchemaStmt"](path, options, print) { const node = path.getValue(); const output = []; output.push("CREATE"); if (node.replace) { output.push("OR REPLACE"); } output.push("SCHEMA"); output.push(node.schemaname); return output.join(" "); }, ["TransactionStmt"](path, options, print) { const node = path.getValue(); whitelistKeys(node, ["kind", "options"]); const parts = []; const TRANSACTION_STMT_BY_KIND: { [key: number]: string | undefined } = { 0: "BEGIN", 2: "COMMIT", }; const stmt = TRANSACTION_STMT_BY_KIND[node.kind]; if (!stmt) { throw new Error(`Don't understand transaction statement '${node.kind}'`); } parts.push(stmt); const opts: any = node.options ? optionsToHash(node.options) : {}; if (opts.transaction_isolation) { const val = deConst(opts.transaction_isolation); parts.push(` ISOLATION LEVEL ${val.toUpperCase()}`); } if (opts.transaction_read_only) { const val = deConst(opts.transaction_read_only); if (val === 0) { parts.push(" READ WRITE"); } else if (val === 1) { parts.push(" READ ONLY"); } else { throw new Error("Invalid transaction option"); } } if (opts.transaction_deferrable) { const val = deConst(opts.transaction_deferrable); if (val === 0) { parts.push(" NOT DEFERRABLE"); } else if (val === 1) { parts.push(" DEFERRABLE"); } else { throw new Error("Invalid transaction option"); } } return concat(parts); }, ["SortBy"](path, options, print) { const node = path.getValue(); const output = []; output.push(deparse(node.node)); if (node.sortby_dir === 1) { output.push("ASC"); } if (node.sortby_dir === 2) { output.push("DESC"); } if (node.sortby_dir === 3) { output.push(`USING ${deparseNodes(node.useOp)}`); } if (node.sortby_nulls === 1) { output.push("NULLS FIRST"); } if (node.sortby_nulls === 2) { output.push("NULLS LAST"); } return output.join(" "); }, ["String"](_path, _options, _print) { throw new Error( "Do *NOT* call String directly - we don't know which quotes to use!", ); }, ["SubLink"](path, options, print) { const node = path.getValue(); switch (true) { case node.subLinkType === 0: return format("EXISTS (%s)", deparse(node.subselect)); case node.subLinkType === 1: return format( "%s %s ALL (%s)", deparse(node.testexpr), deparse(node.operName[0]), deparse(node.subselect), ); case node.subLinkType === 2 && !(node.operName != null): return format( "%s IN (%s)", deparse(node.testexpr), deparse(node.subselect), ); case node.subLinkType === 2: return format( "%s %s ANY (%s)", deparse(node.testexpr), deparse(node.operName[0]), deparse(node.subselect), ); case node.subLinkType === 3: return format( "%s %s (%s)", deparse(node.testexpr), deparse(node.operName[0]), deparse(node.subselect), ); case node.subLinkType === 4: return format("(%s)", deparse(node.subselect)); case node.subLinkType === 5: // TODO(zhm) what is this? return fail("SubLink", node); // MULTIEXPR_SUBLINK // format('(%s)', @deparse(node.subselect)) case node.subLinkType === 6: return format("ARRAY (%s)", deparse(node.subselect)); default: return fail("SubLink", node); } }, ["TypeCast"](path, options, print) { return concat([ path.call(print, "arg"), "::", path.call(print, "typeName"), ]); }, ["TypeName"](path, options, print) { const node = path.getValue(); if (_.last(node.names).String.str === "interval") { return deparseInterval(node); } let args = null; if (node.typmods != null) { args = path.map(print, "typmods"); } return concat([ node.setof ? concat(["SETOF", line]) : "", getType(node.names, args ? join(commaLine, args) : null), node.arrayBounds != null ? "[]" : "", ]); }, ["CaseWhen"](path, options, print) { const node = path.getValue(); const output = ["WHEN"]; output.push(deparse(node.expr)); output.push("THEN"); output.push(deparse(node.result)); return output.join(" "); }, ["WindowDef"](path, options, print) { const node = path.getValue(); // TODO: fix this. const isWindowContext = path.getParentNode().windowClause === node; const output = []; if (!isWindowContext) { if (node.name) { output.push(node.name); } } const empty = !(node.partitionClause != null) && !(node.orderClause != null); const frameOptions = deparseFrameOptions( node.frameOptions, node.refname, node.startOffset, node.endOffset, ); if ( empty && !isWindowContext && !(node.name != null) && frameOptions.length === 0 ) { return "()"; } const windowParts = []; let useParens = false; if (node.partitionClause) { const partition = ["PARTITION BY"]; const clause = node.partitionClause.map((item) => deparse(item)); partition.push(clause.join(", ")); windowParts.push(partition.join(" ")); useParens = true; } if (node.orderClause) { windowParts.push("ORDER BY"); const orders = node.orderClause.map((item) => { return deparse(item); }); windowParts.push(orders.join(", ")); useParens = true; } if (frameOptions.length) { useParens = true; windowParts.push(frameOptions); } if (useParens && !isWindowContext) { return output.join(" ") + " (" + windowParts.join(" ") + ")"; } return output.join(" ") + windowParts.join(" "); }, ["WithClause"](path, options, print) { const node = path.getValue(); const output = ["WITH"]; if (node.recursive) { output.push("RECURSIVE"); } output.push(list(node.ctes)); return output.join(" "); }, DefElem(path, options, print) { const node = path.getValue(); if (node && node.defname === "as") { return node.arg[0].String.str; } else { throw new Error( "Do not understand this type of DefElem: " + JSON.stringify(node), ); } }, }; /* const nodeTypes = Object.keys(TYPES); const defs = []; const stmtTypes = []; const exprTypes = []; const allNodes = []; nodeTypes.forEach((t) => { defs.push(`export interface ${t}Def {[key: string]: any /* TODO *`+`/};`); defs.push(`export type ${t}Node = {${t}: ${t}Def};`); defs.push(); allNodes.push(`${t}Node`); if (t.endsWith("Stmt")) { stmtTypes.push(`${t}Node`); } else if (t.endsWith("Expr")) { exprTypes.push(`${t}Node`); } }); const str = `\ ${defs.join("\n")} export type ExprNode = | ${exprTypes.join("\n | ")}; export type StmtNode = | ${stmtTypes.join("\n | ")}; export type PGNode = | ${allNodes.join("\n | ")}; `; */ //////////////////////////////////////////////////////////////////////////////// // ported from https://github.com/lfittl/pg_query/blob/master/lib/pg_query/deparse/interval.rb const MASKS = { 0: "RESERV", 1: "MONTH", 2: "YEAR", 3: "DAY", 4: "JULIAN", 5: "TZ", 6: "DTZ", 7: "DYNTZ", 8: "IGNORE_DTF", 9: "AMPM", 10: "HOUR", 11: "MINUTE", 12: "SECOND", 13: "MILLISECOND", 14: "MICROSECOND", 15: "DOY", 16: "DOW", 17: "UNITS", 18: "ADBC", 19: "AGO", 20: "ABS_BEFORE", 21: "ABS_AFTER", 22: "ISODATE", 23: "ISOTIME", 24: "WEEK", 25: "DECADE", 26: "CENTURY", 27: "MILLENNIUM", 28: "DTZMOD", }; const BITS = _.invert(MASKS); const INTERVALS = {}; INTERVALS[1 << BITS.YEAR] = ["year"]; INTERVALS[1 << BITS.MONTH] = ["month"]; INTERVALS[1 << BITS.DAY] = ["day"]; INTERVALS[1 << BITS.HOUR] = ["hour"]; INTERVALS[1 << BITS.MINUTE] = ["minute"]; INTERVALS[1 << BITS.SECOND] = ["second"]; INTERVALS[(1 << BITS.YEAR) | (1 << BITS.MONTH)] = ["year", "month"]; INTERVALS[(1 << BITS.DAY) | (1 << BITS.HOUR)] = ["day", "hour"]; INTERVALS[(1 << BITS.DAY) | (1 << BITS.HOUR) | (1 << BITS.MINUTE)] = [ "day", "minute", ]; INTERVALS[ (1 << BITS.DAY) | (1 << BITS.HOUR) | (1 << BITS.MINUTE) | (1 << BITS.SECOND) ] = ["day", "second"]; INTERVALS[(1 << BITS.HOUR) | (1 << BITS.MINUTE)] = ["hour", "minute"]; INTERVALS[(1 << BITS.HOUR) | (1 << BITS.MINUTE) | (1 << BITS.SECOND)] = [ "hour", "second", ]; INTERVALS[(1 << BITS.MINUTE) | (1 << BITS.SECOND)] = ["minute", "second"]; // utils/timestamp.h // #define INTERVAL_FULL_RANGE (0x7FFF) const INTERVAL_FULL_RANGE = 32767; INTERVALS[INTERVAL_FULL_RANGE] = []; function interval(mask) { return INTERVALS[mask.toString()]; }
the_stack
import { resolve } from "https://deno.land/std/path/mod.ts"; const CLOCKID_REALTIME = 0; const CLOCKID_MONOTONIC = 1; const CLOCKID_PROCESS_CPUTIME_ID = 2; const CLOCKID_THREAD_CPUTIME_ID = 3; const ERRNO_SUCCESS = 0; const ERRNO_2BIG = 1; const ERRNO_ACCES = 2; const ERRNO_ADDRINUSE = 3; const ERRNO_ADDRNOTAVAIL = 4; const ERRNO_AFNOSUPPORT = 5; const ERRNO_AGAIN = 6; const ERRNO_ALREADY = 7; const ERRNO_BADF = 8; const ERRNO_BADMSG = 9; const ERRNO_BUSY = 10; const ERRNO_CANCELED = 11; const ERRNO_CHILD = 12; const ERRNO_CONNABORTED = 13; const ERRNO_CONNREFUSED = 14; const ERRNO_CONNRESET = 15; const ERRNO_DEADLK = 16; const ERRNO_DESTADDRREQ = 17; const ERRNO_DOM = 18; const ERRNO_DQUOT = 19; const ERRNO_EXIST = 20; const ERRNO_FAULT = 21; const ERRNO_FBIG = 22; const ERRNO_HOSTUNREACH = 23; const ERRNO_IDRM = 24; const ERRNO_ILSEQ = 25; const ERRNO_INPROGRESS = 26; const ERRNO_INTR = 27; const ERRNO_INVAL = 28; const ERRNO_IO = 29; const ERRNO_ISCONN = 30; const ERRNO_ISDIR = 31; const ERRNO_LOOP = 32; const ERRNO_MFILE = 33; const ERRNO_MLINK = 34; const ERRNO_MSGSIZE = 35; const ERRNO_MULTIHOP = 36; const ERRNO_NAMETOOLONG = 37; const ERRNO_NETDOWN = 38; const ERRNO_NETRESET = 39; const ERRNO_NETUNREACH = 40; const ERRNO_NFILE = 41; const ERRNO_NOBUFS = 42; const ERRNO_NODEV = 43; const ERRNO_NOENT = 44; const ERRNO_NOEXEC = 45; const ERRNO_NOLCK = 46; const ERRNO_NOLINK = 47; const ERRNO_NOMEM = 48; const ERRNO_NOMSG = 49; const ERRNO_NOPROTOOPT = 50; const ERRNO_NOSPC = 51; const ERRNO_NOSYS = 52; const ERRNO_NOTCONN = 53; const ERRNO_NOTDIR = 54; const ERRNO_NOTEMPTY = 55; const ERRNO_NOTRECOVERABLE = 56; const ERRNO_NOTSOCK = 57; const ERRNO_NOTSUP = 58; const ERRNO_NOTTY = 59; const ERRNO_NXIO = 60; const ERRNO_OVERFLOW = 61; const ERRNO_OWNERDEAD = 62; const ERRNO_PERM = 63; const ERRNO_PIPE = 64; const ERRNO_PROTO = 65; const ERRNO_PROTONOSUPPORT = 66; const ERRNO_PROTOTYPE = 67; const ERRNO_RANGE = 68; const ERRNO_ROFS = 69; const ERRNO_SPIPE = 70; const ERRNO_SRCH = 71; const ERRNO_STALE = 72; const ERRNO_TIMEDOUT = 73; const ERRNO_TXTBSY = 74; const ERRNO_XDEV = 75; const ERRNO_NOTCAPABLE = 76; const RIGHTS_FD_DATASYNC = 0x0000000000000001n; const RIGHTS_FD_READ = 0x0000000000000002n; const RIGHTS_FD_SEEK = 0x0000000000000004n; const RIGHTS_FD_FDSTAT_SET_FLAGS = 0x0000000000000008n; const RIGHTS_FD_SYNC = 0x0000000000000010n; const RIGHTS_FD_TELL = 0x0000000000000020n; const RIGHTS_FD_WRITE = 0x0000000000000040n; const RIGHTS_FD_ADVISE = 0x0000000000000080n; const RIGHTS_FD_ALLOCATE = 0x0000000000000100n; const RIGHTS_PATH_CREATE_DIRECTORY = 0x0000000000000200n; const RIGHTS_PATH_CREATE_FILE = 0x0000000000000400n; const RIGHTS_PATH_LINK_SOURCE = 0x0000000000000800n; const RIGHTS_PATH_LINK_TARGET = 0x0000000000001000n; const RIGHTS_PATH_OPEN = 0x0000000000002000n; const RIGHTS_FD_READDIR = 0x0000000000004000n; const RIGHTS_PATH_READLINK = 0x0000000000008000n; const RIGHTS_PATH_RENAME_SOURCE = 0x0000000000010000n; const RIGHTS_PATH_RENAME_TARGET = 0x0000000000020000n; const RIGHTS_PATH_FILESTAT_GET = 0x0000000000040000n; const RIGHTS_PATH_FILESTAT_SET_SIZE = 0x0000000000080000n; const RIGHTS_PATH_FILESTAT_SET_TIMES = 0x0000000000100000n; const RIGHTS_FD_FILESTAT_GET = 0x0000000000200000n; const RIGHTS_FD_FILESTAT_SET_SIZE = 0x0000000000400000n; const RIGHTS_FD_FILESTAT_SET_TIMES = 0x0000000000800000n; const RIGHTS_PATH_SYMLINK = 0x0000000001000000n; const RIGHTS_PATH_REMOVE_DIRECTORY = 0x0000000002000000n; const RIGHTS_PATH_UNLINK_FILE = 0x0000000004000000n; const RIGHTS_POLL_FD_READWRITE = 0x0000000008000000n; const RIGHTS_SOCK_SHUTDOWN = 0x0000000010000000n; const WHENCE_SET = 0; const WHENCE_CUR = 1; const WHENCE_END = 2; const FILETYPE_UNKNOWN = 0; const FILETYPE_BLOCK_DEVICE = 1; const FILETYPE_CHARACTER_DEVICE = 2; const FILETYPE_DIRECTORY = 3; const FILETYPE_REGULAR_FILE = 4; const FILETYPE_SOCKET_DGRAM = 5; const FILETYPE_SOCKET_STREAM = 6; const FILETYPE_SYMBOLIC_LINK = 7; const ADVICE_NORMAL = 0; const ADVICE_SEQUENTIAL = 1; const ADVICE_RANDOM = 2; const ADVICE_WILLNEED = 3; const ADVICE_DONTNEED = 4; const ADVICE_NOREUSE = 5; const FDFLAGS_APPEND = 0x0001; const FDFLAGS_DSYNC = 0x0002; const FDFLAGS_NONBLOCK = 0x0004; const FDFLAGS_RSYNC = 0x0008; const FDFLAGS_SYNC = 0x0010; const FSTFLAGS_ATIM = 0x0001; const FSTFLAGS_ATIM_NOW = 0x0002; const FSTFLAGS_MTIM = 0x0004; const FSTFLAGS_MTIM_NOW = 0x0008; const LOOKUPFLAGS_SYMLINK_FOLLOW = 0x0001; const OFLAGS_CREAT = 0x0001; const OFLAGS_DIRECTORY = 0x0002; const OFLAGS_EXCL = 0x0004; const OFLAGS_TRUNC = 0x0008; const EVENTTYPE_CLOCK = 0; const EVENTTYPE_FD_READ = 1; const EVENTTYPE_FD_WRITE = 2; const EVENTRWFLAGS_FD_READWRITE_HANGUP = 1; const SUBCLOCKFLAGS_SUBSCRIPTION_CLOCK_ABSTIME = 1; const SIGNAL_NONE = 0; const SIGNAL_HUP = 1; const SIGNAL_INT = 2; const SIGNAL_QUIT = 3; const SIGNAL_ILL = 4; const SIGNAL_TRAP = 5; const SIGNAL_ABRT = 6; const SIGNAL_BUS = 7; const SIGNAL_FPE = 8; const SIGNAL_KILL = 9; const SIGNAL_USR1 = 10; const SIGNAL_SEGV = 11; const SIGNAL_USR2 = 12; const SIGNAL_PIPE = 13; const SIGNAL_ALRM = 14; const SIGNAL_TERM = 15; const SIGNAL_CHLD = 16; const SIGNAL_CONT = 17; const SIGNAL_STOP = 18; const SIGNAL_TSTP = 19; const SIGNAL_TTIN = 20; const SIGNAL_TTOU = 21; const SIGNAL_URG = 22; const SIGNAL_XCPU = 23; const SIGNAL_XFSZ = 24; const SIGNAL_VTALRM = 25; const SIGNAL_PROF = 26; const SIGNAL_WINCH = 27; const SIGNAL_POLL = 28; const SIGNAL_PWR = 29; const SIGNAL_SYS = 30; const RIFLAGS_RECV_PEEK = 0x0001; const RIFLAGS_RECV_WAITALL = 0x0002; const ROFLAGS_RECV_DATA_TRUNCATED = 0x0001; const SDFLAGS_RD = 0x0001; const SDFLAGS_WR = 0x0002; const PREOPENTYPE_DIR = 0; const clock_res_realtime = function() : bigint { return BigInt(1e6); }; const clock_res_monotonic = function() : bigint { return BigInt(1e3); }; const clock_res_process = clock_res_monotonic; const clock_res_thread = clock_res_monotonic; const clock_time_realtime = function() : bigint { return BigInt(Date.now()) * BigInt(1e6); }; const clock_time_monotonic = function() : bigint { const t = performance.now(); const s = Math.trunc(t); const ms = Math.floor((t - s) * 1e3); return (BigInt(s) * BigInt(1e9)) + (BigInt(ms) * BigInt(1e6)); }; const clock_time_process = clock_time_monotonic; const clock_time_thread = clock_time_monotonic; function errno(err : Error) { switch (err.name) { case "NotFound": return ERRNO_NOENT; case "PermissionDenied": return ERRNO_ACCES; case "ConnectionRefused": return ERRNO_CONNREFUSED; case "ConnectionReset": return ERRNO_CONNRESET; case "ConnectionAborted": return ERRNO_CONNABORTED; case "NotConnected": return ERRNO_NOTCONN; case "AddrInUse": return ERRNO_ADDRINUSE; case "AddrNotAvailable": return ERRNO_ADDRNOTAVAIL; case "BrokenPipe": return ERRNO_PIPE; case "InvalidData": return ERRNO_INVAL; case "TimedOut": return ERRNO_TIMEDOUT; case "Interrupted": return ERRNO_INTR; case "BadResource": return ERRNO_BADF; case "Busy": return ERRNO_BUSY; default: return ERRNO_INVAL; } } export type ModuleOptions = { args? : string[]; env? : { [key: string]: string | undefined }; preopens?: { [key: string]: string }; memory? : WebAssembly.Memory; }; export class Module { args : string[]; env : { [key: string]: string | undefined }; memory : WebAssembly.Memory; fds : any[]; exports: { [key: string]: any }; constructor(options : ModuleOptions) { this.args = options.args ? options.args : []; this.env = options.env ? options.env : {}; this.memory = options.memory as WebAssembly.Memory; this.fds = [ { type: FILETYPE_CHARACTER_DEVICE, handle: Deno.stdin, }, { type: FILETYPE_CHARACTER_DEVICE, handle: Deno.stdout, }, { type: FILETYPE_CHARACTER_DEVICE, handle: Deno.stderr, }, ]; if (options.preopens) { for (const [ vpath, path ] of Object.entries(options.preopens)) { const info = Deno.statSync(path); if (!info.isDirectory) { throw new TypeError(`${path} is not a directory`); } const type = FILETYPE_DIRECTORY; const entry = { type, path, vpath, }; this.fds.push(entry); } } this.exports = { args_get: (argv_ptr : number, argv_buf_ptr : number) : number => { const args = this.args; const text = new TextEncoder(); const heap = new Uint8Array(this.memory.buffer); const view = new DataView(this.memory.buffer); for (let arg of args) { view.setUint32(argv_ptr, argv_buf_ptr, true); argv_ptr += 4; const data = text.encode(`${arg}\0`); heap.set(data, argv_buf_ptr); argv_buf_ptr += data.length; } return ERRNO_SUCCESS; }, args_sizes_get: (argc_out : number, argv_buf_size_out : number) : number => { const args = this.args; const text = new TextEncoder(); const view = new DataView(this.memory.buffer); view.setUint32(argc_out, args.length, true); view.setUint32(argv_buf_size_out, args.reduce(function(acc, arg) { return acc + text.encode(`${arg}\0`).length; }, 0), true); return ERRNO_SUCCESS; }, environ_get: (environ_ptr : number, environ_buf_ptr : number) : number => { const entries = Object.entries(this.env); const text = new TextEncoder(); const heap = new Uint8Array(this.memory.buffer); const view = new DataView(this.memory.buffer); for (let [key, value] of entries) { view.setUint32(environ_ptr, environ_buf_ptr, true); environ_ptr += 4; const data = text.encode(`${key}=${value}\0`); heap.set(data, environ_buf_ptr); environ_buf_ptr += data.length; } return ERRNO_SUCCESS; }, environ_sizes_get: (environc_out : number, environ_buf_size_out : number) : number => { const entries = Object.entries(this.env); const text = new TextEncoder(); const view = new DataView(this.memory.buffer); view.setUint32(environc_out, entries.length, true); view.setUint32(environ_buf_size_out, entries.reduce(function(acc, [key, value]) { return acc + text.encode(`${key}=${value}\0`).length; }, 0), true); return ERRNO_SUCCESS; }, clock_res_get: (id: number, resolution_out : number) : number => { const view = new DataView(this.memory.buffer); switch (id) { case CLOCKID_REALTIME: view.setBigUint64(resolution_out, clock_res_realtime(), true); break; case CLOCKID_MONOTONIC: view.setBigUint64(resolution_out, clock_res_monotonic(), true); break; case CLOCKID_PROCESS_CPUTIME_ID: view.setBigUint64(resolution_out, clock_res_process(), true); break; case CLOCKID_THREAD_CPUTIME_ID: view.setBigUint64(resolution_out, clock_res_thread(), true); break; default: return ERRNO_INVAL; } return ERRNO_SUCCESS; }, clock_time_get: (id: number, precision : bigint, time_out : number) : number => { const view = new DataView(this.memory.buffer); switch (id) { case CLOCKID_REALTIME: view.setBigUint64(time_out, clock_time_realtime(), true); break; case CLOCKID_MONOTONIC: view.setBigUint64(time_out, clock_time_monotonic(), true); break; case CLOCKID_PROCESS_CPUTIME_ID: view.setBigUint64(time_out, clock_time_process(), true); break; case CLOCKID_THREAD_CPUTIME_ID: view.setBigUint64(time_out, clock_time_thread(), true); break; default: return ERRNO_INVAL; } return ERRNO_SUCCESS; }, fd_advise: (fd : number, offset : bigint, len : bigint, advice : number) : number => { return ERRNO_NOSYS; }, fd_allocate: (fd : number, offset : bigint, len : bigint) : number => { return ERRNO_NOSYS; }, fd_close: (fd : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } entry.handle.close(); delete this.fds[fd]; return ERRNO_SUCCESS; }, fd_datasync: (fd : number) : number => { return ERRNO_NOSYS; }, fd_fdstat_get: (fd : number, stat_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } const view = new DataView(this.memory.buffer); view.setUint8(stat_out, entry.type); view.setUint16(stat_out + 4, 0, true); // TODO view.setBigUint64(stat_out + 8, 0n, true); // TODO view.setBigUint64(stat_out + 16, 0n, true); // TODO return ERRNO_SUCCESS; }, fd_fdstat_set_flags: (fd : number, flags : number) : number => { return ERRNO_NOSYS; }, fd_fdstat_set_rights: (fd : number, fs_rights_base : bigint, fs_rights_inheriting : bigint) : number => { return ERRNO_NOSYS; }, fd_filestat_get: (fd : number, buf_out : number) : number => { return ERRNO_NOSYS; }, fd_filestat_set_size: (fd : number, size : bigint) : number => { return ERRNO_NOSYS; }, fd_filestat_set_times: (fd : number, atim : bigint, mtim : bigint, fst_flags : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.path) { return ERRNO_INVAL; } if ((fst_flags & FSTFLAGS_ATIM_NOW) == FSTFLAGS_ATIM_NOW) { atim = BigInt(Date.now() * 1e6); } if ((fst_flags & FSTFLAGS_MTIM_NOW) == FSTFLAGS_MTIM_NOW) { mtim = BigInt(Date.now() * 1e6); } try { Deno.utimeSync(entry.path, Number(atim), Number(mtim)); } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, fd_pread: (fd : number, iovs_ptr : number, iovs_len : number, offset : bigint, nread_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } const seek = entry.handle.seekSync(0, Deno.SeekMode.Current); const view = new DataView(this.memory.buffer); let nread = 0; for (let i = 0; i < iovs_len; i++) { const data_ptr = view.getUint32(iovs_ptr, true); iovs_ptr += 4; const data_len = view.getUint32(iovs_ptr, true); iovs_ptr += 4; const data = new Uint8Array(this.memory.buffer, data_ptr, data_len); nread += entry.handle.readSync(data); } entry.handle.seekSync(seek, Deno.SeekMode.Start); view.setUint32(nread_out, nread, true); return ERRNO_SUCCESS; }, fd_prestat_get: (fd : number, buf_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.vpath) { return ERRNO_BADF; } const view = new DataView(this.memory.buffer); view.setUint8(buf_out, PREOPENTYPE_DIR); view.setUint32(buf_out + 4, new TextEncoder().encode(entry.vpath).byteLength, true); return ERRNO_SUCCESS; }, fd_prestat_dir_name: (fd : number, path_ptr : number, path_len : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.vpath) { return ERRNO_BADF; } const data = new Uint8Array(this.memory.buffer, path_ptr, path_len); data.set(new TextEncoder().encode(entry.vpath)); return ERRNO_SUCCESS; }, fd_pwrite: (fd : number, iovs_ptr : number, iovs_len : number, offset : bigint, nwritten_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } const seek = entry.handle.seekSync(0, Deno.SeekMode.Current); const view = new DataView(this.memory.buffer); let nwritten = 0; for (let i = 0; i < iovs_len; i++) { const data_ptr = view.getUint32(iovs_ptr, true); iovs_ptr += 4; const data_len = view.getUint32(iovs_ptr, true); iovs_ptr += 4; const data = new Uint8Array(this.memory.buffer, data_ptr, data_len); nwritten += entry.handle.writeSync(data); } entry.handle.seekSync(seek, Deno.SeekMode.Start); view.setUint32(nwritten_out, nwritten, true); return ERRNO_SUCCESS; }, fd_read: (fd : number, iovs_ptr : number, iovs_len : number, nread_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } const view = new DataView(this.memory.buffer); let nread = 0; for (let i = 0; i < iovs_len; i++) { const data_ptr = view.getUint32(iovs_ptr, true); iovs_ptr += 4; const data_len = view.getUint32(iovs_ptr, true); iovs_ptr += 4; const data = new Uint8Array(this.memory.buffer, data_ptr, data_len); nread += entry.handle.readSync(data); } view.setUint32(nread_out, nread, true); return ERRNO_SUCCESS; }, fd_readdir: (fd : number, buf_ptr : number, buf_len : number, cookie : bigint, bufused_out : number) : number => { return ERRNO_NOSYS; }, fd_renumber: (fd : number, to : number) : number => { if (!this.fds[fd]) { return ERRNO_BADF; } if (!this.fds[to]) { return ERRNO_BADF; } this.fds[to].handle.close(); this.fds[to] = this.fds[fd]; delete this.fds[fd]; return ERRNO_SUCCESS; }, fd_seek: (fd : number, offset : bigint, whence : number, newoffset_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } const view = new DataView(this.memory.buffer); try { // FIXME Deno does not support seeking with big integers const newoffset = entry.handle.seekSync(Number(offset), whence); view.setBigUint64(newoffset_out, BigInt(newoffset), true); } catch (err) { return ERRNO_INVAL; } return ERRNO_SUCCESS; }, fd_sync: (fd : number) : number => { return ERRNO_NOSYS; }, fd_tell: (fd : number, offset_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } const view = new DataView(this.memory.buffer); try { const offset = entry.handle.seekSync(0, Deno.SeekMode.Current); view.setBigUint64(offset_out, offset, true); } catch (err) { return ERRNO_INVAL; } return ERRNO_NOSYS; }, fd_write: (fd : number, iovs_ptr : number, iovs_len : number, nwritten_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } const view = new DataView(this.memory.buffer); let nwritten = 0; for (let i = 0; i < iovs_len; i++) { const data_ptr = view.getUint32(iovs_ptr, true); iovs_ptr += 4; const data_len = view.getUint32(iovs_ptr, true); iovs_ptr += 4; nwritten += entry.handle.writeSync(new Uint8Array(this.memory.buffer, data_ptr, data_len)); } view.setUint32(nwritten_out, nwritten, true); return ERRNO_SUCCESS; }, path_create_directory: (fd : number, path_ptr : number, path_len : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.path) { return ERRNO_INVAL; } const text = new TextDecoder(); const data = new Uint8Array(this.memory.buffer, path_ptr, path_len); const path = resolve(entry.path, text.decode(data)); try { Deno.mkdirSync(path); } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, path_filestat_get: (fd : number, flags : number, path_ptr : number, path_len : number, buf_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.path) { return ERRNO_INVAL; } const text = new TextDecoder(); const data = new Uint8Array(this.memory.buffer, path_ptr, path_len); const path = resolve(entry.path, text.decode(data)); const view = new DataView(this.memory.buffer); try { const info = Deno.statSync(path); view.setBigUint64(buf_out, BigInt(info.dev ? info.dev : 0), true); buf_out += 8; view.setBigUint64(buf_out, BigInt(info.ino ? info.ino : 0), true); buf_out += 8; switch (true) { case info.isFile: view.setUint8(buf_out, FILETYPE_REGULAR_FILE); buf_out += 4; break; case info.isDirectory: view.setUint8(buf_out, FILETYPE_DIRECTORY); buf_out += 4; break; case info.isSymlink: view.setUint8(buf_out, FILETYPE_SYMBOLIC_LINK); buf_out += 4; break; default: view.setUint8(buf_out, FILETYPE_UNKNOWN); buf_out += 4; break; } view.setUint32(buf_out, Number(info.nlink), true); buf_out += 4; view.setBigUint64(buf_out, BigInt(info.size), true); buf_out += 8; view.setBigUint64(buf_out, BigInt(info.atime ? info.atime.getTime() * 1e6 : 0), true); buf_out += 8; view.setBigUint64(buf_out, BigInt(info.mtime ? info.mtime.getTime() * 1e6 : 0), true); buf_out += 8; view.setBigUint64(buf_out, BigInt(info.birthtime ? info.birthtime.getTime() * 1e6 : 0), true); buf_out += 8; } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, path_filestat_set_times: (fd : number, flags : number, path_ptr : number, path_len : number, atim : bigint, mtim : bigint, fst_flags : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.path) { return ERRNO_INVAL; } const text = new TextDecoder(); const data = new Uint8Array(this.memory.buffer, path_ptr, path_len); const path = resolve(entry.path, text.decode(data)); if ((fst_flags & FSTFLAGS_ATIM_NOW) == FSTFLAGS_ATIM_NOW) { atim = BigInt(Date.now()) * BigInt(1e6); } if ((fst_flags & FSTFLAGS_MTIM_NOW) == FSTFLAGS_MTIM_NOW) { mtim = BigInt(Date.now()) * BigInt(1e6); } try { Deno.utimeSync(path, Number(atim), Number(mtim)); } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, path_link: (old_fd : number, old_flags : number, old_path_ptr : number, old_path_len : number, new_fd : number, new_path_ptr : number, new_path_len : number) : number => { const old_entry = this.fds[old_fd]; const new_entry = this.fds[new_fd]; if (!old_entry || !new_entry) { return ERRNO_BADF; } if (!old_entry.path || !new_entry.path) { return ERRNO_INVAL; } const text = new TextDecoder(); const old_data = new Uint8Array(this.memory.buffer, old_path_ptr, old_path_len); const old_path = resolve(old_entry.path, text.decode(old_data)); const new_data = new Uint8Array(this.memory.buffer, new_path_ptr, new_path_len); const new_path = resolve(new_entry.path, text.decode(new_data)); try { Deno.linkSync(old_path, new_path); } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, path_open: (fd : number, dirflags : number, path_ptr : number, path_len : number, oflags : number, fs_rights_base : number | bigint, fs_rights_inherting : number | bigint, fdflags : number, opened_fd_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.path) { return ERRNO_INVAL; } const text = new TextDecoder(); const data = new Uint8Array(this.memory.buffer, path_ptr, path_len); const path = resolve(entry.path, text.decode(data)); const options = { read: false, write: false, append: false, truncate: false, create: false, createNew: false, }; if ((oflags & OFLAGS_CREAT) !== 0) { options.create = true; options.write = true; } if ((oflags & OFLAGS_DIRECTORY) !== 0) { // TODO (caspervonb) review if we can // emulate this; unix supports opening // directories, windows does not. } if ((oflags & OFLAGS_EXCL) !== 0) { options.createNew = true; } if ((oflags & OFLAGS_TRUNC) !== 0) { options.truncate = true; options.write = true; } if ((BigInt(fs_rights_base) & BigInt(RIGHTS_FD_READ | RIGHTS_FD_READDIR)) != 0n) { options.read = true; } if ((BigInt(fs_rights_base) & BigInt(RIGHTS_FD_DATASYNC | RIGHTS_FD_WRITE | RIGHTS_FD_ALLOCATE | RIGHTS_FD_FILESTAT_SET_SIZE)) != 0n) { options.write = true; } if ((fdflags & FDFLAGS_APPEND) != 0) { options.append = true; } if ((fdflags & FDFLAGS_DSYNC) != 0) { // TODO (caspervonb) review if we can emulate this. } if ((fdflags & FDFLAGS_NONBLOCK) != 0) { // TODO (caspervonb) review if we can emulate this. } if ((fdflags & FDFLAGS_RSYNC) != 0) { // TODO (caspervonb) review if we can emulate this. } if ((fdflags & FDFLAGS_SYNC) != 0) { // TODO (caspervonb) review if we can emulate this. } if (!options.read && !options.write && !options.truncate) { options.read = true; } try { const handle = Deno.openSync(path, options); const opened_fd = this.fds.push({ handle, path, }) - 1; const view = new DataView(this.memory.buffer); view.setUint32(opened_fd_out, opened_fd, true); } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, path_readlink: (fd : number, path_ptr : number, path_len : number, buf_ptr : number, buf_len : number, bufused_out : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.path) { return ERRNO_INVAL; } const view = new DataView(this.memory.buffer); const heap = new Uint8Array(this.memory.buffer); const data = new Uint8Array(this.memory.buffer, path_ptr, path_len); const path = resolve(entry.path, new TextDecoder().decode(data)); try { const link = Deno.readLinkSync(path); const data = new TextEncoder().encode(link); heap.set(new Uint8Array(data, 0, buf_len), buf_ptr); const bufused = Math.min(data.byteLength, buf_len); view.setUint32(bufused_out, bufused, true); } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, path_remove_directory: (fd : number, path_ptr : number, path_len : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.path) { return ERRNO_INVAL; } const text = new TextDecoder(); const data = new Uint8Array(this.memory.buffer, path_ptr, path_len); const path = resolve(entry.path, text.decode(data)); try { if (!Deno.statSync(path).isDirectory) { return ERRNO_NOTDIR; } Deno.removeSync(path); } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, path_rename: (fd : number, old_path_ptr : number, old_path_len : number, new_fd : number, new_path_ptr : number, new_path_len : number) : number => { const old_entry = this.fds[fd]; const new_entry = this.fds[new_fd]; if (!old_entry || !new_entry) { return ERRNO_BADF; } if (!old_entry.path || !new_entry.path) { return ERRNO_INVAL; } const text = new TextDecoder(); const old_data = new Uint8Array(this.memory.buffer, old_path_ptr, old_path_len); const old_path = resolve(old_entry.path, text.decode(old_data)); const new_data = new Uint8Array(this.memory.buffer, new_path_ptr, new_path_len); const new_path = resolve(new_entry.path, text.decode(new_data)); try { Deno.renameSync(old_path, new_path); } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, path_symlink: (old_path_ptr : number, old_path_len : number, fd : number, new_path_ptr : number, new_path_len : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.path) { return ERRNO_INVAL; } const text = new TextDecoder(); const old_data = new Uint8Array(this.memory.buffer, old_path_ptr, old_path_len); const old_path = text.decode(old_data); const new_data = new Uint8Array(this.memory.buffer, new_path_ptr, new_path_len); const new_path = resolve(entry.path, text.decode(new_data)); try { Deno.symlinkSync(old_path, new_path); } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, path_unlink_file: (fd : number, path_ptr : number, path_len : number) : number => { const entry = this.fds[fd]; if (!entry) { return ERRNO_BADF; } if (!entry.path) { return ERRNO_INVAL; } const text = new TextDecoder(); const data = new Uint8Array(this.memory.buffer, path_ptr, path_len); const path = resolve(entry.path, text.decode(data)); try { Deno.removeSync(path); } catch (err) { return errno(err); } return ERRNO_SUCCESS; }, poll_oneoff: (in_ptr : number, out_ptr : number, nsubscriptions : number, nevents_out : number) : number => { return ERRNO_NOSYS; }, proc_exit: (rval : number) : never => { Deno.exit(rval); }, proc_raise: (sig : number) : number => { return ERRNO_NOSYS; }, sched_yield: () : number => { return ERRNO_SUCCESS; }, random_get: (buf_ptr : number, buf_len : number) : number => { const buffer = new Uint8Array(this.memory.buffer, buf_ptr, buf_len); crypto.getRandomValues(buffer); return ERRNO_SUCCESS; }, sock_recv: (fd : number, ri_data_ptr : number, ri_data_len : number, ri_flags : number, ro_datalen_out : number, ro_flags_out : number) : number => { return ERRNO_NOSYS; }, sock_send: (fd : number, si_data_ptr : number, si_data_len : number, si_flags : number, so_datalen_out : number) : number => { return ERRNO_NOSYS; }, sock_shutdown: (fd : number, how : number) : number => { return ERRNO_NOSYS; }, }; } }; export default Module;
the_stack
'use strict'; import * as React from 'react'; import { connect } from 'react-redux'; import { IStateGlobal } from 'chord/workbench/api/common/state/stateGlobal'; import { makeListKey } from 'chord/platform/utils/common/keys'; import { ORIGIN } from 'chord/music/common/origin'; import { IArtist } from 'chord/music/api/artist'; import { IListOption } from 'chord/music/api/listOption'; import { MiddleButton } from 'chord/workbench/parts/common/component/buttons'; import ArtistItemView from 'chord/workbench/parts/mainView/browser/component/home/component/artists/artistList'; import { handleGetArtists, handleShowArtistListView } from 'chord/workbench/parts/mainView/browser/action/home/artists'; import { ARTIST_LIST_OPTIONS as xiamiArtistListOptions } from 'chord/music/xiami/common'; import { ARTIST_LIST_OPTIONS as neteaseArtistListOptions } from 'chord/music/netease/common'; import { ARTIST_LIST_OPTIONS as qqArtistListOptions } from 'chord/music/qq/common'; const ARTIST_SIZE = 40; // origin function argument to ArtistListOptionsView.state const ARGUMENT_NAMES_MAP = { [ORIGIN.xiami]: { language: 'area', tag: 'genre', gender: 'gender', index: 'index', }, [ORIGIN.netease]: { category: 'genre', initial: 'index', }, [ORIGIN.qq]: { area: 'area', genre: 'genre', sex: 'gender', index: 'index', } }; interface IArtistsMap { [key: string]: Array<IArtist>; } function hash(area, genre, gender, index): string { return [area, genre, gender, index].map(arg => arg == null ? 'null' : arg).join('|'); } function initiateState(origin: string): any { switch (origin) { case ORIGIN.xiami: return { area: '0', // 全部 genre: '0', // 全部 gender: '0', // 全部 index: null, // 热门 }; case ORIGIN.netease: return { area: null, // 全部 genre: null, // 全部 gender: null, // 全部 index: '-1', // 热门 }; case ORIGIN.qq: return { area: '-100', // 内地 genre: '-100', // 全部 gender: '-100', // 全部 index: '-100', // 热门 }; default: throw new Error(`[ERROR] [ArtistListOptionsView.initiateState] Here will never be occured. [args]: ${origin}`); } } const OPTIONS_SET = { [ORIGIN.xiami]: xiamiArtistListOptions, [ORIGIN.netease]: neteaseArtistListOptions, [ORIGIN.qq]: qqArtistListOptions, }; interface IArtistOptionsViewProps { origin: string; view: string; toShowArtistList: () => boolean; handleShowArtistListView: (origin) => void; } interface IArtistOptionsViewState { area: string; genre: string; gender: string; index: string; artists: Array<IArtist>; } class ArtistListOptionsView extends React.Component<IArtistOptionsViewProps, IArtistOptionsViewState> { private artistsMap: IArtistsMap; private currentLength: number; private more: boolean; constructor(props: IArtistOptionsViewProps) { super(props); this.state = { ...initiateState(this.props.origin), artists: [], }; this.artistsMap = {}; this.currentLength = 0; this.more = true; this._handleShowArtistListView = this._handleShowArtistListView.bind(this); this._hash = this._hash.bind(this); this._getArtistList = this._getArtistList.bind(this); this._showMoreArtists = this._showMoreArtists.bind(this); this._showArtistList = this._showArtistList.bind(this); this._update_argument = this._update_argument.bind(this); this._getTitleView = this._getTitleView.bind(this); this._getOptionView = this._getOptionView.bind(this); this._getOptionsView = this._getOptionsView.bind(this); this._getArtistListOptionsView = this._getArtistListOptionsView.bind(this); } _hash(): string { let { area, genre, gender, index } = this.state; return hash(area, genre, gender, index); } async _getArtistList(): Promise<void> { let { area, genre, gender, index } = this.state; let origin = this.props.origin; if (origin == ORIGIN.xiami) { let h = hash(area, genre, gender, null); if (this.artistsMap[h]) return; } let h = this._hash(); let offset = (this.artistsMap[h] || []).length; return handleGetArtists(origin, area, genre, gender, index, offset, ARTIST_SIZE) .then(items => { if (origin == ORIGIN.xiami) { let [artists, pinyins] = items; let seq = artists.findIndex(artist => artist == null); let hotArtists = artists.slice(0, seq); let otherArtists = artists.slice(seq + 1); let h = hash(area, genre, gender, null); this.artistsMap[h] = hotArtists; for (let i = 0; i < otherArtists.length; i += 1) { let artist = otherArtists[i]; let pinyin = pinyins[seq + 1 + i].trim(); let code = pinyin ? pinyin[0].toUpperCase().charCodeAt(0) - 65 : -1; let hstr = (code >= 0 && code <= 25) ? pinyin[0].toUpperCase() : '#'; let h = hash(area, genre, gender, hstr); let list = this.artistsMap[h] || []; list.push(artist); this.artistsMap[h] = list; } } else { let artists = items; let h = hash(area, genre, gender, index); let list = this.artistsMap[h] || []; this.artistsMap[h] = [...list, ...artists]; if (artists.length < ARTIST_SIZE) { this.more = false; } } }); } _showArtistList() { // reset this.currentLength = ARTIST_SIZE; this.more = true; let h = this._hash(); let artists = (this.artistsMap[h] || []).slice(0, ARTIST_SIZE); if (artists.length > 0) { this.setState({ artists }); } else { this._getArtistList() .then(() => { let artists = this.artistsMap[h].slice(0, ARTIST_SIZE); this.setState({ artists }); }); } } _showMoreArtists() { let h = this._hash(); let { origin } = this.props; this.currentLength = this.currentLength + ARTIST_SIZE; if (origin == ORIGIN.xiami) { if (this.currentLength > this.artistsMap[h].length) { this.more = false; } let artists = this.artistsMap[h].slice(0, this.currentLength); this.setState({ artists }); } this._getArtistList() .then(() => { if (this.currentLength > this.artistsMap[h].length) { this.more = false; } let artists = this.artistsMap[h].slice(0, this.currentLength); this.setState({ artists }) }); } _handleShowArtistListView() { this._showArtistList(); process.nextTick(() => this.props.handleShowArtistListView(this.props.origin)); } _update_argument(name: string, value: string) { let origin = this.props.origin; let key = ARGUMENT_NAMES_MAP[origin][name]; this.setState({ [key]: value }); } _getTitleView(title: string) { return ( <div className='chunk-title'> {title} </div> ); } _getOptionView(option: IListOption) { let type = option.type; let origin = this.props.origin; let list = option.items.map((item, index) => { let key = ARGUMENT_NAMES_MAP[origin][type]; let active = this.state[key] == item.id; let className = active ? 'chunk-item chunk-item-selected a-like cursor-pointer' : 'chunk-item a-like cursor-pointer'; return ( <div className={className} key={makeListKey(index, 'artist', 'option', 'item')} onClick={() => this._update_argument(type, item.id)}> {item.name} </div> ); }); return ( <div className='chunk-container'> {list} </div> ); } _getOptionsView(options: Array<IListOption>) { let classes = options.map((option, index) => { let titleView = this._getTitleView(option.name); let optionView = this._getOptionView(option); return ( <div className='chunk' key={makeListKey(index, 'artist', 'option')}> {titleView} {optionView} </div> ); }); return classes; } _getArtistListOptionsView(options: Array<IListOption>) { let origin = this.props.origin; let classes = this._getOptionsView(options); return ( <div className='options-item'> <div className='options-item-title'> {origin.toLocaleUpperCase()} </div> <div className='options-item-container'> {classes} </div> </div> ); } render() { let origin = this.props.origin; let options = OPTIONS_SET[origin]; let artistListOptionsView = this._getArtistListOptionsView(options); let artistListView = (this.props.toShowArtistList() && this.props.view == 'artists') ? ( <ArtistItemView artists={this.state.artists} more={this.more} handleGetMoreArtists={() => this._showMoreArtists()} />) : null; return ( <div> <div className='options-container'> {artistListOptionsView} <div className='options-container-title'> <MiddleButton title="Show Me" click={this._handleShowArtistListView} /> </div> </div> {artistListView} </div> ); } } function mapStateToProps(state: IStateGlobal) { let { view } = state.mainView.homeView.artistsView; return { view }; } function mapDispatchToProps(dispatch) { return { handleShowArtistListView: (origin) => dispatch(handleShowArtistListView(origin)), }; } export default connect(mapStateToProps, mapDispatchToProps)(ArtistListOptionsView);
the_stack
import { AstroTime, Body, Observer, GeoVector, EquatorFromVector, Constellation, ConstellationInfo, PairLongitude, SearchHourAngle, SearchLocalSolarEclipse, NextLocalSolarEclipse, LocalSolarEclipseInfo, SearchLunarApsis, NextLunarApsis, Apsis, SearchLunarEclipse, NextLunarEclipse, LunarEclipseInfo, SearchMaxElongation, SearchMoonQuarter, NextMoonQuarter, MoonQuarter, SearchPlanetApsis, NextPlanetApsis, SearchPeakMagnitude, SearchRelativeLongitude, SearchRiseSet, SearchTransit, NextTransit, TransitInfo, Seasons, } from "./astronomy"; class AstroEvent { constructor( public time: AstroTime, public title: string, public creator: AstroEventEnumerator) {} } interface AstroEventEnumerator { FindFirst(startTime: AstroTime): AstroEvent; FindNext(): AstroEvent; } class EventCollator implements AstroEventEnumerator { private eventQueue: AstroEvent[]; constructor(private enumeratorList: AstroEventEnumerator[]) {} FindFirst(startTime: AstroTime): AstroEvent { this.eventQueue = []; for (let enumerator of this.enumeratorList) this.InsertEvent(enumerator.FindFirst(startTime)); return this.FindNext(); } FindNext(): AstroEvent { if (this.eventQueue.length === 0) return null; const evt = this.eventQueue.shift(); const another = evt.creator.FindNext(); this.InsertEvent(another); return evt; } InsertEvent(evt: AstroEvent): void { if (evt !== null) { // Insert the event in time order -- after anything that happens before it. let i = 0; while (i < this.eventQueue.length && this.eventQueue[i].time.tt < evt.time.tt) ++i; this.eventQueue.splice(i, 0, evt); } } } class RiseSetEnumerator implements AstroEventEnumerator { private nextSearchTime: AstroTime; constructor(private observer: Observer, private body: Body, private direction: number, private title: string) {} FindFirst(startTime: AstroTime): AstroEvent { this.nextSearchTime = SearchRiseSet(this.body, this.observer, this.direction, startTime, 366.0); if (this.nextSearchTime) return new AstroEvent(this.nextSearchTime, this.title, this); return null; } FindNext(): AstroEvent { if (this.nextSearchTime) { const startTime = this.nextSearchTime.AddDays(0.01); return this.FindFirst(startTime); } return null; } } class SeasonEnumerator implements AstroEventEnumerator { private slist: AstroEvent[]; private year: number; private index: number; FindFirst(startTime: AstroTime): AstroEvent { this.year = startTime.date.getUTCFullYear(); this.LoadYear(this.year); while (this.index < this.slist.length && this.slist[this.index].time.tt < startTime.tt) ++this.index; return this.FindNext(); } FindNext(): AstroEvent { if (this.index === this.slist.length) this.LoadYear(++this.year); return this.slist[this.index++]; } private LoadYear(year: number): void { const seasons = Seasons(year); this.slist = [ new AstroEvent(seasons.mar_equinox, 'March equinox', this), new AstroEvent(seasons.jun_solstice, 'June solstice', this), new AstroEvent(seasons.sep_equinox, 'September equinox', this), new AstroEvent(seasons.dec_solstice, 'December solstice', this) ]; this.index = 0; } } class MoonQuarterEnumerator implements AstroEventEnumerator { private mq: MoonQuarter; FindFirst(startTime: AstroTime): AstroEvent { this.mq = SearchMoonQuarter(startTime); return this.MakeEvent(); } FindNext(): AstroEvent { this.mq = NextMoonQuarter(this.mq); return this.MakeEvent(); } private MakeEvent(): AstroEvent { return new AstroEvent( this.mq.time, ['new moon', 'first quarter', 'full moon', 'third quarter'][this.mq.quarter], this ); } } class ConjunctionOppositionEnumerator implements AstroEventEnumerator { private title: string; private nextTime: AstroTime; constructor(private body: Body, private targetRelLon: number, kind: string) { this.title = `${body} ${kind}`; // e.g. "Jupiter opposition" or "Venus inferior conjunction" } FindFirst(startTime: AstroTime): AstroEvent { this.nextTime = startTime; return this.FindNext(); } FindNext(): AstroEvent { const time = SearchRelativeLongitude(this.body, this.targetRelLon, this.nextTime); this.nextTime = time.AddDays(1); return new AstroEvent(time, this.title, this); } } class MaxElongationEnumerator implements AstroEventEnumerator { private nextTime: AstroTime; constructor(private body: Body) {} FindFirst(startTime: AstroTime): AstroEvent { this.nextTime = startTime; return this.FindNext(); } FindNext(): AstroEvent { const elon = SearchMaxElongation(this.body, this.nextTime); this.nextTime = elon.time.AddDays(1); return new AstroEvent( elon.time, `${this.body} max ${elon.visibility} elongation: ${elon.elongation.toFixed(2)} degrees from Sun`, this); } } class VenusPeakMagnitudeEnumerator implements AstroEventEnumerator { private nextTime: AstroTime; FindFirst(startTime: AstroTime): AstroEvent { this.nextTime = startTime; return this.FindNext(); } FindNext(): AstroEvent { const illum = SearchPeakMagnitude(Body.Venus, this.nextTime); const rlon = PairLongitude(Body.Venus, Body.Sun, illum.time); this.nextTime = illum.time.AddDays(1); return new AstroEvent( illum.time, `Venus peak magnitude ${illum.mag.toFixed(2)} in ${(rlon < 180) ? 'evening' : 'morning'} sky`, this ); } } class LunarEclipseEnumerator implements AstroEventEnumerator { private nextTime: AstroTime; FindFirst(startTime: AstroTime): AstroEvent { const info = SearchLunarEclipse(startTime); return this.MakeEvent(info); } FindNext(): AstroEvent { const info = NextLunarEclipse(this.nextTime); return this.MakeEvent(info); } private MakeEvent(info: LunarEclipseInfo): AstroEvent { this.nextTime = info.peak; return new AstroEvent(info.peak, `${info.kind} lunar eclipse`, this); } } class LocalSolarEclipseEnumerator implements AstroEventEnumerator { private nextTime: AstroTime; constructor(private observer: Observer) {} FindFirst(startTime: AstroTime): AstroEvent { const info = SearchLocalSolarEclipse(startTime, this.observer); return this.MakeEvent(info); } FindNext(): AstroEvent { const info = NextLocalSolarEclipse(this.nextTime, this.observer); return this.MakeEvent(info); } private MakeEvent(info: LocalSolarEclipseInfo): AstroEvent { this.nextTime = info.peak.time; return new AstroEvent(info.peak.time, `${info.kind} solar eclipse peak at ${info.peak.altitude.toFixed(2)} degrees altitude`, this); } } class TransitEnumerator implements AstroEventEnumerator { private nextTime: AstroTime; constructor(private body: Body) {} FindFirst(startTime: AstroTime): AstroEvent { const info = SearchTransit(this.body, startTime); return this.MakeEvent(info); } FindNext(): AstroEvent { const info = NextTransit(this.body, this.nextTime); return this.MakeEvent(info); } private MakeEvent(info: TransitInfo): AstroEvent { this.nextTime = info.peak; return new AstroEvent(info.peak, `transit of ${this.body}`, this); } } class LunarApsisEnumerator implements AstroEventEnumerator { private apsis: Apsis; FindFirst(startTime: AstroTime): AstroEvent { this.apsis = SearchLunarApsis(startTime); return this.MakeEvent(); } FindNext(): AstroEvent { this.apsis = NextLunarApsis(this.apsis); return this.MakeEvent(); } private MakeEvent(): AstroEvent { const kind = (this.apsis.kind === 0) ? 'perigee' : 'apogee'; return new AstroEvent(this.apsis.time, `lunar ${kind} at ${this.apsis.dist_km.toFixed(0)} km`, this); } } class PlanetApsisEnumerator implements AstroEventEnumerator { private apsis: Apsis; constructor(private body: Body) {} FindFirst(startTime: AstroTime): AstroEvent { this.apsis = SearchPlanetApsis(this.body, startTime); return this.MakeEvent(); } FindNext(): AstroEvent { this.apsis = NextPlanetApsis(this.body, this.apsis); return this.MakeEvent(); } private MakeEvent(): AstroEvent { const kind = (this.apsis.kind === 0) ? 'perihelion' : 'aphelion'; return new AstroEvent(this.apsis.time, `${this.body} ${kind} at ${this.apsis.dist_au.toFixed(4)} AU`, this); } } class BodyCulminationEnumerator implements AstroEventEnumerator { private nextTime: AstroTime; constructor(private observer: Observer, private body: Body) {} FindFirst(startTime: AstroTime): AstroEvent { this.nextTime = startTime; return this.FindNext(); } FindNext(): AstroEvent { const info = SearchHourAngle(this.body, this.observer, 0, this.nextTime); this.nextTime = info.time.AddDays(0.5); return new AstroEvent(info.time, `${this.body} culminates ${info.hor.altitude.toFixed(2)} degrees above the horizon`, this); } } class ConstellationEnumerator implements AstroEventEnumerator { private nextTime: AstroTime; private currentConst: ConstellationInfo; constructor(private body: Body, private dayIncrement: number) {} FindFirst(startTime: AstroTime): AstroEvent { this.nextTime = startTime; this.currentConst = this.BodyConstellation(startTime); return this.FindNext(); } FindNext(): AstroEvent { const tolerance = 0.1 / (24 * 3600); // one tenth of a second, expressed in days // Step through one time increment at a time until we see a constellation change. let t1 = this.nextTime; let c1 = this.currentConst; for(;;) { let t2 = t1.AddDays(this.dayIncrement); let c2 = this.BodyConstellation(t2); if (c1.symbol === c2.symbol) { t1 = t2; } else { // The body moved from one constellation to another during this time step. // Narrow in on the exact moment by doing a binary search. for(;;) { let dt = t2.ut - t1.ut; let tx = t1.AddDays(dt/2); let cx = this.BodyConstellation(tx); if (cx.symbol === c1.symbol) { t1 = tx; } else { if (dt < tolerance) { // We have found the transition time within tolerance. // Always end the search inside the new constellation. this.nextTime = tx; this.currentConst = cx; return new AstroEvent(tx, `${this.body} moves from ${c1.name} to ${cx.name}`, this); } else { t2 = tx; } } } } } } private BodyConstellation(time: AstroTime): ConstellationInfo { const vec = GeoVector(this.body, time, false); const equ = EquatorFromVector(vec); return Constellation(equ.ra, equ.dec); } } function RunTest(): void { const startTime = new AstroTime(new Date('2021-05-12T00:00:00Z')); const observer = new Observer(28.6, -81.2, 10.0); var enumeratorList: AstroEventEnumerator[] = [ new RiseSetEnumerator(observer, Body.Sun, +1, 'sunrise'), new RiseSetEnumerator(observer, Body.Sun, -1, 'sunset'), new RiseSetEnumerator(observer, Body.Moon, +1, 'moonrise'), new RiseSetEnumerator(observer, Body.Moon, -1, 'moonset'), new BodyCulminationEnumerator(observer, Body.Sun), new BodyCulminationEnumerator(observer, Body.Moon), new SeasonEnumerator(), new MoonQuarterEnumerator(), new VenusPeakMagnitudeEnumerator(), new LunarEclipseEnumerator(), new LocalSolarEclipseEnumerator(observer), new LunarApsisEnumerator() ]; // Inferior and superior conjunctions of inner planets. // Maximum elongation of inner planets. // Transits of inner planets. for (let body of [Body.Mercury, Body.Venus]) { enumeratorList.push( new ConjunctionOppositionEnumerator(body, 0, 'inferior conjunction'), new ConjunctionOppositionEnumerator(body, 180, 'superior conjunction'), new MaxElongationEnumerator(body), new TransitEnumerator(body) ); } // Conjunctions and oppositions of outer planets. for (let body of [Body.Mars, Body.Jupiter, Body.Saturn, Body.Uranus, Body.Neptune, Body.Pluto]) { enumeratorList.push( new ConjunctionOppositionEnumerator(body, 0, 'opposition'), new ConjunctionOppositionEnumerator(body, 180, 'conjunction') ); } // Perihelion and aphelion of all planets. // Constellation change of all planets. for (let body of [Body.Mercury, Body.Venus, Body.Earth, Body.Mars, Body.Jupiter, Body.Saturn, Body.Uranus, Body.Neptune, Body.Pluto]) { enumeratorList.push(new PlanetApsisEnumerator(body)); if (body !== Body.Earth) { enumeratorList.push(new ConstellationEnumerator(body, 1)); } } const collator = new EventCollator(enumeratorList); const stopYear = startTime.date.getUTCFullYear() + 12; let evt:AstroEvent = collator.FindFirst(startTime); while (evt !== null && evt.time.date.getUTCFullYear() < stopYear) { console.log(`${evt.time} ${evt.title}`); evt = collator.FindNext(); } } RunTest();
the_stack
import { configureTestSuite } from '../../test-utils/configure-suite'; import { TestBed, waitForAsync } from '@angular/core/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { IgxHierarchicalGridModule } from './public_api'; import { Component, ViewChild, DebugElement} from '@angular/core'; import { IgxHierarchicalGridComponent } from './hierarchical-grid.component'; import { wait, UIInteractions, waitForSelectionChange, waitForGridScroll } from '../../test-utils/ui-interactions.spec'; import { IgxRowIslandComponent } from './row-island.component'; import { By } from '@angular/platform-browser'; import { IgxHierarchicalRowComponent } from './hierarchical-row.component'; import { setupHierarchicalGridScrollDetection } from '../../test-utils/helper-utils.spec'; import { GridFunctions } from '../../test-utils/grid-functions.spec'; import { IGridCellEventArgs } from '../grid/public_api'; import { IgxChildGridRowComponent } from './child-grid-row.component'; const DEBOUNCE_TIME = 60; const GRID_CONTENT_CLASS = '.igx-grid__tbody-content'; const GRID_FOOTER_CLASS = '.igx-grid__tfoot'; describe('IgxHierarchicalGrid Basic Navigation #hGrid', () => { let fixture; let hierarchicalGrid: IgxHierarchicalGridComponent; let baseHGridContent: DebugElement; configureTestSuite((() => { TestBed.configureTestingModule({ declarations: [ IgxHierarchicalGridTestBaseComponent ], imports: [ NoopAnimationsModule, IgxHierarchicalGridModule] }); })); beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(IgxHierarchicalGridTestBaseComponent); fixture.detectChanges(); hierarchicalGrid = fixture.componentInstance.hgrid; setupHierarchicalGridScrollDetection(fixture, hierarchicalGrid); baseHGridContent = GridFunctions.getGridContent(fixture); GridFunctions.focusFirstCell(fixture, hierarchicalGrid); })); // simple tests it('should allow navigating down from parent row into child grid.', (async () => { hierarchicalGrid.expandChildren = false; hierarchicalGrid.height = '600px'; hierarchicalGrid.width = '800px'; fixture.componentInstance.rowIsland.height = '350px'; fixture.detectChanges(); await wait(DEBOUNCE_TIME); // expand row const row1 = hierarchicalGrid.dataRowList.toArray()[0] as IgxHierarchicalRowComponent; UIInteractions.simulateClickAndSelectEvent(row1.expander); fixture.detectChanges(); await wait(DEBOUNCE_TIME); // activate cell const fCell = hierarchicalGrid.dataRowList.toArray()[0].cells.toArray()[0]; GridFunctions.focusCell(fixture, fCell); fixture.detectChanges(); // arrow down UIInteractions.triggerEventHandlerKeyDown('arrowdown', baseHGridContent, false, false, false); fixture.detectChanges(); // verify selection in child. const selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.value).toEqual(0); expect(selectedCell.column.field).toMatch('ID'); })); it('should allow navigating up from child row into parent grid.', () => { const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const childFirstCell = childGrid.dataRowList.toArray()[0].cells.toArray()[0]; GridFunctions.focusCell(fixture, childFirstCell); fixture.detectChanges(); childGrid.cdr.detectChanges(); // arrow up in child const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('arrowup', childGridContent, false, false, false); fixture.detectChanges(); // verify selection in parent. const selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.value).toEqual(0); expect(selectedCell.column.field).toMatch('ID'); }); it('should allow navigating down in child grid when child grid selected cell moves outside the parent view port.', (async () => { const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const childCell = childGrid.dataRowList.toArray()[3].cells.toArray()[0]; GridFunctions.focusCell(fixture, childCell); fixture.detectChanges(); // arrow down in child const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('arrowdown', childGridContent, false, false, false); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // parent should scroll down so that cell in child is in view. const selectedCell = fixture.componentInstance.selectedCell; const selectedCellElem = childGrid.gridAPI.get_cell_by_index(selectedCell.row.index, selectedCell.column.field); const gridOffsets = hierarchicalGrid.tbody.nativeElement.getBoundingClientRect(); const rowOffsets = selectedCellElem.intRow.nativeElement.getBoundingClientRect(); expect(rowOffsets.top >= gridOffsets.top && rowOffsets.bottom <= gridOffsets.bottom).toBeTruthy(); })); it('should allow navigating up in child grid when child grid selected cell moves outside the parent view port.', (async () => { hierarchicalGrid.verticalScrollContainer.scrollTo(2); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const childCell = childGrid.dataRowList.toArray()[4].cells.toArray()[0]; GridFunctions.focusCell(fixture, childCell); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const prevScrTop = hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop; const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('arrowup', childGridContent, false, false, false); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // parent should scroll up so that cell in child is in view. const currScrTop = hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop; expect(prevScrTop - currScrTop).toBeGreaterThanOrEqual(childGrid.rowHeight); })); it('should allow navigating to end in child grid when child grid target row moves outside the parent view port.', (async () => { const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const childCell = childGrid.dataRowList.toArray()[0].cells.toArray()[0]; GridFunctions.focusCell(fixture, childCell); fixture.detectChanges(); const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('end', childGridContent, false, false, true); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); await wait(DEBOUNCE_TIME); // verify selection in child. const selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.row.index).toEqual(9); expect(selectedCell.column.field).toMatch('childData2'); // parent should be scrolled down const currScrTop = hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop; expect(currScrTop).toBeGreaterThanOrEqual(childGrid.rowHeight * 5); })); it('should allow navigating to start in child grid when child grid target row moves outside the parent view port.', (async () => { hierarchicalGrid.verticalScrollContainer.scrollTo(2); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const horizontalScrDir = childGrid.dataRowList.toArray()[0].virtDirRow; horizontalScrDir.scrollTo(6); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const childLastCell = childGrid.dataRowList.toArray()[9].cells.toArray()[3]; GridFunctions.focusCell(fixture, childLastCell); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('home', childGridContent, false, false, true); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); await wait(DEBOUNCE_TIME); const selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.value).toEqual(0); expect(selectedCell.column.index).toBe(0); expect(selectedCell.row.index).toBe(0); // check if child row is in view of parent. const gridOffsets = hierarchicalGrid.tbody.nativeElement.getBoundingClientRect(); const rowElem = childGrid.gridAPI.get_row_by_index(selectedCell.row.index); const rowOffsets = rowElem.nativeElement.getBoundingClientRect(); expect(rowOffsets.top >= gridOffsets.top && rowOffsets.bottom <= gridOffsets.bottom).toBeTruthy(); })); it('should allow navigating to bottom in child grid when child grid target row moves outside the parent view port.', (async () => { const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const childCell = childGrid.dataRowList.toArray()[0].cells.toArray()[0]; GridFunctions.focusCell(fixture, childCell); fixture.detectChanges(); const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('arrowdown', childGridContent, false, false, true); fixture.detectChanges(); // wait for parent grid to complete scroll to child cell. await waitForGridScroll(hierarchicalGrid); fixture.detectChanges(); const selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.value).toBe(9); expect(selectedCell.column.index).toBe(0); expect(selectedCell.row.index).toBe(9); const currScrTop = hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop; expect(currScrTop).toBeGreaterThanOrEqual(childGrid.rowHeight * 5); })); it('should not lose activation when pressing Ctrl+ArrowDown is pressed at the bottom row(expended) in a child grid.', (async () => { hierarchicalGrid.height = '600px'; hierarchicalGrid.width = '800px'; fixture.componentInstance.rowIsland.height = '400px'; await wait(); fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; childGrid.data = childGrid.data.slice(0, 5); await wait(); fixture.detectChanges(); childGrid.dataRowList.toArray()[4].expander.nativeElement.click(); await wait(); fixture.detectChanges(); const childCell = childGrid.dataRowList.toArray()[4].cells.toArray()[0]; GridFunctions.focusCell(fixture, childCell); fixture.detectChanges(); const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('arrowdown', childGridContent, false, false, true); fixture.detectChanges(); await wait(30); fixture.detectChanges(); const childLastRowCell = childGrid.dataRowList.toArray()[4].cells.toArray()[0]; const selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.row.index).toBe(childLastRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(childLastRowCell.column.visibleIndex); expect(selectedCell.column.index).toBe(childLastRowCell.column.index); expect(selectedCell.value).toBe(childLastRowCell.value); const currScrTop = hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop; expect(currScrTop).toEqual(0); })); it('should allow navigating to top in child grid when child grid target row moves outside the parent view port.', (async () => { hierarchicalGrid.verticalScrollContainer.scrollTo(2); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const childLastRowCell = childGrid.dataRowList.toArray()[9].cells.toArray()[0]; GridFunctions.focusCell(fixture, childLastRowCell); fixture.detectChanges(); const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('arrowup', childGridContent, false, false, true); fixture.detectChanges(); await wait(200); fixture.detectChanges(); await wait(DEBOUNCE_TIME); const childFirstRowCell = childGrid.dataRowList.toArray()[0].cells.toArray()[0]; const selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.row.index).toBe(childFirstRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(childFirstRowCell.column.visibleIndex); expect(selectedCell.column.index).toBe(childFirstRowCell.column.index); expect(selectedCell.value).toBe(childFirstRowCell.value); // check if child row is in view of parent. const gridOffsets = hierarchicalGrid.tbody.nativeElement.getBoundingClientRect(); const selectedCellElem = childGrid.gridAPI.get_cell_by_index(selectedCell.row.index, selectedCell.column.field); const rowOffsets = selectedCellElem.intRow.nativeElement.getBoundingClientRect(); expect(rowOffsets.top >= gridOffsets.top && rowOffsets.bottom <= gridOffsets.bottom).toBeTruthy(); })); it('should scroll top of child grid into view when pressing Ctrl + Arrow Up when cell is selected in it.', (async () => { await wait(DEBOUNCE_TIME); fixture.detectChanges(); hierarchicalGrid.verticalScrollContainer.scrollTo(7); await wait(DEBOUNCE_TIME); fixture.detectChanges(); hierarchicalGrid.verticalScrollContainer.scrollTo(7); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[3]; const childLastRowCell = childGrid.dataRowList.toArray()[9].cells.toArray()[0]; const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; GridFunctions.focusCell(fixture, childLastRowCell); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('arrowup', childGridContent, false, false, true); await wait(200); fixture.detectChanges(); await wait(200); fixture.detectChanges(); const childFirstRowCell = childGrid.dataRowList.toArray()[0].cells.toArray()[0]; const selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.row.index).toBe(childFirstRowCell.row.index); expect(selectedCell.column.visibleIndex).toBe(childFirstRowCell.column.visibleIndex); expect(selectedCell.column.index).toBe(childFirstRowCell.column.index); expect(selectedCell.value).toBe(childFirstRowCell.value); // check if child row is in view of parent. const gridOffsets = hierarchicalGrid.tbody.nativeElement.getBoundingClientRect(); const rowElem = childGrid.gridAPI.get_row_by_index(selectedCell.row.index); const rowOffsets = rowElem.nativeElement.getBoundingClientRect(); expect(rowOffsets.top >= gridOffsets.top && rowOffsets.bottom <= gridOffsets.bottom).toBeTruthy(); })); it('when navigating down from parent into child should scroll child grid to top and start navigation from first row.', (async () => { const ri = fixture.componentInstance.rowIsland; ri.height = '200px'; fixture.detectChanges(); await wait(DEBOUNCE_TIME); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; childGrid.verticalScrollContainer.scrollTo(9); await wait(DEBOUNCE_TIME); fixture.detectChanges(); let currScrTop = childGrid.verticalScrollContainer.getScroll().scrollTop; expect(currScrTop).toBeGreaterThan(0); const fCell = hierarchicalGrid.dataRowList.toArray()[0].cells.toArray()[0]; GridFunctions.focusCell(fixture, fCell); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('arrowdown', baseHGridContent, false, false, false); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const childFirstCell = childGrid.dataRowList.toArray()[0].cells.toArray()[0]; const selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.row.index).toBe(childFirstCell.row.index); expect(selectedCell.column.index).toBe(childFirstCell.column.index); currScrTop = childGrid.verticalScrollContainer.getScroll().scrollTop; expect(currScrTop).toBe(0); })); it('when navigating up from parent into child should scroll child grid to bottom and start navigation from last row.', (async () => { const ri = fixture.componentInstance.rowIsland; ri.height = '200px'; fixture.detectChanges(); await wait(DEBOUNCE_TIME); hierarchicalGrid.verticalScrollContainer.scrollTo(2); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const parentCell = hierarchicalGrid.gridAPI.get_cell_by_key(1, 'ID'); GridFunctions.focusCell(fixture, parentCell); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('arrowup', baseHGridContent, false, false, false); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); await wait(DEBOUNCE_TIME); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const vertScr = childGrid.verticalScrollContainer.getScroll(); const currScrTop = vertScr.scrollTop; // should be scrolled to bottom expect(currScrTop).toBe(vertScr.scrollHeight - vertScr.clientHeight); })); it('should move activation to last data cell in grid when ctrl+end is used.', (async () => { const parentCell = hierarchicalGrid.dataRowList.toArray()[0].cells.toArray()[0]; GridFunctions.focusCell(fixture, parentCell); await wait(DEBOUNCE_TIME); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('end', baseHGridContent, false, false, true); fixture.detectChanges(); await waitForSelectionChange(hierarchicalGrid); fixture.detectChanges(); const lastDataCell = hierarchicalGrid.getCellByKey(19, 'childData2'); const selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.row.index).toBe(lastDataCell.row.index); expect(selectedCell.column.index).toBe(lastDataCell.column.index); })); it('if next child cell is not in view should scroll parent so that it is in view.', (async () => { hierarchicalGrid.verticalScrollContainer.scrollTo(4); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const parentCell = hierarchicalGrid.dataRowList.toArray()[0].cells.toArray()[0]; GridFunctions.focusCell(fixture, parentCell); fixture.detectChanges(); const prevScroll = hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop; UIInteractions.triggerEventHandlerKeyDown('arrowdown', baseHGridContent, false, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // check if selected row is in view of parent. const selectedCell = fixture.componentInstance.selectedCell; const gridOffsets = hierarchicalGrid.tbody.nativeElement.getBoundingClientRect(); const rowElem = hierarchicalGrid.gridAPI.get_row_by_index(parentCell.row.index); const rowOffsets = rowElem.nativeElement.getBoundingClientRect(); expect(rowOffsets.top >= gridOffsets.top && rowOffsets.bottom <= gridOffsets.bottom).toBeTruthy(); expect(hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop - prevScroll).toBeGreaterThanOrEqual(100); })); it('should expand/collapse hierarchical row using ALT+Arrow Right/ALT+Arrow Left.', ( async () => { const parentRow = hierarchicalGrid.dataRowList.toArray()[0] as IgxHierarchicalRowComponent; expect(parentRow.expanded).toBe(true); const parentCell = parentRow.cells.toArray()[0]; GridFunctions.focusCell(fixture, parentCell); fixture.detectChanges(); // collapse UIInteractions.triggerEventHandlerKeyDown('arrowleft', baseHGridContent, true, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); expect(parentRow.expanded).toBe(false); // expand UIInteractions.triggerEventHandlerKeyDown('arrowright', baseHGridContent, true, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); expect(parentRow.expanded).toBe(true); })); it('should retain active cell when expand/collapse hierarchical row using ALT+Arrow Right/ALT+Arrow Left.', (async () => { // scroll to last row const lastDataIndex = hierarchicalGrid.dataView.length - 2; hierarchicalGrid.verticalScrollContainer.scrollTo(lastDataIndex); await wait(DEBOUNCE_TIME); fixture.detectChanges(); hierarchicalGrid.verticalScrollContainer.scrollTo(lastDataIndex); await wait(DEBOUNCE_TIME); fixture.detectChanges(); let parentCell = hierarchicalGrid.gridAPI.get_cell_by_index(38, 'ID'); GridFunctions.focusCell(fixture, parentCell); fixture.detectChanges(); // collapse UIInteractions.triggerEventHandlerKeyDown('arrowleft', baseHGridContent, true, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); parentCell = hierarchicalGrid.gridAPI.get_cell_by_index(38, 'ID'); expect(parentCell.active).toBeTruthy(); // expand UIInteractions.triggerEventHandlerKeyDown('arrowright', baseHGridContent, true, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); parentCell = hierarchicalGrid.gridAPI.get_cell_by_index(38, 'ID'); expect(parentCell.active).toBeTruthy(); })); it('should expand/collapse hierarchical row using ALT+Arrow Down/ALT+Arrow Up.', (async () => { const parentRow = hierarchicalGrid.dataRowList.toArray()[0] as IgxHierarchicalRowComponent; expect(parentRow.expanded).toBe(true); let parentCell = parentRow.cells.toArray()[0]; GridFunctions.focusCell(fixture, parentCell); fixture.detectChanges(); // collapse UIInteractions.triggerEventHandlerKeyDown('arrowup', baseHGridContent, true, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); expect(parentRow.expanded).toBe(false); // expand parentCell = parentRow.cells.toArray()[0]; UIInteractions.triggerEventHandlerKeyDown('arrowdown', baseHGridContent, true, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); expect(parentRow.expanded).toBe(true); })); it('should skip child grids that have no data when navigating up/down', (async () => { // set first child to not have data const child1 = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; child1.data = []; fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const parentRow = hierarchicalGrid.dataRowList.toArray()[0]; const parentCell = parentRow.cells.toArray()[0]; GridFunctions.focusCell(fixture, parentCell); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('arrowdown', baseHGridContent, false, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // second data row in parent should be focused const parentRow2 = hierarchicalGrid.getRowByIndex(2); const parentCell2 = parentRow2.cells[0]; let selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.row.index).toBe(parentCell2.row.index); expect(selectedCell.column.index).toBe(parentCell2.column.index); UIInteractions.triggerEventHandlerKeyDown('arrowup', baseHGridContent, false, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // first data row in parent should be selected selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.row.index).toBe(parentCell.row.index); expect(parentCell.selected).toBeTruthy(); })); it('should skip nested child grids that have no data when navigating up/down', (async () => { pending('Related with issue #7300'); const child1 = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; child1.height = '150px'; await wait(DEBOUNCE_TIME); fixture.detectChanges(); const row = child1.getRowByIndex(0); (row as IgxHierarchicalRowComponent).toggle(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // set nested child to not have data const subChild = child1.hgridAPI.getChildGrids(false)[0]; subChild.data = []; subChild.cdr.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const fchildRowCell = row.cells.toArray()[0]; GridFunctions.focusCell(fixture, fchildRowCell); fixture.detectChanges(); const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('arrowdown', childGridContent, false, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // second child row should be in view const sChildRowCell = child1.getRowByIndex(2).cells.toArray()[0]; let selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell).toBe(sChildRowCell); expect(child1.verticalScrollContainer.getScroll().scrollTop).toBeGreaterThanOrEqual(150); UIInteractions.triggerEventHandlerKeyDown('arrowup', childGridContent, false, false, false); fixture.detectChanges(); await wait(300); fixture.detectChanges(); selectedCell = fixture.componentInstance.selectedCell; expect(selectedCell.row.index).toBe(0); expect(child1.verticalScrollContainer.getScroll().scrollTop).toBe(0); })); it('should navigate inside summary row with Ctrl + Arrow Right/ Ctrl + Arrow Left', (async () => { const col = hierarchicalGrid.getColumnByName('ID'); col.hasSummary = true; fixture.detectChanges(); let summaryCells = hierarchicalGrid.summariesRowList.toArray()[0].summaryCells.toArray(); const firstCell = summaryCells[0]; GridFunctions.focusCell(fixture, firstCell); fixture.detectChanges(); const footerContent = fixture.debugElement.queryAll(By.css(GRID_FOOTER_CLASS))[2].children[0]; UIInteractions.triggerEventHandlerKeyDown('arrowright', footerContent, false, false, true); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); summaryCells = hierarchicalGrid.summariesRowList.toArray()[0].summaryCells.toArray(); const lastCell = summaryCells.find((s) => s.column.field === 'childData2'); expect(lastCell.active).toBeTruthy(); UIInteractions.triggerEventHandlerKeyDown('arrowleft', footerContent, false, false, true); await wait(DEBOUNCE_TIME); fixture.detectChanges(); summaryCells = hierarchicalGrid.summariesRowList.toArray()[0].summaryCells.toArray(); const fCell = summaryCells.find((s) => s.column.field === 'ID'); expect(fCell.active).toBeTruthy(); })); it('should navigate to Cancel button when there is row in edit mode', async () => { hierarchicalGrid.columnList.forEach((c) => { if (c.field !== hierarchicalGrid.primaryKey) { c.editable = true; } }); fixture.detectChanges(); hierarchicalGrid.rowEditable = true; await wait(50); fixture.detectChanges(); const cellElem = hierarchicalGrid.gridAPI.get_cell_by_index(0, 'ID'); GridFunctions.focusCell(fixture, cellElem); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('end', baseHGridContent, false, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const cell = hierarchicalGrid.gridAPI.get_cell_by_index(0, 'childData2'); UIInteractions.simulateDoubleClickAndSelectEvent(cell); await wait(DEBOUNCE_TIME); fixture.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('tab', cell.nativeElement, true); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const activeEl = document.activeElement; expect(activeEl.innerHTML).toEqual('Cancel'); UIInteractions.triggerKeyDownEvtUponElem('tab', activeEl, true, false, true); await wait(DEBOUNCE_TIME); fixture.detectChanges(); expect(document.activeElement.tagName.toLowerCase()).toBe('input'); }); it('should navigate to row edit button "Done" on shift + tab', async () => { hierarchicalGrid.columnList.forEach((c) => { if (c.field !== hierarchicalGrid.primaryKey) { c.editable = true; } }); fixture.detectChanges(); hierarchicalGrid.rowEditable = true; await wait(50); fixture.detectChanges(); hierarchicalGrid.getColumnByName('ID').hidden = true; await wait(50); fixture.detectChanges(); hierarchicalGrid.navigateTo(2); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const cell = hierarchicalGrid.gridAPI.get_cell_by_index(2, 'ChildLevels'); UIInteractions.simulateDoubleClickAndSelectEvent(cell); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); UIInteractions.triggerKeyDownEvtUponElem('tab', cell.nativeElement, true, false, true); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const activeEl = document.activeElement; expect(activeEl.innerHTML).toEqual('Done'); UIInteractions.triggerKeyDownEvtUponElem('tab', activeEl, true); await wait(DEBOUNCE_TIME); fixture.detectChanges(); expect(document.activeElement.tagName.toLowerCase()).toBe('input'); }); }); describe('IgxHierarchicalGrid Complex Navigation #hGrid', () => { configureTestSuite(); let fixture; let hierarchicalGrid: IgxHierarchicalGridComponent; let baseHGridContent; beforeAll(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ IgxHierarchicalGridTestComplexComponent ], imports: [ NoopAnimationsModule, IgxHierarchicalGridModule] }).compileComponents(); })); beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(IgxHierarchicalGridTestComplexComponent); fixture.detectChanges(); hierarchicalGrid = fixture.componentInstance.hgrid; setupHierarchicalGridScrollDetection(fixture, hierarchicalGrid); baseHGridContent = GridFunctions.getGridContent(fixture); GridFunctions.focusFirstCell(fixture, hierarchicalGrid); })); // complex tests it('in case prev cell is not in view port should scroll the closest scrollable parent so that cell comes in view.', (async () => { // scroll parent so that child top is not in view hierarchicalGrid.verticalScrollContainer.addScrollTop(300); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const child = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const nestedChild = child.hgridAPI.getChildGrids(false)[0]; const nestedChildCell = nestedChild.dataRowList.toArray()[1].cells.toArray()[0]; GridFunctions.focusCell(fixture, nestedChildCell); let oldScrTop = hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop; await wait(DEBOUNCE_TIME); fixture.detectChanges(); // navigate up const nestedChildGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[2]; UIInteractions.triggerEventHandlerKeyDown('arrowup', nestedChildGridContent, false, false, false); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); let nextCell = nestedChild.dataRowList.toArray()[0].cells.toArray()[0]; let currScrTop = hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop; const elemHeight = nestedChildCell.intRow.nativeElement.clientHeight; // check if parent of parent has been scroll up so that the focused cell is in view expect(oldScrTop - currScrTop).toEqual(elemHeight); oldScrTop = currScrTop; expect(nextCell.selected).toBe(true); expect(nextCell.active).toBe(true); expect(nextCell.rowIndex).toBe(0); // navigate up into parent UIInteractions.triggerEventHandlerKeyDown('arrowup', nestedChildGridContent, false, false, false); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); nextCell = child.dataRowList.toArray()[0].cells.toArray()[0]; currScrTop = hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop; expect(oldScrTop - currScrTop).toBeGreaterThanOrEqual(100); expect(nextCell.selected).toBe(true); expect(nextCell.active).toBe(true); expect(nextCell.rowIndex).toBe(0); })); it('in case next cell is not in view port should scroll the closest scrollable parent so that cell comes in view.', (async () => { const child = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const nestedChild = child.hgridAPI.getChildGrids(false)[0]; const nestedChildCell = nestedChild.dataRowList.toArray()[1].cells.toArray()[0]; // navigate down in nested child GridFunctions.focusCell(fixture, nestedChildCell); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const nestedChildGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[2]; UIInteractions.triggerEventHandlerKeyDown('arrowdown', nestedChildGridContent, false, false, false); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // check if parent has scrolled down to show focused cell. expect(child.verticalScrollContainer.getScroll().scrollTop).toBe(nestedChildCell.intRow.nativeElement.clientHeight); const nextCell = nestedChild.dataRowList.toArray()[2].cells.toArray()[0]; expect(nextCell.selected).toBe(true); expect(nextCell.active).toBe(true); expect(nextCell.rowIndex).toBe(2); })); it('should allow navigating up from parent into nested child grid', (async () => { hierarchicalGrid.verticalScrollContainer.scrollTo(2); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const child = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const lastIndex = child.dataView.length - 1; child.verticalScrollContainer.scrollTo(lastIndex); await wait(DEBOUNCE_TIME); fixture.detectChanges(); child.verticalScrollContainer.scrollTo(lastIndex); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const parentCell = hierarchicalGrid.gridAPI.get_cell_by_index(2, 'ID'); GridFunctions.focusCell(fixture, parentCell); await wait(DEBOUNCE_TIME * 2); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('arrowup', baseHGridContent , false, false, false); fixture.detectChanges(); await wait(DEBOUNCE_TIME * 2); fixture.detectChanges(); const nestedChild = child.hgridAPI.getChildGrids(false)[5]; const lastCell = nestedChild.gridAPI.get_cell_by_index(4, 'ID'); expect(lastCell.selected).toBe(true); expect(lastCell.active).toBe(true); expect(lastCell.rowIndex).toBe(4); })); }); describe('IgxHierarchicalGrid sibling row islands Navigation #hGrid', () => { let fixture; let hierarchicalGrid: IgxHierarchicalGridComponent; let baseHGridContent; configureTestSuite((() => { TestBed.configureTestingModule({ declarations: [ IgxHierarchicalGridMultiLayoutComponent ], imports: [ NoopAnimationsModule, IgxHierarchicalGridModule] }); })); beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(IgxHierarchicalGridMultiLayoutComponent); fixture.detectChanges(); hierarchicalGrid = fixture.componentInstance.hgrid; setupHierarchicalGridScrollDetection(fixture, hierarchicalGrid); baseHGridContent = GridFunctions.getGridContent(fixture); GridFunctions.focusFirstCell(fixture, hierarchicalGrid); })); it('should allow navigating up between sibling child grids.', (async () => { hierarchicalGrid.verticalScrollContainer.scrollTo(2); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const child1 = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const child2 = hierarchicalGrid.hgridAPI.getChildGrids(false)[5]; const child2Cell = child2.dataRowList.toArray()[0].cells.toArray()[0]; GridFunctions.focusCell(fixture, child2Cell); const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[2]; UIInteractions.triggerEventHandlerKeyDown('arrowup', childGridContent, false, false, false); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const lastCellPrevRI = child1.dataRowList.last.cells.toArray()[0]; expect(lastCellPrevRI.active).toBe(true); expect(lastCellPrevRI.selected).toBe(true); expect(lastCellPrevRI.rowIndex).toBe(9); })); it('should allow navigating down between sibling child grids.', (async () => { hierarchicalGrid.verticalScrollContainer.scrollTo(2); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const child1 = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const child2 = hierarchicalGrid.hgridAPI.getChildGrids(false)[5]; child1.verticalScrollContainer.scrollTo(child1.dataView.length - 1); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const child2Cell = child2.dataRowList.toArray()[0].cells.toArray()[0]; const lastCellPrevRI = child1.dataRowList.last.cells.toArray()[0]; GridFunctions.focusCell(fixture, lastCellPrevRI); const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('arrowdown', childGridContent, false, false, false); fixture.detectChanges(); await wait(DEBOUNCE_TIME); fixture.detectChanges(); expect(child2Cell.selected).toBe(true); expect(child2Cell.active).toBe(true); })); it('should navigate up from parent row to the correct child sibling.', (async () => { const parentCell = hierarchicalGrid.dataRowList.toArray()[1].cells.toArray()[0]; GridFunctions.focusCell(fixture, parentCell); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // Arrow Up into prev child grid UIInteractions.triggerEventHandlerKeyDown('arrowup', baseHGridContent, false, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const child2 = hierarchicalGrid.hgridAPI.getChildGrids(false)[5]; const child2Cell = child2.dataRowList.last.cells.toArray()[0]; expect(child2Cell.selected).toBe(true); expect(child2Cell.active).toBe(true); expect(child2Cell.rowIndex).toBe(9); })); it('should navigate down from parent row to the correct child sibling.', (async () => { const parentCell = hierarchicalGrid.dataRowList.toArray()[0].cells.toArray()[0]; GridFunctions.focusCell(fixture, parentCell); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // Arrow down into next child grid UIInteractions.triggerEventHandlerKeyDown('arrowdown', baseHGridContent, false, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const child1 = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const child1Cell = child1.dataRowList.toArray()[0].cells.toArray()[0]; expect(child1Cell.selected).toBe(true); expect(child1Cell.active).toBe(true); expect(child1Cell.rowIndex).toBe(0); })); it('should navigate to last cell in previous child using Arrow Up from last cell of sibling with more columns', (async () => { const childGrid2 = hierarchicalGrid.hgridAPI.getChildGrids(false)[5]; childGrid2.dataRowList.toArray()[0].virtDirRow.scrollTo(7); await wait(100); fixture.detectChanges(); const child2LastCell = childGrid2.gridAPI.get_cell_by_index(0, 'childData2'); GridFunctions.focusCell(fixture, child2LastCell); await wait(100); fixture.detectChanges(); const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[2]; UIInteractions.triggerEventHandlerKeyDown('arrowup', childGridContent, false, false, false); await wait(100); fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const childLastCell = childGrid.gridAPI.get_cell_by_index(9, 'childData'); expect(childLastCell.selected).toBeTruthy(); expect(childLastCell.active).toBeTruthy(); })); }); describe('IgxHierarchicalGrid Smaller Child Navigation #hGrid', () => { configureTestSuite(); let fixture; let hierarchicalGrid: IgxHierarchicalGridComponent; let baseHGridContent; beforeAll(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ IgxHierarchicalGridSmallerChildComponent ], imports: [ NoopAnimationsModule, IgxHierarchicalGridModule] }).compileComponents(); })); beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(IgxHierarchicalGridSmallerChildComponent); fixture.detectChanges(); hierarchicalGrid = fixture.componentInstance.hgrid; setupHierarchicalGridScrollDetection(fixture, hierarchicalGrid); baseHGridContent = GridFunctions.getGridContent(fixture); GridFunctions.focusFirstCell(fixture, hierarchicalGrid); })); it('should navigate to last cell in next row for child grid using Arrow Down from last cell of parent with more columns', (async () => { const parentCell = hierarchicalGrid.gridAPI.get_cell_by_index(0, 'Col2'); GridFunctions.focusCell(fixture, parentCell); await wait(DEBOUNCE_TIME); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('arrowdown', baseHGridContent, false, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // last cell in child should be focused const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const childLastCell = childGrid.gridAPI.get_cell_by_index(0, 'Col1'); expect(childLastCell.selected).toBe(true); expect(childLastCell.active).toBe(true); })); it('should navigate to last cell in next row for child grid using Arrow Up from last cell of parent with more columns', (async () => { hierarchicalGrid.verticalScrollContainer.scrollTo(2); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const parentCell = hierarchicalGrid.gridAPI.get_cell_by_index(2, 'Col2'); GridFunctions.focusCell(fixture, parentCell); await wait(DEBOUNCE_TIME); fixture.detectChanges(); UIInteractions.triggerEventHandlerKeyDown('arrowup', baseHGridContent, false, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); // last cell in child should be focused const childGrids = fixture.debugElement.queryAll(By.directive(IgxChildGridRowComponent)); const childGrid = childGrids[1].query(By.directive(IgxHierarchicalGridComponent)).componentInstance; const childLastCell = childGrid.gridAPI.get_cell_by_index(9, 'ProductName'); expect(childLastCell.selected).toBe(true); expect(childLastCell.active).toBe(true); })); it('should navigate to last cell in next child using Arrow Down from last cell of previous child with more columns', (async () => { const childGrids = fixture.debugElement.queryAll(By.directive(IgxChildGridRowComponent)); const firstChildGrid = childGrids[0].query(By.directive(IgxHierarchicalGridComponent)).componentInstance; const secondChildGrid = childGrids[1].query(By.directive(IgxHierarchicalGridComponent)).componentInstance; firstChildGrid.verticalScrollContainer.scrollTo(9); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const firstChildCell = firstChildGrid.gridAPI.get_cell_by_index(9, 'Col1'); GridFunctions.focusCell(fixture, firstChildCell); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const childGridContent = fixture.debugElement.queryAll(By.css(GRID_CONTENT_CLASS))[1]; UIInteractions.triggerEventHandlerKeyDown('arrowdown', childGridContent, false, false, false); await wait(DEBOUNCE_TIME); fixture.detectChanges(); const secondChildCell = secondChildGrid.gridAPI.get_cell_by_index(0, 'ProductName'); expect(secondChildCell.selected).toBe(true); expect(secondChildCell.active).toBe(true); })); }); @Component({ template: ` <igx-hierarchical-grid #grid1 [data]="data" (selected)='selected($event)' [autoGenerate]="true" [height]="'400px'" [width]="'500px'" #hierarchicalGrid primaryKey="ID" [expandChildren]='true'> <igx-row-island (selected)='selected($event)' [key]="'childData'" [autoGenerate]="true" [height]="null" #rowIsland> <igx-row-island (selected)='selected($event)' [key]="'childData'" [autoGenerate]="true" [height]="null" #rowIsland2 > </igx-row-island> </igx-row-island> </igx-hierarchical-grid>` }) export class IgxHierarchicalGridTestBaseComponent { @ViewChild('hierarchicalGrid', { read: IgxHierarchicalGridComponent, static: true }) public hgrid: IgxHierarchicalGridComponent; @ViewChild('rowIsland', { read: IgxRowIslandComponent, static: true }) public rowIsland: IgxRowIslandComponent; @ViewChild('rowIsland2', { read: IgxRowIslandComponent, static: true }) public rowIsland2: IgxRowIslandComponent; public data; public selectedCell; constructor() { // 3 level hierarchy this.data = this.generateData(20, 3); } public selected(event: IGridCellEventArgs) { this.selectedCell = event.cell; } public generateData(count: number, level: number) { const prods = []; const currLevel = level; let children; for (let i = 0; i < count; i++) { if (level > 0 ) { children = this.generateData(count / 2 , currLevel - 1); } prods.push({ ID: i, ChildLevels: currLevel, ProductName: 'Product: A' + i, Col1: i, Col2: i, Col3: i, childData: children, childData2: children }); } return prods; } } @Component({ template: ` <igx-hierarchical-grid #grid1 [height]="'400px'" [width]="'500px'" [data]="data" [autoGenerate]="true" [expandChildren]='true' #hierarchicalGrid> <igx-row-island [key]="'childData'" [autoGenerate]="true" [expandChildren]='true' [height]="'300px'" #rowIsland> <igx-row-island [key]="'childData'" [autoGenerate]="true" #rowIsland2 [height]="'200px'" > </igx-row-island> </igx-row-island> </igx-hierarchical-grid>` }) export class IgxHierarchicalGridTestComplexComponent extends IgxHierarchicalGridTestBaseComponent { constructor() { super(); // 3 level hierarchy this.data = this.generateData(20, 3); } } @Component({ template: ` <igx-hierarchical-grid #grid1 [data]="data" [autoGenerate]="true" [height]="'500px'" [width]="'500px'" [expandChildren]='true' #hierarchicalGrid> <igx-row-island [key]="'childData'" [autoGenerate]="true" [height]="'150px'"> <igx-row-island [key]="'childData2'" [autoGenerate]="true" [height]="'100px'"> </igx-row-island> </igx-row-island> <igx-row-island [key]="'childData2'" [autoGenerate]="true" [height]="'150px'"> </igx-row-island> </igx-hierarchical-grid>` }) export class IgxHierarchicalGridMultiLayoutComponent extends IgxHierarchicalGridTestBaseComponent {} @Component({ template: ` <igx-hierarchical-grid #grid1 [data]="data" [autoGenerate]="false" [height]="'500px'" [width]="'800px'" [expandChildren]='true' #hierarchicalGrid> <igx-column field="ID"></igx-column> <igx-column field="ChildLevels"></igx-column> <igx-column field="ProductName"></igx-column> <igx-column field="Col1"></igx-column> <igx-column field="Col2"></igx-column> <igx-row-island [key]="'childData'" [autoGenerate]="false" [height]="'200px'"> <igx-column field="ID"></igx-column> <igx-column field="ChildLevels"></igx-column> <igx-column field="ProductName"></igx-column> <igx-column field="Col1"></igx-column> <igx-row-island [key]="'childData2'" [autoGenerate]="true" [height]="'100px'"> </igx-row-island> </igx-row-island> <igx-row-island [key]="'childData2'" [autoGenerate]="false" [height]="'200px'"> <igx-column field="ID"></igx-column> <igx-column field="ChildLevels"></igx-column> <igx-column field="ProductName"></igx-column> <igx-row-island [key]="'childData2'" [autoGenerate]="true" [height]="'100px'"> </igx-row-island> </igx-row-island> </igx-hierarchical-grid>` }) export class IgxHierarchicalGridSmallerChildComponent extends IgxHierarchicalGridTestBaseComponent {}
the_stack
import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'; import { Observable, of as observableOf, combineLatest as observableCombineLatest, Subscription, BehaviorSubject } from 'rxjs'; import { filter, map, take } from 'rxjs/operators'; import { DynamicDatePickerModel, DynamicFormControlModel, DynamicFormGroupModel, DynamicSelectModel } from '@ng-dynamic-forms/core'; import { ResourcePolicy } from '../../../core/resource-policy/models/resource-policy.model'; import { DsDynamicInputModel } from '../../form/builder/ds-dynamic-form-ui/models/ds-dynamic-input.model'; import { RESOURCE_POLICY_FORM_ACTION_TYPE_CONFIG, RESOURCE_POLICY_FORM_DATE_GROUP_CONFIG, RESOURCE_POLICY_FORM_DATE_GROUP_LAYOUT, RESOURCE_POLICY_FORM_DESCRIPTION_CONFIG, RESOURCE_POLICY_FORM_END_DATE_CONFIG, RESOURCE_POLICY_FORM_END_DATE_LAYOUT, RESOURCE_POLICY_FORM_NAME_CONFIG, RESOURCE_POLICY_FORM_POLICY_TYPE_CONFIG, RESOURCE_POLICY_FORM_START_DATE_CONFIG, RESOURCE_POLICY_FORM_START_DATE_LAYOUT } from './resource-policy-form.model'; import { DsDynamicTextAreaModel } from '../../form/builder/ds-dynamic-form-ui/models/ds-dynamic-textarea.model'; import { DSpaceObject } from '../../../core/shared/dspace-object.model'; import { DSONameService } from '../../../core/breadcrumbs/dso-name.service'; import { hasValue, isEmpty, isNotEmpty, hasValueOperator } from '../../empty.util'; import { FormService } from '../../form/form.service'; import { RESOURCE_POLICY } from '../../../core/resource-policy/models/resource-policy.resource-type'; import { RemoteData } from '../../../core/data/remote-data'; import { dateToISOFormat, stringToNgbDateStruct } from '../../date.util'; import { EPersonDataService } from '../../../core/eperson/eperson-data.service'; import { GroupDataService } from '../../../core/eperson/group-data.service'; import { getFirstSucceededRemoteData } from '../../../core/shared/operators'; import { RequestService } from '../../../core/data/request.service'; export interface ResourcePolicyEvent { object: ResourcePolicy; target: { type: string, uuid: string }; } @Component({ selector: 'ds-resource-policy-form', templateUrl: './resource-policy-form.component.html', }) /** * Component that show form for adding/editing a resource policy */ export class ResourcePolicyFormComponent implements OnInit, OnDestroy { /** * If given contains the resource policy to edit * @type {ResourcePolicy} */ @Input() resourcePolicy: ResourcePolicy; /** * A boolean representing if form submit operation is processing * @type {boolean} */ @Input() isProcessing: Observable<boolean> = observableOf(false); /** * An event fired when form is canceled. * Event's payload is empty. */ @Output() reset: EventEmitter<any> = new EventEmitter<any>(); /** * An event fired when form is submitted. * Event's payload equals to a new ResourcePolicy. */ @Output() submit: EventEmitter<ResourcePolicyEvent> = new EventEmitter<ResourcePolicyEvent>(); /** * The form id * @type {string} */ public formId: string; /** * The form model * @type {DynamicFormControlModel[]} */ public formModel: DynamicFormControlModel[]; /** * The eperson or group that will be granted the permission * @type {DSpaceObject} */ public resourcePolicyGrant: DSpaceObject; /** * The type of the object that will be grant of the permission. It could be 'eperson' or 'group' * @type {string} */ public resourcePolicyGrantType: string; /** * The name of the eperson or group that will be granted the permission * @type {BehaviorSubject<string>} */ public resourcePolicyTargetName$: BehaviorSubject<string> = new BehaviorSubject(''); /** * A boolean representing if component is active * @type {boolean} */ private isActive: boolean; /** * Array to track all subscriptions and unsubscribe them onDestroy * @type {Array} */ private subs: Subscription[] = []; /** * Initialize instance variables * * @param {DSONameService} dsoNameService * @param {EPersonDataService} ePersonService * @param {FormService} formService * @param {GroupDataService} groupService * @param {RequestService} requestService */ constructor( private dsoNameService: DSONameService, private ePersonService: EPersonDataService, private formService: FormService, private groupService: GroupDataService, private requestService: RequestService, ) { } /** * Initialize the component, setting up the form model */ ngOnInit(): void { this.isActive = true; this.formId = this.formService.getUniqueId('resource-policy-form'); this.formModel = this.buildResourcePolicyForm(); if (!this.canSetGrant()) { const epersonRD$ = this.ePersonService.findByHref(this.resourcePolicy._links.eperson.href, false).pipe( getFirstSucceededRemoteData() ); const groupRD$ = this.groupService.findByHref(this.resourcePolicy._links.group.href, false).pipe( getFirstSucceededRemoteData() ); const dsoRD$: Observable<RemoteData<DSpaceObject>> = observableCombineLatest([epersonRD$, groupRD$]).pipe( map((rdArr: RemoteData<DSpaceObject>[]) => { return rdArr.find((rd: RemoteData<DSpaceObject>) => isNotEmpty(rd.payload)); }), hasValueOperator(), ); this.subs.push( dsoRD$.pipe( filter(() => this.isActive), ).subscribe((dsoRD: RemoteData<DSpaceObject>) => { this.resourcePolicyGrant = dsoRD.payload; this.resourcePolicyTargetName$.next(this.getResourcePolicyTargetName()); }) ); } } /** * Method to check if the form status is valid or not * * @return Observable that emits the form status */ isFormValid(): Observable<boolean> { return this.formService.isValid(this.formId).pipe( map((isValid: boolean) => isValid && isNotEmpty(this.resourcePolicyGrant)) ); } /** * Initialize the form model * * @return the form models */ private buildResourcePolicyForm(): DynamicFormControlModel[] { const formModel: DynamicFormControlModel[] = []; // TODO to be removed when https://jira.lyrasis.org/browse/DS-4477 will be implemented const policyTypeConf = Object.assign({}, RESOURCE_POLICY_FORM_POLICY_TYPE_CONFIG, { disabled: isNotEmpty(this.resourcePolicy) }); // TODO to be removed when https://jira.lyrasis.org/browse/DS-4477 will be implemented const actionConf = Object.assign({}, RESOURCE_POLICY_FORM_ACTION_TYPE_CONFIG, { disabled: isNotEmpty(this.resourcePolicy) }); formModel.push( new DsDynamicInputModel(RESOURCE_POLICY_FORM_NAME_CONFIG), new DsDynamicTextAreaModel(RESOURCE_POLICY_FORM_DESCRIPTION_CONFIG), new DynamicSelectModel(policyTypeConf), new DynamicSelectModel(actionConf) ); const startDateModel = new DynamicDatePickerModel( RESOURCE_POLICY_FORM_START_DATE_CONFIG, RESOURCE_POLICY_FORM_START_DATE_LAYOUT ); const endDateModel = new DynamicDatePickerModel( RESOURCE_POLICY_FORM_END_DATE_CONFIG, RESOURCE_POLICY_FORM_END_DATE_LAYOUT ); const dateGroupConfig = Object.assign({}, RESOURCE_POLICY_FORM_DATE_GROUP_CONFIG, { group: [] }); dateGroupConfig.group.push(startDateModel, endDateModel); formModel.push(new DynamicFormGroupModel(dateGroupConfig, RESOURCE_POLICY_FORM_DATE_GROUP_LAYOUT)); this.initModelsValue(formModel); return formModel; } /** * Setting up the form models value * * @return the form models */ initModelsValue(formModel: DynamicFormControlModel[]): DynamicFormControlModel[] { if (this.resourcePolicy) { formModel.forEach((model: any) => { if (model.id === 'date') { if (hasValue(this.resourcePolicy.startDate)) { model.get(0).value = stringToNgbDateStruct(this.resourcePolicy.startDate); } if (hasValue(this.resourcePolicy.endDate)) { model.get(1).value = stringToNgbDateStruct(this.resourcePolicy.endDate); } } else { if (this.resourcePolicy.hasOwnProperty(model.id) && this.resourcePolicy[model.id]) { model.value = this.resourcePolicy[model.id]; } } }); } return formModel; } /** * Return a boolean representing If is possible to set policy grant * * @return true if is possible, false otherwise */ canSetGrant(): boolean { return isEmpty(this.resourcePolicy); } /** * Return the name of the eperson or group that will be granted the permission * * @return the object name */ getResourcePolicyTargetName(): string { return isNotEmpty(this.resourcePolicyGrant) ? this.dsoNameService.getName(this.resourcePolicyGrant) : ''; } /** * Update reference to the eperson or group that will be granted the permission */ updateObjectSelected(object: DSpaceObject, isEPerson: boolean): void { this.resourcePolicyGrant = object; this.resourcePolicyGrantType = isEPerson ? 'eperson' : 'group'; } /** * Method called on reset * Emit a new reset Event */ onReset(): void { this.reset.emit(); } /** * Method called on submit. * Emit a new submit Event whether the form is valid */ onSubmit(): void { this.formService.getFormData(this.formId).pipe(take(1)) .subscribe((data) => { const eventPayload: ResourcePolicyEvent = Object.create({}); eventPayload.object = this.createResourcePolicyByFormData(data); eventPayload.target = { type: this.resourcePolicyGrantType, uuid: this.resourcePolicyGrant.id }; this.submit.emit(eventPayload); }); } /** * Create e new ResourcePolicy by form data * * @return the new ResourcePolicy object */ createResourcePolicyByFormData(data): ResourcePolicy { const resourcePolicy = new ResourcePolicy(); resourcePolicy.name = (data.name) ? data.name[0].value : null; resourcePolicy.description = (data.description) ? data.description[0].value : null; resourcePolicy.policyType = (data.policyType) ? data.policyType[0].value : null; resourcePolicy.action = (data.action) ? data.action[0].value : null; resourcePolicy.startDate = (data.date && data.date.start) ? dateToISOFormat(data.date.start[0].value) : null; resourcePolicy.endDate = (data.date && data.date.end) ? dateToISOFormat(data.date.end[0].value) : null; resourcePolicy.type = RESOURCE_POLICY; return resourcePolicy; } /** * Unsubscribe from all subscriptions */ ngOnDestroy(): void { this.isActive = false; this.formModel = null; this.subs .filter((subscription) => hasValue(subscription)) .forEach((subscription) => subscription.unsubscribe()); } }
the_stack
import { Observable, ReplaySubject } from 'rxjs'; import { vec2, vec4 } from 'gl-matrix'; import { assert, logIf, LogLevel } from './auxiliaries'; import { clamp, v2 } from './gl-matrix-extensions'; import { ChangeLookup } from './changelookup'; import { Context } from './context'; import { Controllable } from './controller'; import { EventProvider } from './eventhandler' import { Initializable } from './initializable'; import { GLclampf4, GLfloat2, GLsizei2, tuple2 } from './tuples'; import { Wizard } from './wizard'; /* spellchecker: enable */ /** * The interface to a callback that is called if the renderer is invalidated. */ export interface Invalidate { (force: boolean): void; } export enum LoadingStatus { Started, Finished, } /** * Base class for hardware-accelerated processing and/or image-synthesis. It provides information such as the current * canvas, the canvas's size (native resolution), and the multi-frame number (for progressive rendering). A renderer's * properties are expected to be managed by its owning object or the canvas and should not be set directly/manually. * Alterations to these properties can be tracked with the `_altered` property. This allows an inheritor to implement * partial asset reallocation and, e.g., speed up dynamic multi-frame reconfiguration. The alterable object can be * extended using `Object.assign(this._alterable, ... some structure of booleans)`. * * This base class further provides the invalidate method that invokes an invalidation callback also provided by the * owning/controlling canvas. * * Since Initializable is extended, the initialization workflow applies to all specialized renderers (requires super * calls in constructor as well as in initialize and uninitialize). * * Note that a renderer is currently intended to always render to the canvas it is bound to. Hence, there is no * interface for setting a frame target. */ export abstract class Renderer extends Initializable implements Controllable { /** * The renderer's invalidation callback. This should usually be setup by the canvas and refer to a function in the * canvas's controller, e.g., it should trigger an update within the controller. */ protected _invalidate: Invalidate; /** @see {@link context} */ protected _context: Context; /** * Alterable auxiliary object for tracking changes on renderer input and lazy updates. */ protected readonly _altered = Object.assign(new ChangeLookup(), { any: false, multiFrameNumber: false, frameSize: false, canvasSize: false, framePrecision: false, clearColor: false, debugTexture: false, }); /** * This multi-frame number is for lazy reconfiguration and set on update. The inheritor can react to changes using * this.altered.multiFrameNumber. */ protected _multiFrameNumber: number; /** * Targeted resolution for image synthesis. This might differ from the canvas resolution and should be used in * frame calls of inheritors. */ protected _frameSize: GLsizei2 = [0, 0]; /** * Actual, native resolution for the canvas currently in charge of controlling the renderer. This might differ from * the targeted frame resolution but is required, e.g., for specific non-proportional ratios between frame size and * canvas size. */ protected _canvasSize: GLsizei2 = [0, 0]; /** * Targeted frame precision, e.g., used for frame accumulation. Note that any renderer is currently * expected to take advantage of progressive rendering (e.g., multi-frame sampling) and accumulation as well as a * blit pass (since main intend is multi-frame based rendering). */ protected _framePrecision: Wizard.Precision = Wizard.Precision.half; /** * The clear color, provided by the canvas the renderer is bound to. This is used in frame calls of inheritors. */ protected _clearColor: GLclampf4 = [0.0, 0.0, 0.0, 1.0]; /** * List of textures for debugging purposes such as normals, ids, depth, masks, etc. that can be populated by the * inheritor. The index of a texture identifier can then be for specifying a debug output of a render texture. */ protected _debugTextures = new Array<string>(); /** * @see {@link debugTexture} * This property can be observed, e.g., `aRenderer.debugTextureObservable.subscribe()`. */ protected _debugTexture: GLint; protected _debugTextureSubject = new ReplaySubject<GLint>(1); /** * @see {@link isLoading} */ protected _isLoading: boolean; /** * This property can be observed via `aRenderer.loadingState$.observe()`. It is triggered when `finishLoading` or * `startLoading` is called on this renderer. */ protected _loadingStatusSubscription: ReplaySubject<LoadingStatus>; /** @callback Invalidate * A callback intended to be invoked whenever the specialized renderer itself or one of its objects is invalid. This * callback should be passed during initialization to all objects that might handle invalidation internally as well. * As a result, rendering of a new frame will be triggered and enforced. */ @Initializable.assert_initialized() protected invalidate(force: boolean = false): void { this._invalidate(force); } /** * Utility for communicating this._debugTexture changes to its associated subject. */ protected debugTextureNext(): void { this._debugTextureSubject.next(this._debugTexture); } /** * Context that can be used for processing and rendering as well as passed to rendering stages. */ protected get context(): Context { this.assertInitialized(); return this._context; } protected get canvasSize(): GLsizei2 { this.assertInitialized(); return this._canvasSize; } /** * Whether or not any of the (relevant/monitored) rendering properties has been altered. This concept should be used * by other classes (e.g., camera, rendering stages) for detecting modifications relevant for rendering output. */ protected get altered(): boolean { return this._altered.any; } /** * Actual initialize call specified by inheritor. * @returns - whether initialization was successful */ protected abstract onInitialize(context: Context, callback: Invalidate, eventProvider: EventProvider): boolean; /** * Actual uninitialize call specified by inheritor. */ protected abstract onUninitialize(): void; /** * Actual discard call specified by inheritor. */ protected abstract onDiscarded(): void; /** * Actual update call specified by inheritor. This is invoked in order to check if rendering of a frame is required * by means of implementation specific evaluation (e.g., lazy non continuous rendering). Regardless of the return * value a new frame (preparation, frame, swap) might be invoked anyway, e.g., when update is forced or canvas or * context properties have changed or the renderer was invalidated @see{@link invalidate}. * @returns - Whether to redraw */ protected abstract onUpdate(): boolean; /** * Actual prepare call specified by inheritor. This is invoked in order to prepare rendering of one or more frames. * This should be used for rendering preparation, e.g., when using multi-frame rendering this might specify uniforms * that do not change for every intermediate frame. */ protected abstract onPrepare(): void; /** * Actual frame call specified by inheritor. After (1) update and (2) preparation are invoked, a frame is invoked. * This should be used for actual rendering implementation. */ protected abstract onFrame(frameNumber: number): void; /** * Actual swap call specified by inheritor. After (1) update, (2) preparation, and (3) frame are invoked, a swap * might be invoked. In case of experimental batch rendering when using multi-frame a swap might be withhold for * multiple frames. Any implementation is expected to ensure that contents of a frame to be on the OpenGL * back buffer. The swap of front buffer and back buffer is scheduled after the invocation of this function by * the browser. */ protected onSwap(): void { /* default empty impl. */ } /** * This method needs to be called by a renderer, when a loading process is started in order to notify listeners via * the observable loadingState$. */ protected startLoading(): void { this._isLoading = true; this._loadingStatusSubscription.next(LoadingStatus.Started); } /** * This method needs to be called when a loading process is finished in order to notify listeners via * the observable loadingState$. */ protected finishLoading(): void { this._isLoading = false; this._loadingStatusSubscription.next(LoadingStatus.Finished); } /** * When extending (specializing) this class, initialize should initialize all required stages and allocate assets * that are shared between multiple stages. Note that `super.initialize()` should always be called first when * 'overriding' this function. * * Note: the context handle is stored in a property, but should be passed to the stages by specializing * renderer instead. The renderer itself should not allocate rendering resources directly, thus, it should not * require a webgl context. * * @param context - Wrapped gl context for function resolution (passed to all stages). * @param callback - Functions that is invoked when the renderer (or any stage) is invalidated. * @param eventProvider - Provider for mouse events referring to the canvas element. */ @Initializable.initialize() initialize(context: Context, callback: Invalidate, eventProvider: EventProvider): boolean { assert(context !== undefined, `valid webgl context required`); this._context = context; assert(callback !== undefined, `valid multi-frame update callback required`); this._invalidate = callback; this._isLoading = true; this._loadingStatusSubscription = new ReplaySubject(); return this.onInitialize(context, callback, eventProvider); } /** * Should release all assets and uninitialize all stages. `super.uninitialize()` should always be called first when * overriding this function. */ @Initializable.uninitialize() uninitialize(): void { this.onUninitialize(); } /** * Should discard all assets and uninitialize all stages. `super.discarded()` should always be called first when * overriding this function. */ @Initializable.discard() public discard(): void { this.onDiscarded(); } /** * */ @Initializable.assert_initialized() update(multiFrameNumber: number): boolean { if (this._canvasSize[0] !== this._context.gl.canvas.width || this._canvasSize[1] !== this._context.gl.canvas.height) { this._canvasSize[0] = this._context.gl.canvas.width; this._canvasSize[1] = this._context.gl.canvas.height; this._altered.alter('canvasSize'); } if (this._multiFrameNumber !== multiFrameNumber) { this._multiFrameNumber = multiFrameNumber; this._altered.alter('multiFrameNumber'); } return this.onUpdate() || this._altered.any; } /** * Prepares the rendering of the next frame (or subsequent frames when multi-frame rendering). * This is part of the controllable interface. The renderer should reconfigure as lazy as possible. * @param multiFrameNumber - The multi-frame number as requested by controller. */ @Initializable.assert_initialized() prepare(): void { this.onPrepare(); } /** * Controllable interface intended to trigger rendering of a full pass of the renderer that results in either an * intermediate frame for accumulation to a full multi-frame or full frame for itself. The inheritor should invoke * frames of relevant rendering and processing stages. * @param frameNumber - The current frame number forwarded to onFrame. */ @Initializable.assert_initialized() frame(frameNumber: number): void { this.onFrame(frameNumber); } /** * Interface intended to trigger swap (by controller). */ @Initializable.assert_initialized() swap(): void { this.onSwap(); } /** * Transforms local viewport coordinates into local intermediate frame coordinates. * @param x - Horizontal coordinate for the upper left corner of the viewport origin. * @param y - Vertical coordinate for the upper left corner of the viewport origin. */ frameCoords(x: GLint, y: GLint): GLfloat2 { const position = vec2.divide(v2(), this._frameSize, this.canvasSize); vec2.floor(position, vec2.multiply(position, [x + 0.5, y + 0.5], position)); vec2.add(position, position, [0.5, 0.5]); return tuple2<GLfloat>(position); } // /** // * @interface CoordsAccess // * Look up a fragments coordinates by unprojecting the depth using the renderer's camera. // * @param x - Horizontal coordinate for the upper left corner of the viewport origin. // * @param y - Vertical coordinate for the upper left corner of the viewport origin. // * @param zInNDC - optional depth parameter (e.g., from previous query). // * @returns - 3D coordinate reprojected from NDC/depth to world space. // */ // abstract coordsAt(x: GLint, y: GLint, zInNDC?: number, viewProjectionInverse?: mat4): vec3 | undefined; // /** // * @interface IDAccess // * Look up an object id at a specific fragment. // * @param x - Horizontal coordinate for the upper left corner of the viewport origin. // * @param y - Vertical coordinate for the upper left corner of the viewport origin. // * @returns - ID encoded of an object rendered/visible at given position. // */ // abstract idAt(x: GLint, y: GLint): GLsizei | undefined; /** * Changes the frame size for rendering. This setter should only be used by the canvas this renderer is bound to. * Changing the frame size invalidates the renderer. * * Note: the frame size is detached from the canvas size. When blitting the frame into the canvas, the frame is * rescaled to fill or fit the canvas size. * * @param size - Resolution of the framebuffer. */ set frameSize(size: GLsizei2) { this.assertInitialized(); if (vec2.equals(this._frameSize, size)) { return; } Object.assign(this._frameSize, size); this._altered.alter('frameSize'); this.invalidate(); } /** * Set the frame precision. * @param format - The accumulation format. Expected values are one of 'byte', 'half', 'float', or 'auto' */ set framePrecision(precision: Wizard.Precision) { this.assertInitialized(); if (this._framePrecision === precision) { return; } this._framePrecision = precision; this._altered.alter('framePrecision'); this.invalidate(); } /** * Sets the color used for clearing the background. This setter should only be used by the canvas this renderer is * bound to. Changing the frame size invalidates the renderer. * @param color - Red, green, blue, and alpha color components. */ set clearColor(color: GLclampf4) { this.assertInitialized(); if (vec4.equals(this._clearColor, color)) { return; } Object.assign(this._clearColor, color); this._altered.alter('clearColor'); this.invalidate(); } /** * Read only access to the renderers registered render textures that can be blit to the back buffer for debugging. * @returns - Array of render texture identifiers. */ get debugTextures(): Array<string> { this.assertInitialized(); return this._debugTextures; } /** * The render texture index for debug output. This is -1 when debug output is disabled. This should be used in * the renderers swap implementation. */ get debugTexture(): GLint { this.assertInitialized(); return this._debugTexture; } /** * Enables to specify the index of a render texture to be blit to the back buffer for debugging. This invalidates * but should result in a blit only if nothing else changed. When the requested debug texture was blit (and * debugTexture was actually altered) `this.debugTextureNext()` should be called to inform observers. * @param index - Render texture index based on debuggableTextures array. This should be in [-1, length of array]. */ set debugTexture(index: GLint) { this.assertInitialized(); if (this._debugTexture === index) { return; } logIf(index >= this._debugTextures.length, LogLevel.Error, `invalid texture index, ` + `debug texture disabled (index set to -1) | ${index} not in [-1,+${this._debugTextures.length - 1}]`); this._debugTexture = index < this._debugTextures.length ? clamp(index, -1, this._debugTextures.length - 1) : -1; this._altered.alter('debugTexture'); this.invalidate(); } /** * Observable that can be used to subscribe to debug texture changes. */ get debugTexture$(): Observable<GLint> { return this._debugTextureSubject.asObservable(); } /** * This property indicated whether a loading process is currently in progress. * It can be changed by calling `startLoading` or `finishLoading` on this renderer. */ get isLoading(): boolean { return this._isLoading; } /** * Observable to subscribe to the current loading state of this renderer. * Use `aRenderer.loadingStatus$.subscribe()` to register a new subscriber. */ get loadingStatus$(): Observable<LoadingStatus> { return this._loadingStatusSubscription.asObservable(); } }
the_stack
import type {ComponentType} from './component'; import type {Entity} from './entity'; import type {System} from './system'; interface Waitable<T> { markAwaited?(): void; isReady(): boolean; cancel?(): void; value?: T; error?: Error | undefined; } /** * An exception thrown by coroutines when they've been canceled. You should normally rethrow it * from any catch blocks, and it will be caught and ignored at the top coroutine nesting level. */ export class CanceledError extends Error { canceled = true; constructor() { super('Canceled'); } } /** * A handle that you can use to configure a coroutine execution. You can obtain one from * {@link System.start} explicitly, or implicitly by using the {@link co} decorator. * * The `cancel` family of methods will silently cancel (abort) the coroutine whenever a condition is * fulfilled at any `yield` statement, even if the coroutine is currently blocked. These are * typically called when the coroutine is started. If you specify a `scope` for the coroutine it can * affect how the `cancel` conditions work. */ export interface Coroutine { // The same cancelation methods are also declared below for coDecorator, and in overlays.d.ts. /** * Unconditionally cancels (aborts) this coroutine, or the most deeply nested one that this * coroutine is currently waiting on. This will throw a {@link CanceledError} from that * coroutine's current (or next) `yield` statement. */ cancel(): void; /** * Cancels this coroutine if the given condition is true at any `yield` point. * @param condition The condition to check at every `yield` point. */ cancelIf(condition: () => boolean): this; /** * Constrains the entity's scope to the given entity. The coroutine will automatically be * canceled if the entity is deleted, and any conditional cancelations will only trigger if the * event's scope matches. * * The scope cannot be changed once set, and cannot be set once any cancelation conditions have * been added. * @param entity The entity that this coroutine is processing somehow. */ scope(entity: Entity): this; /** * Cancels this coroutine if the give component is missing from the scoped entity at any `yield` * point. * @param type The type of component to check for. */ cancelIfComponentMissing(type: ComponentType<any>): this; /** * Cancels this coroutine if another coroutine is started within this system. By default, any * coroutine will trigger cancelation. If this coroutine has a scope, then the newly started * coroutine must have the same scope. If a `coroutineFn` is given, then the newly started * coroutine must be that one. * @param coroutineFn A specific mutually exclusive coroutine. You can use `co.self` as a * shortcut for the currently running coroutine. */ cancelIfCoroutineStarted(coroutineFn?: CoroutineFunction): this; } /** * A handle to the currently executing coroutine. You can access it via `co`, but only from inside * an executing coroutine. * * This has all the normal coroutine control methods and adds a bunch of `wait` methods for blocking * the coroutine until something happens. You must pass the return value of the `wait` methods into * a `yield` expression for them to work. */ export interface CurrentCoroutine extends Coroutine { // The same waiting methods are also declared below for coDecorator. /** * Blocks the coroutine for the given number of frames. Blocking for 1 frame will execute on the * next frame, for 2 frames will skip a round of executions, etc. * * Yielding on `co.waitForFrames(1)` is equivalent to a `yield` with no argument. * @param frames The number of frames to block the coroutine for. */ waitForFrames(frames: number): Waitable<void>; /** * Blocks the coroutine for at least the given number of seconds (or whatever unit of time you're * using if you've customized the world's time counter). Always waits at least until the next * frame. * @param seconds The number of seconds to block the coroutine for. */ waitForSeconds(seconds: number): Waitable<void>; /** * Blocks the coroutine until the given condition returns `true`. Always waits at least until the * next frame. * @param condition The condition to check every frame until it returns `true`. */ waitUntil(condition: () => boolean): Waitable<void>; } let currentCoroutine: CoroutineImpl<any> | void; class CoroutineImpl<T> implements Coroutine, Waitable<T>, CoroutineGenerator { private __cancellers: (() => boolean)[] = []; private __blocker: Waitable<any> | void; private __scope?: Entity; private __done = false; private __awaited = false; private __error?: Error; private __value: T; private __firstRun = true; constructor( private readonly __generator: Generator<Waitable<any> | void, T, any>, readonly __fn: CoroutineFunction, private readonly __supervisor: Supervisor ) {} __checkCancelation(): void { if (this.__firstRun) { this.__firstRun = false; this.__supervisor.cancelMatching(this, this.__scope, this.__fn); } if (!this.__done) { for (const canceller of this.__cancellers) { if (canceller()) { this.cancel(); break; } } } } __step(): void { currentCoroutine = this; try { if (!this.__done && (this.__blocker?.isReady() ?? true)) { try { let next; if (this.__blocker?.error) { next = this.__generator.throw(this.__blocker.error); } else { next = this.__generator.next(this.__blocker?.value); } if (next.done) { this.__done = true; this.__value = next.value; this.__blocker = undefined; } else { this.__blocker = next.value; this.__blocker?.markAwaited?.(); } } catch (e) { this.__done = true; if (!this.__error) this.__error = e as Error; this.__blocker = undefined; } } if (this.__error && !(this.__awaited || this.__error instanceof CanceledError)) { throw this.__error; } } finally { currentCoroutine = undefined; } } // Waitable methods isReady(): boolean { return this.__done; } get value(): T { return this.__value; } get error(): Error | undefined { return this.__error; } markAwaited(): void { this.__awaited = true; } // CurrentCoroutine methods waitForFrames(frames: number): Waitable<void> { CHECK: if (frames <= 0) throw new Error('Number of frames to wait for must be >0'); return { isReady() {return --frames <= 0;} }; } waitForSeconds(seconds: number): Waitable<void> { const system = this.__supervisor.system; const targetTime = system.time + seconds; return { isReady() {return system.time >= targetTime;} }; } waitUntil(condition: () => boolean): Waitable<void> { return {isReady: condition}; } // Coroutine methods cancel(): this { if (this.__blocker?.cancel) { this.__blocker.cancel(); } else { this.__error = new CanceledError(); this.__done = true; } return this; } cancelIf(condition: () => boolean): this { this.__cancellers.push(condition); return this; } scope(entity: Entity): this { CHECK: if (this.__scope) throw new Error('Scope already set for this coroutine'); CHECK: if (this.__cancellers.length) { throw new Error('Scope must be set before any cancelation conditions'); } this.__scope = entity; this.cancelIf(() => !entity.alive); return this; } cancelIfComponentMissing(type: ComponentType<any>): this { CHECK: if (!this.__scope) throw new Error('Required scope not set for this coroutine'); this.cancelIf(() => !this.__scope?.has(type)); return this; } cancelIfCoroutineStarted(coroutineFn?: CoroutineFunction): this { this.__supervisor.registerCancelIfStarted( this, this.__scope, coroutineFn === coDecorator.self ? this.__fn : coroutineFn); return this; } // We need to stub out all the Generator methods because we're overloading the type. They must // not be called by the user, however. return(value: void): IteratorResult<any, void> { throw new Error('Generator methods not available for coroutines'); } throw(e: any): IteratorResult<any, void> { throw new Error('Generator methods not available for coroutines'); } next(...args: [] | [unknown]): IteratorResult<any, void> { throw new Error('Generator methods not available for coroutines'); } [Symbol.iterator](): Generator<any, void, unknown> { throw new Error('Generator methods not available for coroutines'); } } export type CoroutineGenerator = Generator<any, any, any>; export type CoroutineFunction = (...args: any[]) => CoroutineGenerator; type Self = {get self(): CoroutineFunction}; function coDecorator( target: System, name: string, descriptor: TypedPropertyDescriptor<CoroutineFunction> ): TypedPropertyDescriptor<CoroutineFunction> { const coroutine = descriptor.value!; return { value(this: System, ...args: []): CoroutineImpl<unknown> { return this.start(coroutine, ...args) as CoroutineImpl<unknown>; }, }; } coDecorator.waitForFrames = function(frames: number): Waitable<void> { CHECK: checkCurrentCoroutine(); return currentCoroutine!.waitForFrames(frames); }; coDecorator.waitForSeconds = function(seconds: number): Waitable<void> { CHECK: checkCurrentCoroutine(); return currentCoroutine!.waitForSeconds(seconds); }; coDecorator.waitUntil = function(condition: () => boolean): Waitable<void> { CHECK: checkCurrentCoroutine(); return currentCoroutine!.waitUntil(condition); }; coDecorator.cancel = function(): void { CHECK: checkCurrentCoroutine(); currentCoroutine!.cancel(); }; coDecorator.cancelIf = function(condition: () => boolean): CurrentCoroutine { CHECK: checkCurrentCoroutine(); return currentCoroutine!.cancelIf(condition); }; coDecorator.scope = function(entity: Entity): CurrentCoroutine { CHECK: checkCurrentCoroutine(); return currentCoroutine!.scope(entity); }; coDecorator.cancelIfComponentMissing = function(type: ComponentType<any>): CurrentCoroutine { CHECK: checkCurrentCoroutine(); return currentCoroutine!.cancelIfComponentMissing(type); }; coDecorator.cancelIfCoroutineStarted = function(coroutineFn?: CoroutineFunction): CurrentCoroutine { CHECK: checkCurrentCoroutine(); return currentCoroutine!.cancelIfCoroutineStarted(coroutineFn); }; coDecorator.self = function*() {yield;}; function checkCurrentCoroutine(): void { if (!currentCoroutine) throw new Error('Cannot call co methods outside coroutine context'); } /** * This object can be used in two ways: * 1. As a decorator, to wrap coroutine methods in a call to {@link System.start} so you can invoke * them directly. * 2. As a handle to the currently executing coroutine, so you can invoke coroutine control methods * from within the coroutine's code. */ export const co: typeof coDecorator & CurrentCoroutine & Self = coDecorator; export class Supervisor { private readonly coroutines: CoroutineImpl<any>[] = []; private readonly mutuallyExclusiveCoroutines = new Map<string, Coroutine[]>(); constructor(readonly system: System) {} start<CoFn extends CoroutineFunction>(coroutineFn: CoFn, ...args: Parameters<CoFn>): Coroutine { const coroutine = new CoroutineImpl(coroutineFn.apply(this.system, args), coroutineFn, this); this.coroutines.push(coroutine); return coroutine; } execute(): void { // Execute in reverse order, so that the most recently started coroutines execute first. That // way, if coroutine A started coroutine B and is waiting for it to complete, it will resume in // the same frame as B finishes rather than having to wait for another go-around. At the same // time, if new coroutines are started while we're processing, keep iterating to execute the // extra ones within the same frame. let processedLength = 0; while (processedLength < this.coroutines.length) { const endIndex = processedLength; processedLength = this.coroutines.length; for (let i = processedLength - 1; i >= endIndex; i--) { this.system.accessRecentlyDeletedData(false); this.coroutines[i].__checkCancelation(); } for (let i = processedLength - 1; i >= endIndex; i--) { this.system.accessRecentlyDeletedData(false); const coroutine = this.coroutines[i]; coroutine.__step(); if (coroutine.isReady()) { this.coroutines.splice(i, 1); processedLength -= 1; } } } } registerCancelIfStarted( targetCoroutine: Coroutine, scope: Entity | undefined, coroutineFn: CoroutineFunction | undefined ): void { const key = (scope?.__id ?? '') + (coroutineFn?.name ?? ''); if (!this.mutuallyExclusiveCoroutines.has(key)) this.mutuallyExclusiveCoroutines.set(key, []); this.mutuallyExclusiveCoroutines.get(key)?.push(targetCoroutine); } cancelMatching( startingCoroutine: Coroutine, scope: Entity | undefined, coroutineFn: CoroutineFunction ): void { this.cancelMatchingKey(startingCoroutine, ''); this.cancelMatchingKey(startingCoroutine, coroutineFn.name); if (scope) { this.cancelMatchingKey(startingCoroutine, '' + scope.__id); this.cancelMatchingKey(startingCoroutine, '' + scope.__id + coroutineFn.name); } } private cancelMatchingKey(requestingCoroutine: Coroutine, key: string): void { const coroutines = this.mutuallyExclusiveCoroutines.get(key); if (coroutines) { let hasRequesting = false; for (const coroutine of coroutines) { if (coroutine === requestingCoroutine) { hasRequesting = true; } else { coroutine.cancel(); } } coroutines.length = 0; if (hasRequesting) coroutines.push(requestingCoroutine); } } }
the_stack
import * as validators from '../../validate/validators'; import { validatorFactory } from './factory'; // MARK: Custom export const passed = function (options?: any) { return validatorFactory(validators.passed, [], { message: '$field must be passed!', ...options, }); }; export const Passed = passed; // MARK: Common export const accepted = function (options?: any) { return validatorFactory(validators.accepted, [], { message: '$field must be yes,on or 1', ...options, }); }; export const Accepted = accepted; export const is = function (comparison: any, options?: any) { return validatorFactory(validators.is, [comparison], { message: '$field must is $1', ...options, }); }; export const Is = is; export const required = function (options?: any) { return validatorFactory(validators.required, [], { message: '$feild must not be undefined', ...options, }); }; export const Required = required; export const equals = function (comparison: any, options?: any) { return validatorFactory(validators.equals, [comparison], { message: '$field must be equal to $1', ...options, }); }; export const Equals = equals; export const notEquals = function (comparison: any, options?: any) { return validatorFactory(validators.notEquals, [comparison], { message: '$field shoud not equal to $1', ...options, }); }; export const NotEquals = notEquals; export const isEmpty = function (options?: any) { return validatorFactory(validators.isEmpty, [], { message: '$field must be empty', ...options, }); }; export const IsEmpty = isEmpty; export const isNotEmpty = function (options?: any) { return validatorFactory(validators.isNotEmpty, [], { message: '$field should not be empty', ...options, }); }; export const IsNotEmpty = isNotEmpty; // MARK: Number export const isDivisibleBy = function (num: any, options?: any) { return validatorFactory(validators.isDivisibleBy, [num], { message: '$field must be divisible by $1', ...options, }); }; export const IsDivisibleBy = isDivisibleBy; export const isPositive = function (options?: any) { return validatorFactory(validators.isPositive, [], { message: '$field must be a positive number', ...options, }); }; export const IsPositive = isPositive; export const isNegative = function (options?: any) { return validatorFactory(validators.isNegative, [], { message: '$field must be a negative number', ...options, }); }; export const IsNegative = isNegative; export const min = function (min: any, options?: any) { return validatorFactory(validators.min, [min], { message: '$field must not be less than $1', ...options, }); }; export const Min = min; export const max = function (max: any, options?: any) { return validatorFactory(validators.max, [max], { message: '$field must not be greater than $1', ...options, }); }; export const Max = max; // MARK: Date export const afterDate = function (date: any, options?: any) { return validatorFactory(validators.afterDate, [date], { message: '$field date must not be before than $1', ...options, }); }; export const AfterDate = afterDate; export const beforeDate = function (date: any, options?: any) { return validatorFactory(validators.beforeDate, [date], { message: '$field date must not be after than $1', ...options, }); }; export const BeforeDate = beforeDate; // MARK: Type export const isBoolean = function (options?: any) { return validatorFactory(validators.isBoolean, [], { message: '$field must be a boolean value', ...options, }); }; export const IsBoolean = isBoolean; export const isDate = function (options?: any) { return validatorFactory(validators.isDate, [], { message: '$field must be a date value', ...options, }); }; export const IsDate = isDate; export const isString = function (options?: any) { return validatorFactory(validators.isString, [], { message: '$field must be a string value', ...options, }); }; export const IsString = isString; export const isNumber = function (options?: any) { return validatorFactory(validators.isNumber, [], { message: '$field must be a number value', ...options, }); }; export const IsNumber = isNumber; export const isArray = function (options?: any) { return validatorFactory(validators.isArray, [], { message: '$field must be a array value', ...options, }); }; export const IsArray = isArray; export const isError = function (options?: any) { return validatorFactory(validators.isError, [], { message: '$field must be an error', ...options, }); }; export const IsError = isError; export const isFunction = function (options?: any) { return validatorFactory(validators.isFunction, [], { message: '$field must be a function', ...options, }); }; export const IsFunction = isFunction; export const isBuffer = function (options?: any) { return validatorFactory(validators.isBuffer, [], { message: '$field must be a buffer', ...options, }); }; export const IsBuffer = isBuffer; export const isObject = function (options?: any) { return validatorFactory(validators.isObject, [], { message: '$field must be an object value', ...options, }); }; export const IsObject = isObject; export const isRegExp = function (options?: any) { return validatorFactory(validators.isRegExp, [], { message: '$field must be a regexp', ...options, }); }; export const IsRegExp = isRegExp; export const isSymbol = function (options?: any) { return validatorFactory(validators.isSymbol, [], { message: '$field must be a symbol value', ...options, }); }; export const IsSymbol = isSymbol; export const isNullOrUndefined = function (options?: any) { return validatorFactory(validators.isNullOrUndefined, [], { message: '$field must be null or undefined', ...options, }); }; export const IsNullOrUndefined = isNullOrUndefined; export const isNull = function (options?: any) { return validatorFactory(validators.isNull, [], { message: '$field must be null', ...options, }); }; export const IsNull = isNull; export const isUndefined = function (options?: any) { return validatorFactory(validators.isUndefined, [], { message: '$field must be undefined', ...options, }); }; export const IsUndefined = isUndefined; // MARK: String Type export const isDateString = function (options?: any) { return validatorFactory(validators.isDateString, [], { message: '$field must be a date string value', ...options, }); }; export const IsDateString = isDateString; export const isBooleanString = function (options?: any) { return validatorFactory(validators.isBooleanString, [], { message: '$field must be a boolean string value', ...options, }); }; export const IsBooleanString = isBooleanString; export const isNumberString = function (options?: any) { const _options = options ? [options] : []; return validatorFactory(validators.isNumberString, _options, { message: '$field must be a number string value', ...options, }); }; export const IsNumberString = isNumberString; // MARK: String export const contains = function (seed: any, options?: any) { return validatorFactory(validators.contains, [seed], { message: '$field must contain a $1 string', ...options, }); }; export const Contains = contains; export const notContains = function (seed: any, options?: any) { return validatorFactory(validators.notContains, [seed], { message: '$field should not contain a $1 string', ...options, }); }; export const NotContains = notContains; export const isAlpha = function (locale?: any, options?: any) { const defaultMessage = '$field must contain only letters (a-zA-Z)'; if (locale && typeof locale === 'object') { return validatorFactory(validators.isAlpha, [locale.locale], { message: defaultMessage, ...locale, }); } return validatorFactory(validators.isAlpha, [locale], { message: defaultMessage, ...options, }); }; export const IsAlpha = isAlpha; export const isAlphanumeric = function (locale?: any, options?: any) { const defaultMessage = '$field must contain only letters and numbers'; if (locale && typeof locale === 'object') { return validatorFactory(validators.isAlphanumeric, [locale.locale], { message: defaultMessage, ...locale, }); } return validatorFactory(validators.isAlphanumeric, [locale], { message: defaultMessage, ...options, }); }; export const IsAlphanumeric = isAlphanumeric; export const isAscii = function (options?: any) { return validatorFactory(validators.isAscii, [], { message: '$field must contain only ASCII characters', ...options, }); }; export const IsAscii = isAscii; export const isBase64 = function (options?: any) { return validatorFactory(validators.isBase64, [], { message: '$field must be base64 encoded', ...options, }); }; export const IsBase64 = isBase64; export const isByteLength = function (min: any, max: any, options?: any) { return validatorFactory(validators.isByteLength, [min, max], { message: '$field\'s byte length must fall into($1, $2) range', ...options, }); }; export const IsByteLength = isByteLength; export const isCreditCard = function (options?: any) { return validatorFactory(validators.isCreditCard, [], { message: '$field must be a credit card', ...options, }); }; export const IsCreditCard = isCreditCard; export const isCurrency = function (options?: any) { const _options = options ? [options] : []; return validatorFactory(validators.isCurrency, _options, { message: '$field must be a currency', ...options, }); }; export const IsCurrency = isCurrency; export const isEmail = function (options?: any) { const _options = options ? [options] : []; return validatorFactory(validators.isEmail, _options, { message: '$field must be an email', ...options, }); }; export const IsEmail = isEmail; export const isFQDN = function (options?: any) { const _options = options ? [options] : []; return validatorFactory(validators.isFQDN, _options, { message: '$field must be a valid domain name', ...options, }); }; export const IsFQDN = isFQDN; export const isFullWidth = function (options?: any) { return validatorFactory(validators.isFullWidth, [], { message: '$field must contain a full-width characters', ...options, }); }; export const IsFullWidth = isFullWidth; export const isHalfWidth = function (options?: any) { return validatorFactory(validators.isHalfWidth, [], { message: '$field must contain a half-width characters', ...options, }); }; export const IsHalfWidth = isHalfWidth; export const isHexColor = function (options?: any) { return validatorFactory(validators.isHexColor, [], { message: '$field must be a hex color', ...options, }); }; export const IsHexColor = isHexColor; export const isHexadecimal = function (options?: any) { return validatorFactory(validators.isHexadecimal, [], { message: '$field must be a hexadecimal number', ...options, }); }; export const IsHexadecimal = isHexadecimal; export const isIP = function (version?: any, options?: any) { const defaultMessage = '$field must be an ip address'; if (version && typeof version === 'object') { return validatorFactory(validators.isIP, [version.version], { message: defaultMessage, ...version, }); } return validatorFactory(validators.isIP, [version], { message: defaultMessage, ...options, }); }; export const IsIP = isIP; export const isISBN = function (version?: any, options?: any) { const defaultMessage = '$field must be an ISBN'; if (version && typeof version === 'object') { return validatorFactory(validators.isISBN, [version.version], { message: defaultMessage, ...version, }); } return validatorFactory(validators.isISBN, [version], { message: defaultMessage, ...options, }); }; export const IsISBN = isISBN; export const isISSN = function (options?: any) { const _options = options ? [options] : []; return validatorFactory(validators.isISSN, _options, { message: '$field must be an ISSN', ...options, }); }; export const IsISSN = isISSN; export const isISIN = function (options?: any) { return validatorFactory(validators.isISIN, [], { message: '$field must be an ISIN (stock/security identifier)', ...options, }); }; export const IsISIN = isISIN; export const isISO8601 = function (options?: any) { return validatorFactory(validators.isISO8601, [], { message: '$field must be a valid ISO 8601 date string', ...options, }); }; export const IsISO8601 = isISO8601; export const isJSON = function (options?: any) { return validatorFactory(validators.isJSON, [], { message: '$field must be a json string', ...options, }); }; export const IsJSON = isJSON; export const isLowercase = function (options?: any) { return validatorFactory(validators.isLowercase, [], { message: '$field must be a lowercase string', ...options, }); }; export const IsLowercase = isLowercase; export const isMobilePhone = function (locale?: any, options?: any) { if (locale && typeof locale === 'object') { return validatorFactory(validators.isMobilePhone, [locale.locale, locale], locale); } return validatorFactory(validators.isMobilePhone, [locale, options], { message: '$field must be a mobile phone number', ...options, }); }; export const IsMobilePhone = isMobilePhone; export const isMongoId = function (options?: any) { return validatorFactory(validators.isMongoId, [], { message: '$field must be a mongodb id', ...options, }); }; export const IsMongoId = isMongoId; export const isMultibyte = function (options?: any) { return validatorFactory(validators.isMultibyte, [], { message: '$field must contain one or more multibyte chars', ...options, }); }; export const IsMultibyte = isMultibyte; export const isSurrogatePair = function (options?: any) { return validatorFactory(validators.isSurrogatePair, [], { message: '$field must contain any surrogate pairs chars', ...options, }); }; export const IsSurrogatePair = isSurrogatePair; export const isURL = function (options?: any) { const _options = options ? [options] : []; return validatorFactory(validators.isURL, _options, { message: '$field must be an URL address', ...options, }); }; export const IsURL = isURL; export const isUUID = function (version?: any, options?: any) { const defaultMessage = '$field must be an UUID'; if (version && typeof version === 'object') { return validatorFactory(validators.isUUID, [version.version], { message: defaultMessage, ...version, }); } return validatorFactory(validators.isUUID, [version], { message: defaultMessage, ...options, }); }; export const IsUUID = isUUID; export const isUppercase = function (options?: any) { return validatorFactory(validators.isUppercase, [], { message: '$field must be an uppercase string', ...options, }); }; export const IsUppercase = isUppercase; export const length = function (min: any, max: any, options?: any) { return validatorFactory(validators.length, [min, max], { message: '$field must be between $1 and $2', ...options, }); }; export const Length = length; export const minLength = function (min: any, options?: any) { return validatorFactory(validators.minLength, [min], { message: '$field must not be shorter than $1', ...options, }); }; export const MinLength = minLength; export const maxLength = function (max: any, options?: any) { return validatorFactory(validators.maxLength, [max], { message: '$field must not be longer than $1', ...options, }); }; export const MaxLength = maxLength; export const matches = function (pattern: any, modifiers?: any, options?: any) { const defaultMessage = '$field must match $1 regular expression'; if (modifiers && typeof modifiers === 'object') { return validatorFactory( validators.matches, [pattern, modifiers.modifiers, modifiers], { message: defaultMessage, ...modifiers, }, ); } return validatorFactory(validators.matches, [pattern, modifiers, options], { message: defaultMessage, ...options, }); }; export const Matches = matches;
the_stack
import * as vscode from "vscode"; import axios from "axios"; import { writeFile, unlink } from "fs"; import { UserDataFolder } from "../common/UserDataFolder"; import { RestyaBoard, RestyaboardList, RestyaboardCard, RestyaboardChecklist, RestyaboardActionComment, CheckItem, RestyaboardMember, RestyaboardLabel } from "./restyaboardComponents"; import { RestyaboardItem } from "./RestyaboardItem"; import { VSCODE_VIEW_COLUMN, TEMP_RESTYABOARD_FILE_NAME, SETTING_PREFIX, SETTING_CONFIG, GLOBALSTATE_CONFIG, } from "./constants"; export class RestyaboardUtils { private globalState: any; private API_TOKEN: string | undefined; private SITE_URL: string | undefined; private tempRestyaboardFile: string; constructor(context?: vscode.ExtensionContext) { this.globalState = context ? context.globalState : {}; this.tempRestyaboardFile = new UserDataFolder().getPathCodeSettings() + TEMP_RESTYABOARD_FILE_NAME || ""; this.getCredentials(); this.setMarkdownPreviewBreaks(); } setMarkdownPreviewBreaks(): void { try { const config = vscode.workspace.getConfiguration("markdown.preview", null); const showPreviewBreaks = config.get<boolean>("breaks"); if (!showPreviewBreaks) { config.update("breaks", true, true); } } catch (error) { console.error(error); } } isCredentialsProvided(): boolean { return (!this.API_TOKEN && !this.SITE_URL); } getCredentials(): void { try { this.API_TOKEN = this.globalState.get(GLOBALSTATE_CONFIG.API_TOKEN); this.SITE_URL = this.globalState.get(GLOBALSTATE_CONFIG.SITE_URL); } catch (error) { console.error(error); vscode.window.showErrorMessage("Error getting credentials"); } } setRestyaboardCredential(isPassword: boolean, placeHolderText: string): Thenable<string | undefined> { return vscode.window.showInputBox({ ignoreFocusOut: true, password: isPassword, placeHolder: placeHolderText }); } // Allows user to set api key and token directly using the vscode input box async setCredentials(): Promise<void> { try { const siteURL = await this.setRestyaboardCredential(false, "Your RestyaBoard URL"); const apiToken = await this.setRestyaboardCredential(true, "Your Restyaboard API token"); if (siteURL !== undefined) this.globalState.update(GLOBALSTATE_CONFIG.SITE_URL, siteURL); if (apiToken !== undefined) this.globalState.update(GLOBALSTATE_CONFIG.API_TOKEN, apiToken); this.getCredentials(); } catch (error) { console.error(error); vscode.window.showErrorMessage("Error while setting credentials"); } } // Generates a Restyaboard API token and opens link in external browser async fetchApiToken(siteURL: string): Promise<void> { const apiTokenUrl = `${siteURL}/oauth/authorize?response_type=code&client_id=9335847554774492&scope=read%20write&state=1562312999016&redirect_uri=${siteURL}/apps/r_visualstudio/login.html`; try { vscode.commands.executeCommand("vscode.open", vscode.Uri.parse(apiTokenUrl)); const apiToken = await this.setRestyaboardCredential(true, "Your Restya Access token"); if (apiToken !== undefined) this.globalState.update(GLOBALSTATE_CONFIG.API_TOKEN, apiToken); if (siteURL !== undefined) this.globalState.update(GLOBALSTATE_CONFIG.SITE_URL, siteURL); } catch (error) { console.error(error); vscode.window.showErrorMessage("Error fetching API token"); } } // Opens browser links for user to get Restyaboard API Key and then Token async authenticate(): Promise<void> { try { const siteURL = await this.setRestyaboardCredential(false, "Your RestyaBoard URL"); if (siteURL !== undefined) { this.globalState.update(GLOBALSTATE_CONFIG.SITE_URL, siteURL); await this.fetchApiToken(siteURL); this.getCredentials(); } else { await vscode.window.showInformationMessage( "Get your Restyaboard Access Token by entering your restyaboard URL"); } vscode.commands.executeCommand("restyaboardViewer.refresh"); } catch (error) { console.error(error); vscode.window.showErrorMessage("Error during authentication"); } } // Deletes all saved info in globalstate (key, token, favouriteList) resetCredentials(): void { Object.keys(GLOBALSTATE_CONFIG).forEach(key => { const value: string = GLOBALSTATE_CONFIG[key]; this.globalState.update(value, undefined); }); vscode.window.showInformationMessage("Credentials have been reset"); this.getCredentials(); vscode.commands.executeCommand("restyaboardViewer.refresh"); } showRestyaboardInfo(): void { this.getCredentials(); const info = ` API_TOKEN = ${this.API_TOKEN}, SITE_URL = ${this.SITE_URL} `; vscode.window.showInformationMessage(info); } async showSuccessMessage(msg: string, url?: string) { let cardUrl; if (url) { cardUrl = await vscode.window.showInformationMessage(msg, url); if (cardUrl) { vscode.commands.executeCommand("vscode.open", vscode.Uri.parse(cardUrl)); } } else { vscode.window.showInformationMessage(msg); } } async restyaboardApiGetRequest(url: string, params: object): Promise<any> { try { axios.defaults.baseURL = this.SITE_URL; const res = await axios.get(url, { params }); return (res.data.data)? res.data.data: []; } catch (error) { if (error.response) { console.error("GET error", error.response); vscode.window.showErrorMessage(`HTTP error: ${error.response.status} - ${error.response.data}`); } } return null; } async restyaboardApiSingleGetRequest(url: string, params: object): Promise<any> { try { axios.defaults.baseURL = this.SITE_URL; const res = await axios.get(url, { params }); return res.data; } catch (error) { if (error.response) { console.error("GET error", error.response); vscode.window.showErrorMessage(`HTTP error: ${error.response.status} - ${error.response.data}`); } } return null; } async restyaboardApiPostRequest(url: string, data: object): Promise<any> { try { axios.defaults.baseURL = this.SITE_URL; const res = await axios.post(url, data); return res; } catch (error) { if (error.response) { console.error("POST error", error.response); vscode.window.showErrorMessage(`HTTP error: ${error.response.status} - ${error.response.data}`); } } return null; } async restyaboardApiPutRequest(url: string, data: object): Promise<any> { try { axios.defaults.baseURL = this.SITE_URL; const res = await axios.put(url, data); return res.data; } catch (error) { if (error.response) { console.error("PUT error", error.response); vscode.window.showErrorMessage(`HTTP error: ${error.response.status} - ${error.response.data}`); } } return null; } async restyaboardApiDeleteRequest(url: string, params: object): Promise<any> { try { axios.defaults.baseURL = this.SITE_URL; const res = await axios.delete(url, { params }); return res.data; } catch (error) { if (error.response) { console.error("DELETE error", error.response); vscode.window.showErrorMessage(`HTTP error: ${error.response.status} - ${error.response.data}`); } } return null; } async getBoardById(boardId: string): Promise<RestyaBoard> { const res = await this.restyaboardApiSingleGetRequest(`/api/v1/boards/${boardId}.json`, { token: this.API_TOKEN, }); return res; } async getListById(listId: string): Promise<RestyaboardList> { const list = await this.restyaboardApiGetRequest(`/api/v1/lists/${listId}`, { token: this.API_TOKEN, }); return list; } getBoards(starredBoards?: boolean): Promise<RestyaBoard[]> { const res = this.restyaboardApiGetRequest("/api/v1/boards.json", { filter: starredBoards ? "starred" : "all", type: 'simple', token: this.API_TOKEN, }); console.log(JSON.stringify(res)); return res; } getListsFromBoard(boardId: string): Promise<RestyaboardList[]> { const res = this.restyaboardApiGetRequest(`/api/v1/boards/${boardId}/lists.json`, { token: this.API_TOKEN, }); return res; } getCardsFromList(listId: string, boardId: string): Promise<RestyaboardCard[]> { const res = this.restyaboardApiGetRequest(`/api/v1/boards/${boardId}/lists/${listId}/cards.json`, { token: this.API_TOKEN, }); return res; } getCardById(cardId: string, boardId: string | undefined, listId: string | undefined): Promise<RestyaboardCard> { const res = this.restyaboardApiSingleGetRequest(`/api/v1/boards/${boardId}/lists/${listId}/cards/${cardId}.json`, { token: this.API_TOKEN, }); return res; } getcardComments(cardId: string, boardId: string | undefined, listId: string | undefined): Promise<RestyaboardCard> { const res = this.restyaboardApiGetRequest(`/api/v1/boards/${boardId}/lists/${listId}/cards/${cardId}/activities.json`, { token: this.API_TOKEN, view:'modal_card', mode:'comment' }); return res; } async addCardToList(list: RestyaboardItem): Promise<Number> { if (!list) { vscode.window.showErrorMessage("Could not get valid list"); return 1; } const cardName = await vscode.window.showInputBox({ ignoreFocusOut: true, placeHolder: "Enter name of card" }); if (cardName === undefined) return 2; const resData = await this.restyaboardApiPostRequest(`/api/v1/boards/${list.boardId}/lists/${list.id}/cards.json?token=${this.API_TOKEN}`, { list_id: list.id, name: cardName, is_offline:true, board_id:list.boardId, }); if (!resData) return 3; vscode.commands.executeCommand("restyaboardViewer.refresh"); let card_url = this.SITE_URL+'/#/board/'+list.boardId+'/card/'+resData.data.activity.card_id; this.showSuccessMessage(`Created Card: ${resData.data.activity.card_id}-${resData.data.activity.card_name}`, card_url); return 0; } async editTitle(card: RestyaboardItem): Promise<Number> { if (!card) { vscode.window.showErrorMessage("Could not get valid card"); return 1; } const restyaboardCard: RestyaboardCard = await this.getCardById(card.id, card.boardId, card.listId); const name = await vscode.window.showInputBox({ ignoreFocusOut: true, value: restyaboardCard.title }); if (name === undefined) return 2; const resData = await this.restyaboardApiPutRequest(`/api/v1/boards/${card.boardId}/lists/${card.listId}/cards/${card.id}.json?token=${this.API_TOKEN}`, { name, }); if (!resData) return 3; vscode.commands.executeCommand("restyaboardViewer.refresh"); this.showSuccessMessage(`Updated title for card: ${name}`); return 0; } async editDescription(card: RestyaboardItem): Promise<Number> { if (!card) { vscode.window.showErrorMessage("Could not get valid card"); return 1; } const restyaboardCard: RestyaboardCard = await this.getCardById(card.id, card.boardId, card.listId); // parse new line chars and remove quotes from start and end let descRaw = JSON.stringify(restyaboardCard.description); descRaw = descRaw.slice(1, descRaw.length - 1); const descUpdated = await vscode.window.showInputBox({ ignoreFocusOut: true, value: descRaw, placeHolder: "Enter description for card", }); if (descUpdated === undefined) return 2; // replaces "\n" with javascript return character required for Restyaboard api const description = descUpdated.replace(/\\n/g, "\x0A"); const resData = await this.restyaboardApiPutRequest(`/api/v1/boards/${card.boardId}/lists/${card.listId}/cards/${card.id}.json?token=${this.API_TOKEN}`, { description, }); if (!resData) return 3; vscode.commands.executeCommand("restyaboardViewer.refresh"); this.showSuccessMessage(`Updated description for card: ${resData.activity.description}`); return 0; } async addComment(card: RestyaboardItem): Promise<Number> { if (!card) { vscode.window.showErrorMessage("Could not get valid card"); return 1; } const user: any = await this.getSelf(); const comment = await vscode.window.showInputBox({ ignoreFocusOut: true, placeHolder: "Add comment", }); if (comment === undefined) return 2; const resData = await this.restyaboardApiPostRequest(`/api/v1/boards/${card.boardId}/lists/${card.listId}/cards/${card.id}/comments.json?token=${this.API_TOKEN}`, { board_id:card.boardId, card_id:card.id, is_offline:true, list_id:card.listId, user_id:user.id, comment: comment, }); if (!resData) return 3; vscode.commands.executeCommand("restyaboardViewer.refresh"); this.showSuccessMessage(`Added comment to card: ${card.label}`); return 0; } private getSelf(): Promise<RestyaboardMember> { return this.restyaboardApiSingleGetRequest(`/api/v1/users/me.json`, { token: this.API_TOKEN, }); } async addSelfToCard(card: RestyaboardItem): Promise<Number> { if (!card) { vscode.window.showErrorMessage("Could not get valid Card"); return 1; } const user: any = await this.getSelf(); const resData = await this.restyaboardApiPostRequest(`/api/v1/boards/${card.boardId}/lists/${card.listId}/cards/${card.id}/users/${user.id}.json?token=${this.API_TOKEN}`, { card_id: card.id, user_id: user.id, }); if (!resData) return 3; vscode.commands.executeCommand("restyaboardViewer.refresh"); this.showSuccessMessage(`Added user ${user.user.initials} to card`); return 0; } async removeSelfFromCard(card: RestyaboardItem): Promise<Number> { if (!card) { vscode.window.showErrorMessage("Could not get valid Card"); return 1; } const user: any = await this.getSelf(); const usersOnCard = await this.getCardById(card.id, card.boardId, card.listId); if (!usersOnCard.cards_users && !usersOnCard.cards_users.length) { vscode.window.showErrorMessage("Card not assigned to you!."); return 3; } let removeUser = usersOnCard.cards_users.find((useroncard: any) => useroncard.user_id == user.id); if (!removeUser){ vscode.window.showErrorMessage("Card not assigned to you!."); return 3; } const resData = await this.restyaboardApiDeleteRequest(`/api/v1/boards/${card.boardId}/lists/${card.listId}/cards/${card.id}/cards_users/${removeUser.id}.json`, { token: this.API_TOKEN, }); if (!resData) return 3; vscode.commands.executeCommand("restyaboardViewer.refresh"); this.showSuccessMessage(`Removed user ${user.user.initials} from card`); return 0; } async addUserToCard(card: RestyaboardItem): Promise<Number> { if (!card) { vscode.window.showErrorMessage("Could not get valid Card"); return 1; } const board_details = await this.getBoardById(card.boardId || "-1"); const usersOnBoard = board_details.boards_users; if (!usersOnBoard) return 3; const quickPickUsers = usersOnBoard.map((user: any) => { return { label: user.full_name, userId: user.user_id, }; }); const addUser : any = await vscode.window.showQuickPick(quickPickUsers, { placeHolder: "Add user from board:" }); if (addUser === undefined) return 2; const resData = await this.restyaboardApiPostRequest(`/api/v1/boards/${card.boardId}/lists/${card.listId}/cards/${card.id}/users/${addUser.userId}.json?token=${this.API_TOKEN}`, { card_id: card.id, user_id: addUser.userId, }); if (!resData) return 3; vscode.commands.executeCommand("restyaboardViewer.refresh"); this.showSuccessMessage(`Added user ${addUser.label} to card`); return 0; } async removeUserFromCard(card: RestyaboardItem): Promise<Number> { if (!card) { vscode.window.showErrorMessage("Could not get valid Card"); return 1; } const usersOnCard = await this.getCardById(card.id, card.boardId, card.listId); if (!usersOnCard) return 3; const quickPickUsers = usersOnCard.cards_users.map((user: any) => { return { label: user.full_name, userId: user.id, }; }); const removeUser : any = await vscode.window.showQuickPick(quickPickUsers, { placeHolder: "Remove user from board:" }); if (removeUser === undefined) return 2; const resData = await this.restyaboardApiDeleteRequest(`/api/v1/boards/${card.boardId}/lists/${card.listId}/cards/${card.id}/cards_users/${removeUser.userId}.json`, { token: this.API_TOKEN, }); if (!resData) return 3; vscode.commands.executeCommand("restyaboardViewer.refresh"); this.showSuccessMessage(`Removed user ${removeUser.label} from card`); return 0; } async moveCardToList(card: RestyaboardItem): Promise<Number> { if (!card) { vscode.window.showErrorMessage("Could not get valid card"); return 1; } const listsForBoard = await this.getListsFromBoard(card.boardId || "-1"); if (!listsForBoard) return 3; const quickPickLists = listsForBoard.map(list => { return { label: list.name, listId: list.id, }; }); const restyaboardCard: RestyaboardCard = await this.getCardById(card.id, card.boardId, card.listId); const toList = await vscode.window.showQuickPick(quickPickLists, { placeHolder: "Move card to list:" }); if (toList === undefined) return 2; const resData = await this.restyaboardApiPutRequest(`/api/v1/boards/${card.boardId}/lists/${card.listId}/cards/${card.id}.json?token=${this.API_TOKEN}`, { list_id: toList.listId, board_id:card.boardId, position:restyaboardCard.position }); if (!resData) return 3; vscode.commands.executeCommand("restyaboardViewer.refresh"); this.showSuccessMessage(`Moved card to list: ${toList.label}`); return 0; } async archiveCard(card: RestyaboardItem): Promise<Number> { if (!card) { vscode.window.showErrorMessage("Could not get valid card"); return 1; } const resData = await this.restyaboardApiPutRequest(`/api/v1/boards/${card.boardId}/lists/${card.listId}/cards/${card.id}.json?token=${this.API_TOKEN}`, { is_archived: 1, }); if (!resData) return 3; vscode.commands.executeCommand("restyaboardViewer.refresh"); let card_url = this.SITE_URL+'/#/board/'+card.boardId+'/card/'+resData.activity.card_id; this.showSuccessMessage(`Archived Card: ${resData.activity.card_id}-${resData.activity.card_name}`, card_url); return 0; } showCardMembersAsString(members: RestyaboardMember[]): string { if (!members || members.length == 0) { return ""; } return members.map(member => member.initials).join(", "); } showCardLabelsAsString(labels: RestyaboardLabel[]): string { if (!labels || labels.length == 0) { return ""; } return labels.map(label => label.name).join(", "); } showChecklistsAsMarkdown(checklists: RestyaboardChecklist[]): string { if (!checklists || checklists.length == 0) { return ""; } let checklistMarkdown: string = ""; checklists.map(checklist => { checklistMarkdown += `\n> ${checklist.name}\n\n`; checklist.checklists_items .sort((checkItem1: CheckItem, checkItem2: CheckItem) => checkItem1.position - checkItem2.position) .map((checkItem: CheckItem) => { checklistMarkdown += checkItem.is_completed == "1" ? `✅ ~~${checkItem.name}~~ \n` : `🔳 ${checkItem.name} \n`; }); }); return checklistMarkdown; } showCommentsAsMarkdown(comments: RestyaboardActionComment[]): string { if (!comments || comments.length == 0) { return ""; } let commentsMarkdown: string = ""; comments.map((comment: RestyaboardActionComment) => { const date = new Date(comment.created); const dateString = `${date.toLocaleString("en-GB", { day: "2-digit", month: "short", year: "numeric" })}`; const timeString = `${date.toLocaleString("en-GB", { hour: "2-digit", minute: "2-digit", hour12: true, })}`; let depth_string: string = ""; for(let i=0; i<=comment.depth; i++){ depth_string += '>'; } commentsMarkdown += `\n${depth_string} ${comment.full_name} - ${dateString} at ${timeString} ${ comment.revisions ? "(edited)" : "" } \n`; commentsMarkdown += `\n\n${comment.comment}\n\n`; }); return commentsMarkdown; } showMarkdownDecorated(header: string, content: string | undefined): string { return content ? `## **\`${header}\`** \n${content}\n\n--- \n` : ""; } async showCard(card: RestyaboardCard): Promise<void> { if (!card) { vscode.window.showErrorMessage("No card selected or invalid card."); return; } let Cardcomments: any = await this.getcardComments(card.id, card.board_id, card.list_id); const cardMembers: string = this.showCardMembersAsString(card.cards_users); const cardLabels: string = this.showCardLabelsAsString(card.cards_labels); const checklistItems: string = this.showChecklistsAsMarkdown(card.cards_checklists); const commentItems: string = this.showCommentsAsMarkdown(Cardcomments); const cardCoverImageUrl = !!card.attachments && card.attachments.length > 0 ? card.attachments[0].url : ""; const cardContentAndHeaders = [ { header: "URL", content: card.url }, { header: "Title", content: card.name }, { header: "Board Name", content: card.board_name }, { header: "List Name", content: card.list_name }, { header: "Members", content: cardMembers }, { header: "Labels", content: cardLabels }, { header: "Description", content: card.description }, { header: "Checklists", content: checklistItems }, { header: "Comments", content: commentItems }, ]; if(card.due_date){ cardContentAndHeaders.push( { header: "Due Date", content: card.due_date }); } let cardContent: string = ""; // cardContent += "| Board Name | List Name |\n| ------------- | ------------- |\n| "+card.board_name+" | "+card.list_name+" |\n"; cardContentAndHeaders.map(({ header, content }) => { cardContent += this.showMarkdownDecorated(header, content); }); cardContent += cardCoverImageUrl ? `<img src="${cardCoverImageUrl}" alt="Image not found" />` : ""; // Write temp markdown file at user's vs code default settings directory writeFile(this.tempRestyaboardFile, cardContent, err => { if (err) { vscode.window.showErrorMessage(`Error writing to temp file: ${err}`); } console.info(`✍ Writing to file: ${this.tempRestyaboardFile}`); }); // open markdown file and preview view let viewColumn: vscode.ViewColumn = vscode.workspace.getConfiguration(SETTING_PREFIX, null).get(SETTING_CONFIG.VIEW_COLUMN) || SETTING_CONFIG.DEFAULT_VIEW_COLUMN; if (!(VSCODE_VIEW_COLUMN.indexOf(viewColumn) > -1)) { vscode.window.showInformationMessage(`Invalid ${SETTING_PREFIX}.viewColumn ${viewColumn} specified`); viewColumn = SETTING_CONFIG.DEFAULT_VIEW_COLUMN; } const doc = await vscode.workspace.openTextDocument(this.tempRestyaboardFile); await vscode.window.showTextDocument(doc, viewColumn, false); await vscode.commands.executeCommand("markdown.showPreview"); vscode.commands.executeCommand("markdown.preview.toggleLock"); } } export function removeTempRestyaboardFile() { const userDataFolder = new UserDataFolder(); const tempRestyaboardFile = userDataFolder.getPathCodeSettings() + TEMP_RESTYABOARD_FILE_NAME; unlink(tempRestyaboardFile, err => { if (err) throw err; console.info(`❌ Deleted file: ${tempRestyaboardFile}`); }); }
the_stack
export declare type Arrayish = string | ArrayLike<number>; export declare abstract class BigNumber { abstract fromTwos(value: number): BigNumber; abstract toTwos(value: number): BigNumber; abstract add(other: BigNumberish): BigNumber; abstract sub(other: BigNumberish): BigNumber; abstract div(other: BigNumberish): BigNumber; abstract mul(other: BigNumberish): BigNumber; abstract mod(other: BigNumberish): BigNumber; abstract pow(other: BigNumberish): BigNumber; abstract maskn(value: number): BigNumber; abstract eq(other: BigNumberish): boolean; abstract lt(other: BigNumberish): boolean; abstract lte(other: BigNumberish): boolean; abstract gt(other: BigNumberish): boolean; abstract gte(other: BigNumberish): boolean; abstract isZero(): boolean; abstract toNumber(): number; abstract toString(): string; abstract toHexString(): string; } export declare type BigNumberish = BigNumber | string | number | Arrayish; export declare type ConnectionInfo = { url: string; user?: string; password?: string; allowInsecure?: boolean; }; export interface OnceBlockable { once(eventName: "block", handler: () => void): void; } export declare type PollOptions = { timeout?: number; floor?: number; ceiling?: number; interval?: number; onceBlock?: OnceBlockable; }; export declare type SupportedAlgorithms = 'sha256' | 'sha512'; export interface Signature { r: string; s: string; recoveryParam?: number; v?: number; } export declare type Network = { name: string; chainId: number; ensAddress?: string; }; export declare type Networkish = Network | string | number; export declare type CoerceFunc = (type: string, value: any) => any; export declare type ParamType = { name?: string; type: string; indexed?: boolean; components?: Array<any>; }; export declare type EventFragment = { type: string; name: string; anonymous: boolean; inputs: Array<ParamType>; }; export declare type FunctionFragment = { type: string; name: string; constant: boolean; inputs: Array<ParamType>; outputs: Array<ParamType>; payable: boolean; stateMutability: string; }; export declare type UnsignedTransaction = { to?: string; nonce?: number; gasLimit?: BigNumberish; gasPrice?: BigNumberish; data?: Arrayish; value?: BigNumberish; chainId?: number; }; export interface Transaction { hash?: string; to?: string; from?: string; nonce: number; gasLimit: BigNumber; gasPrice: BigNumber; data: string; value: BigNumber; chainId: number; r?: string; s?: string; v?: number; } export declare type BlockTag = string | number; export interface Block { hash: string; parentHash: string; number: number; timestamp: number; nonce: string; difficulty: number; gasLimit: BigNumber; gasUsed: BigNumber; miner: string; extraData: string; transactions: Array<string>; } export declare type Filter = { fromBlock?: BlockTag; toBlock?: BlockTag; address?: string; topics?: Array<string | Array<string>>; }; export interface Log { blockNumber?: number; blockHash?: string; transactionIndex?: number; removed?: boolean; transactionLogIndex?: number; address: string; data: string; topics: Array<string>; transactionHash?: string; logIndex?: number; } export interface TransactionReceipt { contractAddress?: string; transactionIndex?: number; root?: string; gasUsed?: BigNumber; logsBloom?: string; blockHash?: string; transactionHash?: string; logs?: Array<Log>; blockNumber?: number; cumulativeGasUsed?: BigNumber; byzantium: boolean; status?: number; } export declare type TransactionRequest = { to?: string | Promise<string>; from?: string | Promise<string>; nonce?: number | string | Promise<number | string>; gasLimit?: BigNumberish | Promise<BigNumberish>; gasPrice?: BigNumberish | Promise<BigNumberish>; data?: Arrayish | Promise<Arrayish>; value?: BigNumberish | Promise<BigNumberish>; chainId?: number | Promise<number>; }; export interface TransactionResponse extends Transaction { blockNumber?: number; blockHash?: string; timestamp?: number; from: string; raw?: string; wait: (timeout?: number) => Promise<TransactionReceipt>; } export declare abstract class Indexed { readonly hash: string; } export interface DeployDescription { readonly inputs: Array<ParamType>; readonly payable: boolean; encode(bytecode: string, params: Array<any>): string; } export interface FunctionDescription { readonly type: "call" | "transaction"; readonly name: string; readonly signature: string; readonly sighash: string; readonly inputs: Array<ParamType>; readonly outputs: Array<ParamType>; readonly payable: boolean; encode(params: Array<any>): string; decode(data: string): any; } export interface EventDescription { readonly name: string; readonly signature: string; readonly inputs: Array<ParamType>; readonly anonymous: boolean; readonly topic: string; encodeTopics(params: Array<any>): Array<string>; decode(data: string, topics?: Array<string>): any; } export interface LogDescription { readonly name: string; readonly signature: string; readonly topic: string; readonly values: Array<any>; } export interface TransactionDescription { readonly name: string; readonly args: Array<any>; readonly signature: string; readonly sighash: string; readonly decode: (data: string) => any; readonly value: BigNumber; } export declare type ContractFunction = (...params: Array<any>) => Promise<any>; export declare type EventFilter = { address?: string; topics?: Array<string>; }; export interface Event extends Log { args: Array<any>; decode: (data: string, topics?: Array<string>) => any; event: string; eventSignature: string; removeListener: () => void; getBlock: () => Promise<Block>; getTransaction: () => Promise<TransactionResponse>; getTransactionReceipt: () => Promise<TransactionReceipt>; } export declare type EventType = string | Array<string> | Filter; export declare type Listener = (...args: Array<any>) => void; /** * Provider * * Note: We use an abstract class so we can use instanceof to determine if an * object is a Provider. */ export declare abstract class MinimalProvider implements OnceBlockable { abstract getNetwork(): Promise<Network>; abstract getBlockNumber(): Promise<number>; abstract getGasPrice(): Promise<BigNumber>; abstract getBalance(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<BigNumber>; abstract getTransactionCount(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<number>; abstract getCode(addressOrName: string | Promise<string>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>; abstract getStorageAt(addressOrName: string | Promise<string>, position: BigNumberish | Promise<BigNumberish>, blockTag?: BlockTag | Promise<BlockTag>): Promise<string>; abstract sendTransaction(signedTransaction: string | Promise<string>): Promise<TransactionResponse>; abstract call(transaction: TransactionRequest): Promise<string>; abstract estimateGas(transaction: TransactionRequest): Promise<BigNumber>; abstract getBlock(blockHashOrBlockTag: BlockTag | string | Promise<BlockTag | string>): Promise<Block>; abstract getTransaction(transactionHash: string): Promise<TransactionResponse>; abstract getTransactionReceipt(transactionHash: string): Promise<TransactionReceipt>; abstract getLogs(filter: Filter): Promise<Array<Log>>; abstract resolveName(name: string | Promise<string>): Promise<string>; abstract lookupAddress(address: string | Promise<string>): Promise<string>; abstract on(eventName: EventType, listener: Listener): MinimalProvider; abstract once(eventName: EventType, listener: Listener): MinimalProvider; abstract listenerCount(eventName?: EventType): number; abstract listeners(eventName: EventType): Array<Listener>; abstract removeAllListeners(eventName: EventType): MinimalProvider; abstract removeListener(eventName: EventType, listener: Listener): MinimalProvider; abstract waitForTransaction(transactionHash: string, timeout?: number): Promise<TransactionReceipt>; } export declare type AsyncProvider = { isMetaMask?: boolean; host?: string; path?: string; sendAsync: (request: any, callback: (error: any, response: any) => void) => void; }; export declare type ProgressCallback = (percent: number) => void; export declare type EncryptOptions = { iv?: Arrayish; entropy?: Arrayish; mnemonic?: string; path?: string; client?: string; salt?: Arrayish; uuid?: string; scrypt?: { N?: number; r?: number; p?: number; }; }; /** * Signer * * Note: We use an abstract class so we can use instanceof to determine if an * object is a Signer. */ export declare abstract class Signer { provider?: MinimalProvider; abstract getAddress(): Promise<string>; abstract signMessage(message: Arrayish | string): Promise<string>; abstract sendTransaction(transaction: TransactionRequest): Promise<TransactionResponse>; } export declare abstract class HDNode { readonly privateKey: string; readonly publicKey: string; readonly mnemonic: string; readonly path: string; readonly chainCode: string; readonly index: number; readonly depth: number; abstract derivePath(path: string): HDNode; } export interface Wordlist { locale: string; getWord(index: number): string; getWordIndex(word: string): number; split(mnemonic: string): Array<string>; join(words: Array<string>): string; } //# sourceMappingURL=types.d.ts.map
the_stack
module Kiwi.Files { /** * Base class which handles the loading of an external data file an xhr. * TextureFile, AudioFile contain fallback loading via tags and all extended Files contain methods for processing the files. * * Also can contain information about the file (like file size, last modified, e.t.c.) * Uses an object literal in its constructor since 1.2 (which is preferred), but also contains previous construction support. * * @class File * @namespace Kiwi.Files * @constructor * @param game {Kiwi.Game} The game that this file is for * @param params {Object} Options for this file. * @param params.key {String} User defined name for this file. This would be how the user would access it in the file store. * @param params.url {String} Location of the file to be loaded. * @param {Object} [params.metadata={}] Any metadata to be associated with the file. * @param [params.state=null] {Kiwi.State} The state that this file belongs to. Used for defining global assets vs local assets. * @param [params.fileStore=null] {Kiwi.Files.FileStore} The filestore that this file should be save in automatically when loaded. * @param [params.type=UNKNOWN] {Number} The type of file this is. * @param [params.tags] {Array} Any tags to be associated with this file. * @param [params.timeout=TIMEOUT_DELAY] {Number} Sets the timeout delay when loading via ajax. * @return {Kiwi.Files.File} * */ export class File { constructor(game: Kiwi.Game, params:any) { this.game = game; this.onComplete = new Kiwi.Signal; this.onProgress = new Kiwi.Signal; if (Kiwi.Utils.Common.isNumeric(params)) { //Deprecate this._parseParamsOld(params, arguments[2], arguments[3], arguments[4], arguments[5]); } else { this.key = params.key; this._assignFileDetails(params.url); this.parseParams(params); } } /** * Assigns properties and variables for the constructor as in pre 1.2 Kiwi versions. * * @method _parseParamsOld * @since 1.2.0 * @param dataType {Number} The type of file that is being loaded. For this you can use the STATIC properties that are located on this class for quick code completion. * @param path {String} The location of the file that is to be loaded. * @param [name=''] {String} A name for the file. If no name is specified then the files name will be used. * @param [saveToFileStore=true] {Boolean} If the file should be saved on the file store or not. * @param [storeAsGlobal=true] {Boolean} If this file should be stored as a global file, or if it should be destroyed when this state gets switched out. * @private */ private _parseParamsOld(dataType: number, url: string, name: string = '', saveToFileStore: boolean = true, storeAsGlobal: boolean = true) { this.dataType = dataType; this._assignFileDetails(url); if (saveToFileStore) { this.fileStore = this.game.fileStore; } if (this.game.states.current && !storeAsGlobal) { this.ownerState = this.game.states.current; } } /** * Sets properties for this instance based on an object literal passed. Used when the class is being created. * * @method parseParams * @since 1.2.0 * @param [params] {Object} * @param [params.metadata={}] {Object} Any metadata to be associated with the file. * @param [params.state=null] {Kiwi.State} The state that this file belongs to. Used for defining global assets vs local assets. * @param [params.fileStore=null] {Kiwi.Files.FileStore} The filestore that this file should be save in automatically when loaded. * @param [params.type=UNKNOWN] {Number} The type of file this is. * @param [params.tags] {Array} Any tags to be associated with this file. * @param [params.timeout=TIMEOUT_DELAY] {Number} Sets the timeout delay when loading via ajax. * @protected */ protected parseParams(params: any) { this.fileStore = params.fileStore || null; this.ownerState = params.state || null; this.metadata = params.metadata || {}; if ( Kiwi.Utils.Common.isUndefined(params.timeout) ) { this.timeOutDelay = params.timeout; } else { this.timeOutDelay = Kiwi.Files.File.TIMEOUT_DELAY; } if (Kiwi.Utils.Common.isUndefined(params.type)) { this.dataType = File.UNKNOWN; } else { this.dataType = params.type; } if (params.tags && Kiwi.Utils.Common.isArray(params.tags)) { for (var i = 0; i < params.tags.length; i++) { this.addTag(params.tags[i]); } } } /** * Gets the file details from the URL passed. Name, extension, and path are extracted. * * @method _assignFileDetails * @param url {String} * @private * @since 1.2.0 */ private _assignFileDetails( url:string ) { this.URL = url; if ( url.lastIndexOf('/') > -1) { this.name = url.substr( url.lastIndexOf('/') + 1 ); this.path = url.substr(0, url.lastIndexOf('/') + 1); } else { this.path = ''; this.name = url; } // Not safe if there is a query string after the file extension this.extension = url.substr( url.lastIndexOf('.') + 1).toLowerCase(); } /** * Returns the type of this object * @method objType * @return {String} "File" * @public */ public objType() { return "File"; } /** * The game that this file belongs to. * @property game * @type Kiwi.Game * @since 1.2.0 * @public */ public game: Kiwi.Game; /** * --------------- * Generic Properties * --------------- **/ /** * Indicates if this file can be loaded in parallel to other files. * This is usually only used files are using the tag loaders and not XHR. * * @property _loadInParallel * @type Boolean * @default false * @since 1.2.0 * @private */ protected _loadInParallel: boolean = false; /** * READ ONLY: Indicates if this file can be loaded in parallel to other files. * This is usually only used files are using the tag loaders and not XHR. * * @property loadInParallel * @type Boolean * @default false * @readOnly * @since 1.2.0 * @private */ public get loadInParallel(): boolean { return this._loadInParallel; } /** * The filestore this file should be added to when it has loaded. * This can be replaced with a custom one if wanted. * * @property fileStore * @type Kiwi.Files.FileStore * @since 1.2.0 * @public */ public fileStore: Kiwi.Files.FileStore; /** * If this file is using tag loading instead of the XHR method. * Only used by extended classes * * @property useTagLoader * @type Boolean * @since 1.2.0 * @protected */ protected useTagLoader: boolean = false; /** * The 'key' is the user defined name and the users way of accessing this file once loaded. * @property key * @type String * @public */ public key: string; /** * A dictionary, stores any information relating to this file. * Used when loading images that are to be used as a spritesheet or texture atlas. * @property data * @type Any * @public */ public metadata: any; /** * Holds the type of data that is being loaded. * This should be used with the STATIC properties that hold the various datatypes that can be loaded. * * @property dataType * @type String * @public */ public dataType: number; /** * --------------- * File Information * --------------- */ /** * The name of the file being loaded. * * @property name * @type String * @since 1.2.0 * @public */ public name: string; /** * The location of where the file is placed without the file itself (So without the files name). * Example: If the file you are load is located at 'images/awesomeImage.png' then the filepath will be 'images/' * * @property path * @type String * @since 1.2.0 * @public */ public path: string; /** * The extension of the file that is being loaded. * This is based upon what the file path that the developer specifies. * * @property extension * @type String * @since 1.2.0 * @public */ public extension: string; /** * The full filepath including the file itself. * * @property URL * @type String * @since 1.2.0 * @public */ public URL: string; /** * The type of file that is being loaded. * Is only ever given a value when used with the XHR method of loading OR if you use 'loadDetails' before hand. * The value is based off of the 'Content-Type' of the XHR's response header returns. * * @property type * @type String * @public */ public type: string; /** * The size of the file that was/is being loaded. * Only has a value when the file was loaded by the XHR method OR you request the file information beforehand using 'loadDetails'. * * @property size * @type Number * @default 0 * @since 1.2.0 * @public */ public size: number = 0; /** * --------------- * Callbacks * --------------- */ /** * Signal which dispatches events when the file has successfully loaded. * * @property onComplete * @type Kiwi.Signal * @since 1.2.0 * @public */ public onComplete: Kiwi.Signal; /** * Signal which dispatches events when the file is loading. * Not guarenteed to dispatch events as it depends on the method of loading being performed * * @property onProgress * @type Kiwi.Signal * @since 1.2.0 * @public */ public onProgress: Kiwi.Signal; /** * --------------- * Loading * --------------- **/ /** * The particular piece of data that the developer wanted loaded. This is in a format that is based upon the datatype passed. * @property data * @type Any * @public */ public data: any; /** * The number of milliseconds that the XHR should wait before timing out. * Set this to NULL if you want it to not timeout. * * Default changed in v1.3.1 to null * * @property timeOutDelay * @type Number * @default null * @public */ public timeOutDelay: number = Kiwi.Files.File.TIMEOUT_DELAY; /** * The default number of milliseconds that the XHR should wait before timing out. * By default this is set to NULL, and so requests will not timeout. * * Default changed in v1.3.1 to null * * @property TIMEOUT_DELAY * @type Number * @static * @since 1.2.0 * @default null * @public */ public static TIMEOUT_DELAY: number = null; /** * The number of attempts at loading there have currently been at loading the file. * This is only used with XHR methods of loading. * @property attemptCounter * @type Number * @protected */ protected attemptCounter: number = 0; /** * The maximum attempts at loading the file that there is allowed. * @property maxLoadAttempts * @type Number * @default 2 * @public */ public maxLoadAttempts: number = Kiwi.Files.File.MAX_LOAD_ATTEMPTS; /** * The default maximum attempts at loading the file that there is allowed. * @property MAX_LOAD_ATTEMPTS * @type Number * @default 2 * @static * @since 1.2.0 * @public */ public static MAX_LOAD_ATTEMPTS: number = 2; /** * Starts the loading process for this file. * Passing parameters to this method has been deprecated and only exists for backwards compatibility. * * @method load * @public */ public load(onCompleteCallback?: any, onProgressCallback?: any, customFileStore?: Kiwi.Files.FileStore, maxLoadAttempts?: number, timeout?: number) { //Not currently loading? if (this.loading) { Kiwi.Log.error('Kiwi.Files.File: File loading is in progress. Cannot be told to load again.', '#loading'); return; } Kiwi.Log.log("Kiwi.Files.File: Starting to load '" + this.name + "'", '#file', '#loading'); //Set the variables based on the parameters passed //To be deprecated if (onCompleteCallback) this.onComplete.add( onCompleteCallback ); if (onProgressCallback) this.onProgress.add( onProgressCallback ); if (customFileStore) this.fileStore = customFileStore; if (typeof maxLoadAttempts !== "undefined") this.maxLoadAttempts = maxLoadAttempts; if (typeof timeout !== "undefined") this.timeOutDelay = timeout; //Start Loading!!! this._start(); this._load(); } /** * Increments the counter, and calls the approprate loading method. * @method _load * @since 1.2.0 * @protected */ protected _load() { this.attemptCounter++; this.xhrLoader( 'GET', 'text' ); } /** * Should be called by the loading method. Dispatches the 'onProgress' callback. * @method loadProgress * @since 1.2.0 * @protected */ protected loadProgress() { this.onProgress.dispatch(this); } /** * Called by the loading methods when the file has been loaded and successfully processed. * Dispatches the 'onComplete' callback and sets the appropriate properties. * @method loadSuccess * @since 1.2.0 * @protected */ protected loadSuccess() { //If already completed skip if (this.complete) { return; } this.success = true; this.hasError = false; this._stop(); if (this.fileStore) { this.fileStore.addFile(this.key, this); } this.onComplete.dispatch(this); } /** * Executed when the loading process fails. * This could be for any reason * * @method loadError * @param error {Any} The event / reason for the file to not be loaded. * @since 1.2.0 * @protected */ protected loadError(error: any) { //Try again? if (this.attemptCounter >= this.maxLoadAttempts) { //Failed Kiwi.Log.log("Kiwi.Files.File: Failed to load file '" + this.name + "'. Trying Again", '#loading'); this.hasError = true; this.success = false; this.error = error; this._stop(); this.onComplete.dispatch(this); } else { Kiwi.Log.log("Kiwi.Files.File: Failed to load file '" + this.name + "'", '#loading'); //Try Again this._load(); } } /** * --------------- * XHR Loading * --------------- **/ /** * Sets up a XHR loader based on the properties of this file and parameters passed. * * @method xhrLoader * @param [method="GET"] {String} The method this request should be made in. * @param [responseType="text"] {String} The type of response we are expecting. * @param [timeoutDelay] {Number} * @protected */ protected xhrLoader(method: string = 'GET', responseType: string = 'text', timeoutDelay: number = this.timeOutDelay) { this._xhr = new XMLHttpRequest(); this._xhr.open(method, this.URL, true); if (timeoutDelay !== null) { this._xhr.timeout = timeoutDelay; } this._xhr.responseType = responseType; this._xhr.onload = (event) => this.xhrOnLoad(event); this._xhr.onerror = (event) => this.loadError(event); this._xhr.onprogress = (event) => this.xhrOnProgress(event); var _that = this; this._xhr.onreadystatechange = function () { _that.readyState = _that._xhr.readyState; }; this._xhr.onloadstart = function (event) { _that.timeStarted = event.timeStamp; _that.lastProgress = event.timeStamp; }; this._xhr.ontimeout = function(event) { _that.hasTimedOut = true; }; this._xhr.onloadend = function (event) { _that.xhrOnLoad(event); }; this._xhr.send(); } /** * Progress event fired whilst the file is loading via XHR. * @method xhrOnProgress * @param event {Any} * @protected */ protected xhrOnProgress(event) { this.bytesLoaded = parseInt(event.loaded); this.bytesTotal = parseInt(event.total); this.percentLoaded = Math.round((this.bytesLoaded / this.bytesTotal) * 100); this.onProgress.dispatch(this); } /** * Fired when the file has been loaded. * Checks that the response contains information before marking it as a success. * * @method xhrOnLoad * @param event {Any} * @protected */ protected xhrOnLoad(event) { //Deprecate this.status = this._xhr.status; this.statusText = this._xhr.statusText; // If there is a status, then use that for our check. Otherwise we will base it on the response if (this.status && this.status === 200 || !this.status && this._xhr.response) { this._getXhrHeaderInfo(); this.buffer = this._xhr.response; //Deprecate this.processXhr(this._xhr.response); } else { this.loadError(event); } } /** * Contains the logic for processing the information retrieved via XHR. * Assigns the data property. * This method is also in charge of calling 'loadSuccess' (or 'loadError') when processing is complete. * * @method processXhr * @param response * @protected */ protected processXhr( response:any ) { this.data = response; this.loadSuccess(); } /** * The XMLHttpRequest object. This only has a value if the xhr method of load is being used, otherwise this is null. * @property _xhr * @type XMLHttpRequest * @protected */ protected _xhr: XMLHttpRequest; /** * ----------------- * Loading Status * ----------------- **/ /** * The time at which the loading started. * @property timeStarted * @type Number * @default 0 * @public */ public timeStarted: number = 0; /** * The time at which progress in loading the file was last occurred. * Only contains a value when using XHR methods of loading. * @property lastProgress * @type Number * @public */ public lastProgress: number = 0; /** * The time at which the load finished. * @property timeFinished * @type Number * @default 0 * @public */ public timeFinished: number = 0; /** * The duration or how long it took to load the file. In milliseconds. * @property duration * @type Number * @default 0 * @public */ public duration: number = 0; /** * Is executed when this file starts loading. * Gets the time and resets properties used in file loading. * @method _start * @private */ private _start() { this.attemptCounter = 0; this.loading = true; this.timeStarted = Date.now(); this.percentLoaded = 0; } /** * Is executed when this file stops loading. * @method _stop * @private */ private _stop() { this.loading = false; this.complete = true; this.percentLoaded = 100; this.timeFinished = Date.now(); this.duration = this.timeFinished - this.timeStarted; } /** * If file loading failed or encountered an error and so was not laoded * @property hasError * @type boolean * @default false * @public */ public hasError: boolean = false; /** * Holds the error (if there was one) when loading the file. * @property error * @type Any * @public */ public error: any; /** * If loading was successful or not. * @property success * @type boolean * @public */ public success: boolean = false; /** * Indication if the file is currently being loaded or not. * @property loading * @type boolean * @public */ public loading: boolean = false; /** * Indicates if the file has attempted to load. * This is regardless of whether it was a success or not. * @property complete * @type boolean * @default false * @public */ public complete: boolean = false; /** * The amount of percent loaded the file is. This is out of 100. * @property percentLoaded * @type Number * @public */ public percentLoaded: number = 0; /** * The number of bytes that have currently been loaded. * Useful when wanting to know exactly how much data has been transferred. * Only has a value when using the XHR method of loading. * * @property bytesLoaded * @type Number * @default 0 * @public */ public bytesLoaded: number = 0; /** * The total number of bytes that the file consists off. * Only has a value when using the XHR method of loading * or you are getting the file details before hand. * * @property bytesTotal * @type Number * @default 0 * @public */ public bytesTotal: number = 0; /** * -------------------- * XHR Header Information * -------------------- **/ /** * The callback method to be executed when the file details have been retrieved. * @property headCompleteCallback * @type Any * @since 1.2.0 * @private */ private headCompleteCallback: any; /** * The context the 'headCompleteCallback' should be executed in.. * The callback is the following arguments. * 1. If the details were recieved * * @property headCompleteContext * @type Any * @since 1.2.0 * @private */ private headCompleteContext: any; /** * An indication of whether this files information has been retrieved or not. * @property detailsReceived * @type boolean * @default false * @since 1.2.0 * @public */ public detailsReceived:boolean = false; /** * Makes a XHR HEAD request to get information about the file that is going to be downloaded. * This is particularly useful when you are wanting to check how large a file is before loading all of the content. * * @method loadDetails * @param [callback] {Any} * @param [context] {Any} * @return {Boolean} If the request was made * @since 1.2.0 * @public */ public loadDetails(callback:any=null, context:any=null) { //Can't continue if regular loading is progressing. if ( this.loading ) { Kiwi.Log.error('Kiwi.Files.File: Cannot get the file details whilst the file is already loading'); return false; } if (callback) this.headCompleteCallback = callback; if (context) this.headCompleteContext = context; this.xhrHeadRequest(); return true; } /** * Retrieves the HEAD information from the XHR. * This method is used for both 'load' and 'loadDetails' methods. * * @method _getXhrHeaderInfo * @since 1.2.0 * @private */ private _getXhrHeaderInfo() { if (!this._xhr) { return; } this.status = this._xhr.status; this.statusText = this._xhr.statusText; //Get the file information... this.type = this._xhr.getResponseHeader('Content-Type'); this.size = parseInt( this._xhr.getResponseHeader('Content-Length') ); this.lastModified = this._xhr.getResponseHeader('Last-Modified'); this.ETag = this._xhr.getResponseHeader('ETag'); this.detailsReceived = true; } /** * Sets up a XMLHttpRequest object and sends a HEAD request. * @method xhrHeadRequest * @since 1.2.0 * @private */ private xhrHeadRequest() { this._xhr = new XMLHttpRequest(); this._xhr.open('HEAD', this.fileURL, true); if (this.timeOutDelay !== null) this._xhr.timeout = this.timeOutDelay; this._xhr.onload = (event) => this.xhrHeadOnLoad(event); this._xhr.onerror = (event) => this.xhrHeadOnError(event); this._xhr.send(); } /** * Executed when a xhr head request fails * @method xhrHeadOnError * @param event {Any} * @private */ private xhrHeadOnError(event) { if (this.headCompleteCallback) { this.headCompleteCallback.call(this.headCompleteContext, false); } } /** * Executed when a XHR head request has loaded. * Checks that the status of the request is 200 before classifying it as a success. * @method xhrHeadOnLoad * @param event {Any} * @private */ private xhrHeadOnLoad(event) { if (this._xhr.status === 200) { this._getXhrHeaderInfo(); if (this.headCompleteCallback) { this.headCompleteCallback.call(this.headCompleteContext, true); } } else { this.xhrHeadOnError(null); } } /** * -------------------- * MISC * -------------------- **/ /** * The Entity Tag that is assigned to the file. O * Only has a value when either using the XHR loader OR when requesting the file details. * @property ETag * @type String * @public */ public ETag: string = ''; /** * The last date/time that this file was last modified. * Only has a value when using the XHR method of loading OR when requesting the file details. * @property lastModified * @type String * @default '' * @public */ public lastModified: string = ''; /** * -------------------- * Tagging + State * -------------------- **/ /** * The state that added the entity - or null if it was added as global * @property ownerState * @type Kiwi.State * @public */ public ownerState: Kiwi.State; /** * Any tags that are on this file. This can be used to grab files/objects on the whole game that have these particular tag. * @property _tags * @type String[] * @default [] * @private */ private _tags: string[]; /** * Adds a new tag to this file. * @method addTag * @param tag {String} The tag that you would like to add * @public */ public addTag(tag: string) { if (this._tags.indexOf(tag) == -1) { this._tags.push(tag); } } /** * Removes a tag from this file. * @method removeTag * @param tag {String} The tag that is to be removed. * @public */ public removeTag(tag: string) { var index: number = this._tags.indexOf(tag); if (index != -1) { this._tags.splice(index, 1); } } /** * Checks to see if a tag that is passed exists on this file. * Returns a boolean that is used as a indication of the results. * True means that the tag exists on this file. * * @method hasTag * @param tag {String} The tag you are checking to see exists. * @return {Boolean} If the tag does exist on this file or not. * @public */ public hasTag(tag: string) { if (this._tags.indexOf(tag) == -1) { return false; } return true; } /** * ------------------- * File Type * ------------------- **/ /** * A STATIC property that has the number associated with the IMAGE Datatype. * @property IMAGE * @type number * @static * @final * @default 0 * @public */ public static IMAGE: number = 0; /** * A STATIC property that has the number associated with the SPRITE_SHEET Datatype. * @property SPRITE_SHEET * @type number * @static * @final * @default 1 * @public */ public static SPRITE_SHEET: number = 1; /** * A STATIC property that has the number associated with the TEXTURE_ATLAS Datatype. * @property TEXTUREATLAS * @type number * @static * @final * @default 2 * @public */ public static TEXTURE_ATLAS: number = 2; /** * A STATIC property that has the number associated with the AUDIO Datatype. * @property AUDIO * @type number * @static * @final * @default 3 * @public */ public static AUDIO: number = 3; /** * A STATIC property that has the number associated with the JSON Datatype. * @property JSON * @type number * @static * @final * @default 4 * @public */ public static JSON: number = 4; /** * A STATIC property that has the number associated with the XML Datatype. * @property XML * @type number * @static * @final * @default 5 * @public */ public static XML: number = 5; /** * A STATIC property that has the number associated with the BINARY_DATA Datatype. * @property BINARY_DATA * @type number * @static * @final * @default 6 * @public */ public static BINARY_DATA: number = 6; /** * A STATIC property that has the number associated with the TEXT_DATA Datatype. * @property TEXT_DATA * @type number * @static * @final * @default 7 * @public */ public static TEXT_DATA: number = 7; /** * * @property UNKNOWN * @type number * @static * @final * @default 8 * @public */ public static UNKNOWN: number = 8; /** * An indication of if this file is texture. This is READ ONLY. * @property isTexture * @type boolean * @readOnly * @public */ public get isTexture(): boolean { return (Kiwi.Files.TextureFile.prototype.objType.call(this) === this.objType()); } /** * An indication of if this file is a piece of audio. This is READ ONLY. * @property isAudio * @type boolean * @readOnly * @public */ public get isAudio(): boolean { return (Kiwi.Files.AudioFile.prototype.objType.call(this) === this.objType()); } /** * An indication of if this file is data. This is READ ONLY. * @property isData * @type boolean * @readOnly * @public */ public get isData(): boolean { return (Kiwi.Files.DataFile.prototype.objType.call(this) === this.objType()); } /** * ------------------ * Clean Up * ------------------ **/ /** * Destroys all external object references on this object. * @method destroy * @since 1.2.0 * @public */ public destroy() { if (this.fileStore) { this.fileStore.removeFile(this.key); } this.onComplete.dispose(); this.onProgress.dispose(); delete this.fileStore; delete this._xhr; delete this.data; delete this.buffer; delete this.game; delete this.error; delete this.headCompleteCallback; delete this.headCompleteContext; delete this.onComplete; delete this.onProgress; delete this.ownerState; } /** * ------------------ * Deprecated * ------------------ **/ /** * The name of the file being loaded. * @property fileName * @type String * @deprecated Use `name`. Deprecated as of 1.2.0 * @public */ public get fileName(): string { return this.name; } public set fileName(val:string) { this.name = val; } /** * The location of where the file is placed without the file itself (So without the files name). * Example: If the file you are load is located at 'images/awesomeImage.png' then the filepath will be 'images/' * @property filePath * @type String * @deprecated Use `path`. Deprecated as of 1.2.0 * @public */ public get filePath(): string { return this.path; } public set filePath(val: string) { this.path = val; } /** * The location of where the file is placed without the file itself (So without the files name). * Example: If the file you are load is located at 'images/awesomeImage.png' then the filepath will be 'images/' * @property filePath * @type String * @deprecated Use `extension`. Deprecated as of 1.2.0 * @public */ public get fileExtension(): string { return this.extension; } public set fileExtension(val: string) { this.extension = val; } /** * The full filepath including the file itself. * @property fileURL * @type String * @deprecated Use `URL`. Deprecated as of 1.2.0 * @public */ public get fileURL(): string { return this.URL; } public set fileURL(val: string) { this.URL = val; } /** * The type of file that is being loaded. * Is only ever given a value when used with the XHR method of loading OR if you use 'getFileDetails' before hand. * The value is based off of the 'Content-Type' of the XHR's response header returns. * @property fileType * @type String * @deprecated Use `type`. Deprecated as of 1.2.0 * @public */ public get fileType():string { return this.type; } public set fileType(val: string) { this.type = val; } /** * The size of the file that was/is being loaded. * Only has a value when the file was loaded by the XHR method OR you request the file information before hand using 'getFileDetails'. * @property fileSize * @type Number * @deprecated Use `size`. Deprecated as of 1.2.0 * @public */ public get fileSize(): number { return this.size; } public set fileSize(val: number) { this.size = val; } /** * A method that is to be executed when this file has finished loading. * @property onCompleteCallback * @type Any * @default null * @deprecated Use `onComplete`. Deprecated as of 1.2.0 * @public */ //public onCompleteCallback: any = null; /** * A method that is to be executed while this file is loading. * @property onProgressCallback * @type Any * @default null * @deprecated Use `onProgress`. Deprecated as of 1.2.0 * @public */ //public onProgressCallback: any = null; /** * The status of this file that is being loaded. * Only used/has a value when the file was/is being loaded by the XHR method. * @property status * @type Number * @default 0 * @deprecated Deprecated as of 1.2.0 * @public */ public status: number = 0; /** * The status piece of text that the XHR returns. * @property statusText * @type String * @default '' * @deprecated Deprecated as of 1.2.0 * @public */ public statusText: string = ''; /** * The ready state of the XHR loader whilst loading. * @property readyState * @type Number * @default 0 * @deprecated Deprecated as of 1.2.0 * @public */ public readyState: number = 0; /** * If this file has timeout when it was loading. * @property hasTimedOut * @type boolean * @default false * @deprecated Deprecated as of 1.2.0 * @public */ public hasTimedOut: boolean = false; /** * If the file timed out or not. * @property timedOut * @type Number * @default 0 * @deprecated Deprecated as of 1.2.0 * @public */ public timedOut: number = 0; /** * The response that is given by the XHR loader when loading is complete. * @property buffer * @type Any * @deprecated Use 'data' instead. Deprecated as of 1.2.0 * @public */ public buffer: any; /** * Attempts to make the file send a XHR HEAD request to get information about the file that is going to be downloaded. * This is particularly useful when you are wanting to check how large a file is before loading all of the content. * @method getFileDetails * @param [callback=null] {Any} The callback to send this FileInfo object to. * @param [maxLoadAttempts=1] {number} The maximum amount of load attempts. Only set this if it is different from the default. * @param [timeout=this.timeOutDelay] {number} The timeout delay. By default this is the same as the timeout delay property set on this file. * @deprecated Use 'loadDetails' instead. Deprecated as of 1.2.0 * @private */ public getFileDetails(callback: any = null, maxLoadAttempts?: number, timeout: number = null) { if (timeout) this.timeOutDelay = timeout; this.loadDetails(callback, null); } } }
the_stack
import * as THREE from "three"; import View3DError from "~/View3DError"; import { getCanvas, range, toRadian, clamp, findIndex, getElement, mix, circulate, merge, getBoxPoints, toPowerOfTwo, } from "~/utils"; import * as ERROR from "~/consts/error"; import { cleanup, createSandbox } from "./test-utils"; describe("Utils", () => { describe("getElement", () => { let wrapper: HTMLElement; beforeEach(() => { wrapper = createSandbox("#wrapper"); }); afterEach(() => { cleanup(); }); it("should search from the document with selector if the parent element is not given", () => { // Given const findingEl = document.createElement("div"); findingEl.id = "target"; // When document.body.appendChild(findingEl); // Then try { expect(getElement("#target")).to.equal(findingEl); } catch (e) { expect(true).to.be.false; // Shouldn't reach here } finally { findingEl.remove(); } }); it("should search with the selector from the parent element if parent element is given", () => { // Given const findingEl = document.createElement("div"); const fakeEl = document.createElement("div"); findingEl.className = "target"; fakeEl.className = "target"; // When document.body.insertBefore(fakeEl, wrapper); wrapper.appendChild(findingEl); // Then try { expect(() => getElement(".target")).not.to.throw(); expect(getElement(".target", wrapper)).to.equal(findingEl); } catch (e) { expect(true).to.be.false; // Shouldn't reach here } finally { fakeEl.remove(); findingEl.remove(); } }); it("will return element itself if HTMLelemnt is given", () => { // Given const testingEl = document.createElement("div"); // When wrapper.appendChild(testingEl); // Then expect(() => getElement(testingEl)).not.to.throw(); expect(getElement(testingEl)).to.equal(testingEl); }); it("will throw View3DError if element with given selector not found", () => { expect(() => getElement("#el-that-definitely-not-exist")) .to.throw(View3DError) .with.property("code", ERROR.CODES.ELEMENT_NOT_FOUND); }); it("will throw View3DError if element with given selector not found inside given parent", () => { // Given const targetEl = document.createElement("div"); targetEl.id = "target"; // When document.body.appendChild(targetEl); // Then expect(() => getElement("#target", wrapper)) .to.throw(View3DError) .with.property("code", ERROR.CODES.ELEMENT_NOT_FOUND); }); it("will return null if given parameter is null", () => { expect(getElement(null)).not.to.throw; expect(getElement(null)).to.be.null; }); }); describe("getCanvas", () => { it("can return canvas element in document if parameter is proper query string", () => { // Given document.body.innerHTML = `<canvas id="view3d-canvas"></canvas>`; // When const canvas = getCanvas("#view3d-canvas"); // Then expect(canvas).not.to.be.null; }); it("can return canvas element in document if parameter is proper HTML canvas element", () => { // Given document.body.innerHTML = `<canvas id="view3d-canvas"></canvas>`; // When const canvas = getCanvas(document.querySelector("#view3d-canvas") as HTMLElement); // Then expect(canvas).not.to.be.null; }); it("should throw an 'Element not found' error when there's no element found with given query string", () => { // Given document.body.innerHTML = ""; try { // When getCanvas("#some-element"); expect(true).to.be.false; // it should fail when it doesn't throw an error } catch (e) { // Then expect(e.code).to.equal(ERROR.CODES.ELEMENT_NOT_FOUND); } }); it("should throw an 'Wrong type' error if given argument's type is wrong", () => { // Given const someWrongTypes = [undefined, null, NaN, {a: 1}, () => ""]; someWrongTypes.forEach(wrongType => { try { // When getCanvas(wrongType as any); expect(true).to.be.false; // it should fail when it doesn't throw an error } catch (e) { // Then expect(e.code).to.equal(ERROR.CODES.WRONG_TYPE); } }); }); it("should throw an 'Element is not canvas' error when found element is not a canvas element", () => { // Given document.body.innerHTML = `<div id="view3d-canvas"></div>`; try { // When getCanvas(document.querySelector("#view3d-canvas") as HTMLElement); expect(true).to.be.false; // it should fail when it doesn't throw an error } catch (e) { // Then expect(e.code).to.equal(ERROR.CODES.ELEMENT_NOT_CANVAS); } }); }); describe("range", () => { it("should return 0 to n - 1", () => { expect(range(5)).deep.equals([0, 1, 2, 3, 4]); expect(range(100).every((val, idx) => val === idx)).to.be.true; }); it("should return an empty array if end value is not given", () => { // @ts-ignore expect(range()).to.deep.equal([]); }); it("should return an empty array if end value is less than 1", () => { expect(range(0)).to.deep.equal([]); expect(range(-1)).to.deep.equal([]); expect(range(-100)).to.deep.equal([]); }); }); describe("toRadian", () => { it("should return correct value", () => { // Given const given = [0, 45, 90, 180]; const expected = [0, Math.PI / 4, Math.PI / 2, Math.PI]; // When const real = given.map(val => toRadian(val)); // Then expect(real).to.deep.equal(expected); }); }); describe("clamp", () => { it("should clamp value to minimum if the given value is equal or smaller than range minimum", () => { // Given const values = [0, -1, -4, -100, -1000]; // When const clamped = values.map(val => clamp(val, 0, 100)); // Then expect(clamped.every(val => val === 0)).to.be.true; }); it("should clamp value to maximum if the given value is equal or bigger than range maximum", () => { // Given const values = [100, 101, 104, 200, 1000]; // When const clamped = values.map(val => clamp(val, 0, 100)); // Then expect(clamped.every(val => val === 100)).to.be.true; }); it("should return original value when it's between range minimum and maximum", () => { // Given const values = [-100, -1, 0, 1, 100]; // When const clamped = values.map(val => clamp(val, -100, 100)); // Then expect(values).to.deep.equal(clamped); }); }); describe("findIndex", () => { it("can find correct index in the array", () => { // Given const array = [1, 2, 3, 4, 5]; // When const index = findIndex(2, array); // Then expect(index).to.equal(1); }); it("should return index of first element found", () => { // Given const array = [1, 2, 2, 2, 2]; // When const index = findIndex(2, array); // Then expect(index).to.equal(1); }); it("should return -1 when it couldn't find element", () => { // Given const array = [0, 1, 2, 3, 4]; // When const index = findIndex(5, array); // Then expect(index).to.equal(-1); }); }); describe("mix", () => { it("should return a if t = 0", () => { expect(mix(1, 2, 0)).to.equal(1); expect(mix(3, 5, 0)).to.equal(3); expect(mix(-1, 0, 0)).to.equal(-1); expect(mix(0, 2, 0)).to.equal(0); expect(mix(4, -2, 0)).to.equal(4); }); it("should return b if t = 1", () => { expect(mix(1, 2, 1)).to.equal(2); expect(mix(3, 5, 1)).to.equal(5); expect(mix(-1, 0, 1)).to.equal(0); expect(mix(0, 2, 1)).to.equal(2); expect(mix(4, -2, 1)).to.equal(-2); }); it("should return (a + b) / 2 if t = 0.5", () => { expect(mix(1, 2, 0.5)).to.equal(1.5); expect(mix(3, 5, 0.5)).to.equal(4); expect(mix(-1, 0, 0.5)).to.equal(-0.5); expect(mix(0, 2, 0.5)).to.equal(1); expect(mix(4, -2, 0.5)).to.equal(1); }); }); describe("circulate", () => { it("should return value itself if it's between min and max value", () => { expect(circulate(0, -5, 5)).to.equal(0); expect(circulate(0, 0, 5)).to.equal(0); expect(circulate(0, -5, 0)).to.equal(0); expect(circulate(0, 0, 0)).to.equal(0); expect(circulate(4, 0, 5)).to.equal(4); expect(circulate(5, -5, 5)).to.equal(5); expect(circulate(-5, -5, 5)).to.equal(-5); }); it("should return circulated value if it's lower than minimum value", () => { expect(circulate(-10, -5, 5)).to.equal(0); expect(circulate(-5, 0, 5)).to.equal(5); expect(circulate(-6, -5, 0)).to.equal(-1); expect(circulate(-10, -5, 0)).to.equal(0); expect(circulate(-1, 0, 5)).to.equal(4); }); it("should return circulated value if it's lower than minimum value", () => { expect(circulate(10, -5, 5)).to.equal(0); expect(circulate(10, 0, 5)).to.equal(0); expect(circulate(5, -5, 0)).to.equal(-5); expect(circulate(10, -5, 0)).to.equal(-5); expect(circulate(6, 0, 5)).to.equal(1); expect(circulate(7, -1, 5)).to.equal(1); }); }); describe("merge", () => { it("should return same reference of the given object", () => { const obj = {}; const merged = merge(obj, { a: 1 }); expect(merged).equals(obj); }); it("should add value", () => { const obj = {}; const merged = merge(obj, { a: 1 }) as { a: number }; expect(merged.a).to.equal(1); }); it("should overwrite value", () => { const obj = { a : 1 }; const merged = merge(obj, { a: 2 }) as { a: number }; expect(merged.a).to.equal(2); }); }); describe("getBoxPoints", () => { it("should return 8 points", () => { const box = new THREE.Box3(new THREE.Vector3(), new THREE.Vector3()); expect(getBoxPoints(box).length).to.equal(8); }); it("should return all points of the given box", () => { const box = new THREE.Box3( new THREE.Vector3(-1, -1, -1), new THREE.Vector3(1, 1, 1), ); const boxPoints = getBoxPoints(box); expect(boxPoints[0]).to.deep.equal(new THREE.Vector3(-1, -1, -1)); expect(boxPoints[1]).to.deep.equal(new THREE.Vector3(-1, -1, 1)); expect(boxPoints[2]).to.deep.equal(new THREE.Vector3(-1, 1, -1)); expect(boxPoints[3]).to.deep.equal(new THREE.Vector3(-1, 1, 1)); expect(boxPoints[4]).to.deep.equal(new THREE.Vector3(1, -1, -1)); expect(boxPoints[5]).to.deep.equal(new THREE.Vector3(1, -1, 1)); expect(boxPoints[6]).to.deep.equal(new THREE.Vector3(1, 1, -1)); expect(boxPoints[7]).to.deep.equal(new THREE.Vector3(1, 1, 1)); }); }); describe("toPowerOfTwo", () => { it("should return given number itself if it's already power of two", () => { const values = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]; values.forEach(val => { expect(toPowerOfTwo(val)).to.equal(val); }); }); it("should return bigger power of two number than given number", () => { const values = [3, 5, 15, 24, 53, 127]; const expected = [4, 8, 16, 32, 64, 128]; values.forEach((val, idx) => { expect(toPowerOfTwo(val)).to.equal(expected[idx]); }); }); }); });
the_stack
import { jest, describe, it, expect } from "@jest/globals"; import { dataset } from "@rdfjs/dataset"; import * as fc from "fast-check"; import { DataFactory } from "n3"; import * as RdfJs from "@rdfjs/types"; import { serializeBoolean, serializeDatetime, serializeDecimal, serializeInteger, xmlSchemaTypes, } from "./datatypes"; import { ImmutableDataset } from "./rdf.internal"; import { addRdfJsQuadToDataset } from "./rdfjs.internal"; import { fromRdfJsDataset, toRdfJsDataset } from "./rdfjs"; describe("fromRdfJsDataset", () => { const fcNamedNode = fc .webUrl({ withFragments: true, withQueryParameters: true }) .map((url) => DataFactory.namedNode(url)); const fcString = fc.string().map((value) => DataFactory.literal(value)); const fcInteger = fc .integer() .map((value) => DataFactory.literal( serializeInteger(value), DataFactory.namedNode(xmlSchemaTypes.integer) ) ); const fcDecimal = fc .float() .map((value) => DataFactory.literal( serializeDecimal(value), DataFactory.namedNode(xmlSchemaTypes.decimal) ) ); const fcDatetime = fc .date() .map((value) => DataFactory.literal( serializeDatetime(value), DataFactory.namedNode(xmlSchemaTypes.dateTime) ) ); const fcBoolean = fc .boolean() .map((value) => DataFactory.literal( serializeBoolean(value), DataFactory.namedNode(xmlSchemaTypes.boolean) ) ); const fcLangString = fc .tuple( fc.string(), fc.oneof(fc.constant("nl-NL"), fc.constant("en-GB"), fc.constant("fr")) ) .map(([value, lang]) => DataFactory.literal(value, lang)); const fcArbitraryLiteral = fc .tuple(fc.string(), fc.webUrl({ withFragments: true })) .map(([value, dataType]) => DataFactory.literal(value, DataFactory.namedNode(dataType)) ); const fcLiteral = fc.oneof( fcString, fcInteger, fcDecimal, fcDatetime, fcBoolean, fcLangString, fcArbitraryLiteral ); const fcBlankNode = fc .asciiString() .map((asciiString) => DataFactory.blankNode(asciiString)); const fcDefaultGraph = fc.constant(DataFactory.defaultGraph()); const fcGraph = fc.oneof(fcDefaultGraph, fcNamedNode); const fcQuadSubject = fc.oneof(fcNamedNode, fcBlankNode); const fcQuadPredicate = fcNamedNode; const fcQuadObject = fc.oneof(fcNamedNode, fcLiteral, fcBlankNode); const fcQuad = fc .tuple(fcQuadSubject, fcQuadPredicate, fcQuadObject, fcGraph) .map(([subject, predicate, object, graph]) => DataFactory.quad(subject, predicate, object, graph) ); const fcDatasetWithReusedBlankNodes = fc.set(fcQuad).map((quads) => { const reusedBlankNode = DataFactory.blankNode(); function maybeReplaceBlankNode(node: RdfJs.BlankNode): RdfJs.BlankNode { return Math.random() < 0.5 ? node : reusedBlankNode; } function maybeReplaceBlankNodesInQuad(quad: RdfJs.Quad): RdfJs.Quad { const subject = quad.subject.termType === "BlankNode" ? maybeReplaceBlankNode(quad.subject) : quad.subject; const object = quad.object.termType === "BlankNode" ? maybeReplaceBlankNode(quad.object) : quad.object; return DataFactory.quad(subject, quad.predicate, object, quad.graph); } return dataset(quads.map(maybeReplaceBlankNodesInQuad)); }); it("loses no data", () => { const runs = process.env.CI ? 1000 : 100; expect.assertions(runs * 2 + 2); function hasMatchingQuads( a: RdfJs.DatasetCore, b: RdfJs.DatasetCore ): boolean { function blankNodeToNull(term: RdfJs.Term): RdfJs.Term | null { return term.termType === "BlankNode" ? null : term; } const aQuads = Array.from(a); const bQuads = Array.from(b); return ( aQuads.every((quad) => b.match( blankNodeToNull(quad.subject), quad.predicate, blankNodeToNull(quad.object), quad.graph ) ) && bQuads.every((quad) => a.match( blankNodeToNull(quad.subject), quad.predicate, blankNodeToNull(quad.object), quad.graph ) ) ); } const fcResult = fc.check( fc.property(fcDatasetWithReusedBlankNodes, (dataset) => { const thereAndBackAgain = toRdfJsDataset(fromRdfJsDataset(dataset)); expect(thereAndBackAgain.size).toBe(dataset.size); expect(hasMatchingQuads(thereAndBackAgain, dataset)).toBe(true); }), { numRuns: runs } ); expect(fcResult.counterexample).toBeNull(); expect(fcResult.failed).toBe(false); }); it("can represent all Quads", () => { const blankNode1 = DataFactory.blankNode(); const blankNode2 = DataFactory.blankNode(); const subject1IriString = "https://some.pod/resource#subject1"; const subject1 = DataFactory.namedNode(subject1IriString); const subject2IriString = "https://some.pod/resource#subject2"; const subject2 = DataFactory.namedNode(subject2IriString); const predicate1IriString = "https://some.vocab/predicate1"; const predicate1 = DataFactory.namedNode(predicate1IriString); const predicate2IriString = "https://some.vocab/predicate2"; const predicate2 = DataFactory.namedNode(predicate2IriString); const literalStringValue = "Some string"; const literalString = DataFactory.literal( literalStringValue, DataFactory.namedNode(xmlSchemaTypes.string) ); const literalLangStringValue = "Some lang string"; const literalLangStringLocale = "en-gb"; const literalLangString = DataFactory.literal( literalLangStringValue, literalLangStringLocale ); const literalIntegerValue = "42"; const literalInteger = DataFactory.literal( literalIntegerValue, DataFactory.namedNode(xmlSchemaTypes.integer) ); const defaultGraph = DataFactory.defaultGraph(); const acrGraphIriString = "https://some.pod/resource?ext=acr"; const acrGraph = DataFactory.namedNode(acrGraphIriString); const quads = [ DataFactory.quad(subject1, predicate1, literalString, defaultGraph), DataFactory.quad(subject1, predicate1, literalLangString, defaultGraph), DataFactory.quad(subject1, predicate1, literalInteger, defaultGraph), DataFactory.quad(subject1, predicate2, subject2, defaultGraph), DataFactory.quad(subject2, predicate1, blankNode1, acrGraph), DataFactory.quad(subject2, predicate1, blankNode2, acrGraph), DataFactory.quad(blankNode1, predicate1, literalString, acrGraph), DataFactory.quad(blankNode2, predicate1, literalString, acrGraph), DataFactory.quad(blankNode2, predicate1, literalInteger, acrGraph), DataFactory.quad(blankNode2, predicate2, literalInteger, acrGraph), ]; const rdfJsDataset = dataset(quads); expect(fromRdfJsDataset(rdfJsDataset)).toStrictEqual({ type: "Dataset", graphs: { default: { [subject1IriString]: { url: subject1IriString, type: "Subject", predicates: { [predicate1IriString]: { literals: { [xmlSchemaTypes.string]: [literalStringValue], [xmlSchemaTypes.integer]: [literalIntegerValue], }, langStrings: { [literalLangStringLocale]: [literalLangStringValue], }, }, [predicate2IriString]: { namedNodes: [subject2IriString], }, }, }, }, [acrGraphIriString]: { [subject2IriString]: { url: subject2IriString, type: "Subject", predicates: { [predicate1IriString]: { blankNodes: [ { [predicate1IriString]: { literals: { [xmlSchemaTypes.string]: [literalStringValue], }, }, }, { [predicate1IriString]: { literals: { [xmlSchemaTypes.string]: [literalStringValue], [xmlSchemaTypes.integer]: [literalIntegerValue], }, }, [predicate2IriString]: { literals: { [xmlSchemaTypes.integer]: [literalIntegerValue], }, }, }, ], }, }, }, }, }, }); }); it("can represent lists", () => { const first = DataFactory.namedNode( "http://www.w3.org/1999/02/22-rdf-syntax-ns#first" ); const rest = DataFactory.namedNode( "http://www.w3.org/1999/02/22-rdf-syntax-ns#rest" ); const nil = DataFactory.namedNode( "http://www.w3.org/1999/02/22-rdf-syntax-ns#nil" ); const item1Node = DataFactory.blankNode(); const item2Node = DataFactory.blankNode(); const quad1 = DataFactory.quad( item1Node, first, DataFactory.literal("First item in a list") ); const quad2 = DataFactory.quad(item1Node, rest, item2Node); const quad3 = DataFactory.quad( item2Node, first, DataFactory.literal("Second item in a list") ); const quad4 = DataFactory.quad(item2Node, rest, nil); const rdfJsDataset = dataset([quad1, quad2, quad3, quad4]); const thereAndBackAgain = toRdfJsDataset(fromRdfJsDataset(rdfJsDataset)); expect(thereAndBackAgain.size).toBe(4); expect( thereAndBackAgain.match( null, null, DataFactory.literal("First item in a list") ).size ).toBe(1); expect( thereAndBackAgain.match( null, null, DataFactory.literal("Second item in a list") ).size ).toBe(1); }); it("does not lose any predicates", () => { const blankNode1 = DataFactory.blankNode(); const blankNode2 = DataFactory.blankNode(); const blankNode3 = DataFactory.blankNode(); const blankNode4 = DataFactory.blankNode(); const predicate1 = DataFactory.namedNode("https://example.com/predicate1"); const predicate2 = DataFactory.namedNode("https://example.com/predicate2"); const predicate3 = DataFactory.namedNode("https://example.com/predicate3"); const acrGraph = DataFactory.namedNode("https://example.com/acrGraph"); const literalString = DataFactory.literal("Arbitrary literal string"); const quads = [ DataFactory.quad(blankNode1, predicate1, blankNode2, acrGraph), DataFactory.quad(blankNode2, predicate2, blankNode3, acrGraph), DataFactory.quad(blankNode3, predicate3, blankNode4, acrGraph), DataFactory.quad(blankNode4, predicate2, literalString, acrGraph), ]; const rdfJsDataset = dataset(quads); const thereAndBackAgain = toRdfJsDataset(fromRdfJsDataset(rdfJsDataset)); expect(thereAndBackAgain.size).toBe(rdfJsDataset.size); }); it("does not trip over circular blank nodes", () => { const namedNode = DataFactory.namedNode("https://example.com/namedNode"); const blankNode1 = DataFactory.blankNode(); const blankNode2 = DataFactory.blankNode(); const blankNode3 = DataFactory.blankNode(); const predicate = DataFactory.namedNode("https://example.com/predicate"); const literalString = DataFactory.literal("Arbitrary literal string"); const quads = [ DataFactory.quad(namedNode, predicate, blankNode2), DataFactory.quad(blankNode1, predicate, blankNode2), DataFactory.quad(blankNode2, predicate, blankNode3), DataFactory.quad(blankNode3, predicate, blankNode1), DataFactory.quad(blankNode2, predicate, literalString), ]; const rdfJsDataset = dataset(quads); const thereAndBackAgain = toRdfJsDataset(fromRdfJsDataset(rdfJsDataset)); expect(thereAndBackAgain.size).toBe(rdfJsDataset.size); }); it("does not trip over blank nodes that appear as the object for different subjects", () => { const namedNode = DataFactory.namedNode("https://example.com/namedNode"); const blankNode1 = DataFactory.blankNode(); const blankNode2 = DataFactory.blankNode(); const blankNode3 = DataFactory.blankNode(); const predicate = DataFactory.namedNode("https://example.com/predicate"); const literalString = DataFactory.literal("Arbitrary literal string"); const quads = [ DataFactory.quad(blankNode1, predicate, blankNode2), DataFactory.quad(blankNode2, predicate, literalString), DataFactory.quad(blankNode3, predicate, blankNode2), ]; const rdfJsDataset = dataset(quads); const thereAndBackAgain = toRdfJsDataset(fromRdfJsDataset(rdfJsDataset)); expect(thereAndBackAgain.size).toBe(rdfJsDataset.size); }); it("does not trip over Datasets that only contain Blank Node Subjects", () => { const blankNode1 = DataFactory.blankNode(); const blankNode2 = DataFactory.blankNode(); const blankNode3 = DataFactory.blankNode(); const predicate = DataFactory.namedNode("https://example.com/predicate"); const literalString = DataFactory.literal("Arbitrary literal string"); const quads = [ DataFactory.quad(blankNode1, predicate, blankNode2), DataFactory.quad(blankNode2, predicate, blankNode3), DataFactory.quad(blankNode3, predicate, blankNode1), DataFactory.quad(blankNode2, predicate, literalString), ]; const rdfJsDataset = dataset(quads); const thereAndBackAgain = toRdfJsDataset(fromRdfJsDataset(rdfJsDataset)); expect(thereAndBackAgain.size).toBe(rdfJsDataset.size); }); describe("addRdfJsQuadToDataset", () => { it("can parse a simple Quad with a Blank Node Object", () => { const mockDataset: ImmutableDataset = { type: "Dataset", graphs: { default: {} }, }; const mockQuad = DataFactory.quad( DataFactory.namedNode("https://some.subject"), DataFactory.namedNode("https://some.predicate"), DataFactory.blankNode("some-blank-node"), DataFactory.defaultGraph() ); const dataset = addRdfJsQuadToDataset(mockDataset, mockQuad); expect(dataset).toStrictEqual({ type: "Dataset", graphs: { default: { "https://some.subject": { type: "Subject", url: "https://some.subject", predicates: { "https://some.predicate": { blankNodes: ["_:some-blank-node"], }, }, }, }, }, }); }); it("throws an error when passed unknown Graph types", () => { const mockDataset: ImmutableDataset = { type: "Dataset", graphs: { default: {} }, }; const mockQuad = DataFactory.quad( DataFactory.namedNode("https://arbitrary.subject"), DataFactory.namedNode("https://arbitrary.predicate"), DataFactory.namedNode("https://arbitrary.object"), { termType: "Unknown term type" } as any ); expect(() => addRdfJsQuadToDataset(mockDataset, mockQuad)).toThrow( "Cannot parse Quads with nodes of type [Unknown term type] as their Graph node." ); }); it("throws an error when passed unknown Subject types", () => { const mockDataset: ImmutableDataset = { type: "Dataset", graphs: { default: {} }, }; const mockQuad = DataFactory.quad( { termType: "Unknown term type" } as any, DataFactory.namedNode("https://arbitrary.predicate"), DataFactory.namedNode("https://arbitrary.object"), DataFactory.defaultGraph() ); expect(() => addRdfJsQuadToDataset(mockDataset, mockQuad)).toThrow( "Cannot parse Quads with nodes of type [Unknown term type] as their Subject node." ); }); it("throws an error when passed unknown Predicate types", () => { const mockDataset: ImmutableDataset = { type: "Dataset", graphs: { default: {} }, }; const mockQuad = DataFactory.quad( DataFactory.namedNode("https://arbitrary.subject"), { termType: "Unknown term type" } as any, DataFactory.namedNode("https://arbitrary.object"), DataFactory.defaultGraph() ); expect(() => addRdfJsQuadToDataset(mockDataset, mockQuad)).toThrow( "Cannot parse Quads with nodes of type [Unknown term type] as their Predicate node." ); }); it("throws an error when passed unknown Predicate types with chain Blank Node Subjects", () => { const mockDataset: ImmutableDataset = { type: "Dataset", graphs: { default: {} }, }; const chainBlankNode = DataFactory.blankNode(); const otherQuad = DataFactory.quad( DataFactory.namedNode("https://arbitrary.subject"), DataFactory.namedNode("https://arbitrary.predicate"), chainBlankNode, DataFactory.defaultGraph() ); const mockQuad = DataFactory.quad( chainBlankNode, { termType: "Unknown term type" } as any, DataFactory.namedNode("https://arbitrary.object"), DataFactory.defaultGraph() ); expect(() => addRdfJsQuadToDataset(mockDataset, otherQuad, { chainBlankNodes: [chainBlankNode], otherQuads: [mockQuad], }) ).toThrow( "Cannot parse Quads with nodes of type [Unknown term type] as their Predicate node." ); }); it("throws an error when passed unknown Predicate types in connecting Quads for chain Blank Node Objects", () => { const mockDataset: ImmutableDataset = { type: "Dataset", graphs: { default: {} }, }; const chainBlankNode1 = DataFactory.blankNode(); const chainBlankNode2 = DataFactory.blankNode(); const otherQuad = DataFactory.quad( DataFactory.namedNode("https://arbitrary.subject"), DataFactory.namedNode("https://arbitrary.predicate"), chainBlankNode1, DataFactory.defaultGraph() ); const inBetweenQuad = DataFactory.quad( chainBlankNode1, { termType: "Unknown term type" } as any, chainBlankNode2, DataFactory.defaultGraph() ); const mockQuad = DataFactory.quad( chainBlankNode2, DataFactory.namedNode("https://arbitrary.predicate"), DataFactory.namedNode("https://arbitrary.object"), DataFactory.defaultGraph() ); expect(() => addRdfJsQuadToDataset(mockDataset, otherQuad, { chainBlankNodes: [chainBlankNode1, chainBlankNode2], otherQuads: [mockQuad, inBetweenQuad], }) ).toThrow( "Cannot parse Quads with nodes of type [Unknown term type] as their Predicate node." ); }); it("throws an error when passed unknown Predicate types in the terminating Quads for chain Blank Node Objects", () => { const mockDataset: ImmutableDataset = { type: "Dataset", graphs: { default: {} }, }; const chainBlankNode1 = DataFactory.blankNode(); const chainBlankNode2 = DataFactory.blankNode(); const otherQuad = DataFactory.quad( DataFactory.namedNode("https://arbitrary.subject"), DataFactory.namedNode("https://arbitrary.predicate"), chainBlankNode1, DataFactory.defaultGraph() ); const inBetweenQuad = DataFactory.quad( chainBlankNode1, DataFactory.namedNode("https://arbitrary.predicate"), chainBlankNode2, DataFactory.defaultGraph() ); const mockQuad = DataFactory.quad( chainBlankNode2, { termType: "Unknown term type" } as any, DataFactory.namedNode("https://arbitrary.object"), DataFactory.defaultGraph() ); expect(() => addRdfJsQuadToDataset(mockDataset, otherQuad, { chainBlankNodes: [chainBlankNode1, chainBlankNode2], otherQuads: [mockQuad, inBetweenQuad], }) ).toThrow( "Cannot parse Quads with nodes of type [Unknown term type] as their Predicate node." ); }); it("throws an error when passed unknown Object types", () => { const mockDataset: ImmutableDataset = { type: "Dataset", graphs: { default: {} }, }; const mockQuad = DataFactory.quad( DataFactory.namedNode("https://arbitrary.subject"), DataFactory.namedNode("https://arbitrary.predicate"), { termType: "Unknown term type" } as any, DataFactory.defaultGraph() ); expect(() => addRdfJsQuadToDataset(mockDataset, mockQuad)).toThrow( "Objects of type [Unknown term type] are not supported." ); }); it("can parse chained Blank Nodes with a single link that end in a dangling Blank Node", () => { const mockDataset: ImmutableDataset = { type: "Dataset", graphs: { default: {} }, }; const chainBlankNode1 = DataFactory.blankNode(); const otherQuad = DataFactory.quad( DataFactory.namedNode("https://some.subject"), DataFactory.namedNode("https://some.predicate/1"), chainBlankNode1, DataFactory.defaultGraph() ); const mockQuad = DataFactory.quad( chainBlankNode1, DataFactory.namedNode("https://some.predicate/2"), DataFactory.blankNode("some-blank-node"), DataFactory.defaultGraph() ); const updatedDataset = addRdfJsQuadToDataset(mockDataset, otherQuad, { chainBlankNodes: [chainBlankNode1], otherQuads: [mockQuad], }); expect(updatedDataset).toStrictEqual({ graphs: { default: { "https://some.subject": { predicates: { "https://some.predicate/1": { blankNodes: [ { "https://some.predicate/2": { blankNodes: ["_:some-blank-node"], }, }, ], }, }, type: "Subject", url: "https://some.subject", }, }, }, type: "Dataset", }); }); it("can parse chained Blank Nodes that end in a dangling Blank Node", () => { const mockDataset: ImmutableDataset = { type: "Dataset", graphs: { default: {} }, }; const chainBlankNode1 = DataFactory.blankNode(); const chainBlankNode2 = DataFactory.blankNode(); const otherQuad = DataFactory.quad( DataFactory.namedNode("https://some.subject"), DataFactory.namedNode("https://some.predicate/1"), chainBlankNode1, DataFactory.defaultGraph() ); const inBetweenQuad = DataFactory.quad( chainBlankNode1, DataFactory.namedNode("https://some.predicate/2"), chainBlankNode2, DataFactory.defaultGraph() ); const mockQuad = DataFactory.quad( chainBlankNode2, DataFactory.namedNode("https://some.predicate/3"), DataFactory.blankNode("some-blank-node"), DataFactory.defaultGraph() ); const updatedDataset = addRdfJsQuadToDataset(mockDataset, otherQuad, { chainBlankNodes: [chainBlankNode1, chainBlankNode2], otherQuads: [mockQuad, inBetweenQuad], }); expect(updatedDataset).toStrictEqual({ graphs: { default: { "https://some.subject": { predicates: { "https://some.predicate/1": { blankNodes: [ { "https://some.predicate/2": { blankNodes: [ { "https://some.predicate/3": { blankNodes: ["_:some-blank-node"], }, }, ], }, }, ], }, }, type: "Subject", url: "https://some.subject", }, }, }, type: "Dataset", }); }); }); }); describe("toRdfJsDataset", () => { const isNotEmpty = (value: object) => { if (typeof value !== "object") { return false; } if (value === null) { return false; } if (Array.isArray(value)) { return value.length > 0; } return Object.keys(value).length > 0; }; const fcLiterals = fc .dictionary( fc.webUrl({ withFragments: true }), fc.set(fc.string(), { minLength: 1 }) ) .filter(isNotEmpty); const fcLangStrings = fc .dictionary( fc.hexaString({ minLength: 1 }).map((str) => str.toLowerCase()), fc.set(fc.string(), { minLength: 1 }) ) .filter(isNotEmpty); const fcLocalNodeIri = fc.webUrl({ withFragments: true }).map((url) => { const originalUrl = new URL(url); return `https://inrupt.com/.well-known/sdk-local-node/${originalUrl.hash}`; }); const fcNamedNodes = fc.set( fc.oneof( fcLocalNodeIri, fc.webUrl({ withFragments: true, withQueryParameters: true }) ), { minLength: 1, } ); const fcObjects = fc .record( { literals: fcLiterals, langStrings: fcLangStrings, namedNodes: fcNamedNodes, // blankNodes: fcBlankNodes, }, { withDeletedKeys: true } ) .filter(isNotEmpty); // Unfortunately I haven't figured out how to generate the nested blank node // structures with fast-check yet, so this does not generate those: const fcPredicates = fc .dictionary(fc.webUrl({ withFragments: true }), fcObjects) .filter(isNotEmpty); const fcGraph = fc .dictionary( fc.oneof( fcLocalNodeIri, fc.webUrl({ withFragments: true, withQueryParameters: true }) ), fc.record({ type: fc.constant("Subject"), url: fc.webUrl({ withFragments: true, withQueryParameters: true }), predicates: fcPredicates, }) ) .filter(isNotEmpty) .map((graph) => { Object.keys(graph).forEach((subjectIri) => { graph[subjectIri].url = subjectIri; }); return graph; }); const fcDataset = fc.record({ type: fc.constant("Dataset"), graphs: fc .tuple( fc.dictionary(fc.webUrl({ withQueryParameters: true }), fcGraph), fcGraph ) .map(([otherGraphs, defaultGraph]) => ({ ...otherGraphs, default: defaultGraph, })), }); it("loses no data when serialising and deserialising to RDF/JS Datasets", () => { const runs = process.env.CI ? 100 : 1; expect.assertions(runs + 2); const fcResult = fc.check( fc.property(fcDataset, (dataset) => { expect( sortObject(fromRdfJsDataset(toRdfJsDataset(dataset as any))) ).toStrictEqual(sortObject(dataset)); }), { numRuns: runs } ); expect(fcResult.counterexample).toBeNull(); expect(fcResult.failed).toBe(false); }); it("can represent dangling Blank Nodes", () => { const datasetWithDanglingBlankNodes: ImmutableDataset = { type: "Dataset", graphs: { default: { "_:danglingSubjectBlankNode": { type: "Subject", url: "_:danglingSubjectBlankNode", predicates: { "http://www.w3.org/ns/auth/acl#origin": { blankNodes: [{}], }, }, }, }, }, }; const rdfJsDataset = toRdfJsDataset(datasetWithDanglingBlankNodes); expect(rdfJsDataset.size).toBe(1); const quad = Array.from(rdfJsDataset)[0]; expect(quad.subject.termType).toBe("BlankNode"); expect(quad.predicate.value).toBe("http://www.w3.org/ns/auth/acl#origin"); expect(quad.object.termType).toBe("BlankNode"); }); it("can take a custom DataFactory", () => { const customDataFactory = { quad: jest.fn(DataFactory.quad), namedNode: jest.fn(DataFactory.namedNode), literal: jest.fn(DataFactory.literal), blankNode: jest.fn(DataFactory.blankNode), defaultGraph: jest.fn(DataFactory.defaultGraph), } as RdfJs.DataFactory; const customDatasetFactory = { dataset: jest.fn(dataset), } as RdfJs.DatasetCoreFactory; const sourceDataset: ImmutableDataset = { type: "Dataset", graphs: { default: { "https://arbitrary.pod/resource#thing": { type: "Subject", url: "https://arbitrary.pod/resource#thing", predicates: { "https://arbitrary.vocab/predicate": { namedNodes: ["https://arbitrary.pod/other-resource#thing"], literals: { "https://arbitrary.vocab/literal-type": ["Arbitrary value"], }, blankNodes: ["_:arbitrary-blank-node"], }, }, }, }, }, }; toRdfJsDataset(sourceDataset, { dataFactory: customDataFactory, datasetFactory: customDatasetFactory, }); expect(customDataFactory.quad).toHaveBeenCalled(); expect(customDataFactory.namedNode).toHaveBeenCalled(); expect(customDataFactory.literal).toHaveBeenCalled(); expect(customDataFactory.blankNode).toHaveBeenCalled(); expect(customDataFactory.defaultGraph).toHaveBeenCalled(); expect(customDatasetFactory.dataset).toHaveBeenCalled(); }); }); function sortObject(value: Record<string, any>): Record<string, any> { if (typeof value !== "object") { return value; } if (Array.isArray(value)) { return [...value].sort(); } if (value === null) { return value; } const keys = Object.keys(value); keys.sort(); return keys.reduce( (newObject, key) => ({ ...newObject, [key]: sortObject(value[key]) }), {} ); }
the_stack
import * as Common from '../../../../core/common/common.js'; import * as Platform from '../../../../core/platform/platform.js'; import * as TextUtils from '../../../../models/text_utils/text_utils.js'; import * as UI from '../../legacy.js'; import type {CodeMirrorTextEditor} from './CodeMirrorTextEditor.js'; export class TextEditorAutocompleteController implements UI.SuggestBox.SuggestBoxDelegate { private textEditor: CodeMirrorTextEditor; private codeMirror: any; private config: UI.TextEditor.AutocompleteConfig; private initialized: boolean; private readonly mouseDown: () => void; private lastHintText: string; private suggestBox: UI.SuggestBox.SuggestBox|null; private currentSuggestion: UI.SuggestBox.Suggestion|null; private hintElement: HTMLSpanElement; private readonly tooltipGlassPane: UI.GlassPane.GlassPane; private readonly tooltipElement: HTMLDivElement; private queryRange: TextUtils.TextRange.TextRange|null; private dictionary?: Common.TextDictionary.TextDictionary; private updatedLines?: any; private hintMarker?: any|null; private anchorBox?: AnchorBox|null; // https://crbug.com/1151919 * = CodeMirror.Editor constructor(textEditor: CodeMirrorTextEditor, codeMirror: any, config: UI.TextEditor.AutocompleteConfig) { this.textEditor = textEditor; this.codeMirror = codeMirror; this.config = config; this.initialized = false; this.onScroll = this.onScroll.bind(this); this.onCursorActivity = this.onCursorActivity.bind(this); this.changes = this.changes.bind(this); this.blur = this.blur.bind(this); this.beforeChange = this.beforeChange.bind(this); this.mouseDown = (): void => { this.clearAutocomplete(); this.tooltipGlassPane.hide(); }; // @ts-ignore CodeMirror types are wrong. this.codeMirror.on('changes', this.changes); this.lastHintText = ''; this.suggestBox = null; this.currentSuggestion = null; this.hintElement = document.createElement('span'); this.hintElement.classList.add('auto-complete-text'); this.tooltipGlassPane = new UI.GlassPane.GlassPane(); this.tooltipGlassPane.setSizeBehavior(UI.GlassPane.SizeBehavior.MeasureContent); this.tooltipGlassPane.setOutsideClickCallback(this.tooltipGlassPane.hide.bind(this.tooltipGlassPane)); this.tooltipElement = document.createElement('div'); this.tooltipElement.classList.add('autocomplete-tooltip'); const shadowRoot = UI.Utils.createShadowRootWithCoreStyles(this.tooltipGlassPane.contentElement, { cssFile: 'ui/legacy/components/text_editor/autocompleteTooltip.css', delegatesFocus: undefined, }); shadowRoot.appendChild(this.tooltipElement); this.queryRange = null; } private initializeIfNeeded(): void { if (this.initialized) { return; } this.initialized = true; // @ts-ignore CodeMirror types are wrong. this.codeMirror.on('scroll', this.onScroll); // @ts-ignore CodeMirror types are wrong. this.codeMirror.on('cursorActivity', this.onCursorActivity); // @ts-ignore CodeMirror types are wrong. this.codeMirror.on('mousedown', this.mouseDown); // @ts-ignore CodeMirror types are wrong. this.codeMirror.on('blur', this.blur); if (this.config.isWordChar) { // @ts-ignore CodeMirror types are wrong. this.codeMirror.on('beforeChange', this.beforeChange); this.dictionary = new Common.TextDictionary.TextDictionary(); // @ts-ignore CodeMirror types are wrong. this.addWordsFromText(this.codeMirror.getValue()); } UI.ARIAUtils.setAutocomplete(this.textEditor.element, UI.ARIAUtils.AutocompleteInteractionModel.both); UI.ARIAUtils.setHasPopup(this.textEditor.element, UI.ARIAUtils.PopupRole.ListBox); } dispose(): void { // @ts-ignore CodeMirror types are wrong. this.codeMirror.off('changes', this.changes); if (this.initialized) { // @ts-ignore CodeMirror types are wrong. this.codeMirror.off('scroll', this.onScroll); // @ts-ignore CodeMirror types are wrong. this.codeMirror.off('cursorActivity', this.onCursorActivity); // @ts-ignore CodeMirror types are wrong. this.codeMirror.off('mousedown', this.mouseDown); // @ts-ignore CodeMirror types are wrong. this.codeMirror.off('blur', this.blur); } if (this.dictionary) { // @ts-ignore CodeMirror types are wrong. this.codeMirror.off('beforeChange', this.beforeChange); this.dictionary.reset(); } UI.ARIAUtils.clearAutocomplete(this.textEditor.element); UI.ARIAUtils.setHasPopup(this.textEditor.element, UI.ARIAUtils.PopupRole.False); } private beforeChange(codeMirror: typeof CodeMirror, changeObject: any): void { this.updatedLines = this.updatedLines || {}; for (let i = changeObject.from.line; i <= changeObject.to.line; ++i) { if (this.updatedLines[i] === undefined) { // @ts-ignore CodeMirror types are wrong. this.updatedLines[i] = this.codeMirror.getLine(i); } } } private addWordsFromText(text: string): void { TextUtils.TextUtils.Utils.textToWords( text, this.config.isWordChar as (arg0: string) => boolean, addWord.bind(this)); function addWord(this: TextEditorAutocompleteController, word: string): void { if (this.dictionary && word.length && (word[0] < '0' || word[0] > '9')) { this.dictionary.addWord(word); } } } private removeWordsFromText(text: string): void { TextUtils.TextUtils.Utils.textToWords( text, this.config.isWordChar as (arg0: string) => boolean, word => this.dictionary && this.dictionary.removeWord(word)); } private substituteRange(lineNumber: number, columnNumber: number): TextUtils.TextRange.TextRange|null { let range: TextUtils.TextRange.TextRange|(TextUtils.TextRange.TextRange | null) = this.config.substituteRangeCallback ? this.config.substituteRangeCallback(lineNumber, columnNumber) : null; if (!range && this.config.isWordChar) { range = this.textEditor.wordRangeForCursorPosition(lineNumber, columnNumber, this.config.isWordChar); } return range; } private wordsWithQuery( queryRange: TextUtils.TextRange.TextRange, substituteRange: TextUtils.TextRange.TextRange, force?: boolean): Promise<UI.SuggestBox.Suggestions> { const external = this.config.suggestionsCallback ? this.config.suggestionsCallback(queryRange, substituteRange, force) : null; if (external) { return external; } if (!this.dictionary || (!force && queryRange.isEmpty())) { return Promise.resolve([]); } let completions = this.dictionary.wordsWithPrefix(this.textEditor.text(queryRange)); const substituteWord = this.textEditor.text(substituteRange); if (this.dictionary.wordCount(substituteWord) === 1) { completions = completions.filter(word => word !== substituteWord); } const dictionary = this.dictionary; completions.sort((a, b) => dictionary.wordCount(b) - dictionary.wordCount(a) || a.length - b.length); return Promise.resolve(completions.map(item => ({ text: item, title: undefined, subtitle: undefined, iconType: undefined, priority: undefined, isSecondary: undefined, subtitleRenderer: undefined, selectionRange: undefined, hideGhostText: undefined, iconElement: undefined, }))); } private changes(codeMirror: typeof CodeMirror, changes: any[]): void { if (!changes.length) { return; } if (this.dictionary && this.updatedLines) { for (const lineNumber in this.updatedLines) { this.removeWordsFromText(this.updatedLines[lineNumber]); } delete this.updatedLines; const linesToUpdate: { [x: string]: string, } = {}; for (let changeIndex = 0; changeIndex < changes.length; ++changeIndex) { const changeObject = changes[changeIndex]; const editInfo = TextUtils.CodeMirrorUtils.changeObjectToEditOperation(changeObject); for (let i = editInfo.newRange.startLine; i <= editInfo.newRange.endLine; ++i) { // @ts-ignore CodeMirror types are wrong. linesToUpdate[String(i)] = this.codeMirror.getLine(i); } } for (const lineNumber in linesToUpdate) { this.addWordsFromText(linesToUpdate[lineNumber]); } } let singleCharInput = false; let singleCharDelete = false; // @ts-ignore CodeMirror types are wrong. const cursor = this.codeMirror.getCursor('head'); for (let changeIndex = 0; changeIndex < changes.length; ++changeIndex) { const changeObject = changes[changeIndex]; if (changeObject.origin === '+input' && changeObject.text.length === 1 && changeObject.text[0].length === 1 && changeObject.to.line === cursor.line && changeObject.to.ch + 1 === cursor.ch) { singleCharInput = true; break; } if (changeObject.origin === '+delete' && changeObject.removed.length === 1 && changeObject.removed[0].length === 1 && changeObject.to.line === cursor.line && changeObject.to.ch - 1 === cursor.ch) { singleCharDelete = true; break; } } if (this.queryRange) { if (singleCharInput) { this.queryRange.endColumn++; } else if (singleCharDelete) { this.queryRange.endColumn--; } if (singleCharDelete || singleCharInput) { this.setHint(this.lastHintText); } } if (singleCharInput || singleCharDelete) { queueMicrotask(() => { this.autocomplete(); }); } else { this.clearAutocomplete(); } } private blur(): void { this.clearAutocomplete(); } private validateSelectionsContexts(mainSelection: TextUtils.TextRange.TextRange): boolean { // @ts-ignore CodeMirror types are wrong. const selections = this.codeMirror.listSelections(); if (selections.length <= 1) { return true; } const mainSelectionContext = this.textEditor.text(mainSelection); for (let i = 0; i < selections.length; ++i) { const wordRange = this.substituteRange(selections[i].head.line, selections[i].head.ch); if (!wordRange) { return false; } const context = this.textEditor.text(wordRange); if (context !== mainSelectionContext) { return false; } } return true; } autocomplete(force?: boolean): void { this.initializeIfNeeded(); // @ts-ignore CodeMirror types are wrong. if (this.codeMirror.somethingSelected()) { this.hideSuggestBox(); return; } // @ts-ignore CodeMirror types are wrong. const cursor = this.codeMirror.getCursor('head'); const substituteRange = this.substituteRange(cursor.line, cursor.ch); if (!substituteRange || !this.validateSelectionsContexts(substituteRange)) { this.hideSuggestBox(); return; } const queryRange = substituteRange.clone(); queryRange.endColumn = cursor.ch; const query = this.textEditor.text(queryRange); let hadSuggestBox = false; if (this.suggestBox) { hadSuggestBox = true; } this.wordsWithQuery(queryRange, substituteRange, force).then(wordsWithQuery => { return wordsAcquired(wordsWithQuery); }); const wordsAcquired = (wordsWithQuery: UI.SuggestBox.Suggestions): void => { if (!wordsWithQuery.length || (wordsWithQuery.length === 1 && query === wordsWithQuery[0].text) || (!this.suggestBox && hadSuggestBox)) { this.hideSuggestBox(); this.onSuggestionsShownForTest([]); return; } if (!this.suggestBox) { this.suggestBox = new UI.SuggestBox.SuggestBox(this, 20); if (this.config.anchorBehavior) { this.suggestBox.setAnchorBehavior(this.config.anchorBehavior); } } const oldQueryRange = this.queryRange; this.queryRange = queryRange; if (!oldQueryRange || queryRange.startLine !== oldQueryRange.startLine || queryRange.startColumn !== oldQueryRange.startColumn) { this.updateAnchorBox(); } this.anchorBox && this.suggestBox.updateSuggestions(this.anchorBox, wordsWithQuery, true, !this.isCursorAtEndOfLine(), query); if (this.suggestBox.visible()) { this.tooltipGlassPane.hide(); } this.onSuggestionsShownForTest(wordsWithQuery); }; } private setHint(hint: string): void { if (this.queryRange === null) { return; } const query = this.textEditor.text(this.queryRange); if (!hint || !this.isCursorAtEndOfLine() || !hint.startsWith(query)) { this.clearHint(); return; } const suffix = hint.substring(query.length).split('\n')[0]; this.hintElement.textContent = Platform.StringUtilities.trimEndWithMaxLength(suffix, 10000); // @ts-ignore CodeMirror types are wrong. const cursor = this.codeMirror.getCursor('to'); if (this.hintMarker) { const position = this.hintMarker.position(); if (!position || !position.equal(TextUtils.TextRange.TextRange.createFromLocation(cursor.line, cursor.ch))) { this.hintMarker.clear(); this.hintMarker = null; } } if (!this.hintMarker) { this.hintMarker = this.textEditor.addBookmark( cursor.line, cursor.ch, this.hintElement as HTMLElement, TextEditorAutocompleteController.HintBookmark, true); } else if (this.lastHintText !== hint) { this.hintMarker.refresh(); } this.lastHintText = hint; } private clearHint(): void { if (!this.hintElement.textContent) { return; } this.lastHintText = ''; this.hintElement.textContent = ''; if (this.hintMarker) { this.hintMarker.refresh(); } } private onSuggestionsShownForTest(_suggestions: UI.SuggestBox.Suggestions): void { } private onSuggestionsHiddenForTest(): void { } clearAutocomplete(): void { this.tooltipGlassPane.hide(); this.hideSuggestBox(); } private hideSuggestBox(): void { if (!this.suggestBox) { return; } this.suggestBox.hide(); this.suggestBox = null; this.queryRange = null; this.anchorBox = null; this.currentSuggestion = null; this.textEditor.dispatchEventToListeners(UI.TextEditor.Events.SuggestionChanged); this.clearHint(); this.onSuggestionsHiddenForTest(); } keyDown(event: KeyboardEvent): boolean { if (this.tooltipGlassPane.isShowing() && event.keyCode === UI.KeyboardShortcut.Keys.Esc.code) { this.tooltipGlassPane.hide(); return true; } if (!this.suggestBox) { return false; } switch (event.keyCode) { case UI.KeyboardShortcut.Keys.Tab.code: this.suggestBox.acceptSuggestion(); this.clearAutocomplete(); return true; case UI.KeyboardShortcut.Keys.End.code: case UI.KeyboardShortcut.Keys.Right.code: if (this.isCursorAtEndOfLine()) { this.suggestBox.acceptSuggestion(); this.clearAutocomplete(); return true; } this.clearAutocomplete(); return false; case UI.KeyboardShortcut.Keys.Left.code: case UI.KeyboardShortcut.Keys.Home.code: this.clearAutocomplete(); return false; case UI.KeyboardShortcut.Keys.Esc.code: this.clearAutocomplete(); return true; } return this.suggestBox.keyPressed(event); } private isCursorAtEndOfLine(): boolean { // @ts-ignore CodeMirror types are wrong. const cursor = this.codeMirror.getCursor('to'); // @ts-ignore CodeMirror types are wrong. return cursor.ch === this.codeMirror.getLine(cursor.line).length; } applySuggestion(suggestion: UI.SuggestBox.Suggestion|null, _isIntermediateSuggestion?: boolean): void { const oldSuggestion = this.currentSuggestion; this.currentSuggestion = suggestion; this.setHint(suggestion ? suggestion.text : ''); if ((oldSuggestion ? oldSuggestion.text : '') !== (suggestion ? suggestion.text : '')) { this.textEditor.dispatchEventToListeners(UI.TextEditor.Events.SuggestionChanged); } } acceptSuggestion(): void { if (this.currentSuggestion === null || this.queryRange === null) { return; } // @ts-ignore CodeMirror types are wrong. const selections = this.codeMirror.listSelections().slice(); const queryLength = this.queryRange.endColumn - this.queryRange.startColumn; const suggestion = this.currentSuggestion.text; // @ts-ignore CodeMirror types are wrong. this.codeMirror.operation(() => { for (let i = selections.length - 1; i >= 0; --i) { const start = selections[i].head; const end = new CodeMirror.Pos(start.line, start.ch - queryLength); // @ts-ignore CodeMirror types are wrong. this.codeMirror.replaceRange(suggestion, start, end, '+autocomplete'); } }); } ariaControlledBy(): Element { return this.textEditor.element; } textWithCurrentSuggestion(): string { if (!this.queryRange || this.currentSuggestion === null) { // @ts-ignore CodeMirror types are wrong. return this.codeMirror.getValue(); } // @ts-ignore CodeMirror types are wrong. const selections = this.codeMirror.listSelections().slice(); let last: { line: any, column: any, }|{ line: number, column: number, } = {line: 0, column: 0}; let text = ''; const queryLength = this.queryRange.endColumn - this.queryRange.startColumn; for (const selection of selections) { const range = new TextUtils.TextRange.TextRange( last.line, last.column, selection.head.line, selection.head.ch - queryLength); text += this.textEditor.text(range); text += this.currentSuggestion.text; last = {line: selection.head.line, column: selection.head.ch}; } const range = new TextUtils.TextRange.TextRange(last.line, last.column, Infinity, Infinity); text += this.textEditor.text(range); return text; } private onScroll(): void { this.tooltipGlassPane.hide(); if (!this.suggestBox) { return; } // @ts-ignore CodeMirror types are wrong. const cursor = this.codeMirror.getCursor(); // @ts-ignore CodeMirror types are wrong. const scrollInfo = this.codeMirror.getScrollInfo(); // @ts-ignore CodeMirror types are wrong. const topmostLineNumber = this.codeMirror.lineAtHeight(scrollInfo.top, 'local'); // @ts-ignore CodeMirror types are wrong. const bottomLine = this.codeMirror.lineAtHeight(scrollInfo.top + scrollInfo.clientHeight, 'local'); if (cursor.line < topmostLineNumber || cursor.line > bottomLine) { this.clearAutocomplete(); } else { this.updateAnchorBox(); this.anchorBox && this.suggestBox.setPosition(this.anchorBox); } } private async updateTooltip(): Promise<void> { // @ts-ignore CodeMirror types are wrong. const cursor = this.codeMirror.getCursor(); const tooltip = this.config.tooltipCallback ? await this.config.tooltipCallback(cursor.line, cursor.ch) : null; // @ts-ignore CodeMirror types are wrong. const newCursor = this.codeMirror.getCursor(); if (newCursor.line !== cursor.line && newCursor.ch !== cursor.ch) { return; } if (this.suggestBox && this.suggestBox.visible) { return; } if (!tooltip) { this.tooltipGlassPane.hide(); return; } const metrics = this.textEditor.cursorPositionToCoordinates(cursor.line, cursor.ch); if (!metrics) { this.tooltipGlassPane.hide(); return; } this.tooltipGlassPane.setContentAnchorBox(new AnchorBox(metrics.x, metrics.y, 0, metrics.height)); this.tooltipElement.removeChildren(); this.tooltipElement.appendChild(tooltip); this.tooltipGlassPane.show(this.textEditor.element.ownerDocument as Document); } private onCursorActivity(): void { this.updateTooltip(); if (!this.suggestBox || this.queryRange === null) { return; } // @ts-ignore CodeMirror types are wrong. const cursor = this.codeMirror.getCursor(); let shouldCloseAutocomplete: boolean = !(cursor.line === this.queryRange.startLine && this.queryRange.startColumn <= cursor.ch && cursor.ch <= this.queryRange.endColumn); // Try not to hide autocomplete when user types in. if (cursor.line === this.queryRange.startLine && cursor.ch === this.queryRange.endColumn + 1) { // @ts-ignore CodeMirror types are wrong. const line = this.codeMirror.getLine(cursor.line); shouldCloseAutocomplete = this.config.isWordChar ? !this.config.isWordChar(line.charAt(cursor.ch - 1)) : false; } if (shouldCloseAutocomplete) { this.clearAutocomplete(); } this.onCursorActivityHandledForTest(); } private onCursorActivityHandledForTest(): void { } private updateAnchorBox(): void { if (this.queryRange === null) { return; } const line = this.queryRange.startLine; const column = this.queryRange.startColumn; const metrics = this.textEditor.cursorPositionToCoordinates(line, column); this.anchorBox = metrics ? new AnchorBox(metrics.x, metrics.y, 0, metrics.height) : null; } // eslint-disable-next-line @typescript-eslint/naming-convention static readonly HintBookmark = Symbol('hint'); }
the_stack
import React from 'react'; import sortBy from 'lodash/sortBy'; import findIndex from 'lodash/findIndex'; import partition from 'lodash/partition'; import reverse from 'lodash/reverse'; import isNumber from 'lodash/isNumber'; import { Wrapper, Footer, HeaderContainer, CompareHeader, NumberOfLocationsText, } from 'components/Compare/Compare.style'; import LocationTable from './LocationTable'; import Filters from 'components/Compare/Filters'; import { SummaryForCompare, RankedLocationSummary, GeoScopeFilter, getShareQuote, trackCompareEvent, HomepageLocationScope, homepageLabelMap, sliderNumberToFilterMap, } from 'common/utils/compare'; import { COLOR_MAP } from 'common/colors'; import ShareButtonGroup from 'components/ShareButtons/ShareButtonGroup'; import { getComparePageUrl, getCompareShareImageUrl } from 'common/urls'; import { EventAction } from 'components/Analytics'; import { Region, MetroArea, State } from 'common/regions'; import { orderedColumns, orderedColumnsVaccineFirst, orderedColumnsVulnerabilityFirst, } from './columns'; import { EventCategory } from 'components/Analytics/utils'; import ExpandableContainer from 'components/ExpandableContainer'; import { ShareBlock } from 'components/Footer/Footer.style'; function trackShare(label: string) { trackCompareEvent(EventAction.SHARE, label); } const CompareTable = (props: { stateName?: string; setShowModal: React.Dispatch<React.SetStateAction<boolean>>; isModal: boolean; locationsViewable?: number; isHomepage?: boolean; // TODO (Chelsi) delete this prop, absence/presence of region does the same thing locations: SummaryForCompare[]; currentCounty: any | null; viewMoreCopy?: string; geoScope: GeoScopeFilter; setGeoScope: React.Dispatch<React.SetStateAction<GeoScopeFilter>>; stateId?: string; sorter: number; setSorter: React.Dispatch<React.SetStateAction<number>>; sortDescending: boolean; setSortDescending: React.Dispatch<React.SetStateAction<boolean>>; sortByPopulation: boolean; setSortByPopulation: React.Dispatch<React.SetStateAction<boolean>>; sliderValue: GeoScopeFilter; createCompareShareId: () => Promise<string>; homepageScope: HomepageLocationScope; setHomepageScope: React.Dispatch<React.SetStateAction<HomepageLocationScope>>; homepageSliderValue: HomepageLocationScope; region?: Region; vaccinesFirst?: boolean; vulnerabilityFirst?: boolean; }) => { const { currentCounty, sorter, setSorter, sortDescending, setSortDescending, sortByPopulation, setSortByPopulation, sliderValue, stateId, homepageScope, setHomepageScope, homepageSliderValue, region, vaccinesFirst, vulnerabilityFirst, } = props; const currentCountyFips = currentCounty ? currentCounty.region.fipsCode : 0; function sortLocationsBy( locations: SummaryForCompare[], getValue: (location: SummaryForCompare) => number | null, ) { const [locationsWithValue, locationsWithoutValue] = partition( locations, location => isNumber(getValue(location)), ); const sortedLocationsAsc = sortBy(locationsWithValue, getValue); const sortedLocations = sortDescending ? reverse(sortedLocationsAsc) : sortedLocationsAsc; return [...sortedLocations, ...locationsWithoutValue]; } let columns = vaccinesFirst ? orderedColumnsVaccineFirst : orderedColumns; columns = vulnerabilityFirst ? orderedColumnsVulnerabilityFirst : columns; const getPopulation = (location: SummaryForCompare) => location.region.population; const getSortByValue = (location: SummaryForCompare) => { // TODO(https://trello.com/c/x0G7LZ91): Not sure if this check should be necessary, // but we seem to be missing projections for Northern Islands Municipality, MP right now. if (!location.metricsInfo) { return null; } let sortedColumn = columns.find(c => c.columnId === sorter) ?? columns[0]; return sortedColumn.getValue(location); }; let sortedLocationsArr = props.locations; if (sortByPopulation) { sortedLocationsArr = sortLocationsBy(props.locations, getPopulation); } else { sortedLocationsArr = sortLocationsBy(props.locations, getSortByValue); } const currentCountyRank = findIndex( sortedLocationsArr, (location: SummaryForCompare) => location.region.fipsCode === currentCountyFips, ); const locationsViewable = props.locationsViewable || sortedLocationsArr.length; //TODO (chelsi): make this a theme- const arrowColorSelected = 'white'; const arrowColorNotSelected = COLOR_MAP.GREY_3; const arrowContainerProps = { sortDescending, sorter, arrowColorSelected, arrowColorNotSelected, }; // checks if there are less counties than the default amount shown (10): const amountDisplayed = props.locationsViewable && sortedLocationsArr.length < props.locationsViewable ? sortedLocationsArr.length : props.locationsViewable; const firstColumnHeaderHomepage = props.homepageScope === HomepageLocationScope.COUNTY ? `${homepageLabelMap[HomepageLocationScope.COUNTY].singular}` : `${homepageLabelMap[homepageScope].singular}`; const firstColumnHeader = props.isHomepage ? firstColumnHeaderHomepage : props.isModal ? `Counties (${sortedLocationsArr.length})` : `County`; const sortedLocations: RankedLocationSummary[] = sortedLocationsArr .filter((location: SummaryForCompare) => location.metricsInfo !== null) .map((summary: SummaryForCompare, i: number) => ({ rank: i + 1, ...summary, })); const currentLocation = currentCounty ? { rank: currentCountyRank + 1, ...currentCounty } : null; const shareQuote = getShareQuote( sorter, sliderNumberToFilterMap[sliderValue], sortedLocationsArr.length, sortDescending, props.homepageScope, currentLocation, sortByPopulation, props.stateName, region, ); // Disabling filters for Northern Mariana Islands because they don't have // any data on metro vs non-metro islands. There may be more elegant solutions // that better handle any region without metro/non-metro regions. // TODO(chris): https://trello.com/c/KdfFwRvf/430-handle-filters-in-compare-table-with-no-results-more-cleanly const disableFilters = stateId === 'MP' || (region && region instanceof MetroArea) || (region && region instanceof State); // Only showing the view more text when all locations are not available. const showViewMore = amountDisplayed !== sortedLocationsArr.length; const getShareUrl = () => props.createCompareShareId().then(id => `${getComparePageUrl(id, region)}`); const getDownloadImageUrl = () => props.createCompareShareId().then(id => `${getCompareShareImageUrl(id)}`); // TODO: What is the best way to label here? const trackLabel = 'Compare'; const onClickShowAll = () => { props.setShowModal(true); trackCompareEvent(EventAction.OPEN_MODAL, 'Show All Locations'); }; /** * Only show limited locations (100 max) in the following scenarios: * - "Counties" tab selected on homepage. * - "Metro areas" tab selected on homepage. * - "USA" tab selected on location page. */ const showAllLocations = (props.isHomepage && props.homepageScope === HomepageLocationScope.STATE) || (!props.isHomepage && props.geoScope !== GeoScopeFilter.COUNTRY); const seeAllText = ( <> See {showAllLocations ? 'all' : 'more'} &nbsp; <NumberOfLocationsText> ({showAllLocations ? sortedLocationsArr.length : 100}) </NumberOfLocationsText> </> ); const containerProps = { collapsedHeightMobile: 'fit-content', collapsedHeightDesktop: 'fit-content', tabTextCollapsed: seeAllText, tabTextExpanded: seeAllText, trackingLabel: 'Open compare modal', trackingCategory: EventCategory.COMPARE, disableArrowChange: true, secondaryOnClick: onClickShowAll, }; const locationTableProps = { firstColumnHeader: firstColumnHeader, setSorter: setSorter, setSortDescending: setSortDescending, columns: columns, isModal: props.isModal, ...arrowContainerProps, pinnedLocation: currentLocation, sortedLocations: sortedLocations, numLocations: locationsViewable, stateName: props.stateName, setSortByPopulation: setSortByPopulation, sortByPopulation: sortByPopulation, isHomepage: props.isHomepage, geoScope: props.geoScope, homepageScope: homepageScope, region: region, }; return ( <Wrapper $isModal={props.isModal} $isHomepage={props.isHomepage}> {!props.isModal && ( <HeaderContainer $isHomepage={props.isHomepage}> <CompareHeader $isHomepage={props.isHomepage}> {props.region ? 'Counties' : 'Compare'} </CompareHeader> {!disableFilters && ( <Filters isHomepage={props.isHomepage} stateId={props.stateId} isCounty={Boolean(currentCounty)} geoScope={props.geoScope} setGeoScope={props.setGeoScope} isModal={props.isModal} sliderValue={sliderValue} homepageScope={homepageScope} setHomepageScope={setHomepageScope} homepageSliderValue={homepageSliderValue} /> )} </HeaderContainer> )} {!props.isModal && showViewMore ? ( <ExpandableContainer {...containerProps}> <LocationTable {...locationTableProps} /> </ExpandableContainer> ) : ( <LocationTable {...locationTableProps} /> )} {!props.isModal && ( <Footer> <ShareBlock> <ShareButtonGroup imageUrl={getDownloadImageUrl} imageFilename="CovidActNow-compare.png" url={getShareUrl} quote={shareQuote} region={region} onCopyLink={() => trackCompareEvent(EventAction.COPY_LINK, trackLabel) } onSaveImage={() => trackCompareEvent(EventAction.SAVE_IMAGE, trackLabel) } onShareOnFacebook={() => trackShare(`Facebook: ${trackLabel}`)} onShareOnTwitter={() => trackShare(`Twitter: ${trackLabel}`)} /> </ShareBlock> </Footer> )} </Wrapper> ); }; export default CompareTable;
the_stack
import { Component, AfterViewInit, ViewChild, DoCheck, Input, ComponentFactoryResolver, OnDestroy } from "@angular/core"; import { TranslateService } from "@ngx-translate/core"; import { IdpService } from "../idp-service.service"; import { IdprestapiService } from "../idprestapi.service"; import { Router } from "@angular/router"; import { IdpdataService } from "../idpdata.service"; import { DataTable, DataTableResource } from "angular-2-data-table"; import { DynamicComponentDirective } from "../custom-directive/dynamicComponent.directive"; import { TriggerComponent } from "../triggerPipeline/triggerPipeline.component"; import {IDPEncryption} from "../idpencryption.service"; import {BsModalService, BsModalRef} from "../../../node_modules/ngx-bootstrap"; declare var jQuery: any; @Component({ selector: "app-workflow-info", templateUrl: "./workflow-info.component.html", styleUrls: ["./workflow-info.component.css"] }) export class WorkflowInfoComponent implements AfterViewInit, OnDestroy { @ViewChild("modalforAlert") modalforAlert; @ViewChild("modalforAlertDataMiss") modalforAlertDataMiss; @ViewChild("modalformandatoryFieldsAlert") modalformandatoryFieldsAlert; @ViewChild("modalforconfirmAlert") modalforconfirmAlert; @ViewChild("modalforTrigger") modalforTrigger; @ViewChild("modalForTriggerDetails") modalForTriggerDetails; workflowData: any = this.Idpdata.workflowData; IDPWorkflowParamData: any= {}; newOrEditWorkflow: string; listToFillFields: any = []; formStatusObject = this.Idpdata.data.formStatus; appPipeNamesAvailable = false; isReleaseAvailable = true; loader: any = "off"; message: any; errorMessage: any; appNames: any = []; pipeNames: any = {}; noPipelines = false; releaseNumberList: any = []; resetFlag = false; initialSequence: any; pipelinesSelection = []; extraMultiselectSettings: any = { enableSearchFilter: true, selectAllText: "Select All", unSelectAllText: "UnSelect All" }; seqCollapseStatus:Array<any> = []; @ViewChild(DynamicComponentDirective) dynamicComponent: DynamicComponentDirective; modalforAlertRef: BsModalRef; modalforAlertDataMissRef: BsModalRef; modalformandatoryFieldsAlertRef: BsModalRef; modalforconfirmAlertRef: BsModalRef; modalforTriggerRef: BsModalRef; modalForTriggerDetailsRef: BsModalRef; constructor(public Idpdata: IdpdataService, private Idprestapi: IdprestapiService, private router: Router, private componentFactoryResolver: ComponentFactoryResolver, public IdpService : IdpService, private idpencryption: IDPEncryption, private modalService: BsModalService ) { console.log(this.Idpdata.triggerJobData); this.initialize(); } ngAfterViewInit() { this.initNavigation(); const filterString = "nonSAP"; this.getApplicationNames(filterString); } ngOnDestroy() { } redirectToBasicInfo() { this.Idpdata.createWorkflowSequenceflag = false; this.router.navigate(["/createConfig/basicInfo"]); } redirectToShowConfiguration() { this.Idpdata.createWorkflowSequenceflag = false; this.router.navigate(["/previousConfig/showConfigurations"]); } initNavigation() { const url: string = this.router.url; if (url.includes("createConfig") && !this.Idpdata.workflowTrigger && this.Idpdata.data.formStatus.basicInfo.appNameStatus === "0") { this.modalforAlertRef = this.modalService.show(this.modalforAlert); } else if ( url.includes("previousConfig") && this.Idpdata.triggerJobData === undefined) { this.redirectToShowConfiguration(); } } initialize() { const url: string = this.router.url; if ( url.includes("createConfig") ) { this.Idpdata.workflowTrigger = false; } else if ( url.includes("previousConfig")) { if (this.Idpdata.triggerJobData === undefined) { this.redirectToShowConfiguration(); } this.Idpdata.workflowTrigger = true; } if (!this.Idpdata.workflowTrigger && (this.Idpdata.createWorkflowSequenceflag === undefined || !this.Idpdata.createWorkflowSequenceflag) ) { this.Idpdata.createWorkflowSequenceflag = true; } if (this.Idpdata.workflowTrigger) { this.IDPWorkflowParamData = { "applicationName": "", "artifactorySelected": "off", "technology": "", "subApplicationName": "", "jobParam": [], "build": { "branchSelected": "", "module": [] }, "deploy": null, "envSelected": "", "pipelineName": "", "releaseNumber": "", "jobBuildId": "", "slaveName": "", "testSlaveName": "", "tfsWorkItem": "", "branchOrTag": "", "testPlanId": "", "testSuitId": "", "mtmStepName": "", "repoDeployStatus": "", "nonRepoDeployStatus": "", "testSelected": "off", "testStep": [], "userName": this.Idpdata.idpUserName, "gitTag": "", "buildartifactNumber": "" }; this.releaseNumberList = this.Idpdata.triggerJobData.hasOwnProperty("releaseNumber") ? this.Idpdata.triggerJobData.releaseNumber : []; this.IDPWorkflowParamData.applicationName = this.Idpdata.triggerJobData.hasOwnProperty("applicationName") ? this.Idpdata.triggerJobData.applicationName : ""; this.IDPWorkflowParamData.pipelineName = this.Idpdata.triggerJobData.hasOwnProperty("pipelineName") ? this.Idpdata.triggerJobData.pipelineName : ""; this.IDPWorkflowParamData.technology = this.Idpdata.triggerJobData.technology; this.Idpdata.triggerWorkflowJobData = this.Idpdata.triggerJobData; this.workflowData.workflowSequence = this.Idpdata.triggerWorkflowJobData.pipelines; console.log("workflow sequence: " + this.Idpdata.triggerWorkflowJobData.pipelines); this.workflowData.pipelines = this.Idpdata.triggerWorkflowJobData.pipelines; let i = 0; this.workflowData.workflowSequenceTemp = []; this.IDPWorkflowParamData.pipelineSelection = []; for (const pipe of this.workflowData.workflowSequence) { let j = 0; this.IDPWorkflowParamData.pipelineSelection.push({}); this.IDPWorkflowParamData.pipelineSelection[i].appSelectionDetails = []; for (const appDetails of pipe.applicationDetails) { this.IDPWorkflowParamData.pipelineSelection[i].appSelectionDetails.push({}); this.IDPWorkflowParamData.pipelineSelection[i].appSelectionDetails[j].pipelineSelectionDetails = []; for (const pipeDetails of appDetails.pipelineDetails) { this.IDPWorkflowParamData.pipelineSelection[i].appSelectionDetails[j].pipelineSelectionDetails.push("on"); this.workflowData.workflowSequence[i].applicationDetails[j].applicationName = pipeDetails.applicationName; if (this.workflowData.workflowSequence[i].applicationDetails[j].pipelineNameTrigger === undefined) { this.workflowData.workflowSequence[i].applicationDetails[j].pipelineNameTrigger = pipeDetails.pipelineName; } else { this.workflowData.workflowSequence[i].applicationDetails[j].pipelineNameTrigger = this.workflowData.workflowSequence[i].applicationDetails[j].pipelineNameTrigger + ", " + pipeDetails.pipelineName; } this.workflowData.workflowSequenceTemp.push({}); this.getPipelineList(pipeDetails.applicationName); this.workflowData.workflowSequenceTemp[i].applicationName = pipeDetails.applicationName; this.workflowData.workflowSequenceTemp[i].pipelineName = pipeDetails.pipelineName; this.workflowData.workflowSequenceTemp[i].appPipeNamesDetails = true; } j++; } i++; } } else if (this.formStatusObject.operation === "copy" || this.formStatusObject.operation === "edit") { this.newOrEditWorkflow = "old"; // edit condition console.log("copy Edit:"); console.log(this.workflowData.workflowSequence); if (this.resetFlag) { try { this.workflowData.workflowSequence = JSON.parse(JSON.stringify(this.initialSequence)); } catch (all) { } // this.workflowData.workflowSequence = this.initialSequence; this.resetFlag = false; } else { try { this.initialSequence = JSON.parse(JSON.stringify(this.workflowData.workflowSequence)); } catch (all) { } // this.initialSequence = this.workflowData.workflowSequence; } this.workflowData.workflowSequenceTemp = []; if (this.workflowData.workflowSequence !== undefined && this.workflowData.workflowSequence.length > 0) { let i = 0; let indexI = 0; for (const pipe of this.workflowData.workflowSequence) { this.workflowData.workflowSequenceTemp.push({ "expand": false, "applicationDetails": [] }); let indexJ = 0; for (const appDetails of pipe.applicationDetails) { this.workflowData.workflowSequenceTemp[indexI].applicationDetails.push({}); appDetails.allPipelineNames = []; const c = 0; for (const pipeDetails of appDetails.pipelineDetails) { appDetails.applicationName = pipeDetails.applicationName; this.getPipelineListCopyEdit(pipeDetails.applicationName, pipeDetails.pipelineName, indexI, indexJ); this.workflowData.workflowSequenceTemp[indexI].applicationDetails[indexJ].applicationName = pipeDetails.applicationName; this.workflowData.workflowSequenceTemp[indexI].appPipeNamesDetails = true; i++; } indexJ++; } indexI++; } } } else { this.newOrEditWorkflow = "new"; if (this.workflowData.workflowSequence === undefined || this.resetFlag) { this.workflowData.workflowSequence = []; this.workflowData.workflowSequenceTemp = []; if (this.resetFlag) { this.resetFlag = false; } } } } getPipelineListCopyEdit(appName, pipeName, indexI, indexJ) { console.log("getting pipeline Names"); console.log(appName); this.Idprestapi.getPipelineListforWorkflow(appName).then(response => { console.log(response); const resp = response.json(); const errorMsg = resp.errorMessage; console.log("required" + JSON.stringify(resp)); this.Idpdata.pipelineNames = []; const pipeNamesList = []; if (resp.resource !== "No Pipelines") { const pipData = JSON.parse(resp.resource); console.log(pipData); let c = 1; for (const i of pipData.names) { if (pipeName === i) { this.workflowData.workflowSequence[indexI].applicationDetails[indexJ].allPipelineNames.push({ "id": c, "itemName": pipeName}); } pipeNamesList.push({ "id": c, "itemName": i}); c = c + 1; } this.pipeNames[appName] = pipeNamesList; } else { this.noPipelines = true; } }); } getPipelineList(appName) { console.log("getting pipeline Names"); console.log(appName); this.Idprestapi.getPipelineListforWorkflow(appName).then(response => { console.log(response); const resp = response.json(); const errorMsg = resp.errorMessage; console.log("required" + JSON.stringify(resp)); this.Idpdata.pipelineNames = []; const pipeNamesList = []; if (resp.resource !== "No Pipelines") { const pipData = JSON.parse(resp.resource); console.log(pipData); let c = 1; for (const i of pipData.names) { pipeNamesList.push({ "id": c, "itemName": i}); c = c + 1; } this.pipeNames[appName] = pipeNamesList; } else { this.noPipelines = true; } }); } togglePanel(i) { if (this.workflowData.workflowSequenceTemp[i].expand === undefined || !this.workflowData.workflowSequenceTemp[i].expand) { this.workflowData.workflowSequenceTemp[i].expand = true; } else { this.workflowData.workflowSequenceTemp[i].expand = false; } console.log(this.workflowData.workflowSequence); } addSequence() { this.workflowData.workflowSequence.push({ applicationDetails: [], allPipelineNames: [] }); this.workflowData.workflowSequenceTemp.push({ "expand": false, applicationDetails: [] }); } removeSequence(index) { const x = confirm("Are you sure you want to delete the Step No_" + (index + 1) + "?"); if (x) { this.workflowData.workflowSequence.splice(index, 1); this.workflowData.workflowSequenceTemp.splice(index, 1); } } addApplication(i) { this.workflowData.workflowSequence[i].applicationDetails.push({ applicationName: "", pipelineDetails: [], allPipelineNames: [] }); this.workflowData.workflowSequenceTemp[i].applicationDetails.push({ applicationName: "", pipelineDetails: [] }); } removeApplication(i, j) { const x = confirm("Are you sure you want to remove application: " + this.workflowData.workflowSequence[i].applicationDetails[j].applicationName); if (x) { this.workflowData.workflowSequence[i].applicationDetails.splice(j, 1); } } getApplicationNames(data) { this.Idprestapi.getFilteredApplicationNames(data) .then(response => { try { console.log("Response: " + response); if (response) { const appDetails = JSON.parse(response.json().resource); this.appNames = appDetails.applicationNames; console.log("Application list " + data + ": " + this.appNames); } } catch (e) { console.log(e); alert("Failed while getting applications names"); } }); } refreshSaveDetails(i, j) { if (this.workflowData.workflowSequenceTemp[i].applicationDetails[j].applicationName !== undefined && this.workflowData.workflowSequenceTemp[i].applicationDetails[j].applicationName !== "" ) { let mesg = "Do you want to reset the pipeline name "; mesg = mesg + this.workflowData.workflowSequence[i].applicationDetails[j].applicationName; const con = confirm(mesg); if (con) { const applicationName = this.workflowData.workflowSequence[i].applicationDetails[j].applicationName; this.workflowData.workflowSequence[i].applicationDetails[j] = { "applicationName" : applicationName, "pipelineDetails" : [], "allPipelineNames" : [], "expand": true }; this.workflowData.workflowSequenceTemp[i].applicationDetails[j] = { "applicationName" : applicationName, "pipelineDetails" : [], "allPipelineNames" : [], "expand": true }; } else { this.workflowData.workflowSequence[i].applicationDetails[j].applicationName = this.workflowData.workflowSequenceTemp[i].applicationDetails[j].applicationName; } } else { this.workflowData.workflowSequenceTemp[i].applicationDetails[j].applicationName = this.workflowData.workflowSequence[i].applicationDetails[j].applicationName; } } fetchPipelineTriggerDetails(reqData, i, j, k):Promise<any> { this.appPipeNamesAvailable = false; return this.Idprestapi.triggerJob(reqData) .then(response => { try { if (response) { const result = response.json().resource; console.log(result); if (result !== "{}" && result !== null) { this.Idpdata.triggerJobData = JSON.parse(result); if (this.Idpdata.triggerJobData.releaseNumber !== null && this.Idpdata.triggerJobData.releaseNumber.length !== 0) { this.Idpdata.appName = reqData.applicationName; this.Idpdata.pipelineName = reqData.pipelineName; this.getComponentToLoad(i, j, k); } else if (this.Idpdata.triggerJobData.roles.indexOf("RELEASE_MANAGER") === -1) { this.isReleaseAvailable = false; alert("No active releases for this pipeline. Please add releases before adding in workflow sequence"); } else { this.isReleaseAvailable = false; alert("No active releases for this pipeline. Please contact the release manager."); } } else { this.isReleaseAvailable = false; alert("Failed to get the Trigger Job Details"); } } } catch (e) { alert("Failed to get trigger details"); console.log(e); } }); } getComponentToLoad(i, j, k) { this.appPipeNamesAvailable = false; console.log("Change In Index(" + i + ") : " + this.dynamicComponent); let componentFactory ; let viewContainerRef; let componentRef; componentFactory = this.componentFactoryResolver.resolveComponentFactory(TriggerComponent); viewContainerRef = this.dynamicComponent.viewContainerRef; viewContainerRef.clear(); componentRef = viewContainerRef.createComponent(componentFactory); this.workflowData.workflowSequenceTemp[i].componentInstance = (<TriggerComponent>componentRef.instance); componentRef.instance.workflowSequenceIndexI = i; componentRef.instance.workflowSequenceIndexJ = j; componentRef.instance.workflowSequenceIndexK = k; componentRef.instance.workflowSequence = this.workflowData.workflowSequence; componentRef.instance.getJobParamDetails(); componentRef.instance.onTriggerDetailsSaved.subscribe((event)=>{ this.modalForTriggerDetails.hide(); }) this.appPipeNamesAvailable = true; } launchTriggerDetailsModal(i, j, k) { if (this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails[k].releaseNumber !== undefined) { alert("You are going to update the saved details; if you fill details and save it?"); } this.Idpdata.index = i; this.getTriggerDetails(i, j, k); } getTriggerDetails(i, j, k) { this.Idpdata.appName = this.workflowData.workflowSequence[i].applicationDetails[j].applicationName; this.Idpdata.pipelineName = this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails[k].pipelineName; const reqData = { "applicationName": this.workflowData.workflowSequence[i].applicationDetails[j].applicationName, "pipelineName": this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails[k].pipelineName, "userName": this.Idpdata.idpUserName }; this.fetchPipelineTriggerDetails(reqData, i, j, k).then(()=>{ if( this.isReleaseAvailable){ this.modalForTriggerDetails.show(); } this.isReleaseAvailable = true; }); } deleteSequenceDetails(i, j) { const appName = this.workflowData.workflowSequence[i].applicationName; const pipeName = this.workflowData.workflowSequence[i].pipelineDetails[j].pipelineName; const x = confirm("Are you sure you want to remove these details?"); if (x) { this.Idpdata.workflowData.workflowSequence[i].pipelineDetails[j] = { applicationName: appName, pipelineName: pipeName }; } } validate() { let f = true; console.log(f); for (const appArray of this.workflowData.workflowSequence) { for (const pipeArray of appArray.applicationDetails) { if (pipeArray.pipelineDetails.length === 0) { f = false; break; } for (const pipe of pipeArray.pipelineDetails) { if (pipe.applicationName !== undefined && pipe.pipelineName !== undefined && pipe.releaseNumber !== undefined) { continue; } else { f = false; break; } } } } if (f) { console.log(f); return f; } else { console.log(f); return f; } } setFormStatus(data) { this.Idpdata.allFormStatus.workflowInfo = data; } submit() { console.log("below line "); console.log(this.workflowData); console.log(JSON.stringify(this.workflowData)); if (this.Idpdata.workflowTrigger) { this.modalforTriggerRef = this.modalService.show(this.modalforTrigger); } else if (this.validate()) { if (this.Idpdata.allFormStatus.basicInfo && this.Idpdata.allFormStatus.workflowInfo ) { this.modalforconfirmAlertRef = this.modalService.show(this.modalforconfirmAlert); } else { if (!this.Idpdata.allFormStatus.basicInfo && this.listToFillFields.indexOf("BasicInfo" ) === -1 ) { this.listToFillFields.push("BasicInfo"); } if (!this.Idpdata.allFormStatus.workflowInfo && this.listToFillFields.indexOf("workflowInfo") === -1 ) { this.listToFillFields.push("workflowInfo"); } this.modalformandatoryFieldsAlertRef = this.modalService.show(this.modalformandatoryFieldsAlert); } } else { this.modalforAlertDataMissRef = this.modalService.show(this.modalforAlertDataMiss); } } submitData(modalforconfirmAlertRef) { modalforconfirmAlertRef.hide(); this.loader = "on"; this.Idpdata.freezeNavBars = true; this.Idpdata.data.masterJson["basicInfo"] = this.Idpdata.data.basicInfo; this.Idpdata.data.masterJson["pipelines"] = this.workflowData.workflowSequence; let data = this.Idpdata.data.masterJson; console.log(data); data = this.idpencryption.encryptAES(JSON.stringify(data)); this.Idprestapi.submit(data) .then(response => { try { const resp = response.json(); const errorMsg = resp.errorMessage; console.log(resp); this.loader = "off"; if (errorMsg === null && resp.resource.toLowerCase() === "success") { this.message = "success"; console.log(this.formStatusObject.operation); if (this.formStatusObject.operation !== "edit") { const actiondata = { "applicationName": this.Idpdata.data.masterJson.basicInfo.applicationName, "method": "create", "pipelineName": this.Idpdata.data.masterJson.basicInfo.pipelineName, "userName": this.Idpdata.idpUserName }; this.Idprestapi.sendPipeMail(actiondata); } else { const actiondata = { "applicationName": this.Idpdata.data.masterJson.basicInfo.applicationName, "method": "edit", "pipelineName": this.Idpdata.data.masterJson.basicInfo.pipelineName, "userName": this.Idpdata.idpUserName }; this.Idprestapi.sendPipeMail(actiondata); } this.redirectTo(); } else { this.Idpdata.freezeNavBars = false; this.message = "error"; this.errorMessage = errorMsg; } } catch (e) { alert("Failed while submiting the trigger job"); console.log(e); } }); } getAppDetails() { this.Idprestapi.getApplicationDetails(this.Idpdata.data.masterJson.basicInfo.applicationName) .then(response => { if (response) { const resp = response.json().resource; let parsed; try { parsed = JSON.parse(resp); if (parsed) { this.Idpdata.application = parsed.appJson; console.log(this.Idpdata.application); console.log(this.Idpdata.data); this.redirectTo(); } } catch (e) { console.log(e); alert("Failed while getting the pipeline details"); this.redirectTo(); } } }); } redirectTo() { setTimeout(() => { this.router.navigate(["/createPipeline/success"]); }, 3000); } resetData() { const x = confirm("Are you sure to reset workflow details ?"); if (x) { this.resetFlag = true; this.initialize(); console.log("Reset initialize again"); } } triggerData(modalRef) { modalRef.hide(); this.loader = "on"; const requestData = this.IDPWorkflowParamData; console.log(requestData); requestData.build = null; requestData.deploy = null; requestData.testSelected = "off"; requestData.envSelected = ""; this.Idprestapi.triggerJobs(requestData) .then(response => { try { if (response) { const err = response.json().errorMessage; if (err === null && response.json().resource.toLowerCase() === "success") { this.loader = "off"; this.message = "success"; setTimeout(() => { this.router.navigate(["/previousConfig/stageviewTrigger"]); }, 7000); } else { this.loader = "off"; this.message = "error"; setTimeout(() => { this.router.navigate(["/previousConfig"]); }, 7000); } } } catch (e) { console.log(e); alert("Failed while triggering "); } }); } onItemSelect(item: any, i, j) { console.log(item); if (!this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails) { this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails = []; } this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails.push({pipelineName: item.itemName}); } OnItemDeSelect(item: any, i, j) { const index = this.workflowData.workflowSequence[i].applicationDetails[j]. pipelineDetails.findIndex(pipeline => pipeline.pipelineName === item.itemName); this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails.splice(index, 1); } onSelectAll(items: any, i, j) { if (!this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails) { this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails = []; } for (const item of items) { const index = this.workflowData.workflowSequence[i]. applicationDetails[j].pipelineDetails.findIndex(pipeline => pipeline.pipelineName === item.itemName); if (index === -1) { this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails.push({pipelineName: item.itemName}); } } } onDeSelectAll(items: any, i, j) { const x = confirm("Are you sure you want to reset all the pipeline names for " + this.workflowData.workflowSequence[i].applicationDetails[j].applicationName + " ?"); if (x) { this.workflowData.workflowSequence[i].applicationDetails[j].pipelineDetails = []; } } }
the_stack
import {expectTranslate} from './test_support'; // TODO(jacobr): merge these tests back in with the other tests. These tests are // only separate because we expected at one point to integrate with TS2Dart // instead of refactoring TS2Dart to only output facades. describe('variables', () => { it('should print variable declaration', () => { expectTranslate('var a:number;').to.equal(`@JS() external num get a; @JS() external set a(num v);`); expectTranslate('var a;').to.equal(`@JS() external get a; @JS() external set a(v);`); expectTranslate('var a:any;').to.equal(`@JS() external dynamic get a; @JS() external set a(dynamic v);`); }); it('should transpile variable declaration lists', () => { expectTranslate('var a: A;').to.equal(`@JS() external A get a; @JS() external set a(A v);`); expectTranslate('var a, b;').to.equal(`@JS() external get a; @JS() external set a(v); @JS() external get b; @JS() external set b(v);`); }); it('support vardecls containing more than one type (implicit or explicit)', () => { expectTranslate('var a: A, b: B;').to.equal(`@JS() external A get a; @JS() external set a(A v); @JS() external B get b; @JS() external set b(B v);`); expectTranslate('var a: number, b: string;').to.equal(`@JS() external num get a; @JS() external set a(num v); @JS() external String get b; @JS() external set b(String v);`); }); it('supports const', () => { expectTranslate('const a:number = 1;').to.equal(`@JS() external num get a;`); expectTranslate('const a:number = 1, b:number = 2;').to.equal(`@JS() external num get a; @JS() external num get b;`); expectTranslate('const a:string').to.equal(`@JS() external String get a;`); expectTranslate('const a:number, b:number;').to.equal(`@JS() external num get a; @JS() external num get b;`); }); }); describe('classes', () => { it('should translate classes', () => { expectTranslate('class X {}').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); }`); }); it('should support extends', () => { expectTranslate('class X extends Y {}').to.equal(`@JS() class X extends Y { // @Ignore X.fakeConstructor$() : super.fakeConstructor$(); }`); }); it('should support implements', () => { expectTranslate('class X implements Y, Z {}').to.equal(`@JS() class X implements Y, Z { // @Ignore X.fakeConstructor$(); }`); }); it('should support implements', () => { expectTranslate('class X extends Y implements Z {}').to.equal(`@JS() class X extends Y implements Z { // @Ignore X.fakeConstructor$() : super.fakeConstructor$(); }`); }); it('should support abstract', () => { expectTranslate('abstract class X {}').to.equal(`@JS() abstract class X { // @Ignore X.fakeConstructor$(); }`); }); describe('members', () => { it('supports empty declarations', () => { expectTranslate('class X { ; }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); }`); }); it('supports fields', () => { expectTranslate('class X { x: number; y: string; }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external num get x; external set x(num v); external String get y; external set y(String v); }`); expectTranslate('class X { x; }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external get x; external set x(v); }`); }); it('ignore field initializers', () => { expectTranslate('class X { x: number = 42; }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external num get x; external set x(num v); }`); }); it('supports visibility modifiers', () => { expectTranslate('class X { private _x; x; }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external get JS$_x; external set JS$_x(v); external get x; external set x(v); }`); expectTranslate('class X { private x; }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external get x; external set x(v); }`); expectTranslate('class X { constructor (private x) {} }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external get x; external set x(v); external factory X(x); }`); expectTranslate('class X { _x; }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external get JS$_x; external set JS$_x(v); }`); }); it('does not support protected', () => { expectTranslate('class X { protected x; }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external get x; external set x(v); }`); }); it('supports static fields', () => { expectTranslate('class X { static x: number = 42; }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external static num get x; external static set x(num v); }`); }); it('supports methods', () => { expectTranslate('class X { x() { return 42; } }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external x(); }`); }); it('supports abstract methods', () => { expectTranslate('abstract class X { abstract x(); }').to.equal(`@JS() abstract class X { // @Ignore X.fakeConstructor$(); external x(); }`); }); it('supports method return types', () => { expectTranslate('class X { x(): number { return 42; } }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external num x(); }`); }); it('supports method params', () => { expectTranslate('class X { x(a, b); }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external x(a, b); }`); }); it('supports method return types', () => { expectTranslate('class X { x( a : number, b : string ) : num }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external num x(num a, String b); }`); }); it('supports get methods', () => { expectTranslate('class X { get y(): number {} }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external num get y; }`); expectTranslate('class X { static get Y(): number {} }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external static num get Y; }`); }); it('supports set methods', () => { expectTranslate('class X { set y(n: number) {} }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external set y(num n); }`); expectTranslate('class X { static get Y(): number {} }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external static num get Y; }`); }); it('supports generic methods', () => { expectTranslate('class X<T> { static Z<T>(): X<T> {} }').to.equal(`@JS() class X<T> { // @Ignore X.fakeConstructor$(); external static X<dynamic /*T*/ > Z/*<T>*/(); }`); expectTranslate('class X<T> { Z(): X<T> {} }').to.equal(`@JS() class X<T> { // @Ignore X.fakeConstructor$(); external X<T> Z(); }`); }); it('merge overrides', () => { expectTranslate(` class X { createElement<T>(tagName: "img"): T; createElement<T>(tagName: "video"): T; createElement<T>(tagName: string): T; }`).to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); /*external T createElement<T>('img' tagName);*/ /*external T createElement<T>('video' tagName);*/ /*external T createElement<T>(String tagName);*/ external dynamic /*T*/ createElement/*<T>*/( String /*'img'|'video'|String*/ tagName); }`); expectTranslate(` class X { createElement<T>(tagName: "img"): T; createElement<T>(tagName: "video"): T; createElement<V>(tagName: string): V; }`).to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); /*external T createElement<T>('img' tagName);*/ /*external T createElement<T>('video' tagName);*/ /*external V createElement<V>(String tagName);*/ external dynamic /*T|V*/ createElement/*<T, V>*/( String /*'img'|'video'|String*/ tagName); }`); expectTranslate(` class X { createElement<T extends HTMLImageElement>(tagName: "img"): T; createElement<T extends HTMLVideoElement>(tagName: "video"): T; createElement<T extends Element>(tagName: string): T; }`).to.equal(`import "dart:html" show ImageElement, VideoElement, Element; @JS() class X { // @Ignore X.fakeConstructor$(); /*external T createElement<T extends ImageElement>('img' tagName);*/ /*external T createElement<T extends VideoElement>('video' tagName);*/ /*external T createElement<T extends Element>(String tagName);*/ external dynamic /*T*/ createElement/*<T>*/( String /*'img'|'video'|String*/ tagName); }`); expectTranslate(`export interface ScaleLinear<O> { (value: number): Output; domain(): Array<O>; } export function scaleLinear(): ScaleLinear<number>; export function scaleLinear<O>(): ScaleLinear<O>;`) .to.equal(`@anonymous @JS() abstract class ScaleLinear<O> { external Output call(num value); external List<O> domain(); } /*external ScaleLinear<num> scaleLinear();*/ /*external ScaleLinear<O> scaleLinear<O>();*/ @JS() external ScaleLinear /*ScaleLinear<num>|ScaleLinear<O>*/ scaleLinear/*<O>*/();`); expectTranslate(` class X { F(a: string): number; F(a: string, b: string|number): string; F(a2: string, b: string, c: number): string; }`).to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); /*external num F(String a);*/ /*external String F(String a, String|num b);*/ /*external String F(String a2, String b, num c);*/ external dynamic /*num|String*/ F(String a_a2, [dynamic /*String|num*/ b, num c]); }`); expectTranslate(` class X { Y(a: string): number {}; Y(a: string, b: number):string {}; Y(a2:string, b: string, c: number):string {}; }`).to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); /*external num Y(String a);*/ /*external String Y(String a, num b);*/ /*external String Y(String a2, String b, num c);*/ external dynamic /*num|String*/ Y(String a_a2, [dynamic /*num|String*/ b, num c]); }`); expectTranslate(` class X { firstElement(elements: HTMLImageElement[]): HTMLImageElement; firstElement(elements: HTMLVideoElement[]): HTMLVideoElement; firstElement(elements: HTMLElement[]): HTMLElement; }`).to.equal(`import "dart:html" show ImageElement, VideoElement, HtmlElement; @JS() class X { // @Ignore X.fakeConstructor$(); /*external ImageElement firstElement(List<ImageElement> elements);*/ /*external VideoElement firstElement(List<VideoElement> elements);*/ /*external HtmlElement firstElement(List<HtmlElement> elements);*/ external dynamic /*ImageElement|VideoElement|HtmlElement*/ firstElement( List< HtmlElement> /*List<ImageElement>|List<VideoElement>|List<HtmlElement>*/ elements); }`); // TODO(jacobr): we should consider special casing so EventLister and // EventListenerObject are treated as the same in Dart even though they // are different. expectTranslate(` interface SampleAudioNode { addEventListener(type: "ended", listener: (ev: Event) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; }`).to.equal(`import "dart:html" show Event; @anonymous @JS() abstract class SampleAudioNode { /*external void addEventListener('ended' type, dynamic listener(Event ev), [bool useCapture]);*/ /*external void addEventListener(String type, EventListener|EventListenerObject listener, [bool useCapture]);*/ external void addEventListener(String /*'ended'|String*/ type, dynamic /*dynamic Function(Event)|EventListener|EventListenerObject*/ listener, [bool useCapture]); }`); expectTranslate(` interface ListenObject { someDummyMethod(evt: string): void; } interface ExampleListener { (evt: string): void; } interface DummySample { addEventListener(type: 'ended', listener: ListenObject): void; addEventListener(type: string, listener: ExampleListener): void; }`).to.equal(`@anonymous @JS() abstract class ListenObject { external void someDummyMethod(String evt); } typedef void ExampleListener(String evt); @anonymous @JS() abstract class DummySample { /*external void addEventListener('ended' type, ListenObject listener);*/ /*external void addEventListener(String type, ExampleListener listener);*/ external void addEventListener(String /*'ended'|String*/ type, dynamic /*ListenObject|ExampleListener*/ listener); }`); expectTranslate(` interface ListenAny { (evt: any): void; } interface ExampleListener { (evt: string): void; } interface DummySample { addEventListener(type: 'ended', listener: ListenAny): void; addEventListener(type: string, listener: ExampleListener): void; }`).to.equal(`typedef void ListenAny(dynamic evt); typedef void ExampleListener(String evt); @anonymous @JS() abstract class DummySample { /*external void addEventListener('ended' type, ListenAny listener);*/ /*external void addEventListener(String type, ExampleListener listener);*/ external void addEventListener(String /*'ended'|String*/ type, Function /*ListenAny|ExampleListener*/ listener); }`); }); it('dot dot dot', () => { expectTranslate(` function buildName(firstName: string, ...restOfName: string[]): string; `).to.equal(`@JS() external String buildName(String firstName, [String restOfName1, String restOfName2, String restOfName3, String restOfName4, String restOfName5]);`); expectTranslate(` function log(...args);`) .to.equal(`@JS() external log([args1, args2, args3, args4, args5]);`); }); it('property bag interfaces', () => { expectTranslate(` interface X { a: string; b: number; c: X; } interface Y extends X { d: number; /* example comment */ e: any; }`).to.equal(`@anonymous @JS() abstract class X { external String get a; external set a(String v); external num get b; external set b(num v); external X get c; external set c(X v); external factory X({String a, num b, X c}); } @anonymous @JS() abstract class Y implements X { external num get d; external set d(num v); /// example comment external dynamic get e; external set e(dynamic v); external factory Y({num d, dynamic e, String a, num b, X c}); }`); expectTranslate(`interface X<A> { a: A; b: num, c: X } interface Y<A,B> extends X<A> { d: B; e: any; }`) .to.equal(`@anonymous @JS() abstract class X<A> { external A get a; external set a(A v); external num get b; external set b(num v); external X get c; external set c(X v); external factory X({A a, num b, X c}); } @anonymous @JS() abstract class Y<A, B> implements X<A> { external B get d; external set d(B v); external dynamic get e; external set e(dynamic v); external factory Y({B d, dynamic e, A a, num b, X c}); }`); }); it('callable', () => { expectTranslate('interface X<T> { (a:T):T; Y():T; }').to.equal(`@anonymous @JS() abstract class X<T> { external T call(T a); external T Y(); }`); }); it('supports constructors', () => { expectTranslate('class X { constructor() { } }').to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external factory X(); }`); }); it('supports parameter properties', () => { expectTranslate(` class X { c: number; constructor(private _bar: B, public foo: string = "hello", private _goggles: boolean = true); }`).to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external B get JS$_bar; external set JS$_bar(B v); external String get foo; external set foo(String v); external bool get JS$_goggles; external set JS$_goggles(bool v); external num get c; external set c(num v); external factory X(B JS$_bar, [String foo, bool JS$_goggles]); }`); expectTranslate(` class X { constructor(public foo: string, b: number, private _marbles: boolean = true) {} }`).to.equal(`@JS() class X { // @Ignore X.fakeConstructor$(); external String get foo; external set foo(String v); external bool get JS$_marbles; external set JS$_marbles(bool v); external factory X(String foo, num b, [bool JS$_marbles]); }`); }); }); }); describe('interfaces', () => { it('translates interfaces to abstract classes', () => { expectTranslate('interface X {}').to.equal(`@anonymous @JS() abstract class X {}`); }); it('translates interface extends to class implements', () => { expectTranslate('interface X extends Y, Z {}').to.equal(`@anonymous @JS() abstract class X implements Y, Z {}`); }); it('supports abstract methods', () => { expectTranslate('interface X { x(); }').to.equal(`@anonymous @JS() abstract class X { external x(); }`); }); it('supports interface properties', () => { expectTranslate('interface X { x: string; y; }').to.equal(`@anonymous @JS() abstract class X { external String get x; external set x(String v); external get y; external set y(v); external factory X({String x, y}); }`); }); }); describe('single call signature interfaces', () => { it('should support declaration', () => { expectTranslate('interface F { (n: number): boolean; }').to.equal('typedef bool F(num n);'); }); it('should support generics', () => { expectTranslate('interface F<A, B> { (a: A): B; }').to.equal('typedef B F<A, B>(A a);'); }); }); describe('enums', () => { it('should support basic enum declaration', () => { expectTranslate('enum Color { Red, Green, Blue }').to.equal(`@JS() class Color { external static num get Red; external static num get Green; external static num get Blue; }`); }); it('empty enum', () => { expectTranslate('enum Color { }').to.equal(`@JS() class Color {}`); }); it('enum with initializer', () => { expectTranslate('enum Color { Red = 1, Green, Blue = 4 }').to.equal(`@JS() class Color { external static num get Red; external static num get Green; external static num get Blue; }`); }); }); describe('renames', () => { it('should support class renames', () => { expectTranslate(` declare namespace m1 { interface A { x(); } } declare namespace m2 { interface A { y(); } } `).to.equal(`// Module m1 @anonymous @JS() abstract class A { external x(); } // End module m1 // Module m2 @anonymous @JS() abstract class m2_A { external y(); } // End module m2`); expectTranslate(` declare namespace foo.m1 { function x(): number; } declare namespace foo.m2 { function x(): string; } declare namespace m2 { function x(): string[]; }`).to.equal(`// Module foo.m1 @JS("foo.m1.x") external num x(); // End module foo.m1 // Module foo.m2 @JS("foo.m2.x") external String m2_x(); // End module foo.m2 // Module m2 @JS("m2.x") external List<String> x2(); // End module m2`); expectTranslate(` declare namespace m1 { class A { constructor(x); } } declare namespace m2 { class A { constructor(y); } }`).to.equal(`// Module m1 @JS("m1.A") class A { // @Ignore A.fakeConstructor$(); external factory A(x); } // End module m1 // Module m2 @JS("m2.A") class m2_A { // @Ignore m2_A.fakeConstructor$(); external factory m2_A(y); } // End module m2`); expectTranslate(` declare namespace m1 { class A { constructor(x:m2.A); } } declare namespace m2 { class A { constructor(y:m1.A); } } `).to.equal(`// Module m1 @JS("m1.A") class A { // @Ignore A.fakeConstructor$(); external factory A(m2_A x); } // End module m1 // Module m2 @JS("m2.A") class m2_A { // @Ignore m2_A.fakeConstructor$(); external factory m2_A(A y); } // End module m2`); }); it('should support member renames', () => { expectTranslate(` declare namespace m1 { interface A { x(); } } declare namespace m2 { export function A(x:m1.A); }`).to.equal(`// Module m1 @anonymous @JS() abstract class A { external x(); } // End module m1 // Module m2 @JS("m2.A") external m2_A(A x); // End module m2`); }); it('handle class renames in type declarations', () => { expectTranslate(` declare namespace m1 { interface A { x(); } } declare namespace m2 { interface A { y(); } } export function register(x:m2.A); `).to.equal(`// Module m1 @anonymous @JS() abstract class A { external x(); } // End module m1 // Module m2 @anonymous @JS() abstract class m2_A { external y(); } // End module m2 @JS() external register(m2_A x);`); expectTranslate(` declare namespace m1 { namespace foo { interface A { x(); } } } declare namespace m2 { namespace foo { interface A { y(); } } } declare namespace m3 { namespace foo { interface A { z(); } } } export function register(y:m2.foo.A, z:m3.foo.A); `).to.equal(`// Module m1 // Module foo @anonymous @JS() abstract class A { external x(); } // End module foo // End module m1 // Module m2 // Module foo @anonymous @JS() abstract class foo_A { external y(); } // End module foo // End module m2 // Module m3 // Module foo @anonymous @JS() abstract class m3_foo_A { external z(); } // End module foo // End module m3 @JS() external register(foo_A y, m3_foo_A z);`); expectTranslate(` declare namespace m1 { interface A { x(); } } declare namespace m2 { interface A { y(); } } export function register(x:m1.A); `).to.equal(`// Module m1 @anonymous @JS() abstract class A { external x(); } // End module m1 // Module m2 @anonymous @JS() abstract class m2_A { external y(); } // End module m2 @JS() external register(A x);`); }); describe('type alias', () => { it('replace with simple type', () => { expectTranslate(` type MyNumber = number; export function add(x: MyNumber, y: MyNumber): MyNumber; `).to.equal(`/*type MyNumber = number;*/ @JS() external num add(num x, num y);`); }); }); it('union types', () => { // TODO(jacobr): we should resolve that listener1 and listener2 are both functions. // TODO(jacobr): ideally the draw method should specify that arg el has type // HtmlElement instead of dynamic. expectTranslate(` type listener1 = ()=>boolean; type listener2 = (e:string)=>boolean; function addEventListener(listener: listener1|listener2);`) .to.equal(`typedef bool listener1(); typedef bool listener2(String e); @JS() external addEventListener(dynamic /*listener1|listener2*/ listener);`); expectTranslate('function draw(el: HTMLCanvasElement|HTMLImageElement):void;') .to.equal(`import "dart:html" show CanvasElement, ImageElement; @JS() external void draw(dynamic /*CanvasElement|ImageElement*/ el);`); }); it('callback this type', () => { expectTranslate(` function addEventListener(type: string, listener: (this: Element, event: Event) => void);`) .to.equal(`import "dart:html" show Element, Event; @JS() external addEventListener( String type, void listener(/*Element this*/ Event event));`); expectTranslate(` function addEventListener(type: 'load', listener: (this: HTMLImageElement, event: Event) => void); function addEventListener(type: string, listener: (this: Element, event: Event) => void); `).to.equal(`import "dart:html" show ImageElement, Event, Element; /*external addEventListener('load' type, void listener(ImageElement JS$this, Event event));*/ /*external addEventListener( String type, void listener(Element JS$this, Event event)); */ @JS() external addEventListener( String /*'load'|String*/ type, void listener(/*Element this*/ Event event));`); }); });
the_stack
module Kiwi.Time { /** * The Timer class hooks into a game Clock and allows you run code at a specified point in game time. * Use the start() method to start a timer. Add TimerEvents to set-up code to be run on the timer interval. * Timer objects can run once or repeat at specified intervals to execute code on a schedule. * * @class Timer * @namespace Kiwi.Time * @constructor * @param name {string} The name of the timer. * @param clock {Kiwi.Time.Clock} The game clock instance this Timer is based on. * @param delay {Number} The number of clock units to wait between firing events. * @param [repeatCount=0] {Number} The number of times to repeat the timer before it is expired. If you don't want it to ever expire, set a value of -1. * @return {Kiwi.Time.Timer} This object. * */ export class Timer { constructor (name: string, clock: Clock, delay: number, repeatCount: number = 0) { this._clock = clock; this._startEvents = []; this._countEvents = []; this._stopEvents = []; this.name = name; this.delay = delay; this.repeatCount = repeatCount; } /** * The type of object that this is. * @method objType * @return {String} "Timer" * @public */ public objType() { return "Timer"; } /** * The number of times the timer has repeated so far. * @property _currentCount * @type Number * @default 0 * @private */ private _currentCount: number = 0; /** * Get the number of times the timer has repeated. * @method getCurrentCount * @return {Number} * @public */ public currentCount(): number { return this._currentCount; } /** * A collection of the TimerEvents associated with TimerEvent.TIMER_START * @property _startEvents * @type Array * @private */ private _startEvents:TimerEvent[] = null; /** * A collection of the TimerEvents associated with TimerEvent.TIMER_COUNT * @property _countEvents * @private * @type Array */ private _countEvents:TimerEvent[] = null; /** * A collection of the TimerEvents associated with TimerEvent.TIMER_STOP * @property _stopEvents * @private * @type Array */ private _stopEvents:TimerEvent[] = null; /** * The clock which this timer bases its timing on. * @property _clock * @type Kiwi.Time.Clock * @private */ private _clock: Clock = null; /** * The time the last repeat occurred in clock units. * @property _timeLastCount * @type Number * @private * @deprecated Better time handling in 1.2.0 deprecates this data. */ private _timeLastCount: number = null; /** * Whether the timer is in a running state. * @property _isRunning * @type boolean * @default false * @private */ private _isRunning: boolean = false; /** * The Timers current state. True if the Timer is running, otherwise false. * @method running * @return {boolean} * @public */ public isRunning(): boolean { return this._isRunning; } /** * Whether the timer is in a stopped state. * @property _isStopped * @type boolean * @default true * @private */ private _isStopped: boolean = true; /** * Whether the timer is in a stopped state. * @method stopped * @return {boolean} * @public */ public isStopped(): boolean { return this._isStopped; } /** * Whether the timer is in a paused state. * @property _isPaused * @type boolean * @default false * @private */ private _isPaused: boolean = false; /** * Whether the timer is in a paused state. * @method paused * @return {boolean} * @public */ public isPaused(): boolean { return this._isPaused; } /** * The name of the timer. * @property name * @type String * @default null * @public */ public name: string = null; /** * The delay, in game clock units, that the timer will wait before firing the event * @property _delay * @type Number * @default 0.016 * @private */ private _delay: number = 0.016; /** * The delay, in game clock units, that the timer will wait before firing the event * * This property must be greater than 0. * @property delay * @type Number * @default 0.016 * @public */ public get delay(): number { return this._delay; } public set delay( value: number ) { if ( value > 0 ) { this._delay = value; } else { Kiwi.Log.error( "Attempted to set timer delay", value, "but value must be greater than 0", "#timer" ); } } /** * The number of times the timer will repeat before stopping. * @property repeatCount * @type Number * @default 0 * @public */ public repeatCount: number = 0; /** * Time elapsed on the current repetition * @property _elapsed * @type number * @private * @since 1.2.0 */ private _elapsed: number = 0; /** * Clock time on last frame, used to calculate frame length and time elapsed * @property _lastElapsed * @type number * @private * @since 1.2.0 */ private _lastElapsed: number; /** * Checks the list of TimerEvents added and processes them based on their type. * @method processEvents * @param type {Number} The type of events to dispatch * @private */ private processEvents(type: number) { if (type === TimerEvent.TIMER_START) { for (var i = 0; i < this._startEvents.length; i++) { this._startEvents[i].run(); } } else if (type === TimerEvent.TIMER_COUNT) { for (var i = 0; i < this._countEvents.length; i++) { this._countEvents[i].run(); } } else if (type === TimerEvent.TIMER_STOP) { for (var i = 0; i < this._stopEvents.length; i++) { this._stopEvents[i].run(); } } } /** * Internal update loop called by the Clock that this Timer belongs to. * @method update * @public */ public update() { var frameLength = this._clock.elapsed() - this._lastElapsed; this._lastElapsed = this._clock.elapsed(); if ( this._isRunning ) { this._elapsed += frameLength; } while ( this._elapsed >= this.delay ) { this._currentCount++; this.processEvents( TimerEvent.TIMER_COUNT ); this._elapsed -= this.delay; if ( this.repeatCount !== -1 && this._currentCount >= this.repeatCount ) { this.stop(); } } while ( this._elapsed < 0 ) { this._currentCount--; this._elapsed += this.delay; // Do not process events; they can happen when time flows forwards if ( this._currentCount < 0 ) { // Timer has regressed before its creation. // When time flows forward again, the Timer will probably // be restarted and repopulated. // There is a potential memory leak: if a Timer is created // for a single task, and has a TimerEvent that will // remove it upon completion, but the Timer is rewound to // before its creation, that removal will never fire. this.clear(); this.stop(); } } } /** * Start the Timer. This will reset the timer and start it. The timer can only be started if it is in a stopped state. * @method start * @return {Kiwi.Time.Timer} this object. * @public */ public start(): Timer { if (this._isStopped === true) { this._isRunning = true; this._isPaused = false; this._isStopped = false; this._currentCount = 0; this._elapsed = 0; this._lastElapsed = this._clock.elapsed() || 0; this.processEvents(TimerEvent.TIMER_START); } return this; } /** * Stop the Timer. Only possible when the timer is running or paused. * @method stop * @return {Kiwi.Time.Timer} this object. * @public */ public stop():Timer { if (this._isRunning === true || this._isPaused === true) { this._isRunning = false; this._isPaused = false; this._isStopped = true; this.processEvents(TimerEvent.TIMER_STOP); } return this; } /** * Pause the Timer. Only possible when the timer is running. * @method pause * @return {Kiwi.Time.Timer} this object. * @public */ public pause():Timer { if (this._isRunning === true) { this._isRunning = false; this._isPaused = true; } return this; } /** * Resume the Timer. Only possible if the timer has been paused. * @method resume * @return {Kiwi.Time.Timer} this object. * @public */ public resume(): Timer { if (this._isPaused === true) { this._isRunning = true; this._isPaused = false; } return this; } /** * Adds an existing TimerEvent object to this Timer. * @method addTimerEvent * @param {Kiwi.Time.TimerEvent} A TimerEvent object * @return {Kiwi.Time.TimerEvent} The TimerEvent object * @public */ public addTimerEvent(event:TimerEvent):TimerEvent { if (event.type === TimerEvent.TIMER_START) { this._startEvents.push(event); } else if (event.type === TimerEvent.TIMER_COUNT) { this._countEvents.push(event); } else if (event.type === TimerEvent.TIMER_STOP) { this._stopEvents.push(event); } return event; } /** * Creates a new TimerEvent and adds it to this Timer * @method createTimerEvent * @param type {Number} The type of TimerEvent to create (TIMER_START, TIMER_COUNT or TIMER_STOP). * @param callback {Function} The function to call when the TimerEvent fires. * @param context {Function} The context in which the given function will run (usually 'this') * @return {Kiwi.Time.TimerEvent} The newly created TimerEvent. * @public */ public createTimerEvent(type:number, callback, context):TimerEvent { if (type === TimerEvent.TIMER_START) { this._startEvents.push(new TimerEvent(type, callback, context)); return this._startEvents[this._startEvents.length - 1]; } else if (type === TimerEvent.TIMER_COUNT) { this._countEvents.push(new TimerEvent(type, callback, context)); return this._countEvents[this._countEvents.length - 1]; } else if (type === TimerEvent.TIMER_STOP) { this._stopEvents.push(new TimerEvent(type, callback, context)); return this._stopEvents[this._stopEvents.length - 1]; } return null; } /** * Removes a TimerEvent object from this Timer * @method removeTimerEvent * @param {Kiwi.Time.TimerEvent} The TimerEvent to remove * @return {boolean} True if the event was removed, otherwise false. * @public */ public removeTimerEvent(event:TimerEvent):boolean { var removed = []; if (event.type === TimerEvent.TIMER_START) { removed = this._startEvents.splice(this._startEvents.indexOf(event), 1); } else if (event.type === TimerEvent.TIMER_COUNT) { removed = this._countEvents.splice(this._countEvents.indexOf(event), 1); } else if (event.type === TimerEvent.TIMER_STOP) { removed = this._stopEvents.splice(this._stopEvents.indexOf(event), 1); } if (removed.length === 1) { return true; } else { return false; } } /** * Removes all TimerEvent objects from this Timer * @method clear * @param type {Number} The type of TimerEvents to remove. Set to zero to remove them all. * @return {boolean} True if the event was removed, otherwise false. * @public */ public clear(type:number = 0) { if (type === 0) { this._startEvents.length = 0; this._countEvents.length = 0; this._stopEvents.length = 0; } else if (type === TimerEvent.TIMER_START) { this._startEvents.length = 0; } else if (type === TimerEvent.TIMER_COUNT) { this._countEvents.length = 0; } else if (type === TimerEvent.TIMER_STOP) { this._stopEvents.length = 0; } } /** * Returns a string representation of this object. * @method toString * @return {string} a string representation of the instance. * @public */ public toString(): string { return "[{Timer (name=" + this.name + " delay=" + this.delay + " repeatCount=" + this.repeatCount + " running=" + this._isRunning + ")}]"; } } }
the_stack
import StatsManager, {lumaStats} from '../utils/stats-manager'; import {log} from '../utils/log'; import {uid} from '../utils/utils'; import {TextureFormat} from './types/texture-formats'; import type {default as CanvasContext, CanvasContextProps} from './canvas-context'; import type {BufferProps} from './resources/buffer'; import Buffer from './resources/buffer'; import type {default as RenderPipeline, RenderPipelineProps} from './resources/render-pipeline'; import type {default as ComputePipeline, ComputePipelineProps} from './resources/compute-pipeline'; import type {default as Sampler, SamplerProps} from './resources/sampler'; import type {default as Shader, ShaderProps} from './resources/shader'; import type {default as Texture, TextureProps, TextureData} from './resources/texture'; import type {default as ExternalTexture, ExternalTextureProps} from './resources/external-texture'; import type {default as Framebuffer, FramebufferProps} from './resources/framebuffer'; import type {default as RenderPass, RenderPassProps} from './resources/render-pass'; import type {default as ComputePass, ComputePassProps} from './resources/compute-pass'; /** Device properties */ export type DeviceProps = { id?: string; type?: 'webgl' | 'webgl1' | 'webgl2' | 'webgpu' | 'best-available'; // Common parameters canvas?: HTMLCanvasElement | OffscreenCanvas | string; // A canvas element or a canvas string id width?: number /** width is only used when creating a new canvas */; height?: number /** height is only used when creating a new canvas */; onContextLost?: (event: Event) => void; onContextRestored?: (event: Event) => void; // WebGLDevice parameters webgl2?: boolean; // Set to false to not create a WebGL2 context (force webgl1) webgl1?: boolean; // set to false to not create a WebGL1 context (fails if webgl2 not available) // WebGLContext PARAMETERS - Can only be set on context creation... alpha?: boolean; // Default render target has an alpha buffer. depth?: boolean; // Default render target has a depth buffer of at least 16 bits. stencil?: boolean; // Default render target has a stencil buffer of at least 8 bits. antialias?: boolean; // Boolean that indicates whether or not to perform anti-aliasing. premultipliedAlpha?: boolean; // Boolean that indicates that the page compositor will assume the drawing buffer contains colors with pre-multiplied alpha. preserveDrawingBuffer?: boolean; // Default render target buffers will not be automatically cleared and will preserve their values until cleared or overwritten failIfMajorPerformanceCaveat?: boolean; // Do not create if the system performance is low. // Unclear if these are still supported debug?: boolean; // Instrument context (at the expense of performance) manageState?: boolean; // Set to false to disable WebGL state management instrumentation break?: Array<any>; // TODO: types // Attach to existing context gl?: WebGLRenderingContext | WebGL2RenderingContext; }; export const DEFAULT_DEVICE_PROPS: Required<DeviceProps> = { id: undefined, type: 'best-available', canvas: undefined, // A canvas element or a canvas string id gl: undefined, webgl2: true, // Attempt to create a WebGL2 context webgl1: true, // Attempt to create a WebGL1 context (false to fail if webgl2 not available) manageState: true, width: 800, // width are height are only used by headless gl height: 600, debug: Boolean(log.get('debug')), // Instrument context (at the expense of performance) break: undefined, onContextLost: () => console.error('WebGL context lost'), onContextRestored: () => console.info('WebGL context restored'), alpha: undefined, depth: undefined, stencil: undefined, antialias: undefined, premultipliedAlpha: undefined, preserveDrawingBuffer: undefined, failIfMajorPerformanceCaveat: undefined }; export type ShadingLanguage = 'glsl' | 'wgsl'; /** * Identifies the GPU vendor and driver. * @see https://www.khronos.org/registry/webgl/extensions/WEBGL_debug_renderer_info/ * @note Current WebGPU support is very limited */ export type DeviceInfo = { type: 'webgl' | 'webgl2' | 'webgpu'; vendor: string; renderer: string; version: string; gpu: 'nvidia' | 'amd' | 'intel' | 'apple' | 'unknown'; shadingLanguages: ShadingLanguage[]; shadingLanguageVersions: Record<string, string>; vendorMasked?: string; rendererMasked?: string; }; /** Limits for a device */ export type DeviceLimits = { readonly maxTextureDimension1D?: number; readonly maxTextureDimension2D?: number; readonly maxTextureDimension3D?: number; readonly maxTextureArrayLayers?: number; readonly maxBindGroups: number; readonly maxDynamicUniformBuffersPerPipelineLayout: number; readonly maxDynamicStorageBuffersPerPipelineLayout: number; readonly maxSampledTexturesPerShaderStage: number; readonly maxSamplersPerShaderStage: number; readonly maxStorageBuffersPerShaderStage: number; readonly maxStorageTexturesPerShaderStage: number; readonly maxUniformBuffersPerShaderStage: number; readonly maxUniformBufferBindingSize: number; readonly maxStorageBufferBindingSize?: number; readonly minUniformBufferOffsetAlignment?: number; readonly minStorageBufferOffsetAlignment?: number; readonly maxVertexBuffers?: number; readonly maxVertexAttributes?: number; readonly maxVertexBufferArrayStride?: number; readonly maxInterStageShaderComponents?: number; readonly maxComputeWorkgroupStorageSize?: number; readonly maxComputeInvocationsPerWorkgroup?: number; readonly maxComputeWorkgroupSizeX?: number; readonly maxComputeWorkgroupSizeY?: number; readonly maxComputeWorkgroupSizeZ?: number; readonly maxComputeWorkgroupsPerDimension?: number; }; export type WebGPUDeviceFeature = 'depth-clip-control' | 'depth24unorm-stencil8' | 'depth32float-stencil8' | 'timestamp-query' | 'indirect-first-instance' | 'texture-compression-bc' | 'texture-compression-etc2' | 'texture-compression-astc' // obsolete... // 'depth-clamping' | // 'depth24unorm-stencil8' | // 'depth32float-stencil8' | // 'pipeline-statistics-query' | // 'timestamp-query' | // 'texture-compression-bc' ; export type WebGLDeviceFeature = 'webgpu' | 'webgl2' | 'webgl' | // api support (unify with WebGPU timestamp-query?) 'timer-query-webgl' | 'uniform-buffers-webgl' | 'uniforms-webgl' | // texture filtering 'texture-filter-linear-float32-webgl' | 'texture-filter-linear-float16-webgl' | 'texture-filter-anisotropic-webgl' | // texture rendering 'texture-renderable-float32-webgl' | 'texture-renderable-float16-webgl' | 'texture-renderable-rgba32float-webgl' | // TODO - remove // texture blending 'texture-blend-float-webgl1' | // texture format support 'texture-formats-norm16-webgl' | 'texture-formats-srgb-webgl1' | 'texture-formats-depth-webgl1' | 'texture-formats-float32-webgl1' | 'texture-formats-float16-webgl1' | // api support 'vertex-array-object-webgl1' | 'instanced-rendering-webgl1' | 'multiple-render-targets-webgl1' | 'index-uint32-webgl1' | 'blend-minmax-webgl1' | // glsl extensions 'glsl-frag-data' | 'glsl-frag-depth' | 'glsl-derivatives' | 'glsl-texture-lod' ; type WebGLCompressedTextureFeatures = 'texture-compression-bc5-webgl' | 'texture-compression-etc1-webgl' | 'texture-compression-pvrtc-webgl' | 'texture-compression-atc-webgl' ; /** Valid feature strings */ export type DeviceFeature = WebGPUDeviceFeature | WebGLDeviceFeature | WebGLCompressedTextureFeatures; /** * WebGPU Device/WebGL context abstraction */ export default abstract class Device { get [Symbol.toStringTag](): string { return 'Device'; } constructor(props: DeviceProps) { this.props = {...DEFAULT_DEVICE_PROPS, id: uid(this[Symbol.toStringTag]), ...props}; this.id = this.props.id; } readonly id: string; readonly statsManager: StatsManager = lumaStats; readonly props: Required<DeviceProps>; userData: {[key: string]: any} = {}; /** Information about the device (vendor, versions etc) */ abstract info: DeviceInfo; /** Optional capability discovery */ abstract get features(): Set<DeviceFeature>; /** WebGPU style device limits */ abstract get limits(): DeviceLimits; /** Check if device supports a specific texture format (creation and `nearest` sampling) */ abstract isTextureFormatSupported(format: TextureFormat): boolean; /** Check if linear filtering (sampler interpolation) is supported for a specific texture format */ abstract isTextureFormatFilterable(format: TextureFormat): boolean; /** Check if device supports rendering to a specific texture format */ abstract isTextureFormatRenderable(format: TextureFormat): boolean; /** True context is already lost */ abstract get isLost(): boolean; /** Promise that resolves when context is lost */ abstract readonly lost: Promise<{reason: 'destroyed', message: string}>; /** default canvas context */ abstract canvasContext: CanvasContext; /** Creates a new CanvasContext (WebGPU only) */ abstract createCanvasContext(props?: CanvasContextProps): CanvasContext; /** Call after rendering a frame (necessary e.g. on WebGL OffscreenCanvas) */ abstract submit(): void; // Resource creation /** Create a buffer */ createBuffer(props: BufferProps): Buffer; createBuffer(data: ArrayBuffer | ArrayBufferView): Buffer; createBuffer(props: BufferProps | ArrayBuffer | ArrayBufferView): Buffer { if (props instanceof ArrayBuffer || ArrayBuffer.isView(props)) { return this._createBuffer({data: props}); } // Deduce indexType if (props.usage & Buffer.INDEX && !props.indexType) { if (props.data instanceof Uint32Array) { props.indexType = 'uint32'; } else if (props.data instanceof Uint16Array) { props.indexType = 'uint16'; } } return this._createBuffer(props); } /** Create a texture */ createTexture(props: TextureProps): Texture; createTexture(data: Promise<TextureData>): Texture; createTexture(url: string): Texture; createTexture(props: TextureProps | Promise<TextureData> | string): Texture { // Signature: new Texture2D(gl, url | Promise) if (props instanceof Promise || typeof props === 'string') { props = {data: props}; } return this._createTexture(props); } /** Create a temporary texture view of a video source */ abstract createExternalTexture(props: ExternalTextureProps): ExternalTexture; /** Create a sampler */ abstract createSampler(props: SamplerProps): Sampler; abstract createFramebuffer(props: FramebufferProps): Framebuffer; /** Create a shader */ abstract createShader(props: ShaderProps): Shader; /** Create a render pipeline (aka program) */ abstract createRenderPipeline(props: RenderPipelineProps): RenderPipeline; /** Create a compute pipeline (aka program) */ // abstract createComputePipeline(props: ComputePipelineProps): ComputePipeline; /** Create a RenderPass */ abstract beginRenderPass(props: RenderPassProps): RenderPass; /** Create a ComputePass */ // abstract beginComputePass(props?: ComputePassProps): ComputePass; abstract getDefaultRenderPass(): RenderPass; // Implementation protected abstract _createBuffer(props: BufferProps): Buffer; protected abstract _createTexture(props: TextureProps): Texture; }
the_stack
import * as vscode from 'vscode'; import * as parser from 'web-tree-sitter'; import * as jsonc from 'jsonc-parser'; import * as fs from 'fs'; import * as path from 'path'; // Grammar class const parserPromise = parser.init(); class Grammar { // Parser readonly lang: string; parser: parser; // Grammar readonly simpleTerms: { [sym: string]: string } = {}; readonly complexTerms: string[] = []; readonly complexScopes: { [sym: string]: string } = {}; readonly complexDepth: number = 0; readonly complexOrder: boolean = false; // Constructor constructor(lang: string) { // Parse grammar file this.lang = lang; const grammarFile = __dirname + "/../grammars/" + lang + ".json"; const grammarJson = jsonc.parse(fs.readFileSync(grammarFile).toString()); for (const t in grammarJson.simpleTerms) this.simpleTerms[t] = grammarJson.simpleTerms[t]; for (const t in grammarJson.complexTerms) this.complexTerms[t] = grammarJson.complexTerms[t]; for (const t in grammarJson.complexScopes) this.complexScopes[t] = grammarJson.complexScopes[t]; for (const s in this.complexScopes) { const depth = s.split(">").length; if (depth > this.complexDepth) this.complexDepth = depth; if (s.indexOf("[") >= 0) this.complexOrder = true; } this.complexDepth--; } // Parser initialization async init() { // Load wasm parser await parserPromise; this.parser = new parser(); let langFile = path.join(__dirname, "../parsers", this.lang + ".wasm"); const langObj = await parser.Language.load(langFile); this.parser.setLanguage(langObj); } // Build syntax tree tree(doc: string) { return this.parser.parse(doc); } // Parse syntax tree parse(tree: parser.Tree) { // Travel tree and peek terms let terms: { term: string; range: vscode.Range }[] = []; let stack: parser.SyntaxNode[] = []; let node = tree.rootNode.firstChild; while (stack.length > 0 || node) { // Go deeper if (node) { stack.push(node); node = node.firstChild; } // Go back else { node = stack.pop(); let type = node.type; if (!node.isNamed()) type = '"' + type + '"'; // Simple one-level terms let term: string | undefined = undefined; if (!this.complexTerms.includes(type)) { term = this.simpleTerms[type]; } // Complex terms require multi-level analyzes else { // Build complex scopes let desc = type; let scopes = [desc]; let parent = node.parent; for (let i = 0; i < this.complexDepth && parent; i++) { let parentType = parent.type; if (!parent.isNamed()) parentType = '"' + parentType + '"'; desc = parentType + " > " + desc; scopes.push(desc); parent = parent.parent; } // If there is also order complexity if (this.complexOrder) { let index = 0; let sibling = node.previousSibling; while (sibling) { if (sibling.type === node.type) index++; sibling = sibling.previousSibling; } let rindex = -1; sibling = node.nextSibling; while (sibling) { if (sibling.type === node.type) rindex--; sibling = sibling.nextSibling; } let orderScopes: string[] = []; for (let i = 0; i < scopes.length; i++) orderScopes.push(scopes[i], scopes[i] + "[" + index + "]", scopes[i] + "[" + rindex + "]"); scopes = orderScopes; } // Use most complex scope for (const d of scopes) if (d in this.complexScopes) term = this.complexScopes[d]; } // If term is found add it if (term) { terms.push({ term: term, range: new vscode.Range( new vscode.Position( node.startPosition.row, node.startPosition.column), new vscode.Position( node.endPosition.row, node.endPosition.column)) }); } // Go right node = node.nextSibling } } return terms; } } // Semantic token legend const termMap = new Map<string, { type: string, modifiers?: string[] }>(); function buildLegend() { // Terms vocabulary termMap.set("type", { type: "type" }); termMap.set("scope", { type: "namespace" }); termMap.set("function", { type: "function" }); termMap.set("variable", { type: "variable" }); termMap.set("number", { type: "number" }); termMap.set("string", { type: "string" }); termMap.set("comment", { type: "comment" }); termMap.set("constant", { type: "variable", modifiers: ["readonly", "defaultLibrary"] }); termMap.set("directive", { type: "macro" }); termMap.set("control", { type: "keyword" }); termMap.set("operator", { type: "operator" }); termMap.set("modifier", { type: "type", modifiers: ["modification"] }); termMap.set("punctuation", { type: "punctuation" }); // Tokens and modifiers in use let tokens: string[] = []; let modifiers: string[] = []; termMap.forEach(t => { if (!tokens.includes(t.type)) tokens.push(t.type); t.modifiers?.forEach(m => { if (!modifiers.includes(m)) modifiers.push(m); }); }); // Construct semantic token legend return new vscode.SemanticTokensLegend(tokens, modifiers); } const legend = buildLegend(); // Semantic token provider class TokensProvider implements vscode.DocumentSemanticTokensProvider, vscode.HoverProvider { readonly grammars: { [lang: string]: Grammar } = {}; readonly trees: { [doc: string]: parser.Tree } = {}; readonly supportedTerms: string[] = []; readonly debugDepth: number; constructor() { // Terms const availableTerms: string[] = [ "type", "scope", "function", "variable", "number", "string", "comment", "constant", "directive", "control", "operator", "modifier", "punctuation", ]; const enabledTerms: string[] = vscode.workspace. getConfiguration("syntax").get("highlightTerms"); availableTerms.forEach(term => { if (enabledTerms.includes(term)) this.supportedTerms.push(term); }); if (!vscode.workspace.getConfiguration("syntax").get("highlightComment")) if (this.supportedTerms.includes("comment")) this.supportedTerms.splice(this.supportedTerms.indexOf("comment"), 1); this.debugDepth = vscode.workspace.getConfiguration("syntax").get("debugDepth"); } // Provide document tokens async provideDocumentSemanticTokens( doc: vscode.TextDocument, token: vscode.CancellationToken): Promise<vscode.SemanticTokens> { // Grammar const lang = doc.languageId; if (!(lang in this.grammars)) { this.grammars[lang] = new Grammar(lang); await this.grammars[lang].init(); } // Parse document const grammar = this.grammars[lang]; const tree = grammar.tree(doc.getText()); const terms = grammar.parse(tree); this.trees[doc.uri.toString()] = tree; // Build tokens const builder = new vscode.SemanticTokensBuilder(legend); terms.forEach((t) => { if (!this.supportedTerms.includes(t.term)) return; const type = termMap.get(t.term).type; const modifiers = termMap.get(t.term).modifiers; if (t.range.start.line === t.range.end.line) return builder.push(t.range, type, modifiers); let line = t.range.start.line; builder.push(new vscode.Range(t.range.start, doc.lineAt(line).range.end), type, modifiers); for (line = line + 1; line < t.range.end.line; line++) builder.push(doc.lineAt(line).range, type, modifiers); builder.push(new vscode.Range(doc.lineAt(line).range.start, t.range.end), type, modifiers); }); return builder.build(); } // Provide hover tooltips async provideHover( doc: vscode.TextDocument, pos: vscode.Position, token: vscode.CancellationToken): Promise<vscode.Hover> { const uri = doc.uri.toString(); if (!(uri in this.trees)) return null; const grammar = this.grammars[doc.languageId]; const tree = this.trees[uri]; const xy: parser.Point = { row: pos.line, column: pos.character }; let node = tree.rootNode.descendantForPosition(xy); if (!node) return null; let type = node.type; if (!node.isNamed()) type = '"' + type + '"'; let parent = node.parent; const depth = Math.max(grammar.complexDepth, this.debugDepth); for (let i = 0; i < depth && parent; i++) { let parentType = parent.type; if (!parent.isNamed()) parentType = '"' + parentType + '"'; type = parentType + " > " + type; parent = parent.parent; } // If there is also order complexity if (grammar.complexOrder) { let index = 0; let sibling = node.previousSibling; while (sibling) { if (sibling.type === node.type) index++; sibling = sibling.previousSibling; } let rindex = -1; sibling = node.nextSibling; while (sibling) { if (sibling.type === node.type) rindex--; sibling = sibling.nextSibling; } type = type + "[" + index + "]" + "[" + rindex + "]"; } return { contents: [type], range: new vscode.Range( node.startPosition.row, node.startPosition.column, node.endPosition.row, node.endPosition.column) }; } } // Extension activation export async function activate(context: vscode.ExtensionContext) { // Languages let availableGrammars: string[] = []; fs.readdirSync(__dirname + "/../grammars/").forEach(name => { availableGrammars.push(path.basename(name, ".json")); }); let availableParsers: string[] = []; fs.readdirSync(__dirname + "/../parsers/").forEach(name => { availableParsers.push(path.basename(name, ".wasm")); }); const enabledLangs: string[] = vscode.workspace.getConfiguration("syntax").get("highlightLanguages"); let supportedLangs: { language: string }[] = []; availableGrammars.forEach(lang => { if (availableParsers.includes(lang) && enabledLangs.includes(lang)) supportedLangs.push({language: lang}); }); const engine = new TokensProvider(); context.subscriptions.push( vscode.languages.registerDocumentSemanticTokensProvider( supportedLangs, engine, legend)); // Register debug hover providers // Very useful tool for implementation and fixing of grammars if (vscode.workspace.getConfiguration("syntax").get("debugHover")) for (const lang of supportedLangs) vscode.languages.registerHoverProvider(lang, engine); }
the_stack
import { EntityMgr, Entity } from "./ECS/entityMgr"; import { Accessor, Mesh } from "./mesh/mesh"; import { Texture } from "./texture"; import { Material, RenderQueue } from "./material/material"; import { vec3, vec4, mat4 } from "./math"; import { TransformSystem, Transform } from "./transform"; import { Skin } from "./skin"; import { Animation, AnimationChannel } from "./animation"; import { Camera } from "./camera"; export class gltfScene { gltf; scene = EntityMgr.create('scene'); entities; constructor(gltf) { this.gltf = gltf; // TODO: gltf.useHDR = gltf.hasEnvmap && gltf.envmap.data != null // Materials // set default material if materials does not exist if(!gltf.materials) { gltf.materials = [{name: 'Default_Material'}]; } gltf.materials = gltf.materials.map(config => { let mat = new Material(gltf.commonShader, config.name, config.doubleSided); this.detectConfig(mat, config); Material.setTexture(mat, 'brdfLUT', gltf.brdfLUT); if(gltf.hasEnvmap) { mat.shader.macros['HAS_ENV_MAP'] = ''; if(gltf.useHDR) { mat.shader.macros['USE_HDR'] = ''; } Material.setTexture(mat, 'env', gltf.envmap); if (gltf.diffmap) { mat.shader.macros['HAS_DIFFENV_MAP'] = ''; Material.setTexture(mat, 'diffenv', gltf.diffmap); } } // if(gltf.skins) { // mat.shader.macros['HAS_SKINS'] = ''; // } return mat; }); // Set up all Vertexes gltf.accessors = gltf.accessors.map(acc => { acc.bufferView = gltf.bufferViews[acc.bufferView]; let attr = new Accessor(acc); return attr; }); // Create mesh gltf.meshes = gltf.meshes.map(mesh => { return mesh.primitives.map(meshData => { let {attributes, targets} = meshData; // Pick up attributes let accessors: Accessor[] = []; for (let attr in attributes) { let acc: Accessor = gltf.accessors[attributes[attr]]; acc.attribute = attr; // Set attribute name accessors.push(acc); } // Triangles let ebo = gltf.accessors[meshData.indices]; let mf = new Mesh(accessors, ebo, meshData.mode); if (attributes.TANGENT == null && attributes.TEXCOORD_0 != null) { console.warn('Using computed tagent!'); try { Mesh.preComputeTangent(mf); } catch (error) { } } if(attributes.NORMAL == null) { console.warn('Try to calculate normal!'); try { Mesh.preComputeNormal(mf); } catch (error) { console.log(error); } } let mat = gltf.materials[meshData.material || 0]; if (attributes.JOINTS_0 != null) { mat.shader.macros['HAS_SKINS'] = ''; } // Morph targets if(targets) { mat.shader.macros['HAS_MORPH_TARGETS'] = ''; Material.setUniform(mat, 'weights', new Float32Array([0.5])); for (let target of targets) { for (let tar in target) { let acc: Accessor = gltf.accessors[target[tar]]; acc.attribute = 'TAR_' + tar; mf.attributes.push(acc); } } } return [mf, mat]; }) }); } async assemble() { // Create entity instance for each node let gltf = this.gltf; let { scene, scenes, nodes, skins, animations } = gltf; this.entities = gltf.nodes.map((node, index) => this.createEntity(node, index)); if (skins) { skins = skins.map(skin => { skin.joints = skin.joints.map(jointIndex => this.entities[jointIndex].components.Transform); if(skin.entity == null) { return; } let skinComp = new Skin(); // Set up releated materials skinComp.materials = skin.materials; skinComp.joints = skin.joints; let acc: Accessor = gltf.accessors[skin.inverseBindMatrices]; skinComp.ibm = Accessor.getFloat32Blocks(acc); skinComp.outputMat = new Float32Array(acc.count * acc.size); skinComp.jointMat = Accessor.getSubChunks(acc, skinComp.outputMat); // https://github.com/KhronosGroup/glTF/issues/1270 // https://github.com/KhronosGroup/glTF/pull/1195 // for (let mat of skin.materials) { // mat.shader.macros['JOINT_AMOUNT'] = Math.min(skin.joints.length, 200); // mat.shader.isDirty = true; // } for (let trans of skin.transforms as Transform[]) { trans.jointsMatrices = skinComp.outputMat; let mat = trans.entity.components.Material as Material; mat.shader.macros['JOINT_AMOUNT'] = Math.min(skin.joints.length, 200); } if(skin.entity) skin.entity.addComponent(skinComp); return skinComp; }); } if (animations) { for (let { channels, samplers } of animations) { for (let { sampler, target } of channels) { let e = this.entities[target.node]; let trans = e.components.Transform as Transform; let mat = e.components.Material as Material; let controlChannel: Float32Array; switch (target.path) { case 'translation': controlChannel = trans.translate; break; case 'rotation': controlChannel = trans.quaternion; break; case 'scale': controlChannel = trans.scale; break; case 'weights': // controlChannel = mat.uniforms['weights']; break; } if (controlChannel != null) { let { input, interpolation, output } = samplers[sampler]; let timeline = gltf.accessors[input]; let keyframe = gltf.accessors[output]; if (e.components.Animation == null) { e.addComponent(new Animation()); } let anim = e.components.Animation as Animation; Animation.attachChannel(anim, new AnimationChannel(controlChannel, timeline, keyframe)) // console.log(anim); } } } } // assemble scene tree let roots = scenes[scene || 0].nodes; for (let r of roots) { let root = this.parseNode(r, nodes); this.scene.appendChild(root); } console.log(this); return this; } waitEntity(node, index) { return new Promise((resolve: (e:Entity)=>void, reject) => { setTimeout(() => { resolve(this.createEntity(node, index)); }, 0); }) } detectTexture(mat: Material, texName, texInfo) { let { index, texCoord } = texInfo; let gltf = this.gltf; if (index != null) { // common texture Material.setTexture(mat, texName, gltf.textures[index]); // Multi UV if(texCoord) { // > 0 mat.shader.macros[`${texName}_uv`] = `uv${texCoord}`; } } } detectConfig(mat: Material, config) { let shader = mat.shader; for(let key in config) { let value = config[key]; // assueme current property is an texture info this.detectTexture(mat, key, value); switch(key) { // Textures case 'normalTexture': shader.macros['HAS_NORMAL_MAP'] = ''; break; case 'occlusionTexture': shader.macros['HAS_AO_MAP'] = ''; break; case 'baseColorTexture': shader.macros['HAS_BASECOLOR_MAP'] = ''; break; case 'metallicRoughnessTexture': shader.macros['HAS_METALLIC_ROUGHNESS_MAP'] = ''; break; case 'emissiveTexture': shader.macros['HAS_EMISSIVE_MAP'] = ''; break; // Factors - pbrMetallicRoughness case 'baseColorFactor': shader.macros['BASECOLOR_FACTOR'] = `vec4(${value.join(',')})`; break; case 'metallicFactor': shader.macros['METALLIC_FACTOR'] = `float(${value})`; break; case 'roughnessFactor': shader.macros['ROUGHNESS_FACTOR'] = `float(${value})`; break; // Alpha Blend Mode case 'alphaMode': shader.macros[value] = ''; if(value != 'OPAQUE') { mat.queue = RenderQueue.Blend; } break; case 'alphaCutoff': shader.macros['ALPHA_CUTOFF'] = `float(${value})`; break; case 'pbrMetallicRoughness': this.detectConfig(mat, value); break; } } } createEntity(node, index) { let { mesh, name, matrix, rotation, scale, translation, skin, camera } = node; name = name || 'node_' + index; let entity = EntityMgr.create(name); let trans = entity.components.Transform as Transform; if (matrix != null) { mat4.set(trans.localMatrix, ...matrix); TransformSystem.decomposeMatrix(trans); } else { if (rotation != null) { vec4.set(trans.quaternion, ...rotation); } if (scale != null) { vec3.set(trans.scale, ...scale); } if (translation != null) { vec3.set(trans.translate, ...translation); } } TransformSystem.updateMatrix(trans); let transCache = []; // let matCache = []; if (mesh != null) { let renderTarget = entity; let meshChunk = this.gltf.meshes[mesh]; let hasSubnode = meshChunk.length - 1; for(let [i, meshData] of meshChunk.entries()) { let [mf, mat] = meshData; if (hasSubnode) { renderTarget = entity.appendChild(EntityMgr.create('subNode_' + i)); } renderTarget.addComponent(mf); renderTarget.addComponent(mat); transCache.push(renderTarget.components.Transform); // matCache.push(mat); } } if (skin != null) { this.gltf.skins[skin].entity = entity; if(!this.gltf.skins[skin].transforms) { this.gltf.skins[skin].transforms = []; } this.gltf.skins[skin].transforms.push(...transCache); // this.gltf.skins[skin].materials = matCache; } if (camera != null) { entity.addComponent(this.gltf.cameras[camera]); } return entity; } parseNode(nodeIndex, nodeList) { let node = nodeList[nodeIndex]; let entity = this.entities[nodeIndex]; if(node.children) { for(let child of node.children) { entity.appendChild(this.parseNode(child, nodeList)); } } return entity; } }
the_stack
import tape from 'tape' import td from 'testdouble' import Common, { Chain as CommonChain, Hardfork } from '@ethereumjs/common' import { FeeMarketEIP1559Transaction, Transaction } from '@ethereumjs/tx' import { Block, BlockHeader } from '@ethereumjs/block' import { DefaultStateManager, StateManager } from '@ethereumjs/vm/dist/state' import { Account, Address, BN } from 'ethereumjs-util' import { Config } from '../../lib/config' import { FullSynchronizer } from '../../lib/sync/fullsync' import { Chain } from '../../lib/blockchain' import { Miner } from '../../lib/miner' import { Event } from '../../lib/types' import { wait } from '../integration/util' const A = { address: new Address(Buffer.from('0b90087d864e82a284dca15923f3776de6bb016f', 'hex')), privateKey: Buffer.from( '64bf9cc30328b0e42387b3c82c614e6386259136235e20c1357bd11cdee86993', 'hex' ), } const B = { address: new Address(Buffer.from('6f62d8382bf2587361db73ceca28be91b2acb6df', 'hex')), privateKey: Buffer.from( '2a6e9ad5a6a8e4f17149b8bc7128bf090566a11dbd63c30e5a0ee9f161309cd6', 'hex' ), } const setBalance = async (stateManager: StateManager, address: Address, balance: BN) => { // this fn can be replaced with modifyAccountFields() when #1369 is available await stateManager.checkpoint() await stateManager.putAccount(address, new Account(new BN(0), balance)) await stateManager.commit() } tape('[Miner]', async (t) => { BlockHeader.prototype.validate = td.func<any>() td.replace('@ethereumjs/block', { BlockHeader }) DefaultStateManager.prototype.setStateRoot = td.func<any>() td.replace('@ethereumjs/vm/dist/state', { DefaultStateManager }) class PeerPool { open() {} close() {} get peers() { return [] } } class FakeChain { open() {} close() {} update() {} get headers() { return { latest: BlockHeader.fromHeaderData(), height: new BN(0), } } get blocks() { return { latest: Block.fromBlockData(), height: new BN(0), } } blockchain: any = { putBlock: async () => {}, cliqueActiveSigners: () => [A.address], cliqueSignerInTurn: async () => true, cliqueCheckRecentlySigned: () => false, // eslint-disable-next-line no-invalid-this copy: () => this.blockchain, } } const common = new Common({ chain: CommonChain.Rinkeby, hardfork: Hardfork.Berlin }) common.setMaxListeners(50) const accounts: [Address, Buffer][] = [[A.address, A.privateKey]] const config = new Config({ transports: [], accounts, mine: true, common }) config.events.setMaxListeners(50) const createTx = ( from = A, to = B, nonce = 0, value = 1, gasPrice = 1000000000, gasLimit = 100000 ) => { const txData = { nonce, gasPrice, gasLimit, to: to.address, value, } const tx = Transaction.fromTxData(txData, { common }) const signedTx = tx.sign(from.privateKey) return signedTx } const txA01 = createTx() // A -> B, nonce: 0, value: 1, normal gasPrice const txA02 = createTx(A, B, 1, 1, 2000000000) // A -> B, nonce: 1, value: 1, 2x gasPrice const txA03 = createTx(A, B, 2, 1, 3000000000) // A -> B, nonce: 2, value: 1, 3x gasPrice const txB01 = createTx(B, A, 0, 1, 2500000000) // B -> A, nonce: 0, value: 1, 2.5x gasPrice t.test('should initialize correctly', (t) => { const pool = new PeerPool() as any const chain = new FakeChain() as any const synchronizer = new FullSynchronizer({ config, pool, chain, }) const miner = new Miner({ config, synchronizer }) t.notOk(miner.running) t.end() }) t.test('should start/stop', async (t) => { t.plan(4) const pool = new PeerPool() as any const chain = new FakeChain() as any const synchronizer = new FullSynchronizer({ config, pool, chain, }) let miner = new Miner({ config, synchronizer }) t.notOk(miner.running) miner.start() t.ok(miner.running) await wait(10) miner.stop() t.notOk(miner.running) // Should not start when config.mine=false const configMineFalse = new Config({ transports: [], accounts, mine: false }) miner = new Miner({ config: configMineFalse, synchronizer }) miner.start() t.notOk(miner.running, 'miner should not start when config.mine=false') }) t.test('assembleBlocks() -> with a single tx', async (t) => { t.plan(1) const pool = new PeerPool() as any const chain = new FakeChain() as any const synchronizer = new FullSynchronizer({ config, pool, chain, }) const miner = new Miner({ config, synchronizer }) const { txPool } = synchronizer const { vm } = synchronizer.execution txPool.start() miner.start() await setBalance(vm.stateManager, A.address, new BN('200000000000001')) // add tx txPool.add(txA01) // disable consensus to skip PoA block signer validation ;(vm.blockchain as any)._validateConsensus = false chain.putBlocks = (blocks: Block[]) => { t.equal(blocks[0].transactions.length, 1, 'new block should include tx') miner.stop() txPool.stop() } await (miner as any).queueNextAssembly(0) await wait(500) }) t.test( 'assembleBlocks() -> with multiple txs, properly ordered by gasPrice and nonce', async (t) => { t.plan(4) const pool = new PeerPool() as any const chain = new FakeChain() as any const synchronizer = new FullSynchronizer({ config, pool, chain, }) const miner = new Miner({ config, synchronizer }) const { txPool } = synchronizer const { vm } = synchronizer.execution txPool.start() miner.start() await setBalance(vm.stateManager, A.address, new BN('400000000000001')) await setBalance(vm.stateManager, B.address, new BN('400000000000001')) // add txs txPool.add(txA01) txPool.add(txA02) txPool.add(txA03) txPool.add(txB01) // disable consensus to skip PoA block signer validation ;(vm.blockchain as any)._validateConsensus = false chain.putBlocks = (blocks: Block[]) => { const msg = 'txs in block should be properly ordered by gasPrice and nonce' const expectedOrder = [txB01, txA01, txA02, txA03] for (const [index, tx] of expectedOrder.entries()) { t.ok(blocks[0].transactions[index].hash().equals(tx.hash()), msg) } miner.stop() txPool.stop() } await (miner as any).queueNextAssembly(0) await wait(500) } ) t.test('assembleBlocks() -> should not include tx under the baseFee', async (t) => { t.plan(1) const customChainParams = { hardforks: [{ name: 'london', block: 0 }] } const common = Common.forCustomChain(CommonChain.Rinkeby, customChainParams, Hardfork.London) const config = new Config({ transports: [], accounts, mine: true, common }) const pool = new PeerPool() as any const chain = new FakeChain() as any const block = Block.fromBlockData({}, { common }) Object.defineProperty(chain, 'headers', { get: function () { return { latest: block.header } }, }) Object.defineProperty(chain, 'blocks', { get: function () { return { latest: block } }, }) const synchronizer = new FullSynchronizer({ config, pool, chain, }) const miner = new Miner({ config, synchronizer }) const { txPool } = synchronizer const { vm } = synchronizer.execution txPool.start() miner.start() // the default block baseFee will be 7 // add tx with maxFeePerGas of 6 const tx = FeeMarketEIP1559Transaction.fromTxData( { to: B.address, maxFeePerGas: 6 }, { common } ).sign(A.privateKey) txPool.add(tx) // disable consensus to skip PoA block signer validation ;(vm.blockchain as any)._validateConsensus = false synchronizer.handleNewBlock = async (block: Block) => { t.equal(block.transactions.length, 0, 'should not include tx') miner.stop() txPool.stop() } await wait(500) await (miner as any).queueNextAssembly(0) await wait(500) }) t.test("assembleBlocks() -> should stop assembling a block after it's full", async (t) => { t.plan(1) const pool = new PeerPool() as any const chain = new FakeChain() as any const gasLimit = 100000 const block = Block.fromBlockData({ header: { gasLimit } }, { common }) Object.defineProperty(chain, 'headers', { get: function () { return { latest: block.header, height: new BN(0) } }, }) Object.defineProperty(chain, 'blocks', { get: function () { return { latest: block, height: new BN(0) } }, }) const synchronizer = new FullSynchronizer({ config, pool, chain, }) const miner = new Miner({ config, synchronizer }) const { txPool } = synchronizer const { vm } = synchronizer.execution txPool.start() miner.start() await setBalance(vm.stateManager, A.address, new BN('200000000000001')) // add txs const data = '0xfe' // INVALID opcode, consumes all gas const tx1FillsBlockGasLimit = Transaction.fromTxData( { gasLimit: gasLimit - 1, data }, { common } ).sign(A.privateKey) const tx2ExceedsBlockGasLimit = Transaction.fromTxData( { gasLimit: 21000, to: B.address, nonce: 1 }, { common } ).sign(A.privateKey) txPool.add(tx1FillsBlockGasLimit) txPool.add(tx2ExceedsBlockGasLimit) // disable consensus to skip PoA block signer validation ;(vm.blockchain as any)._validateConsensus = false chain.putBlocks = (blocks: Block[]) => { t.equal(blocks[0].transactions.length, 1, 'only one tx should be included') miner.stop() txPool.stop() } await (miner as any).queueNextAssembly(0) await wait(500) }) t.test('assembleBlocks() -> should stop assembling when a new block is received', async (t) => { t.plan(2) const pool = new PeerPool() as any const chain = new FakeChain() as any const config = new Config({ transports: [], accounts, mine: true, common }) const synchronizer = new FullSynchronizer({ config, pool, chain, }) const miner = new Miner({ config, synchronizer }) // stub chainUpdated so assemble isn't called again // when emitting Event.CHAIN_UPDATED in this test ;(miner as any).chainUpdated = async () => {} const { txPool } = synchronizer const { vm } = synchronizer.execution txPool.start() miner.start() await setBalance(vm.stateManager, A.address, new BN('200000000000001')) // add many txs to slow assembling for (let i = 0; i < 1000; i++) { txPool.add(createTx()) } chain.putBlocks = () => { t.fail('should have stopped assembling when a new block was received') } await (miner as any).queueNextAssembly(5) await wait(5) t.ok((miner as any).assembling, 'miner should be assembling') config.events.emit(Event.CHAIN_UPDATED) await wait(25) t.notOk((miner as any).assembling, 'miner should have stopped assembling') miner.stop() txPool.stop() }) t.test('should handle mining over the london hardfork block', async (t) => { const customChainParams = { hardforks: [ { name: 'chainstart', block: 0 }, { name: 'berlin', block: 2 }, { name: 'london', block: 3 }, ], } const common = Common.custom(customChainParams, { baseChain: CommonChain.Rinkeby }) common.setHardforkByBlockNumber(0) const pool = new PeerPool() as any const config = new Config({ transports: [], accounts, mine: true, common }) const chain = new Chain({ config }) await chain.open() const synchronizer = new FullSynchronizer({ config, pool, chain, }) const miner = new Miner({ config, synchronizer }) const { vm } = synchronizer.execution vm.blockchain.cliqueActiveSigners = () => [A.address] // stub ;(miner as any).chainUpdated = async () => {} // stub miner.start() await wait(100) // in this test we need to explicitly update common with // setHardforkByBlockNumber() to test the hardfork() value // since the vmexecution run method isn't reached in this // stubbed configuration. // block 1: chainstart await (miner as any).queueNextAssembly(0) await wait(100) config.execCommon.setHardforkByBlockNumber(1) t.equal(config.execCommon.hardfork(), Hardfork.Chainstart) // block 2: berlin await (miner as any).queueNextAssembly(0) await wait(100) config.execCommon.setHardforkByBlockNumber(2) t.equal(config.execCommon.hardfork(), Hardfork.Berlin) const blockHeader2 = await chain.getLatestHeader() // block 3: london await (miner as any).queueNextAssembly(0) await wait(100) const blockHeader3 = await chain.getLatestHeader() config.execCommon.setHardforkByBlockNumber(3) t.equal(config.execCommon.hardfork(), Hardfork.London) t.ok( blockHeader2.gasLimit.muln(2).eq(blockHeader3.gasLimit), 'gas limit should be double previous block' ) const initialBaseFee = new BN(config.execCommon.paramByEIP('gasConfig', 'initialBaseFee', 1559)) t.ok(blockHeader3.baseFeePerGas!.eq(initialBaseFee), 'baseFee should be initial value') // block 4 await (miner as any).queueNextAssembly(0) await wait(100) const blockHeader4 = await chain.getLatestHeader() config.execCommon.setHardforkByBlockNumber(4) t.equal(config.execCommon.hardfork(), Hardfork.London) t.ok( blockHeader4.baseFeePerGas!.eq(blockHeader3.calcNextBaseFee()), 'baseFee should be as calculated' ) t.ok((await chain.getLatestHeader()).number.eqn(4)) miner.stop() await chain.close() }) t.test('should handle mining ethash PoW', async (t) => { t.plan(1) const common = new Common({ chain: CommonChain.Ropsten }) ;(common as any)._chainParams['genesis'].difficulty = 1 const pool = new PeerPool() as any const config = new Config({ transports: [], accounts, mine: true, common }) const chain = new Chain({ config }) await chain.open() const synchronizer = new FullSynchronizer({ config, pool, chain, }) const miner = new Miner({ config, synchronizer }) ;(chain.blockchain as any)._validateConsensus = false ;(miner as any).chainUpdated = async () => {} // stub miner.start() await wait(100) config.events.on(Event.CHAIN_UPDATED, async () => { t.ok(chain.blocks.latest!.header.number.eqn(1)) miner.stop() await chain.close() }) await (miner as any).queueNextAssembly(0) await wait(3000) }) t.test('should reset td', (t) => { td.reset() t.end() }) })
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/filesMappers"; import * as Parameters from "../models/parameters"; import { DataMigrationServiceClientContext } from "../dataMigrationServiceClientContext"; /** Class representing a Files. */ export class Files { private readonly client: DataMigrationServiceClientContext; /** * Create a Files. * @param {DataMigrationServiceClientContext} client Reference to the service client. */ constructor(client: DataMigrationServiceClientContext) { this.client = client; } /** * The project resource is a nested resource representing a stored migration project. This method * returns a list of files owned by a project resource. * @summary Get files in a project * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param [options] The optional parameters * @returns Promise<Models.FilesListResponse> */ list(groupName: string, serviceName: string, projectName: string, options?: msRest.RequestOptionsBase): Promise<Models.FilesListResponse>; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param callback The callback */ list(groupName: string, serviceName: string, projectName: string, callback: msRest.ServiceCallback<Models.FileList>): void; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param options The optional parameters * @param callback The callback */ list(groupName: string, serviceName: string, projectName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.FileList>): void; list(groupName: string, serviceName: string, projectName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.FileList>, callback?: msRest.ServiceCallback<Models.FileList>): Promise<Models.FilesListResponse> { return this.client.sendOperationRequest( { groupName, serviceName, projectName, options }, listOperationSpec, callback) as Promise<Models.FilesListResponse>; } /** * The files resource is a nested, proxy-only resource representing a file stored under the project * resource. This method retrieves information about a file. * @summary Get file information * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param [options] The optional parameters * @returns Promise<Models.FilesGetResponse> */ get(groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase): Promise<Models.FilesGetResponse>; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param callback The callback */ get(groupName: string, serviceName: string, projectName: string, fileName: string, callback: msRest.ServiceCallback<Models.ProjectFile>): void; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param options The optional parameters * @param callback The callback */ get(groupName: string, serviceName: string, projectName: string, fileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectFile>): void; get(groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectFile>, callback?: msRest.ServiceCallback<Models.ProjectFile>): Promise<Models.FilesGetResponse> { return this.client.sendOperationRequest( { groupName, serviceName, projectName, fileName, options }, getOperationSpec, callback) as Promise<Models.FilesGetResponse>; } /** * The PUT method creates a new file or updates an existing one. * @summary Create a file resource * @param parameters Information about the file * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param [options] The optional parameters * @returns Promise<Models.FilesCreateOrUpdateResponse> */ createOrUpdate(parameters: Models.ProjectFile, groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase): Promise<Models.FilesCreateOrUpdateResponse>; /** * @param parameters Information about the file * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param callback The callback */ createOrUpdate(parameters: Models.ProjectFile, groupName: string, serviceName: string, projectName: string, fileName: string, callback: msRest.ServiceCallback<Models.ProjectFile>): void; /** * @param parameters Information about the file * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param options The optional parameters * @param callback The callback */ createOrUpdate(parameters: Models.ProjectFile, groupName: string, serviceName: string, projectName: string, fileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectFile>): void; createOrUpdate(parameters: Models.ProjectFile, groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectFile>, callback?: msRest.ServiceCallback<Models.ProjectFile>): Promise<Models.FilesCreateOrUpdateResponse> { return this.client.sendOperationRequest( { parameters, groupName, serviceName, projectName, fileName, options }, createOrUpdateOperationSpec, callback) as Promise<Models.FilesCreateOrUpdateResponse>; } /** * This method deletes a file. * @summary Delete file * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param callback The callback */ deleteMethod(groupName: string, serviceName: string, projectName: string, fileName: string, callback: msRest.ServiceCallback<void>): void; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param options The optional parameters * @param callback The callback */ deleteMethod(groupName: string, serviceName: string, projectName: string, fileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { groupName, serviceName, projectName, fileName, options }, deleteMethodOperationSpec, callback); } /** * This method updates an existing file. * @summary Update a file * @param parameters Information about the file * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param [options] The optional parameters * @returns Promise<Models.FilesUpdateResponse> */ update(parameters: Models.ProjectFile, groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase): Promise<Models.FilesUpdateResponse>; /** * @param parameters Information about the file * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param callback The callback */ update(parameters: Models.ProjectFile, groupName: string, serviceName: string, projectName: string, fileName: string, callback: msRest.ServiceCallback<Models.ProjectFile>): void; /** * @param parameters Information about the file * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param options The optional parameters * @param callback The callback */ update(parameters: Models.ProjectFile, groupName: string, serviceName: string, projectName: string, fileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ProjectFile>): void; update(parameters: Models.ProjectFile, groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ProjectFile>, callback?: msRest.ServiceCallback<Models.ProjectFile>): Promise<Models.FilesUpdateResponse> { return this.client.sendOperationRequest( { parameters, groupName, serviceName, projectName, fileName, options }, updateOperationSpec, callback) as Promise<Models.FilesUpdateResponse>; } /** * This method is used for requesting storage information using which contents of the file can be * downloaded. * @summary Request storage information for downloading the file content * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param [options] The optional parameters * @returns Promise<Models.FilesReadResponse> */ read(groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase): Promise<Models.FilesReadResponse>; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param callback The callback */ read(groupName: string, serviceName: string, projectName: string, fileName: string, callback: msRest.ServiceCallback<Models.FileStorageInfo>): void; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param options The optional parameters * @param callback The callback */ read(groupName: string, serviceName: string, projectName: string, fileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.FileStorageInfo>): void; read(groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.FileStorageInfo>, callback?: msRest.ServiceCallback<Models.FileStorageInfo>): Promise<Models.FilesReadResponse> { return this.client.sendOperationRequest( { groupName, serviceName, projectName, fileName, options }, readOperationSpec, callback) as Promise<Models.FilesReadResponse>; } /** * This method is used for requesting information for reading and writing the file content. * @summary Request information for reading and writing file content. * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param [options] The optional parameters * @returns Promise<Models.FilesReadWriteResponse> */ readWrite(groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase): Promise<Models.FilesReadWriteResponse>; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param callback The callback */ readWrite(groupName: string, serviceName: string, projectName: string, fileName: string, callback: msRest.ServiceCallback<Models.FileStorageInfo>): void; /** * @param groupName Name of the resource group * @param serviceName Name of the service * @param projectName Name of the project * @param fileName Name of the File * @param options The optional parameters * @param callback The callback */ readWrite(groupName: string, serviceName: string, projectName: string, fileName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.FileStorageInfo>): void; readWrite(groupName: string, serviceName: string, projectName: string, fileName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.FileStorageInfo>, callback?: msRest.ServiceCallback<Models.FileStorageInfo>): Promise<Models.FilesReadWriteResponse> { return this.client.sendOperationRequest( { groupName, serviceName, projectName, fileName, options }, readWriteOperationSpec, callback) as Promise<Models.FilesReadWriteResponse>; } /** * The project resource is a nested resource representing a stored migration project. This method * returns a list of files owned by a project resource. * @summary Get files in a project * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.FilesListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.FilesListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.FileList>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.FileList>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.FileList>, callback?: msRest.ServiceCallback<Models.FileList>): Promise<Models.FilesListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.FilesListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/projects/{projectName}/files", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName, Parameters.projectName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.FileList }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/projects/{projectName}/files/{fileName}", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName, Parameters.projectName, Parameters.fileName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ProjectFile }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/projects/{projectName}/files/{fileName}", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName, Parameters.projectName, Parameters.fileName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.ProjectFile, required: true } }, responses: { 200: { bodyMapper: Mappers.ProjectFile }, 201: { bodyMapper: Mappers.ProjectFile }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/projects/{projectName}/files/{fileName}", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName, Parameters.projectName, Parameters.fileName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.ApiError } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/projects/{projectName}/files/{fileName}", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName, Parameters.projectName, Parameters.fileName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.ProjectFile, required: true } }, responses: { 200: { bodyMapper: Mappers.ProjectFile }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const readOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/projects/{projectName}/files/{fileName}/read", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName, Parameters.projectName, Parameters.fileName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.FileStorageInfo }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const readWriteOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{groupName}/providers/Microsoft.DataMigration/services/{serviceName}/projects/{projectName}/files/{fileName}/readwrite", urlParameters: [ Parameters.subscriptionId, Parameters.groupName, Parameters.serviceName, Parameters.projectName, Parameters.fileName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.FileStorageInfo }, default: { bodyMapper: Mappers.ApiError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.FileList }, default: { bodyMapper: Mappers.ApiError } }, serializer };
the_stack
import { AfterContentInit, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, HostListener, Input, OnInit, Output, QueryList, } from '@angular/core'; import { CommonDataService } from '../../services/data/common.data.service'; import { DeviceQueryService } from '../../services/device/device.query.service'; import { SideNavNodeComponent } from '../sidenav/sidenavnode.component'; @Component({ selector: 'amexio-side-nav', templateUrl: './sidenav.component.html', }) export class AmexioSideNavComponent implements OnInit, AfterContentInit { /* Properties name : data datatype : any version : 4.0 onwards default : none description : Local data for sidenav. */ @Input() data: any[]; /* Properties name : http-url datatype : string version : 4.0 onwards default : none description : REST url for fetching datasource. */ @Input('http-url') httpurl: string; /* Properties name : http-url datatype : string version : 4.0 onwards default : none description : Type of HTTP call, POST,GET. */ @Input('http-method') httpmethod: string; /* Properties name : data-reader datatype : string version : 4.0 onwards default : none description : Key in JSON datasource for records */ @Input('data-reader') datareader: string; /* Properties name : position datatype : any version : 4.0 onwards default : none description : Sidenav bar rendering position. example position='relative','right' */ @Input() position: any; /* Properties name : titleimage datatype : string version : 4.0 onwards default : none description : Title image of sidenav bar */ @Input() titleimage: string; /* Events name : nodeClick datatype : none version : none default : none description : Fire when sidenav bar menu click */ @Output() nodeClick: any = new EventEmitter<any>(); /* Events name : onDrag datatype : none version : 4.2.9 default : none description : Fire when you drag node */ @Output() onDrag: any = new EventEmitter<any>(); /* Properties name : width datatype : string version : 4.0 onwards default : none description : Width of sidenav */ @Input() width: string; /* Properties name : height datatype : string version : 4.0 onwards default : none description : height of sidenav */ @Input() height: string; /* Properties name : title datatype : string version : 4.0 onwards default : none description : Title of sidenav bar */ @Input('title') sidenavtitle: string; /* Properties name : enable-drag datatype : boolean version : 5.0.0 onwards default : false description : nodes can be dragged */ @Input('enable-drag') enabledrag: boolean; /* Properties name : display-key datatype : string version : 5.2.0 onwards default : text description : Name of key inside response data to display on ui. */ @Input('display-key') displaykey: string; /* Properties name : child-array-key datatype : string version : 5.2.0 onwards default : children description : Name of key for child array name inside response data to display on ui. */ @Input('child-array-key') childarraykey: string; /* Properties name : enable-border datatype : boolean version : 5.5.5 onwards default : true description : By default enable-border is enabled */ @Input('enable-border') enableborder = true; /* Properties name : background datatype : string version : 5.5.5 onwards default : description : User can define custom background color or pass gradient */ @Input('background') background: string; /* Properties name : color datatype : string version : 5.5.5 onwards default : children description : User can define custom background color or pass gradient */ @Input('color') color: string; /* Properties name : background-image datatype : string version : 5.5.5 onwards default : children description : User can pass background image */ @Input('bg-image') bgimage: string; homepageType: string; @Output() onMouseLeave: any = new EventEmitter<any>(); @Output() onMouseOver: any = new EventEmitter<any>(); @ContentChildren(SideNavNodeComponent) sidennavnodearray: QueryList<SideNavNodeComponent>; smalldevice: boolean; nodearray: any; activenode: any; sidenavexpandedinsmalldevice: boolean; handleMobileDevice = true; responseData: any; isSideNavExpand: boolean; nodes: any = []; isShowOnlyIcon = false; isSideNavEnable = true; constructor(public dataService: CommonDataService, public matchMediaService: DeviceQueryService, public element: ElementRef, private cd: ChangeDetectorRef) { this.position = 'left'; this.smalldevice = false; this.sidenavexpandedinsmalldevice = false; this.width = '0%'; const that = this; this.displaykey = 'text'; this.childarraykey = 'children'; if (this.matchMediaService.IsTablet() || this.matchMediaService.IsPhone()) { this.smalldevice = true; this.width = '0%'; } else { this.width = '19%'; } /*--------------------------------------------------- TAP INTO LISTENERS FOR WHEN DEVICE WIDTH CHANGES ---------------------------------------------------*/ this.matchMediaService.OnPhone((mediaQueryList: MediaQueryList) => { that.handleDeviceSettings(false); }); this.matchMediaService.OnTablet((mediaQueryList: MediaQueryList) => { that.handleDeviceSettings(false); }); this.matchMediaService.OnDesktop((mediaQueryList: MediaQueryList) => { that.handleDeviceSettings(false); }); } ngOnInit() { if (this.httpmethod && this.httpurl) { this.dataService.fetchData(this.httpurl, this.httpmethod).subscribe((response) => { this.responseData = response; }, (error) => { }, () => { this.setData(this.responseData); }); } if (this.data && (!this.httpmethod || !this.httpurl)) { this.setData(this.data); } if (this.position == null) { this.position = 'left'; } if (!this.height) { this.height = '100%'; } } ngAfterContentInit() { this.nodearray = this.sidennavnodearray.toArray(); this.nodearray.forEach((element: SideNavNodeComponent) => { element.nodeEmitToSideNav.subscribe((node: any) => { node.forEach((nodeelement: any) => { if (nodeelement.active === true) { this.activenode = nodeelement; } }); this.activateNode = JSON.parse(JSON.stringify(node)); this.findObj(node); }); }); } toggle() { this.handleDeviceSettings(true); } findObj(currentnode: any) { this.nodearray.forEach((element: SideNavNodeComponent) => { if (element.node && (element.node.length > 0)) { (element.node).forEach((individualnode: any) => { if ((this.activenode.text === individualnode.text) && (this.activenode.active === individualnode.active)) { individualnode.active = true; } else { individualnode.active = false; } }); } }); } onClick(node: any) { this.activateNode(this.data, node); if (this.matchMediaService.IsTablet() || this.matchMediaService.IsPhone()) { this.smalldevice = true; } else { this.smalldevice = false; } this.nodeClick.emit(node); if (this.smalldevice && (!node.children || node.children === null || node.children === '')) { this.isSideNavExpand = false; } else { this.isSideNavEnable = true; } } collapseSidenav() { this.width = '0%'; this.isSideNavExpand = false; this.sidenavexpandedinsmalldevice = false; } generateIndex(data: any) { data.forEach((element: any, index: any) => { if (element[this.childarraykey]) { element[this.childarraykey].forEach((innerelement: any) => { innerelement['tabindex'] = '-1'; if (innerelement[this.childarraykey]) { innerelement[this.childarraykey].forEach((innerelement2: any) => { innerelement2['tabindex'] = '-1'; }); } }); } }); } setData(httpResponse: any) { // Check if key is added? let responsedata = httpResponse; if (this.datareader != null) { const dr = this.datareader.split('.'); for (const ir of dr) { responsedata = responsedata[ir]; } } else { responsedata = httpResponse; } this.data = responsedata; this.generateIndex(this.data); this.activateNode(this.data, null); this.handleDeviceSettings(false); } activateNode(data: any[], node: any) { for (const i of data) { if (node === i && !i[this.childarraykey]) { i['active'] = true; } else { i['active'] = false; } if (i[this.childarraykey]) { this.activateNode(i[this.childarraykey], node); } } } toggleSideNav() { this.isSideNavEnable = true; this.handleDeviceSettings(!this.isSideNavExpand); } close() { this.handleDeviceSettings(false); } handleDeviceSettings(expand: boolean) { if (this.position !== 'relative') { if (this.matchMediaService.IsTablet() || this.matchMediaService.IsPhone()) { this.smalldevice = true; if (expand) { this.width = '80%'; this.isSideNavExpand = true; this.sidenavexpandedinsmalldevice = true; } else { this.width = '0%'; this.isSideNavExpand = false; this.sidenavexpandedinsmalldevice = false; } } else { if (this.isShowOnlyIcon) { this.width = '5%'; } else { this.width = '19%'; } this.smalldevice = false; } } } getNodeDragEvent(event: any) { this.onDrag.emit(event); } // THIS METHOD IS USED FOR SETTING HOMEPAGE TYPE setHomePageType(type: any) { this.homepageType = type; if (this.homepageType === '3') { this.nodearray.forEach((element: SideNavNodeComponent) => { element.setShowOnlyIconFlag(this.isShowOnlyIcon); }); } this.cd.detectChanges(); } }
the_stack
import _debug from "debug"; import { uniqBy, some, has, transform } from "lodash"; import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor"; import { MappedDataSource } from "./MappedDataSource"; import { DataSourceMapping } from "./DataSourceMapping"; import { MappedField } from "./MappedField"; import { MappedSingleSourceOperation } from "./MappedSingleSourceOperation"; import { MappedSingleSourceQueryOperation } from "./MappedSingleSourceQueryOperation"; import { ResolveInfoVisitor } from "./ResolveInfoVisitor"; import { Dict, PartialDeep } from "./utils/util-types"; import { indexBy, MemoizeGetter } from "./utils/utils"; import { MappedAssociation } from "./MappedAssociation"; import { AssociationFetchConfig, isPreFetchConfig, AssociationPreFetchConfig, isPostFetchConfig, AssociationPostFetchConfig, isJoinConfig, AssociationJoinConfig, MappedForeignOperation, } from "./AssociationMapping"; import { SourceAwareOperationResolver, BaseStoreParams } from "./SourceAwareOperationResolver"; import { Paginator, PageContainer } from "./Paginator"; import { MaybePaginatedResolveInfoVisitor, PaginatedResolveInfoVisitor } from "./PaginatedResolveInfoVisitor"; import { SourceAwareResolverContext } from "./SourceAwareResolverContext"; const debug = _debug("greldal:QueryOperationResolver"); /** * @api-category ConfigType */ export interface PrimaryRowMapper { readonly field: MappedField; readonly tablePath: string[]; readonly columnAlias?: string; } /** * @api-category ConfigType */ export interface PreFetchedRowMapper<TResult, TParent> { readonly propertyPath: string[]; readonly result: Promise<TResult[]>; readonly reverseAssociate: (parents: TParent[], results: TResult[]) => void; } /** * @api-category ConfigType */ export interface PostFetchedRowMapper<TResult, TParent> { readonly propertyPath: string[]; readonly run: (parents: TParent[]) => Promise<TResult[]>; readonly reverseAssociate: (parents: TParent[], results: TResult[]) => void; } export type ColumnSelection = { /* Column alias: */ [k: string]: /* Mapped field name: */ string }[]; /** * @api-category ConfigType */ export interface StoreQueryParams<T extends MappedDataSource> extends BaseStoreParams { readonly whereParams: Dict; readonly columns: ColumnSelection; readonly primaryMappers: PrimaryRowMapper[]; readonly secondaryMappers: { readonly preFetched: PreFetchedRowMapper<any, Partial<T["ShallowEntityType"]>>[]; readonly postFetched: PostFetchedRowMapper<any, Partial<T["ShallowEntityType"]>>[]; }; } /** * Implements query operation resolution on a single data source * * @api-category CRUDResolvers */ export class SingleSourceQueryOperationResolver< TCtx extends SourceAwareResolverContext<TMappedOperation, TSrc, TArgs>, TSrc extends MappedDataSource, TMappedOperation extends MappedSingleSourceQueryOperation<TSrc, TArgs>, TArgs extends {}, TResolved > extends SourceAwareOperationResolver<TCtx, TSrc, TArgs, TResolved> { resultRows?: Dict[]; aliasColumnsToTableScope: boolean = true; private paginator?: Paginator; constructor(public resolverContext: TCtx) { super(resolverContext); if (this.operation.paginationConfig) { this.paginator = new Paginator( this.operation.paginationConfig, resolverContext, this.aliasHierarchyVisitor, ); } } @MemoizeGetter get aliasHierarchyVisitor() { const source = this.resolverContext.primaryDataSource; return this.getAliasHierarchyVisitorFor(source); } @MemoizeGetter get storeParams(): StoreQueryParams<TCtx["DataSourceType"]> { const source = this.resolverContext.primaryDataSource; const storeParams = { whereParams: this.resolverContext.primaryDataSource.mapQueryParams( this.resolverContext.operation.deriveWhereParams( this.resolverContext.primaryResolveInfoVisitor.parsedResolveInfo.args as any, ), this.getAliasHierarchyVisitorFor(source), ), queryBuilder: this.createRootQueryBuilder(source), columns: [], primaryMappers: [], secondaryMappers: { preFetched: [], postFetched: [], }, }; debug("storeParams:", storeParams); return storeParams; } async resolve(): Promise<TResolved> { const source = this.resolverContext.primaryDataSource; return this.wrapInTransaction(async () => { this.resolveFields<TSrc>( [], this.getAliasHierarchyVisitorFor(source), source, this.resolverContext.primaryResolveInfoVisitor, ); const resultRows = await this.runQuery(); if (this.paginator) { this.resultRows = resultRows.slice(0, this.paginator.pageSize); } else { this.resultRows = resultRows; } debug("Fetched rows:", this.resultRows); const entities: TSrc["EntityType"][] = await source.mapRowsToEntities( this.resultRows!, this.storeParams as any, ); if (this.paginator) { const pageInfoResolveInfo = this.paginator.parsedPageInfoResolveInfo; let totalCount: number; if (pageInfoResolveInfo && pageInfoResolveInfo.totalCount) { totalCount = await this.paginator!.getTotalCount(this.getQueryBuilder()); } const pageContainer: PageContainer<TSrc["EntityType"]> = { page: { pageInfo: { prevCursor: () => this.paginator!.getPrevCursor(resultRows), nextCursor: () => this.paginator!.getNextCursor(resultRows), totalCount: totalCount!, }, entities, }, }; return pageContainer as any; } return entities as any; }); } getQueryBuilder() { return this.resolverContext.operation.interceptQueryByArgs( this.storeParams.queryBuilder.where(this.storeParams.whereParams), this.resolverContext.args, ); } async runQuery() { let queryBuilder = this.getQueryBuilder().clone(); if (this.paginator) { this.resolverContext.primaryPaginatedResolveInfoVisitor!.parsedResolveInfo; queryBuilder = this.paginator.interceptQuery(queryBuilder, this.storeParams.columns); } if (this.resolverContext.operation.singular) { const { primaryColumnNames } = this.resolverContext.primaryDataSource; const { alias } = this.aliasHierarchyVisitor; if (primaryColumnNames.length > 0) { const primaryColsSatisfied = !some( primaryColumnNames, colName => !has(this.storeParams.whereParams, `${alias}.${colName}`), ); if (!primaryColsSatisfied) { const pkQueryBuilder = queryBuilder .clone() .columns(primaryColumnNames.map(c => `${alias}.${c}`)) .limit(1); const pkVals: Dict[] = await pkQueryBuilder; const whereParams = transform( pkVals[0], (result: Dict, primaryColVal, primaryColName) => { result[`${alias}.${primaryColName}`] = primaryColVal; }, {}, ); queryBuilder.clearWhere().where(whereParams); } } } const rows = await queryBuilder.columns(this.storeParams.columns); return rows; } resolveFields<TCurSrc extends MappedDataSource>( tablePath: string[] = [], aliasHierarchyVisitor: AliasHierarchyVisitor, dataSource: TCurSrc, resolveInfoVisitor: ResolveInfoVisitor<TCurSrc>, typeName = this.resolverContext.operation.shallow ? dataSource.shallowMappedName : dataSource.mappedName, ignoreMissing = false, ) { for (const { fieldName } of resolveInfoVisitor!.iterateFieldsOf(typeName)) { this.resolveFieldName( fieldName, tablePath, aliasHierarchyVisitor, dataSource, resolveInfoVisitor, ignoreMissing, ); } } private resolveFieldName< TCurSrcMapping extends DataSourceMapping, TCurSrc extends MappedDataSource<TCurSrcMapping> >( fieldName: keyof TCurSrc["fields"] | keyof TCurSrc["associations"], tablePath: string[], aliasHierarchyVisitor: AliasHierarchyVisitor, dataSource: MappedDataSource<TCurSrcMapping>, resolveInfoVisitor: ResolveInfoVisitor<TCurSrc>, ignoreMissing = false, ) { const fieldName_: any = fieldName; const field: MappedField<MappedDataSource<TCurSrcMapping>> = (dataSource.fields as Dict< MappedField<MappedDataSource<TCurSrcMapping>> >)[fieldName_]; if (field) { debug("Identified field corresponding to fieldName %s -> %O", fieldName, field); this.deriveColumnsForField(field, tablePath, aliasHierarchyVisitor, this.aliasColumnsToTableScope); return; } if (!this.resolverContext.operation.shallow) { const association = (dataSource.associations as Dict<MappedAssociation<MappedDataSource<TCurSrcMapping>>>)[ fieldName_ ]; if (association) { debug("Identified candidate associations corresponding to fieldName %s -> %O", fieldName, association); const fetchConfig = association.getFetchConfig<TCtx, TSrc, TMappedOperation, TArgs>(this); if (!fetchConfig) { throw new Error("Unable to resolve association through any of the specified fetch configurations"); } this.resolveAssociation(association, fetchConfig, tablePath, aliasHierarchyVisitor, resolveInfoVisitor); return; } } if (ignoreMissing) return; throw new Error(`Unable to resovle fieldName ${fieldName} in dataSource: ${dataSource.mappedName}`); } private resolveAssociation<TCurSrc extends MappedDataSource>( association: MappedAssociation<TCurSrc>, fetchConfig: AssociationFetchConfig<TCurSrc, any>, tablePath: string[], aliasHierarchyVisitor: AliasHierarchyVisitor, resolveInfoVisitor: ResolveInfoVisitor<TCurSrc>, ) { const associationVisitor = resolveInfoVisitor.visitRelation(association); if (isPreFetchConfig(fetchConfig)) { this.storeParams.secondaryMappers.preFetched.push({ propertyPath: tablePath, reverseAssociate: association.associateResultsWithParents( fetchConfig as AssociationPreFetchConfig<any, any>, ), result: this.invokeSideLoader( () => association.preFetch(fetchConfig as AssociationPreFetchConfig<any, any>, this), associationVisitor, ), }); } else if (isPostFetchConfig(fetchConfig)) { this.storeParams.secondaryMappers.postFetched.push({ propertyPath: tablePath, reverseAssociate: association.associateResultsWithParents( fetchConfig as AssociationPostFetchConfig<any, any>, ), run: async (parents: PartialDeep<TCurSrc["EntityType"]>[]) => this.invokeSideLoader( () => association.postFetch(fetchConfig as AssociationPostFetchConfig<any, any>, this, parents), associationVisitor, ), }); } else if (isJoinConfig(fetchConfig)) { if (associationVisitor instanceof PaginatedResolveInfoVisitor) { throw new Error("Pagination is current not supported with joined associations"); } this.deriveJoinedQuery(association, fetchConfig, tablePath, aliasHierarchyVisitor, associationVisitor); } else { throw new Error(`Every specified association should be resolvable through a preFetch, postFetch or join`); } } private deriveJoinedQuery<TCurSrc extends MappedDataSource>( association: MappedAssociation<TCurSrc>, fetchConfig: AssociationJoinConfig<TCurSrc, any>, tablePath: string[], aliasHierarchyVisitor: AliasHierarchyVisitor, resolveInfoVisitor: ResolveInfoVisitor<TCurSrc>, ) { const relDataSource: MappedDataSource = association.target; const nextAliasHierarchyVisitor = association.join( fetchConfig, this.storeParams.queryBuilder, aliasHierarchyVisitor, ); this.resolverContext.primaryDataSource.mapQueryParams( this.resolverContext.operation.deriveWhereParams( resolveInfoVisitor.parsedResolveInfo.args as any, association, ), nextAliasHierarchyVisitor, ); this.resolveFields( tablePath.concat(association.mappedName), nextAliasHierarchyVisitor, relDataSource, resolveInfoVisitor, ); } private invokeSideLoader<TCurSrc extends MappedDataSource>( sideLoad: <TArgs extends {}>() => MappedForeignOperation<MappedSingleSourceOperation<TCurSrc, TArgs>>, associationVisitor: MaybePaginatedResolveInfoVisitor<TCurSrc>, ) { const { operation: query, args } = sideLoad(); return query.resolve( this.resolverContext.source, args, this.resolverContext.context, this.resolverContext.resolveInfoRoot, associationVisitor, resolver => { const r = resolver as SourceAwareOperationResolver<any, any, any, any>; r.isDelegated = true; r.activeTransaction = this.activeTransaction; return r; }, ); } associateResultsWithParents<TCurSrc extends MappedDataSource>(association: MappedAssociation<TCurSrc>) { if (!association.associatorColumns) { throw new Error( "Either association.associatorColumns or association.associateResultsWithParents is mandatory", ); } return (parents: Dict[], results: Dict[]) => { debug("associating results with parents -- parents: %O, results: %O", parents, results); const { inSource, inRelated } = association.associatorColumns!; const parentsIndex = indexBy(parents, inSource); results.forEach(result => { const pkey = result[inRelated] as any; if (!pkey) return; const parent = parentsIndex[pkey] as any; if (!parent) return; if (association.singular) { parent[association.mappedName] = result; } else { parent[association.mappedName] = parent[association.mappedName] || []; parent[association.mappedName].push(result); } }); }; } private deriveColumnsForField( field: MappedField, tablePath: string[], aliasHierarchyVisitor: AliasHierarchyVisitor, aliasColumnsToTableScope = true, ): any { field.getColumnMappingList(aliasHierarchyVisitor, aliasColumnsToTableScope).forEach(colMapping => { this.storeParams.columns.push({ [colMapping.columnAlias]: colMapping.columnRef, }); this.storeParams.primaryMappers.push({ field: colMapping.field, tablePath, columnAlias: colMapping.columnAlias, }); }); if (field.isComputed) { this.storeParams.primaryMappers.push({ field, tablePath, }); } } get primaryFieldMappers() { const { primaryFields } = this.resolverContext.operation.rootSource; if (primaryFields.length === 0) { throw new Error("This operation preset requires one/more primary key fields but none were found"); } const primaryMappers = uniqBy( this.storeParams.primaryMappers.filter(pm => pm.field.isPrimary), pm => pm.field.mappedName, ); if (primaryMappers.length !== primaryFields.length) { throw new Error( `Not all primary keys included in query. Found ${primaryMappers.length} instead of ${primaryFields.length}`, ); } return primaryMappers; } }
the_stack
import * as csstips from 'csstips'; // tslint:disable-next-line:enforce-name-casing import * as React from 'react'; import {stylesheet} from 'typestyle'; import BreadCrumb from '@material-ui/core/Breadcrumbs'; import InputLabel from '@material-ui/core/InputLabel'; import MenuItem from '@material-ui/core/MenuItem'; import Select from '@material-ui/core/Select'; import Typography from '@material-ui/core/Typography'; import {BreadCrumbItem} from './bread_crumb_item'; import {DataModelService, DataModel} from '../service/data_model_service'; import {FieldMetadataViewer} from './field_meta_data_viewer'; import {SearchBar} from './search_bar'; import {SubEntitiesViewer} from './sub_entities_viewer'; import {TopEntitiesViewer} from './top_entities_viewer'; import {SubEntityMeta, TopEntityMeta, SearchResult} from './types'; /** * Properites for the DataModelViewer component. */ interface Props { /** * The service that wrappers API requests to the extension's backend handler. */ dataModelService: DataModelService; /** * A flag indicating whether the components is visible or not. */ isVisible: boolean; } /** * The state maintained by the DataModelViewer component. */ interface State { /** * The JSON path representing the field selected for inspection which will * result in a tool tip being displayed with additional information. */ inspectPath: string; /** * The search result selected from the drop down list of candidate search * results. */ selectedSearchResult: SearchResult; /** * The path of the field that has been selected to drill down into. */ selectedPath: string[]; /** * The list of available data models. */ dataModels: DataModel[]; /** * The currently active data model. */ activeDataModel: DataModel; /** * The ID of the active data model. */ activeDataModelId: string; /** * Flag indicating that the data models have finished loading. */ hasLoaded: boolean; /** * A cache of the top level entities in the active data model. */ topEntities: TopEntityMeta[]; } /** * The JSON schema definition of an entity. */ interface ResourceDefinition { /** * The name of the resource. */ name: string; /** * The JSON schema definition of the resource. */ // tslint:disable-next-line:no-any definition: any; } /** * Convenience class for a subset of the properties of a field. */ interface FieldProperties { /** * The field type. */ type: string; /** * Flag indicating if the field is clickable. */ clickable: boolean; } const localStyles = stylesheet({ header: { borderBottom: 'var(--jp-border-width) solid var(--jp-border-color2)', fontWeight: 600, fontSize: 'var(--jp-ui-font-size0, 11px)', letterSpacing: '1px', margin: 0, padding: '8px 12px', textTransform: 'uppercase', }, panel: { backgroundColor: 'white', height: '100%', width: '100%', ...csstips.vertical, }, select: { margin: 'auto 16px', }, viewer: { width: '100%', backgroundColor: 'white', height: 'calc(100% - 50px)', overflowY: 'auto' as 'auto', }, tree: { height: 110, flexGrow: 1, maxWidth: 400, overflowY: 'scroll', ...csstips.flex, }, table: { minWidth: 150, }, button: { height: '100%', }, selectLabelRoot: { color: 'black', fontSize: '1.3rem', fontWeight: 500, }, tableName: { color: 'black', fontSize: '0.9rem', fontWeight: 600, padding: '15px 2px 5px 2px', margin: 'auto 16px', }, selectRoot: { minWidth: '10rem', }, }); const HEADER_TITLE = 'Data Model Browser Extension'; /** * Component for visualizing a data model schema definition. */ export class DataModelViewer extends React.Component<Props, State> { state: State = { inspectPath: '', selectedSearchResult: null, selectedPath: ['FHIR'], dataModels: [], activeDataModel: null, activeDataModelId: 'FHIR', hasLoaded: false, topEntities: [], }; constructor(props: Props) { super(props); } async componentDidMount() { try { this.getDataModels(); } catch (err) { console.warn('Unexpected error', err); } } /** * Callback invoked when a BreadCrumbItem is clicked. * * @param path - the JSON path, spread across a list, from the root of the * resource to the selected item. */ onListItemClicked = (path: string[]) => { this.setState({ selectedPath: path, }); }; /** * Callback invoked when either a TopEntity or SubEntity is selected for * tool tip inspection. * * @param path - the JSON path from the root of the resource to the selected * item. */ onEntityInspected = (path: string) => { this.setState({ inspectPath: path, }); }; /** * Callback invoked when either a TopEntity or SubEntity is selectd for * further drill down. * * @param name - the name of the entity that was selected. */ onEntitySelected = (name: string) => { this.setState({ selectedPath: this.state.selectedPath.concat([name]), inspectPath: '', }); }; render() { if (!this.state.hasLoaded) { return ( <div className={localStyles.panel}> <header className={localStyles.header}> {HEADER_TITLE} </header> <Typography color="textPrimary">Loading...</Typography> </div> ); } if (this.state.selectedPath.length === 0) { return ( <div className={localStyles.panel}> <header className={localStyles.header}> {HEADER_TITLE} </header> <Typography color="textPrimary">Missing data model schema</Typography> </div> ); } else if (this.state.selectedPath.length === 1) { // No resources have been selected so render the resource list. return ( <div className={localStyles.panel}> <header className={localStyles.header}> {HEADER_TITLE} </header> <div className={localStyles.tableName}> Select version </div> <InputLabel></InputLabel> <Select value={this.state.activeDataModelId} className={localStyles.select} disabled > <MenuItem value="FHIR">{'FHIR-stu3'}</MenuItem> </Select> <div className={localStyles.tableName}> Search tables and fields </div> <SearchBar dataModel={this.state.activeDataModel} onSearchResultSelected={this.onSearchResultSelected} /> <div className={localStyles.tableName}> Resource name </div> <div className={localStyles.viewer}> <TopEntitiesViewer topEntities={this.state.topEntities} onInspect={this.onEntityInspected} onSelect={this.onEntitySelected} selected={this.state.inspectPath} /> </div> </div> ); } const previousPaths = this.state.selectedPath.slice( 0, this.state.selectedPath.length - 1 ); const activePath = this.state.selectedPath[ this.state.selectedPath.length - 1 ]; let pathOffset = 0; return ( <div className={localStyles.panel}> <div className="bread-crumb-wrapper"> <BreadCrumb maxItems={3} aria-label="breadcrumb"> {previousPaths.map(previousPath => { return ( <BreadCrumbItem key={previousPath} path={this.state.selectedPath.slice(0, ++pathOffset)} label={previousPath} onClick={this.onListItemClicked} /> ); })} <Typography color="textPrimary">{activePath}</Typography> </BreadCrumb> </div> <div className={localStyles.tableName}> Select or hover over a resource for more details </div> <SearchBar dataModel={this.state.activeDataModel} onSearchResultSelected={this.onSearchResultSelected} /> <div className={localStyles.viewer}> {this.getSelectionDetails( this.state.selectedPath.slice(1), this.state.activeDataModel.schema )} </div> </div> ); } private async getDataModels() { try { const dm = await this.props.dataModelService.listModels(); if (dm.dataModels.length === 0) { console.warn('Error retrived empty data models list'); throw new Error('Error retrived empty data models list'); } this.setState({activeDataModel: dm.dataModels[0]}); const topEntities: TopEntityMeta[] = Object.keys( this.state.activeDataModel.schema.discriminator.mapping ) .sort() .map(key => { return this.extractTopEntityMeta(key); }); this.setState({topEntities}); this.setState({hasLoaded: true, dataModels: dm.dataModels}); } catch (err) { console.warn('Error retrieving data models', err); } } private onSearchResultSelected = (path: string) => { if (!path || path.length === 0) { this.setState({selectedSearchResult: null}); this.setState({selectedPath: [this.state.activeDataModelId]}); } else { const splits = [this.state.activeDataModelId].concat(path.split(' > ')); this.setState({selectedPath: splits}); const searchResult: SearchResult = { path, resource: splits[0], field: '', }; if (splits.length > 1) { searchResult.field = splits[1]; } this.setState({selectedSearchResult: searchResult}); } }; private extractTopEntityMeta = (name: string): TopEntityMeta => { const description = this.state.activeDataModel.schema.definitions[name] .description; return {name, description}; }; // tslint:disable-next-line:no-any (data from JSON schema) private extractReferenceType = (fieldDetails: any): string => { return fieldDetails.$ref.slice(fieldDetails.$ref.lastIndexOf('/') + 1); }; // tslint:disable-next-line:no-any (data from JSON schema) private resolveFieldProperties = (field: string, fieldDetails: any): FieldProperties => { const fieldProp: FieldProperties = {type: '', clickable: false}; if ('type' in fieldDetails) { if ('items' in fieldDetails && '$ref' in fieldDetails.items) { fieldProp.type = this.extractReferenceType(fieldDetails.items); } else { fieldProp.type = fieldDetails.type; } fieldProp.clickable = true; } else if ('const' in fieldDetails) { fieldProp.type = 'constant: ' + fieldDetails.const; fieldProp.clickable = false; } else if ('enum' in fieldDetails) { fieldProp.type = 'enum: ' + fieldDetails.enum.join(', '); fieldProp.clickable = false; } else if ('$ref' in fieldDetails) { fieldProp.type = this.extractReferenceType(fieldDetails); fieldProp.clickable = true; } return fieldProp; }; // tslint:disable-next-line:no-any (data from JSON schema) private getSubEntityDetails = (name: string, schema: any): SubEntityMeta[] => { const subEntities: SubEntityMeta[] = []; const definition = schema.definitions[name]; if (!!definition && 'properties' in definition) { for (const [field] of Object.entries(definition.properties).sort()) { if (!field.startsWith('_')) { let isRequired = false; if ('required' in definition) { isRequired = definition.required.includes(field); } const fieldDetails = definition.properties[field]; const fieldProperty = this.resolveFieldProperties(field, fieldDetails); const subEntity: SubEntityMeta = { name: field, required: isRequired, type: fieldProperty.type, description: fieldDetails.description, schema: fieldDetails, clickable: fieldProperty.clickable, }; subEntities.push(subEntity); } } } return subEntities; }; private getSelectionDetails = ( pathParts: string[], // tslint:disable-next-line:no-any (data from JSON schema) schema: any ): React.ReactNode => { if (pathParts.length <= 1) { const subEntities = this.getSubEntityDetails(pathParts[0], schema); return ( <SubEntitiesViewer subEntities={subEntities} onInspect={this.onEntityInspected} onSelect={this.onEntitySelected} selected={this.state.inspectPath} /> ); } let parent: ResourceDefinition = { name: pathParts[0], definition: schema.definitions[pathParts[0]], }; let i = 1; while (parent != null) { if (i >= pathParts.length) { break; } const field = pathParts[i++]; if ( !('properties' in parent.definition) || !(field in parent.definition.properties) ) { break; } const fieldDetails = parent.definition.properties[field]; parent = null; if (!!fieldDetails) { const fieldProperty = this.resolveFieldProperties(field, fieldDetails); if (fieldProperty.type in schema.definitions) { parent = { name: fieldProperty.type, definition: schema.definitions[fieldProperty.type], }; } } } if (!parent) { parent = { name: pathParts[i - 1], definition: schema.definitions[pathParts[i - 1]], }; } if ('properties' in parent.definition) { // either a complex type or a primitive base type. const subEntities: SubEntityMeta[] = this.getSubEntityDetails( parent.name, schema ); return ( <SubEntitiesViewer subEntities={subEntities} onInspect={this.onEntityInspected} onSelect={this.onEntitySelected} selected={this.state.inspectPath} /> ); } else { const fieldProperty = this.resolveFieldProperties(parent.name, parent.definition); const subEntity: SubEntityMeta = { name: 'pattern' in parent.definition ? parent.definition.pattern : parent.name, required: false, type: fieldProperty.type, description: parent.definition.description, clickable: fieldProperty.clickable, }; return <FieldMetadataViewer fieldMetadata={subEntity} />; } }; }
the_stack
import { GlobalProps } from 'ojs/ojvcomponent'; import { ComponentChildren } from 'preact'; import { baseComponent, baseComponentEventMap, baseComponentSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..'; export interface ojButton<SP extends ojButtonSettableProperties = ojButtonSettableProperties> extends baseComponent<SP> { chroming: 'solid' | 'outlined' | 'borderless' | 'callToAction' | 'danger' | 'full' | 'half'; disabled: boolean; display: 'all' | 'icons'; label: string | null; addEventListener<T extends keyof ojButtonEventMap<SP>>(type: T, listener: (this: HTMLElement, ev: ojButtonEventMap<SP>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojButtonSettableProperties>(property: T): ojButton<SP>[T]; getProperty(property: string): any; setProperty<T extends keyof ojButtonSettableProperties>(property: T, value: ojButtonSettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojButtonSettableProperties>): void; setProperties(properties: ojButtonSettablePropertiesLenient): void; } export namespace ojButton { interface ojAction extends CustomEvent<{ [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type chromingChanged<SP extends ojButtonSettableProperties = ojButtonSettableProperties> = JetElementCustomEvent<ojButton<SP>["chroming"]>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<SP extends ojButtonSettableProperties = ojButtonSettableProperties> = JetElementCustomEvent<ojButton<SP>["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayChanged<SP extends ojButtonSettableProperties = ojButtonSettableProperties> = JetElementCustomEvent<ojButton<SP>["display"]>; // tslint:disable-next-line interface-over-type-literal type labelChanged<SP extends ojButtonSettableProperties = ojButtonSettableProperties> = JetElementCustomEvent<ojButton<SP>["label"]>; } export interface ojButtonEventMap<SP extends ojButtonSettableProperties = ojButtonSettableProperties> extends baseComponentEventMap<SP> { 'ojAction': ojButton.ojAction; 'chromingChanged': JetElementCustomEvent<ojButton<SP>["chroming"]>; 'disabledChanged': JetElementCustomEvent<ojButton<SP>["disabled"]>; 'displayChanged': JetElementCustomEvent<ojButton<SP>["display"]>; 'labelChanged': JetElementCustomEvent<ojButton<SP>["label"]>; } export interface ojButtonSettableProperties extends baseComponentSettableProperties { chroming: 'solid' | 'outlined' | 'borderless' | 'callToAction' | 'danger' | 'full' | 'half'; disabled: boolean; display: 'all' | 'icons'; label: string | null; } export interface ojButtonSettablePropertiesLenient extends Partial<ojButtonSettableProperties> { [key: string]: any; } export interface ojButtonset<SP extends ojButtonsetSettableProperties = ojButtonsetSettableProperties> extends baseComponent<SP> { addEventListener<T extends keyof ojButtonsetEventMap<SP>>(type: T, listener: (this: HTMLElement, ev: ojButtonsetEventMap<SP>[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojButtonsetSettableProperties>(property: T): ojButtonset<SP>[T]; getProperty(property: string): any; setProperty<T extends keyof ojButtonsetSettableProperties>(property: T, value: ojButtonsetSettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojButtonsetSettableProperties>): void; setProperties(properties: ojButtonsetSettablePropertiesLenient): void; } // These interfaces are empty but required to keep the event chain intact. Avoid lint-rule // tslint:disable-next-line no-empty-interface export interface ojButtonsetEventMap<SP extends ojButtonsetSettableProperties = ojButtonsetSettableProperties> extends baseComponentEventMap<SP> { } // These interfaces are empty but required to keep the component chain intact. Avoid lint-rule // tslint:disable-next-line no-empty-interface export interface ojButtonsetSettableProperties extends baseComponentSettableProperties { } export interface ojButtonsetSettablePropertiesLenient extends Partial<ojButtonsetSettableProperties> { [key: string]: any; } export interface ojButtonsetMany extends ojButtonset<ojButtonsetManySettableProperties> { chroming: 'solid' | 'outlined' | 'borderless' | 'full' | 'half'; describedBy: string | null; disabled: boolean; display: 'all' | 'icons'; focusManagement: 'oneTabstop' | 'none'; labelledBy: string | null; value: any[] | null; addEventListener<T extends keyof ojButtonsetManyEventMap>(type: T, listener: (this: HTMLElement, ev: ojButtonsetManyEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojButtonsetManySettableProperties>(property: T): ojButtonsetMany[T]; getProperty(property: string): any; setProperty<T extends keyof ojButtonsetManySettableProperties>(property: T, value: ojButtonsetManySettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojButtonsetManySettableProperties>): void; setProperties(properties: ojButtonsetManySettablePropertiesLenient): void; } export namespace ojButtonsetMany { // tslint:disable-next-line interface-over-type-literal type chromingChanged = JetElementCustomEvent<ojButtonsetMany["chroming"]>; // tslint:disable-next-line interface-over-type-literal type describedByChanged = JetElementCustomEvent<ojButtonsetMany["describedBy"]>; // tslint:disable-next-line interface-over-type-literal type disabledChanged = JetElementCustomEvent<ojButtonsetMany["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayChanged = JetElementCustomEvent<ojButtonsetMany["display"]>; // tslint:disable-next-line interface-over-type-literal type focusManagementChanged = JetElementCustomEvent<ojButtonsetMany["focusManagement"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojButtonsetMany["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojButtonsetMany["value"]>; } export interface ojButtonsetManyEventMap extends ojButtonsetEventMap<ojButtonsetManySettableProperties> { 'chromingChanged': JetElementCustomEvent<ojButtonsetMany["chroming"]>; 'describedByChanged': JetElementCustomEvent<ojButtonsetMany["describedBy"]>; 'disabledChanged': JetElementCustomEvent<ojButtonsetMany["disabled"]>; 'displayChanged': JetElementCustomEvent<ojButtonsetMany["display"]>; 'focusManagementChanged': JetElementCustomEvent<ojButtonsetMany["focusManagement"]>; 'labelledByChanged': JetElementCustomEvent<ojButtonsetMany["labelledBy"]>; 'valueChanged': JetElementCustomEvent<ojButtonsetMany["value"]>; } export interface ojButtonsetManySettableProperties extends ojButtonsetSettableProperties { chroming: 'solid' | 'outlined' | 'borderless' | 'full' | 'half'; describedBy: string | null; disabled: boolean; display: 'all' | 'icons'; focusManagement: 'oneTabstop' | 'none'; labelledBy: string | null; value: any[] | null; } export interface ojButtonsetManySettablePropertiesLenient extends Partial<ojButtonsetManySettableProperties> { [key: string]: any; } export interface ojButtonsetOne extends ojButtonset<ojButtonsetOneSettableProperties> { chroming: 'solid' | 'outlined' | 'borderless' | 'full' | 'half'; describedBy: string | null; disabled: boolean; display: 'all' | 'icons'; focusManagement: 'oneTabstop' | 'none'; labelledBy: string | null; value: any; addEventListener<T extends keyof ojButtonsetOneEventMap>(type: T, listener: (this: HTMLElement, ev: ojButtonsetOneEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojButtonsetOneSettableProperties>(property: T): ojButtonsetOne[T]; getProperty(property: string): any; setProperty<T extends keyof ojButtonsetOneSettableProperties>(property: T, value: ojButtonsetOneSettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojButtonsetOneSettableProperties>): void; setProperties(properties: ojButtonsetOneSettablePropertiesLenient): void; } export namespace ojButtonsetOne { // tslint:disable-next-line interface-over-type-literal type chromingChanged = JetElementCustomEvent<ojButtonsetOne["chroming"]>; // tslint:disable-next-line interface-over-type-literal type describedByChanged = JetElementCustomEvent<ojButtonsetOne["describedBy"]>; // tslint:disable-next-line interface-over-type-literal type disabledChanged = JetElementCustomEvent<ojButtonsetOne["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayChanged = JetElementCustomEvent<ojButtonsetOne["display"]>; // tslint:disable-next-line interface-over-type-literal type focusManagementChanged = JetElementCustomEvent<ojButtonsetOne["focusManagement"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojButtonsetOne["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojButtonsetOne["value"]>; } export interface ojButtonsetOneEventMap extends ojButtonsetEventMap<ojButtonsetOneSettableProperties> { 'chromingChanged': JetElementCustomEvent<ojButtonsetOne["chroming"]>; 'describedByChanged': JetElementCustomEvent<ojButtonsetOne["describedBy"]>; 'disabledChanged': JetElementCustomEvent<ojButtonsetOne["disabled"]>; 'displayChanged': JetElementCustomEvent<ojButtonsetOne["display"]>; 'focusManagementChanged': JetElementCustomEvent<ojButtonsetOne["focusManagement"]>; 'labelledByChanged': JetElementCustomEvent<ojButtonsetOne["labelledBy"]>; 'valueChanged': JetElementCustomEvent<ojButtonsetOne["value"]>; } export interface ojButtonsetOneSettableProperties extends ojButtonsetSettableProperties { chroming: 'solid' | 'outlined' | 'borderless' | 'full' | 'half'; describedBy: string | null; disabled: boolean; display: 'all' | 'icons'; focusManagement: 'oneTabstop' | 'none'; labelledBy: string | null; value: any; } export interface ojButtonsetOneSettablePropertiesLenient extends Partial<ojButtonsetOneSettableProperties> { [key: string]: any; } export interface ojMenuButton extends ojButton<ojMenuButtonSettableProperties> { chroming: 'solid' | 'outlined' | 'borderless' | 'full' | 'half'; disabled: boolean; display: 'all' | 'icons'; addEventListener<T extends keyof ojMenuButtonEventMap>(type: T, listener: (this: HTMLElement, ev: ojMenuButtonEventMap[T]) => any, options?: (boolean | AddEventListenerOptions)): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: (boolean | AddEventListenerOptions)): void; getProperty<T extends keyof ojMenuButtonSettableProperties>(property: T): ojMenuButton[T]; getProperty(property: string): any; setProperty<T extends keyof ojMenuButtonSettableProperties>(property: T, value: ojMenuButtonSettableProperties[T]): void; setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojMenuButtonSettableProperties>): void; setProperties(properties: ojMenuButtonSettablePropertiesLenient): void; } export namespace ojMenuButton { interface ojAction extends CustomEvent<{ [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type chromingChanged = JetElementCustomEvent<ojMenuButton["chroming"]>; // tslint:disable-next-line interface-over-type-literal type disabledChanged = JetElementCustomEvent<ojMenuButton["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayChanged = JetElementCustomEvent<ojMenuButton["display"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type labelChanged = ojButton.labelChanged<ojMenuButtonSettableProperties>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ojMenuButtonEventMap extends ojButtonEventMap<ojMenuButtonSettableProperties> { 'ojAction': ojMenuButton.ojAction; 'chromingChanged': JetElementCustomEvent<ojMenuButton["chroming"]>; 'disabledChanged': JetElementCustomEvent<ojMenuButton["disabled"]>; 'displayChanged': JetElementCustomEvent<ojMenuButton["display"]>; 'labelChanged': JetElementCustomEvent<ojMenuButton["label"]>; } export interface ojMenuButtonSettableProperties extends ojButtonSettableProperties { chroming: 'solid' | 'outlined' | 'borderless' | 'full' | 'half'; disabled: boolean; display: 'all' | 'icons'; } export interface ojMenuButtonSettablePropertiesLenient extends Partial<ojMenuButtonSettableProperties> { [key: string]: any; } export type ButtonElement<SP extends ojButtonSettableProperties = ojButtonSettableProperties> = ojButton<SP>; export type ButtonsetElement<SP extends ojButtonsetSettableProperties = ojButtonsetSettableProperties> = ojButtonset<SP>; export type ButtonsetManyElement = ojButtonsetMany; export type ButtonsetOneElement = ojButtonsetOne; export type MenuButtonElement = ojMenuButton; export namespace ButtonElement { interface ojAction extends CustomEvent<{ [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type chromingChanged<SP extends ojButtonSettableProperties = ojButtonSettableProperties> = JetElementCustomEvent<ojButton<SP>["chroming"]>; // tslint:disable-next-line interface-over-type-literal type disabledChanged<SP extends ojButtonSettableProperties = ojButtonSettableProperties> = JetElementCustomEvent<ojButton<SP>["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayChanged<SP extends ojButtonSettableProperties = ojButtonSettableProperties> = JetElementCustomEvent<ojButton<SP>["display"]>; // tslint:disable-next-line interface-over-type-literal type labelChanged<SP extends ojButtonSettableProperties = ojButtonSettableProperties> = JetElementCustomEvent<ojButton<SP>["label"]>; } export namespace ButtonsetManyElement { // tslint:disable-next-line interface-over-type-literal type chromingChanged = JetElementCustomEvent<ojButtonsetMany["chroming"]>; // tslint:disable-next-line interface-over-type-literal type describedByChanged = JetElementCustomEvent<ojButtonsetMany["describedBy"]>; // tslint:disable-next-line interface-over-type-literal type disabledChanged = JetElementCustomEvent<ojButtonsetMany["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayChanged = JetElementCustomEvent<ojButtonsetMany["display"]>; // tslint:disable-next-line interface-over-type-literal type focusManagementChanged = JetElementCustomEvent<ojButtonsetMany["focusManagement"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojButtonsetMany["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojButtonsetMany["value"]>; } export namespace ButtonsetOneElement { // tslint:disable-next-line interface-over-type-literal type chromingChanged = JetElementCustomEvent<ojButtonsetOne["chroming"]>; // tslint:disable-next-line interface-over-type-literal type describedByChanged = JetElementCustomEvent<ojButtonsetOne["describedBy"]>; // tslint:disable-next-line interface-over-type-literal type disabledChanged = JetElementCustomEvent<ojButtonsetOne["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayChanged = JetElementCustomEvent<ojButtonsetOne["display"]>; // tslint:disable-next-line interface-over-type-literal type focusManagementChanged = JetElementCustomEvent<ojButtonsetOne["focusManagement"]>; // tslint:disable-next-line interface-over-type-literal type labelledByChanged = JetElementCustomEvent<ojButtonsetOne["labelledBy"]>; // tslint:disable-next-line interface-over-type-literal type valueChanged = JetElementCustomEvent<ojButtonsetOne["value"]>; } export namespace MenuButtonElement { interface ojAction extends CustomEvent<{ [propName: string]: any; }> { } // tslint:disable-next-line interface-over-type-literal type chromingChanged = JetElementCustomEvent<ojMenuButton["chroming"]>; // tslint:disable-next-line interface-over-type-literal type disabledChanged = JetElementCustomEvent<ojMenuButton["disabled"]>; // tslint:disable-next-line interface-over-type-literal type displayChanged = JetElementCustomEvent<ojMenuButton["display"]>; //------------------------------------------------------------ // Start: generated events for inherited properties //------------------------------------------------------------ // tslint:disable-next-line interface-over-type-literal type labelChanged = ojButton.labelChanged<ojMenuButtonSettableProperties>; //------------------------------------------------------------ // End: generated events for inherited properties //------------------------------------------------------------ } export interface ButtonIntrinsicProps extends Partial<Readonly<ojButtonSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAction?: (value: ojButtonEventMap<any>['ojAction']) => void; onchromingChanged?: (value: ojButtonEventMap<any>['chromingChanged']) => void; ondisabledChanged?: (value: ojButtonEventMap<any>['disabledChanged']) => void; ondisplayChanged?: (value: ojButtonEventMap<any>['displayChanged']) => void; onlabelChanged?: (value: ojButtonEventMap<any>['labelChanged']) => void; children?: ComponentChildren; } export interface ButtonsetManyIntrinsicProps extends Partial<Readonly<ojButtonsetManySettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onchromingChanged?: (value: ojButtonsetManyEventMap['chromingChanged']) => void; ondescribedByChanged?: (value: ojButtonsetManyEventMap['describedByChanged']) => void; ondisabledChanged?: (value: ojButtonsetManyEventMap['disabledChanged']) => void; ondisplayChanged?: (value: ojButtonsetManyEventMap['displayChanged']) => void; onfocusManagementChanged?: (value: ojButtonsetManyEventMap['focusManagementChanged']) => void; onlabelledByChanged?: (value: ojButtonsetManyEventMap['labelledByChanged']) => void; onvalueChanged?: (value: ojButtonsetManyEventMap['valueChanged']) => void; children?: ComponentChildren; } export interface ButtonsetOneIntrinsicProps extends Partial<Readonly<ojButtonsetOneSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onchromingChanged?: (value: ojButtonsetOneEventMap['chromingChanged']) => void; ondescribedByChanged?: (value: ojButtonsetOneEventMap['describedByChanged']) => void; ondisabledChanged?: (value: ojButtonsetOneEventMap['disabledChanged']) => void; ondisplayChanged?: (value: ojButtonsetOneEventMap['displayChanged']) => void; onfocusManagementChanged?: (value: ojButtonsetOneEventMap['focusManagementChanged']) => void; onlabelledByChanged?: (value: ojButtonsetOneEventMap['labelledByChanged']) => void; onvalueChanged?: (value: ojButtonsetOneEventMap['valueChanged']) => void; children?: ComponentChildren; } export interface MenuButtonIntrinsicProps extends Partial<Readonly<ojMenuButtonSettableProperties>>, GlobalProps, Pick<preact.JSX.HTMLAttributes, 'ref' | 'key'> { onojAction?: (value: ojMenuButtonEventMap['ojAction']) => void; onchromingChanged?: (value: ojMenuButtonEventMap['chromingChanged']) => void; ondisabledChanged?: (value: ojMenuButtonEventMap['disabledChanged']) => void; ondisplayChanged?: (value: ojMenuButtonEventMap['displayChanged']) => void; onlabelChanged?: (value: ojMenuButtonEventMap['labelChanged']) => void; children?: ComponentChildren; } declare global { namespace preact.JSX { interface IntrinsicElements { "oj-button": ButtonIntrinsicProps; "oj-buttonset-many": ButtonsetManyIntrinsicProps; "oj-buttonset-one": ButtonsetOneIntrinsicProps; "oj-menu-button": MenuButtonIntrinsicProps; } } }
the_stack
import * as webidl from "webidl2" import { StringCompiler } from "./stringcompiler"; import * as fs from "fs" import { O_NOCTTY } from "constants"; import { maxHeaderSize } from "http"; export enum BinderMode { WEBIDL_NONE = -1, WEBIDL_LUA = 0, WEBIDL_CPP = 1, } export class SemanticError extends Error { } export enum ETypeConversion { NONE = 0, CPP_TO_LUA = 1, LUA_TO_CPP = 2, } export class WebIDLBinder { luaC = new StringCompiler(); cppC = new StringCompiler(); outBufLua: string[] = []; outBufCPP: string[] = []; ast: webidl.IDLRootType[]; classLookup: {[n: string]: boolean} = {}; classPrefixLookup: {[n: string]: string} = {}; arrayTypes: {[type: string]: webidl.IDLTypeDescription} = {}; ptrArrayTypes: {[type: string]: webidl.IDLTypeDescription} = {}; static CTypeRenames: {[type: string]: string} = { ["DOMString"]: "char*", ["boolean"]: "bool", ["byte"]: "char", ["octet"]: "unsigned char", ["unsigned short"]: "unsigned short int", ["long"]: "int", ["any"]: "void*", ["VoidPtr"]: "void*", }; specialTypes: {[type: string]: boolean} = { ["DOMString"]: true, ["boolean"]: true, } constructor(public source: string,public mode: BinderMode,public addYieldStub: boolean) { this.ast = webidl.parse(source); } symbolResolver = (symName: string) => {return `__EXPORTS__.${symName}`;}; setSymbolResolver(fn: (symName: string) => string) { this.symbolResolver = fn; } unquote(arg: string | string[]) { if(Array.isArray(arg)) {arg = arg.join("");} return arg.replace(/^"/,"").replace(/"$/,""); } unquoteEx(arg: webidl.ExtendedAttributes | false) { if(arg === false) {return "";} return this.unquote(arg.rhs.value); } getWithRefs(arg: webidl.Argument,noMask?: boolean) { if(this.hasExtendedAttribute("Ref",arg.extAttrs)) { if(noMask) { return `&${arg.name}`; } else { return `*${arg.name}`; } } else { return arg.name; } } rawMangle(ident: string) { return ident.toString().replace(/\s*/g,"").replace(/[^A-Za-z0-9_]/g,(str) => { return `__x${str.charCodeAt(0).toString(16)}`; }); } mangleFunctionName(node: webidl.OperationMemberType | string,namespace: string,isImpl?: boolean) { let out = "_webidl_lua_"; if(isImpl) {out += "internalimpl_";} out += namespace + "_" if(typeof node === "string") { out += node; out += "_void"; } else { out += node.name; for(let i=0;i < node.arguments.length;i++) { let arg = node.arguments[i]; out += "_"; out += arg.idlType.idlType.toString().replace(/\s+/g,"_"); } } return out; } mangleIndexerName(node: webidl.AttributeMemberType,namespace: string,isNewindex?: boolean) { let out = "_webidl_lua_"; out += namespace + "_" out += node.name; if(isNewindex) { out += "_set"; } else { out += "_get"; } return out; } mangleArrayIndexerName(opName: "get" | "set" | "new" | "delete" | "len",arrTypeName: string) { let out = "_webidl_lua_arr_"; arrTypeName = this.rawMangle(arrTypeName) out += arrTypeName; out += "_" + opName; return out; } mangleArrayIndexerNameEx(opName: "get" | "set" | "new" | "delete",idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[] = []) { return this.mangleArrayIndexerName(opName,this.idlTypeToCType(idlType,extAttrs,true)); } getExtendedAttribute(attribute: string,extAttrs: webidl.ExtendedAttributes[]) { for(let i=0;i < extAttrs.length;i++) { if(extAttrs[i].name === attribute) { return extAttrs[i]; } } return false; } hasExtendedAttribute(attribute: string,extAttrs: webidl.ExtendedAttributes[]) { return this.getExtendedAttribute(attribute,extAttrs) !== false; } idlTypeToCType(idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[],maskRef: boolean,tempVar?: boolean) { let prefixes = ""; let suffixes = ""; if(this.hasExtendedAttribute("Const",extAttrs)) { if(!tempVar) { prefixes += "const "; } } if(this.hasExtendedAttribute("Ref",extAttrs)) { if(!tempVar) { if(maskRef) { suffixes += "*"; } else { suffixes += "&"; } } } else if(this.classLookup[idlType.idlType as string]) { if(!tempVar) { suffixes += "*"; } } let body; if(this.hasExtendedAttribute("Size",extAttrs) && (idlType.idlType == "any")) { body = "size_t" } else if(this.hasExtendedAttribute("ArrayLength",extAttrs) && (idlType.idlType == "any")) { body = "size_t" } else if(this.hasExtendedAttribute("ArrayLengthRef",extAttrs) && (idlType.idlType == "any")) { body = "size_t*" } else if(this.hasExtendedAttribute("Enum",extAttrs) && (idlType.idlType == "any")) { let enAttr = this.getExtendedAttribute("Enum",extAttrs); if(enAttr && enAttr.rhs) { body = this.unquote(enAttr.rhs.value); } else { throw new SemanticError("Enum attribute needs a value (enum name)"); } } else { body = idlType.idlType as string; } if(WebIDLBinder.CTypeRenames[body]) { body = WebIDLBinder.CTypeRenames[body]; } else if(this.classPrefixLookup[body]) { body = this.classPrefixLookup[body] + body; } if(this.hasExtendedAttribute("Array",extAttrs)) { body = `_LuaArray<${body}>*` } else if(this.hasExtendedAttribute("PointerArray",extAttrs)) { body = `_LuaArray<${body}*>*` } return `${prefixes} ${body} ${suffixes}`.replace(/\s+/g," ").trim(); } idlTypeToCTypeLite(idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]) { let body; if(this.hasExtendedAttribute("Size",extAttrs) && (idlType.idlType == "any")) { body = "size_t" } else if(this.hasExtendedAttribute("ArrayLength",extAttrs) && (idlType.idlType == "any")) { body = "size_t" } else if(this.hasExtendedAttribute("ArrayLengthRef",extAttrs) && (idlType.idlType == "any")) { body = "psize_t" } else if(this.hasExtendedAttribute("Enum",extAttrs) && (idlType.idlType == "any")) { let enAttr = this.getExtendedAttribute("Enum",extAttrs); if(enAttr && enAttr.rhs) { body = "enum_" + this.unquote(enAttr.rhs.value); } else { throw new SemanticError("Enum attribute needs a value (enum name)"); } } else { body = idlType.idlType as string; } if(WebIDLBinder.CTypeRenames[body]) { body = WebIDLBinder.CTypeRenames[body]; } else if(this.classPrefixLookup[body]) { body = this.classPrefixLookup[body] + body; } return body; } buildOut() { if(this.mode == BinderMode.WEBIDL_LUA) { this.luaC.writeLn(this.outBufLua,"local __CFUNCS__ = {}") this.luaC.writeLn(this.outBufLua,"__IMPORTS__.webidl_cfuncs = __CFUNCS__") } else if(this.mode == BinderMode.WEBIDL_CPP) { this.cppC.writeLn(this.outBufCPP,`#define __CFUNC(name) \\`); this.cppC.writeLn(this.outBufCPP,` __attribute__((__import_module__("webidl_cfuncs"), __import_name__(#name)))`); this.cppC.writeLn(this.outBufCPP,`#define export __attribute__((visibility( "default" )))`); this.cppC.write(this.outBufCPP,`template <typename T> struct _LuaArray {`); this.cppC.indent(); this.cppC.newLine(this.outBufCPP); this.cppC.writeLn(this.outBufCPP,`public:`); this.cppC.writeLn(this.outBufCPP,`_LuaArray(size_t inLen) : totalLen(inLen), len(inLen) {array = new T[inLen]; knownLen = true;};`); this.cppC.writeLn(this.outBufCPP,`_LuaArray(size_t inLen,T* inArray) : totalLen(inLen), len(inLen) {array = inArray; knownLen = true; isOwner = false;};`); this.cppC.writeLn(this.outBufCPP,`_LuaArray(T* inArray) {array = inArray; isOwner = false;};`); this.cppC.writeLn(this.outBufCPP,`~_LuaArray() {if(isOwner) {delete[] array;}};`); this.cppC.writeLn(this.outBufCPP,`bool isOwner = true;`); this.cppC.writeLn(this.outBufCPP,`bool knownLen = false;`); this.cppC.writeLn(this.outBufCPP,`size_t totalLen = 0;`); this.cppC.writeLn(this.outBufCPP,`size_t len = 0;`); this.cppC.write(this.outBufCPP,`T* array;`); this.cppC.newLine(this.outBufCPP); this.cppC.outdent(this.outBufCPP); this.cppC.writeLn(this.outBufCPP,`};`); } for(let i=0;i < this.ast.length;i++) { let node = this.ast[i]; if((node.type == "interface") || (node.type == "interface mixin")) { this.classLookup[node.name] = true; let prefix = this.getExtendedAttribute("Prefix",node.extAttrs); if(prefix) { this.classPrefixLookup[node.name] = this.unquote(prefix.rhs.value); } if(this.mode == BinderMode.WEBIDL_CPP) { // this.cppC.writeLn(this.outBufCPP,`class ${node.name};`); } } } // record all array types for(let i=0;i < this.ast.length;i++) { let node = this.ast[i]; if((node.type == "interface") || (node.type == "namespace")) { let JsImpl = this.getExtendedAttribute("JSImplementation",node.extAttrs) || this.getExtendedAttribute("LuaImplementation",node.extAttrs); for(let j=0;j < node.members.length;j++) { let member = node.members[j]; if((member.type == "operation") || (member.type == "attribute")) { if(member.type == "operation") { for(let k=member.arguments.length-1;k >= 0;k--) { let arrEA = this.getExtendedAttribute("Array",member.arguments[k].extAttrs); if(arrEA) { this.arrayTypes[this.idlTypeToCTypeLite(member.arguments[k].idlType,member.arguments[k].extAttrs)] = member.arguments[k].idlType; if(this.getExtendedAttribute("ArrayLength",member.extAttrs) && JsImpl) { throw new SemanticError("ArrayLength extended attribute is incompatible with functions implemented in Lua"); } else if(this.getExtendedAttribute("ArrayLengthRef",member.extAttrs) && JsImpl) { throw new SemanticError("ArrayLengthRef extended attribute is incompatible with functions implemented in Lua"); } } else { arrEA = this.getExtendedAttribute("PointerArray",member.arguments[k].extAttrs); if(arrEA) { if(!this.classLookup[member.arguments[k].idlType.idlType as string]) { throw new SemanticError(`PointerArrays are unsupported for non-class types like '${member.arguments[k].idlType.idlType as string}'. Are you sure you defined an interface for this type?`); } this.ptrArrayTypes[this.idlTypeToCTypeLite(member.arguments[k].idlType,member.arguments[k].extAttrs)] = member.arguments[k].idlType; } } } } let arrEARet = this.getExtendedAttribute("Array",member.extAttrs); if(arrEARet) { this.arrayTypes[this.idlTypeToCTypeLite(member.idlType,member.extAttrs)] = member.idlType; if(this.getExtendedAttribute("ArrayLength",member.extAttrs)) { throw new SemanticError("ArrayLength extended attribute is incompatible with return types"); } else if(this.getExtendedAttribute("ArrayLengthRef",member.extAttrs)) { throw new SemanticError("ArrayLengthRef extended attribute is incompatible with return types"); } } else { arrEARet = this.getExtendedAttribute("PointerArray",member.extAttrs); if(arrEARet) { if(!this.classLookup[member.idlType.idlType as string]) { throw new SemanticError(`PointerArrays are unsupported for non-class types like '${member.idlType.idlType}'. Are you sure you defined an interface for this type?`); } this.ptrArrayTypes[this.idlTypeToCTypeLite(member.idlType,member.extAttrs)] = member.idlType; } } } } } } // separate out "optional" args into different functions for(let i=0;i < this.ast.length;i++) { let node = this.ast[i]; if(node.type == "interface") { let toAdd = []; for(let j=0;j < node.members.length;j++) { let member = node.members[j]; if(member.type == "operation") { for(let k=member.arguments.length-1;k >= 0;k--) { if(member.arguments[k].optional) { let copy: webidl.OperationMemberType = JSON.parse(JSON.stringify(member)); copy.arguments.splice(k,member.arguments.length - k); toAdd.push(copy); } } } } node.members.push(...toAdd); } } for(let i=0;i < this.ast.length;i++) { this.walkRootType(this.ast[i]); } if(this.mode == BinderMode.WEBIDL_LUA) { for(let i=0;i < this.ast.length;i++) { if(this.ast[i].type == "interface") { let int = this.ast[i] as webidl.InterfaceType; if(int.inheritance) { this.luaC.writeLn(this.outBufLua,`getmetatable(__BINDINGS__.${int.name}).__index = __BINDINGS__.${int.inheritance};`); } else { let JsImpl = this.getExtendedAttribute("JSImplementation",int.extAttrs) || this.getExtendedAttribute("LuaImplementation",int.extAttrs); if(JsImpl) { let jsImplExtends = this.unquote(JsImpl.rhs.value); if(jsImplExtends !== "") { this.luaC.writeLn(this.outBufLua,`getmetatable(__BINDINGS__.${int.name}).__index = __BINDINGS__.${jsImplExtends};`); } } } } } } if(this.mode == BinderMode.WEBIDL_CPP) { // output array operators for(let arrTypeNameKey in this.arrayTypes) { let arrType = this.arrayTypes[arrTypeNameKey]; let arrTypeName = WebIDLBinder.CTypeRenames[arrType.idlType as string] || (arrType.idlType as string); let arrTypeNameAdj = arrTypeName; if(this.classLookup[arrTypeName]) { arrTypeNameAdj += "*"; } this.cppC.write(this.outBufCPP,`export extern "C" ${arrTypeNameAdj} ${this.mangleArrayIndexerName("get",arrTypeNameKey)}(_LuaArray<${arrTypeName}>* arr,size_t index) {`); this.cppC.write(this.outBufCPP,`return `); if(this.classLookup[arrTypeName]) { this.cppC.write(this.outBufCPP,`&`); } this.cppC.write(this.outBufCPP,`arr->array[index];`); this.cppC.writeLn(this.outBufCPP,`};`); this.cppC.write(this.outBufCPP,`export extern "C" void ${this.mangleArrayIndexerName("set",arrTypeNameKey)}(_LuaArray<${arrTypeName}>* arr,size_t index,${arrTypeNameAdj} val) {`); this.cppC.write(this.outBufCPP,`arr->array[index] = `); if(this.classLookup[arrTypeName]) { this.cppC.write(this.outBufCPP,`*`); } this.cppC.write(this.outBufCPP,`val;`); this.cppC.writeLn(this.outBufCPP,`};`); this.cppC.write(this.outBufCPP,`export extern "C" _LuaArray<${arrTypeName}>* ${this.mangleArrayIndexerName("new",arrTypeNameKey)}(size_t len) {`); this.cppC.write(this.outBufCPP,`return new _LuaArray<${arrTypeName}>(len);`); this.cppC.writeLn(this.outBufCPP,`};`); this.cppC.write(this.outBufCPP,`export extern "C" void ${this.mangleArrayIndexerName("delete",arrTypeNameKey)}(_LuaArray<${arrTypeName}>* arr) {`); this.cppC.write(this.outBufCPP,`delete arr;`); this.cppC.writeLn(this.outBufCPP,`};`); this.cppC.write(this.outBufCPP,`export extern "C" size_t ${this.mangleArrayIndexerName("len",arrTypeNameKey)}(_LuaArray<${arrTypeName}>* arr) {`); this.cppC.write(this.outBufCPP,`return arr->len;`); this.cppC.writeLn(this.outBufCPP,`};`); } // output pointer array operators (only classes allowed) for(let arrTypeNameKey in this.ptrArrayTypes) { let arrType = this.ptrArrayTypes[arrTypeNameKey]; let arrTypeName = arrType.idlType as string; this.cppC.write(this.outBufCPP,`export extern "C" ${arrTypeName}* ${this.mangleArrayIndexerName("get",arrTypeNameKey)}(_LuaArray<${arrTypeName}*>* arr,size_t index) {`); this.cppC.write(this.outBufCPP,`return arr->array[index];`); this.cppC.writeLn(this.outBufCPP,`};`); this.cppC.write(this.outBufCPP,`export extern "C" void ${this.mangleArrayIndexerName("set",arrTypeNameKey)}(_LuaArray<${arrTypeName}*>* arr,size_t index,${arrTypeName}* val) {`); this.cppC.write(this.outBufCPP,`arr->array[index] = `); this.cppC.write(this.outBufCPP,`val;`); this.cppC.writeLn(this.outBufCPP,`};`); this.cppC.write(this.outBufCPP,`export extern "C" _LuaArray<${arrTypeName}*>* ${this.mangleArrayIndexerName("new",arrTypeNameKey)}(size_t len) {`); this.cppC.write(this.outBufCPP,`return new _LuaArray<${arrTypeName}*>(len);`); this.cppC.writeLn(this.outBufCPP,`};`); this.cppC.write(this.outBufCPP,`export extern "C" void ${this.mangleArrayIndexerName("delete",arrTypeNameKey)}(_LuaArray<${arrTypeName}*>* arr) {`); this.cppC.write(this.outBufCPP,`delete arr;`); this.cppC.writeLn(this.outBufCPP,`};`); this.cppC.write(this.outBufCPP,`export extern "C" size_t ${this.mangleArrayIndexerName("len",arrTypeNameKey)}(_LuaArray<${arrTypeName}*>* arr) {`); this.cppC.write(this.outBufCPP,`return arr->len;`); this.cppC.writeLn(this.outBufCPP,`};`); } this.cppC.writeLn(this.outBufCPP,`#undef __CFUNC`); this.cppC.writeLn(this.outBufCPP,`#undef export`); } else if(this.mode == BinderMode.WEBIDL_LUA) { // output array operators for(let arrTypeNameKey in this.arrayTypes) { this.luaC.write(this.outBufLua,`__BINDER__.arrays.${this.rawMangle(arrTypeNameKey)} = {`) if(this.specialTypes[arrTypeNameKey]) { if(arrTypeNameKey == "DOMString") { this.luaC.write(this.outBufLua,`get = function(ptr,idx)`) this.luaC.write(this.outBufLua,`local val = ${this.symbolResolver(this.mangleArrayIndexerName("get",arrTypeNameKey))}(ptr,idx)`) this.luaC.write(this.outBufLua,`return __BINDER__.readString(val) end,`) this.luaC.write(this.outBufLua,`set = function(ptr,idx,val)`) this.luaC.write(this.outBufLua,`val = __BINDER__.stringify(val)`) this.luaC.write(this.outBufLua,`${this.symbolResolver(this.mangleArrayIndexerName("set",arrTypeNameKey))}(ptr,idx,val)`) this.luaC.write(this.outBufLua,`end,`) this.luaC.write(this.outBufLua,`delete = function(ptr,len)`) this.luaC.write(this.outBufLua,`for i=1,len or 0 do __BINDER__.freeString(${this.symbolResolver(this.mangleArrayIndexerName("get",arrTypeNameKey))}(ptr)) end `) this.luaC.write(this.outBufLua,`${this.symbolResolver(this.mangleArrayIndexerName("delete",arrTypeNameKey))}(ptr)`) this.luaC.write(this.outBufLua,`end,`) } else if(arrTypeNameKey == "boolean") { this.luaC.write(this.outBufLua,`get = function(ptr,idx)`) this.luaC.write(this.outBufLua,`local val = ${this.symbolResolver(this.mangleArrayIndexerName("get",arrTypeNameKey))}(ptr,idx)`) this.luaC.write(this.outBufLua,`return val ~= 0 end,`) this.luaC.write(this.outBufLua,`set = function(ptr,idx,val)`) this.luaC.write(this.outBufLua,`val = val and 1 or 0`) this.luaC.write(this.outBufLua,`${this.symbolResolver(this.mangleArrayIndexerName("set",arrTypeNameKey))}(ptr,idx,val)`) this.luaC.write(this.outBufLua,`end,`) this.luaC.write(this.outBufLua,`delete = ${this.symbolResolver(this.mangleArrayIndexerName("delete",arrTypeNameKey))},`) } } else { this.luaC.write(this.outBufLua,`get = ${this.symbolResolver(this.mangleArrayIndexerName("get",arrTypeNameKey))},`) this.luaC.write(this.outBufLua,`set = ${this.symbolResolver(this.mangleArrayIndexerName("set",arrTypeNameKey))},`) this.luaC.write(this.outBufLua,`delete = ${this.symbolResolver(this.mangleArrayIndexerName("delete",arrTypeNameKey))},`) } this.luaC.write(this.outBufLua,`new = ${this.symbolResolver(this.mangleArrayIndexerName("new",arrTypeNameKey))},`) this.luaC.write(this.outBufLua,`len = ${this.symbolResolver(this.mangleArrayIndexerName("len",arrTypeNameKey))},`) this.luaC.write(this.outBufLua,`isClass = ${this.classLookup[arrTypeNameKey] ? "true" : "false"},`) this.luaC.writeLn(this.outBufLua,`}`); } // output pointer array operators for(let arrTypeNameKey in this.ptrArrayTypes) { this.luaC.write(this.outBufLua,`__BINDER__.ptrArrays.${this.rawMangle(arrTypeNameKey)} = {`) this.luaC.write(this.outBufLua,`get = ${this.symbolResolver(this.mangleArrayIndexerName("get",arrTypeNameKey))},`) this.luaC.write(this.outBufLua,`set = ${this.symbolResolver(this.mangleArrayIndexerName("set",arrTypeNameKey))},`) this.luaC.write(this.outBufLua,`new = ${this.symbolResolver(this.mangleArrayIndexerName("new",arrTypeNameKey))},`) this.luaC.write(this.outBufLua,`delete = ${this.symbolResolver(this.mangleArrayIndexerName("delete",arrTypeNameKey))},`) this.luaC.write(this.outBufLua,`len = ${this.symbolResolver(this.mangleArrayIndexerName("len",arrTypeNameKey))},`) this.luaC.write(this.outBufLua,`isClass = ${this.classLookup[arrTypeNameKey] ? "true" : "false"},`) this.luaC.writeLn(this.outBufLua,`}`); } } if(this.addYieldStub) { if(this.mode == BinderMode.WEBIDL_LUA) { this.luaC.writeLn(this.outBufLua,"__IMPORTS__.webidl_internal = {main_yield = coroutine.yield}"); this.luaC.writeLn(this.outBufLua,"module.init = coroutine.wrap(module.init)"); } else if(this.mode == BinderMode.WEBIDL_CPP) { this.cppC.writeLn(this.outBufCPP,`extern "C" void _webidl_main_yield() __attribute__((__import_module__("webidl_internal"), __import_name__("main_yield")));`) this.cppC.writeLn(this.outBufCPP,`int main() {_webidl_main_yield(); return 0;}`); } } } writeCArgs(buf: string[],args: webidl.Argument[], needsType: boolean,needsStartingComma: boolean,refToPtr?: boolean,maskRef = true) { if(needsStartingComma) { if(args.length > 0) { this.cppC.write(buf,","); } } for(let j=0;j < args.length;j++) { let overrideVName = false; let skipArg = false; if(needsType) { let lenAttr = this.getExtendedAttribute("ArrayLength",args[j].extAttrs) || this.getExtendedAttribute("ArrayLengthRef",args[j].extAttrs); if(lenAttr) { // skip these args. It's filled in below skipArg = true; } else { this.cppC.write(buf,`${this.idlTypeToCType(args[j].idlType,args[j].extAttrs,maskRef)} `); } } else { let arrAttr = this.getExtendedAttribute("Array",args[j].extAttrs); if(arrAttr) { // needs to point to internal array overrideVName = true; this.cppC.write(buf,`${args[j].name}->array`); } else { let lenAttr = this.getExtendedAttribute("ArrayLength",args[j].extAttrs); if(lenAttr) { // needs to return array len overrideVName = true; let arrVarName = this.unquote(lenAttr.rhs.value); if(arrVarName == "") { throw new SemanticError("ArrayLength attribute needs parameter 'Array name'"); } this.cppC.write(buf,`${arrVarName}->len`); } else { let lenAttr = this.getExtendedAttribute("ArrayLengthRef",args[j].extAttrs); if(lenAttr) { // needs to point to array len overrideVName = true; let arrVarName = this.unquote(lenAttr.rhs.value); if(arrVarName == "") { throw new SemanticError("ArrayLengthRef attribute needs parameter 'Array name'"); } this.cppC.write(buf,`&${arrVarName}->len`); } } } } if(!skipArg) { if(!overrideVName) { this.cppC.write(buf,`${refToPtr ? this.getWithRefs(args[j],!maskRef) : args[j].name}`); } if((j+1) !== args.length) { this.cppC.write(buf,","); } } } } writeLuaArgs(buf: string[],args: webidl.Argument[], needsStartingComma: boolean,typeConversionMode: ETypeConversion) { if(needsStartingComma) { if(args.length > 0) { this.luaC.write(buf,","); } } for(let j=0;j < args.length;j++) { let skipWrite = false; if(this.getExtendedAttribute("ArrayLengthRef",args[j].extAttrs)) { skipWrite = true; } else if(this.getExtendedAttribute("ArrayLength",args[j].extAttrs)) { skipWrite = true; } else { if(typeConversionMode == ETypeConversion.LUA_TO_CPP) { this.convertLuaToCPP_Arg(buf,args[j],j); } else if(typeConversionMode == ETypeConversion.CPP_TO_LUA) { this.convertCPPToLua_Arg(buf,args[j],j); } else { this.luaC.write(buf,`${args[j].name}`); } } if(!skipWrite) { this.luaC.write(buf,","); } } if(buf[buf.length - 1] == ",") {buf.pop();} } walkRootType(node: webidl.IDLRootType) { if(node.type == "interface") { if(this.mode == BinderMode.WEBIDL_LUA) { this.walkInterfaceLua(node); } else if(this.mode == BinderMode.WEBIDL_CPP) { this.walkInterfaceCPP(node); } } else if((node.type == "namespace")) { if(this.mode == BinderMode.WEBIDL_LUA) { this.walkNamespaceLua(node); } else if(this.mode == BinderMode.WEBIDL_CPP) { this.walkNamespaceCPP(node); } } } convertLuaToCPP_Pre(buf: string[],arg: {name: string,idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]} | webidl.Argument,argID: number) { if(this.getExtendedAttribute("ArrayLengthRef",arg.extAttrs)) { return; } else if(this.getExtendedAttribute("ArrayLength",arg.extAttrs)) { return; } if(this.getExtendedAttribute("Array",arg.extAttrs)) { let arrAttr = this.getExtendedAttribute("Array",arg.extAttrs); this.luaC.write(buf,`assert(type(${arg.name}) == "table","Parameter ${arg.name} (${argID + 1}) must be a table")`); this.luaC.write(buf,`local __arg${argID} =`); this.luaC.write(buf,`__BINDER__.luaToWasmArrayInternal(__BINDER__.arrays.${this.rawMangle(this.idlTypeToCTypeLite(arg.idlType,arg.extAttrs))},${arg.name}`); if(arrAttr && arrAttr.rhs) { let arrLen = this.unquote(arrAttr.rhs.value); if(!parseInt(arrLen) || isNaN(parseInt(arrLen))) { throw new SemanticError("Attribute 'Array' must have a numeric value (denoting max array length)"); } this.luaC.write(buf,`,${arrLen}`); } this.luaC.write(buf,`)`); return } else if(this.getExtendedAttribute("PointerArray",arg.extAttrs)) { let ptrArrAttr = this.getExtendedAttribute("PointerArray",arg.extAttrs); this.luaC.write(buf,`assert(type(${arg.name}) == "table","Parameter ${arg.name} (${argID + 1}) must be a table")`); this.luaC.write(buf,`local __arg${argID} =`); this.luaC.write(buf,`__BINDER__.luaToWasmArrayInternal(__BINDER__.ptrArrays.${this.rawMangle(this.idlTypeToCTypeLite(arg.idlType,arg.extAttrs))},${arg.name}`); if(ptrArrAttr && ptrArrAttr.rhs) { let arrLen = this.unquote(ptrArrAttr.rhs.value); if(!parseInt(arrLen) || isNaN(parseInt(arrLen))) { throw new SemanticError("Attribute 'PointerArray' must have a numeric value (denoting max array length)"); } this.luaC.write(buf,`,${arrLen}`); } this.luaC.write(buf,`)`); return } if(arg.idlType.idlType == "DOMString") { this.luaC.write(buf,`assert(type(${arg.name}) == "string","Parameter ${arg.name} (${argID + 1}) must be a string")`); this.luaC.write(buf,`local __arg${argID} = __BINDER__.stringify(${arg.name})`); } else if(arg.idlType.idlType == "boolean") { this.luaC.write(buf,`assert(type(${arg.name}) == "boolean","Parameter ${arg.name} (${argID + 1}) must be a boolean")`); } else if(this.classLookup[arg.idlType.idlType as string]) { this.luaC.write(buf,`assert((type(${arg.name}) == "table") and __BINDER__.isClassInstance(${arg.name},__BINDINGS__.${arg.idlType.idlType}),"Parameter ${arg.name} (${argID + 1}) must be an instance of ${arg.idlType.idlType}")`); if(this.hasExtendedAttribute("ToWASMOwned",arg.extAttrs)) { // If this WASM function accepts ownership of the passed in Lua arg, // let the Lua arg know this.luaC.write(buf,`${arg.name}.__luaOwned = false `); // this.luaC.write(buf,`if ${arg.name}.__luaOwned then ${arg.name}.__luaOwned = false else error("Parameter ${arg.name} is not owned by Lua, and therefore does not have the ability to transfer its ownership to WASM.") end `); } else if(this.hasExtendedAttribute("ToLuaOwned",arg.extAttrs)) { // If this WASM function rejects ownership of the passed in Lua arg, // let the Lua arg know this.luaC.write(buf,`${arg.name}.__luaOwned = true `); } } else { this.luaC.write(buf,`assert(type(${arg.name}) == "number","Parameter ${arg.name} (${argID + 1}) must be a number")`); } } convertLuaToCPP_Arg(buf: string[],arg: {name: string,idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]} | webidl.Argument,argID: number) { let arrAttr = this.getExtendedAttribute("Array",arg.extAttrs) || this.getExtendedAttribute("PointerArray",arg.extAttrs); if(arrAttr) { this.luaC.write(buf,`__arg${argID}`); return } if(arg.idlType.idlType == "DOMString") { this.luaC.write(buf,`__arg${argID}`); } else { this.luaC.write(buf,`${arg.name}`); } if(this.classLookup[arg.idlType.idlType as string]) { this.luaC.write(buf,".__ptr"); } else if(arg.idlType.idlType == "boolean") { this.luaC.write(buf," and 1 or 0"); } } convertLuaToCPP_Post(buf: string[],arg: {name: string,idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]} | webidl.Argument,argID: number) { if(!this.getExtendedAttribute("ConvertInputArray",arg.extAttrs)) { if(this.getExtendedAttribute("Array",arg.extAttrs)) { this.luaC.write(buf,`__BINDER__.arrays.${this.rawMangle(this.idlTypeToCTypeLite(arg.idlType,arg.extAttrs))}.delete(__arg${argID},#${arg.name})`); return } else if(this.getExtendedAttribute("PointerArray",arg.extAttrs)) { this.luaC.write(buf,`__BINDER__.ptrArrays.${this.rawMangle(this.idlTypeToCTypeLite(arg.idlType,arg.extAttrs))}.delete(__arg${argID})`); return } } else { // Only modifiable by ToLuaOwned // ToLuaOwned doesn't make sense here since these values are Lua owned by default let luaOwned = true; if(this.hasExtendedAttribute("ToWASMOwned",arg.extAttrs)) { // This WASM Function's argument's ownership is transferred to WASM luaOwned = false; } else if(this.hasExtendedAttribute("ToLuaOwned",arg.extAttrs)) { throw new SemanticError(`WASM -> Lua arguments are owned by Lua by default. 'ToLuaOwned' is unnecessary in argument ${arg.name}`); } if(this.getExtendedAttribute("Array",arg.extAttrs)) { this.luaC.write(buf,`__BINDER__.wasmToWrappedLuaArrayConvertInternal(${arg.name},__BINDER__.arrays.${this.rawMangle(this.idlTypeToCTypeLite(arg.idlType,arg.extAttrs))},__arg${argID},${luaOwned})`); return } else if(this.getExtendedAttribute("PointerArray",arg.extAttrs)) { this.luaC.write(buf,`__BINDER__.wasmToWrappedLuaArrayConvertInternal(${arg.name},__BINDER__.ptrArrays.${this.rawMangle(this.idlTypeToCTypeLite(arg.idlType,arg.extAttrs))},__arg${argID},${luaOwned})`); return } } if(arg.idlType.idlType == "DOMString") { this.luaC.write(buf,`__BINDER__.freeString(__arg${argID})`); } } convertCPPToLuaReturn(buf: string[],argType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[],argName: string) { // Returns from WASM are owned by WASM by default (so ToWASMOwned doesn't make sense here) let luaOwned = false; if(this.hasExtendedAttribute("ToLuaOwned",extAttrs)) { // Unless Lua accepts ownership luaOwned = true; } else if(this.hasExtendedAttribute("ToWASMOwned",extAttrs)) { throw new SemanticError(`WASM -> Lua return values are owned by WASM by default. 'ToWASMOwned' is unnecessary in argument ${argName}`); } if(this.getExtendedAttribute("Array",extAttrs)) { // let the return value know this.luaC.write(buf,`return __BINDER__.wasmToWrappedLuaArrayInternal(__BINDER__.arrays.${this.rawMangle(this.idlTypeToCTypeLite(argType,extAttrs))},${argName},${luaOwned})`); return } else if(this.getExtendedAttribute("PointerArray",extAttrs)) { // ditto above (re: gc) this.luaC.write(buf,`return __BINDER__.wasmToWrappedLuaArrayInternal(__BINDER__.ptrArrays.${this.rawMangle(this.idlTypeToCTypeLite(argType,extAttrs))},${argName},${luaOwned})`); return } if(this.classLookup[argType.idlType as string]) { // ditto above (re: gc) this.luaC.write(buf,`local __obj = __BINDER__.resolveClass(__BINDINGS__.${argType.idlType},${argName},${luaOwned}) `); if(luaOwned) { this.luaC.write(buf,`__obj.__luaOwned = true `); } this.luaC.write(buf,"return __obj"); } else if(argType.idlType == "DOMString") { // null terminated only :( this.luaC.write(buf,`return __BINDER__.readString(${argName})`); } else if(argType.idlType == "boolean") { this.luaC.write(buf,`return ${argName} ~= 0`); } else { this.luaC.write(buf,`return ${argName}`); } } convertLuaToCPPReturn(buf: string[],argType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[],argName: string) { if(this.getExtendedAttribute("ArrayLengthRef",extAttrs)) { return; } else if(this.getExtendedAttribute("ArrayLength",extAttrs)) { return; } if(this.getExtendedAttribute("Array",extAttrs)) { this.luaC.write(buf,`assert(type(${argName}) == "table","Return value ${argName} must be a table")`); } else if(this.getExtendedAttribute("PointerArray",extAttrs)) { this.luaC.write(buf,`assert(type(${argName}) == "table","Return value ${argName} must be a table")`); } else if(argType.idlType == "DOMString") { this.luaC.write(buf,`assert(type(${argName}) == "string","Return value ${argName} must be a string")`); } else if(argType.idlType == "boolean") { this.luaC.write(buf,`assert(type(${argName}) == "boolean","Return value ${argName} must be a boolean")`); } else if(this.classLookup[argType.idlType as string]) { this.luaC.write(buf,`assert((type(${argName}) == "table") and __BINDER__.isClassInstance(${argName},__BINDINGS__.${argType.idlType}),"Return ${argName} must be an instance of ${argType.idlType}")`); } else { this.luaC.write(buf,`assert(type(${argName}) == "number","Return value ${argName} must be a number")`); } this.luaC.write(buf,`return `); if(this.getExtendedAttribute("Array",extAttrs)) { let arrAttr = this.getExtendedAttribute("Array",extAttrs); this.luaC.write(buf,`__BINDER__.luaToWasmArrayInternal(__BINDER__.arrays.${this.rawMangle(this.idlTypeToCTypeLite(argType,extAttrs))},${argName}`); if(arrAttr && arrAttr.rhs) { let arrLen = this.unquote(arrAttr.rhs.value); if(!parseInt(arrLen) || isNaN(parseInt(arrLen))) { throw new SemanticError("Attribute 'Array' must have a numeric value (denoting max array length)"); } this.luaC.write(buf,`,${arrLen}`); } return } else if(this.getExtendedAttribute("PointerArray",extAttrs)) { let ptrArrAttr = this.getExtendedAttribute("PointerArray",extAttrs); this.luaC.write(buf,`__BINDER__.luaToWasmArrayInternal(__BINDER__.ptrArrays.${this.rawMangle(this.idlTypeToCTypeLite(argType,extAttrs))},${argName}`); if(ptrArrAttr && ptrArrAttr.rhs) { let arrLen = this.unquote(ptrArrAttr.rhs.value); if(!parseInt(arrLen) || isNaN(parseInt(arrLen))) { throw new SemanticError("Attribute 'PointerArray' must have a numeric value (denoting max array length)"); } this.luaC.write(buf,`,${arrLen}`); } this.luaC.write(buf,`)`); return } if(argType.idlType == "DOMString") { this.luaC.write(buf,`__BINDER__.stringify(${argName})`); } else { this.luaC.write(buf,`${argName}`); if(this.classLookup[argType.idlType as string]) { this.luaC.write(buf,".__ptr"); } else if(argType.idlType == "boolean") { this.luaC.write(buf," and 1 or 0"); } } } convertCPPToLua_Pre(buf: string[],arg: {name: string,idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]},argID: number) { if(this.getExtendedAttribute("Array",arg.extAttrs)) { return } else if(this.getExtendedAttribute("PointerArray",arg.extAttrs)) { return } if(this.classLookup[arg.idlType.idlType as string]) { // By default, arguments from WASM to Lua are managed by WASM. let luaOwned = false; if(this.hasExtendedAttribute("ToLuaOwned",arg.extAttrs)) { // Unless otherwise specified luaOwned = true; } else if(this.hasExtendedAttribute("ToWASMOwned",arg.extAttrs)) { throw new SemanticError(`WASM -> Lua arguments are owned by WASM by default. 'ToWASMOwned' is unnecessary in argument ${arg.name}`); } this.luaC.write(buf,`local __arg${argID} = __BINDER__.resolveClass(__BINDINGS__.${arg.idlType.idlType},${arg.name},${luaOwned}) `); if(luaOwned) { this.luaC.write(buf,`__arg${argID}.__luaOwned = true `); } } else if(arg.idlType.idlType == "DOMString") { // null terminated only :( this.luaC.write(buf,`local __arg${argID} = __BINDER__.readString(${arg.name}) `); } } convertCPPToLua_Arg(buf: string[],arg: {name: string,idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]},argID: number) { // By default, arguments from WASM to Lua are managed by WASM. let luaOwned = false; if(this.hasExtendedAttribute("ToLuaOwned",arg.extAttrs)) { // Unless otherwise specified luaOwned = true; } else if(this.hasExtendedAttribute("ToWASMOwned",arg.extAttrs)) { throw new SemanticError(`WASM -> Lua arguments are owned by WASM by default. 'ToWASMOwned' is unnecessary in argument ${arg.name}`); } if(this.getExtendedAttribute("Array",arg.extAttrs)) { this.luaC.write(buf,`__BINDER__.wasmToWrappedLuaArrayInternal(__BINDER__.arrays.${this.rawMangle(this.idlTypeToCTypeLite(arg.idlType,arg.extAttrs))},${arg.name},${luaOwned})`); return } else if(this.getExtendedAttribute("PointerArray",arg.extAttrs)) { this.luaC.write(buf,`__BINDER__.wasmToWrappedLuaArrayInternal(__BINDER__.ptrArrays.${this.rawMangle(this.idlTypeToCTypeLite(arg.idlType,arg.extAttrs))},${arg.name},${luaOwned})`); return } if(this.classLookup[arg.idlType.idlType as string]) { this.luaC.write(buf,`__arg${argID}`); } else if(arg.idlType.idlType == "DOMString") { // null terminated only :( this.luaC.write(buf,`__arg${argID}`); } else if(arg.idlType.idlType == "boolean") { // null terminated only :( this.luaC.write(buf,`${arg.name} ~= 0`); } else { this.luaC.write(buf,`${arg.name}`); } } convertCPPToLua_Post(buf: string[],arg: {name: string,idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]},argID: number) { if(this.getExtendedAttribute("Array",arg.extAttrs)) { return } else if(this.getExtendedAttribute("PointerArray",arg.extAttrs)) { return } // nothing } startWrappedCReturnValue(buf: string[],idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]) { if(this.hasExtendedAttribute("Array",extAttrs)) { let arrType = this.getExtendedAttribute("Array",extAttrs) as webidl.ExtendedAttributes; if(arrType.rhs) { this.cppC.write(buf,`new _LuaArray<${idlType.idlType}>(${this.unquote(arrType.rhs.value)},`); } else { this.cppC.write(buf,`new _LuaArray<${idlType.idlType}>(`); } } else if(this.hasExtendedAttribute("PointerArray",extAttrs)) { let arrType = this.getExtendedAttribute("PointerArray",extAttrs) as webidl.ExtendedAttributes; if(arrType.rhs) { this.cppC.write(buf,`new _LuaArray<${idlType.idlType}*>(${this.unquote(arrType.rhs.value)},`); } else { this.cppC.write(buf,`new _LuaArray<${idlType.idlType}*>(`); } } } endWrappedCReturnValue(buf: string[],idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]) { if(this.hasExtendedAttribute("Array",extAttrs) || this.hasExtendedAttribute("PointerArray",extAttrs)) { this.cppC.write(buf,`)`); } } startWrappedCValue(buf: string[],idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]) { // only a suffix is needed } endWrappedCValue(buf: string[],idlType: webidl.IDLTypeDescription,extAttrs: webidl.ExtendedAttributes[]) { if(this.hasExtendedAttribute("Array",extAttrs) || this.hasExtendedAttribute("PointerArray",extAttrs)) { this.cppC.write(buf,`->array`); } } walkInterfaceLua(node: webidl.InterfaceType) { let JsImpl = this.getExtendedAttribute("JSImplementation",node.extAttrs) || this.getExtendedAttribute("LuaImplementation",node.extAttrs); let hasConstructor = false; this.luaC.writeLn(this.outBufLua,`__BINDINGS__.${node.name} = {} __BINDER__.createClass(__BINDINGS__.${node.name},"${node.name}")`); let funcSig: {[ident: string]: number[]} = {}; for(let i=0;i < node.members.length;i++) { let member = node.members[i]; if(member.type == "operation") { funcSig[member.name] = funcSig[member.name] || [] for(let otherSig of funcSig[member.name]) { if(otherSig == member.arguments.length) { throw new SemanticError(`Function ${node.name}::${member.name} has incompatible overloaded signatures`); } } funcSig[member.name].push(member.arguments.length); } } this.luaC.write(this.outBufLua,`setmetatable(__BINDINGS__.${node.name},{__call = function(self`) if(funcSig[node.name]) { if(funcSig[node.name].length > 1) { this.luaC.write(this.outBufLua,`,`) let maxArg = Math.max(...funcSig[node.name]); for(let i=0;i < maxArg;i++) { this.luaC.write(this.outBufLua,`arg${i}`); if((i+1) !== maxArg) { this.luaC.write(this.outBufLua,","); } } } else { let maxArg = Math.max(...funcSig[node.name]); if(maxArg > 0) { this.luaC.write(this.outBufLua,`,`); for(let i=0;i < maxArg;i++) { this.luaC.write(this.outBufLua,`arg${i}`); if((i+1) !== maxArg) { this.luaC.write(this.outBufLua,","); } } } } } this.luaC.write(this.outBufLua,`)`) // All classes instantiated by Lua should be owned by Lua by default let classLuaOwned = true; if(this.hasExtendedAttribute("NoDelete",node.extAttrs)) { // Except when they can't be deleted. // In that case they should not be GC'd at all classLuaOwned = false; } this.luaC.write(this.outBufLua,`local ins = __BINDER__.instantiateClass(__BINDINGS__.${node.name},0,true)`) this.luaC.write(this.outBufLua,`ins:${node.name}(`) if(funcSig[node.name]) { if(funcSig[node.name].length > 1) { let maxArg = Math.max(...funcSig[node.name]); for(let i=0;i < maxArg;i++) { this.luaC.write(this.outBufLua,`arg${i}`); if((i+1) !== maxArg) { this.luaC.write(this.outBufLua,","); } } } else { let maxArg = Math.max(...funcSig[node.name]); if(maxArg > 0) { for(let i=0;i < maxArg;i++) { this.luaC.write(this.outBufLua,`arg${i}`); if((i+1) !== maxArg) { this.luaC.write(this.outBufLua,","); } } } } } this.luaC.write(this.outBufLua,`)`) this.luaC.write(this.outBufLua,`return ins`) this.luaC.write(this.outBufLua,` end})`) this.luaC.indent(); this.luaC.newLine(this.outBufLua); for(let i=0;i < node.members.length;i++) { let member = node.members[i]; if(member.type == "operation") { if(member.name == node.name) { hasConstructor = true; } this.luaC.write(this.outBufLua,`function __BINDINGS__.${node.name}:${member.name}`); if(funcSig[member.name].length > 1) { this.luaC.write(this.outBufLua,`__internal${member.arguments.length}`); } this.luaC.write(this.outBufLua,`(`); this.writeLuaArgs(this.outBufLua,member.arguments,false,ETypeConversion.NONE); this.luaC.write(this.outBufLua,`)`); if(!JsImpl || (node.name == member.name)) { for(let j=0;j < member.arguments.length;j++) { this.convertLuaToCPP_Pre(this.outBufLua,member.arguments[j],j); } if(member.name == node.name) { this.luaC.write(this.outBufLua,`self.__ptr = `); this.luaC.write(this.outBufLua,`${this.symbolResolver(this.mangleFunctionName(member,node.name))}(`); } else { this.luaC.write(this.outBufLua,`local ret = `); this.luaC.write(this.outBufLua,`${this.symbolResolver(this.mangleFunctionName(member,node.name))}(self.__ptr`); if(member.arguments.length > 0) { this.luaC.write(this.outBufLua,","); } } this.writeLuaArgs(this.outBufLua,member.arguments,false,ETypeConversion.LUA_TO_CPP); this.luaC.write(this.outBufLua,");"); if(member.name == node.name) { this.luaC.write(this.outBufLua,`__BINDINGS__.${node.name}.__cache[self.__ptr] = self;`) } for(let j=0;j < member.arguments.length;j++) { this.convertLuaToCPP_Post(this.outBufLua,member.arguments[j],j); } if(member.name !== node.name) { this.convertCPPToLuaReturn(this.outBufLua,member.idlType,member.extAttrs,"ret"); } } else { this.luaC.write(this.outBufLua,`error("Unimplemented -> ${node.name}::${member.name}()")`); } this.luaC.write(this.outBufLua," end"); this.luaC.newLine(this.outBufLua); if(JsImpl && (member.name !== node.name)) { this.luaC.write(this.outBufLua,`function __CFUNCS__.${this.mangleFunctionName(member,node.name,true)}(selfPtr`); this.writeLuaArgs(this.outBufLua,member.arguments,true,ETypeConversion.NONE); this.luaC.write(this.outBufLua,`)`); for(let j=0;j < member.arguments.length;j++) { this.convertLuaToCPP_Pre(this.outBufLua,member.arguments[j],j); } this.luaC.write(this.outBufLua,`local self = __BINDINGS__.${node.name}.__cache[selfPtr] local ret = self.${member.name}(self`); this.writeLuaArgs(this.outBufLua,member.arguments,true,ETypeConversion.CPP_TO_LUA); this.luaC.write(this.outBufLua,`)`); for(let j=0;j < member.arguments.length;j++) { this.convertLuaToCPP_Post(this.outBufLua,member.arguments[j],j); } this.convertLuaToCPPReturn(this.outBufLua,member.idlType,member.extAttrs,"ret"); this.luaC.write(this.outBufLua," end"); this.luaC.newLine(this.outBufLua); } } else if(member.type == "attribute") { this.luaC.write(this.outBufLua,`function __BINDINGS__.${node.name}.__specialIndex.${member.name}(self,k) `); this.luaC.write(this.outBufLua,`local ret = ${this.symbolResolver(this.mangleIndexerName(member,node.name,false))}(self.__ptr)`); this.convertCPPToLuaReturn(this.outBufLua,member.idlType,member.extAttrs,"ret"); this.luaC.writeLn(this.outBufLua,` end`); this.luaC.write(this.outBufLua,`function __BINDINGS__.${node.name}.__specialNewIndex.${member.name}(self,k,v) `); this.convertLuaToCPP_Pre(this.outBufLua,{name: "v",idlType: member.idlType,extAttrs: member.extAttrs},0); this.luaC.write(this.outBufLua,`${this.symbolResolver(this.mangleIndexerName(member,node.name,true))}(self.__ptr,`); this.convertLuaToCPP_Arg(this.outBufLua,{name: "v",idlType: member.idlType,extAttrs: member.extAttrs},0); this.luaC.write(this.outBufLua,`)`); this.convertLuaToCPP_Post(this.outBufLua,{name: "v",idlType: member.idlType,extAttrs: member.extAttrs},0); this.luaC.writeLn(this.outBufLua,` end`); } } for(let ident in funcSig) { let memberData = funcSig[ident]; if(memberData.length > 1) { // needs resolution this.luaC.write(this.outBufLua,`function __BINDINGS__.${node.name}:${ident}(`); let maxArg = Math.max(...memberData); for(let i=0;i < maxArg;i++) { this.luaC.write(this.outBufLua,`arg${i}`); if((i+1) !== maxArg) { this.luaC.write(this.outBufLua,","); } } this.luaC.write(this.outBufLua,") "); memberData.sort().reverse(); // I'm lazy this.luaC.write(this.outBufLua,"if "); for(let i=0;i < memberData.length;i++) { if(memberData[i] != 0) { this.luaC.write(this.outBufLua,`arg${memberData[i]-1} ~= nil then `); } this.luaC.write(this.outBufLua,`return self:${ident}__internal${memberData[i]}(`); for(let j=0;j < memberData[i];j++) { this.luaC.write(this.outBufLua,`arg${j}`); if((j+1) !== memberData[i]) { this.luaC.write(this.outBufLua,","); } } this.luaC.write(this.outBufLua,") "); if((i+1) !== memberData.length) { if(memberData[i+1] != 0) { this.luaC.write(this.outBufLua,"elseif "); } else { this.luaC.write(this.outBufLua,"else "); } } } this.luaC.writeLn(this.outBufLua,"end end"); } } this.luaC.write(this.outBufLua,`function __BINDINGS__.${node.name}:_delete()`); if(!this.hasExtendedAttribute("NoDelete",node.extAttrs)) { this.luaC.write(this.outBufLua,`return ${this.symbolResolver(this.mangleFunctionName("_delete",node.name))}(self.__ptr)`); } else { this.luaC.writeLn(this.outBufLua,`error("Instances of class ${node.name} cannot be deleted from Lua")`); } this.luaC.writeLn(this.outBufLua,`end`); if(!hasConstructor) { this.luaC.writeLn(this.outBufLua,`function __BINDINGS__.${node.name}:${node.name}() error("Class ${node.name} has no WebIDL constructor and therefore cannot be instantiated via Lua") end`) } this.luaC.outdent(this.outBufLua); this.luaC.newLine(this.outBufLua); } walkInterfaceCPP(node: webidl.InterfaceType) { let JsImpl = this.getExtendedAttribute("JSImplementation",node.extAttrs) || this.getExtendedAttribute("LuaImplementation",node.extAttrs); let Prefix = this.unquoteEx(this.getExtendedAttribute("Prefix",node.extAttrs)); let hasConstructor = false; if(JsImpl) { this.cppC.writeLn(this.outBufCPP,`class ${Prefix}${node.name};`); for(let i=0;i < node.members.length;i++) { let member = node.members[i]; if(member.type == "operation") { if(member.name == node.name) {continue;} this.cppC.write(this.outBufCPP,`export extern "C" ${this.idlTypeToCType(member.idlType,node.extAttrs,true)} ${this.mangleFunctionName(member,node.name,true)}(${Prefix}${node.name}* self`); this.writeCArgs(this.outBufCPP,member.arguments,true,true); this.cppC.writeLn(this.outBufCPP,`) __CFUNC(${this.mangleFunctionName(member,node.name,true)});`); } } this.cppC.write(this.outBufCPP,`class ${Prefix}${node.name}`); let jsImplExtends = this.unquote(JsImpl.rhs.value); if(jsImplExtends !== "") { if(this.classPrefixLookup[jsImplExtends]) { jsImplExtends = `${this.classPrefixLookup[jsImplExtends]}${jsImplExtends}`; } this.cppC.write(this.outBufCPP,` : ${jsImplExtends}`); } this.cppC.writeLn(this.outBufCPP,` {`); this.cppC.write(this.outBufCPP,`public:`); this.cppC.indent(); this.cppC.newLine(this.outBufCPP); for(let i=0;i < node.members.length;i++) { let member = node.members[i]; if(member.type == "operation") { if(member.name == node.name) { hasConstructor = true; continue; } this.cppC.write(this.outBufCPP,`${this.idlTypeToCType(member.idlType,node.extAttrs,false)} `); this.cppC.write(this.outBufCPP,`${member.name}(`); this.writeCArgs(this.outBufCPP,member.arguments,true,false,false,false); this.cppC.write(this.outBufCPP,`) {`); if(member.idlType.idlType !== "void") { this.cppC.write(this.outBufCPP,"return"); } this.cppC.write(this.outBufCPP,` `); if(member.idlType.idlType !== "void") { this.startWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); } this.cppC.write(this.outBufCPP,`${this.mangleFunctionName(member,node.name,true)}(this`); this.writeCArgs(this.outBufCPP,member.arguments,false,true,true,false); this.cppC.write(this.outBufCPP,")"); if(member.idlType.idlType !== "void") { this.endWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); } this.cppC.write(this.outBufCPP,"; };"); this.cppC.newLine(this.outBufCPP); } } this.cppC.outdent(this.outBufCPP) this.cppC.write(this.outBufCPP,"};"); this.cppC.newLine(this.outBufCPP); } for(let i=0;i < node.members.length;i++) { let member = node.members[i]; if(member.type == "operation") { let Operator = this.getExtendedAttribute("Operator",member.extAttrs); let Value = this.getExtendedAttribute("Value",member.extAttrs); // TODO: we're using emscripten's way of wrapping values into static temp vars // I think this is unsafe. We should allocate new memory per return // and make lua garbage collect the result.. if(member.name == node.name) { hasConstructor = true; } else if(JsImpl) {continue;} if(member.name == node.name) { this.cppC.write(this.outBufCPP,`export extern "C" ${Prefix}${node.name}* ${this.mangleFunctionName(member,node.name)}(`); } else { this.cppC.write(this.outBufCPP,`export extern "C" ${this.idlTypeToCType(member.idlType,member.extAttrs,true)} ${this.mangleFunctionName(member,node.name)}(${Prefix}${node.name}* self`); if(member.arguments.length > 0) { this.cppC.write(this.outBufCPP,`,`); } } this.writeCArgs(this.outBufCPP,member.arguments,true,false); this.cppC.write(this.outBufCPP,`) {`); let wrappedCReturnValue = true; if(Value && (member.name !== node.name)) { this.cppC.write(this.outBufCPP,`static ${this.idlTypeToCType(member.idlType,[],false,true)} temp; return (temp = `); this.cppC.write(this.outBufCPP,` `); this.startWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); } else if((member.idlType.idlType !== "void") || (member.name == node.name)) { this.cppC.write(this.outBufCPP,"return"); this.cppC.write(this.outBufCPP,` `); this.startWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); } else { wrappedCReturnValue = false; this.cppC.write(this.outBufCPP,` `); } if(Operator === false) { if(member.name == node.name) { this.cppC.write(this.outBufCPP,`new ${Prefix}${node.name}`); } else { if(this.hasExtendedAttribute("Ref",member.extAttrs)) { this.cppC.write(this.outBufCPP,"&"); } this.cppC.write(this.outBufCPP,`self->${member.name}`); } this.cppC.write(this.outBufCPP,`(`); this.writeCArgs(this.outBufCPP,member.arguments,false,false,true); this.cppC.write(this.outBufCPP,`) `); } else { if(member.arguments.length > 0) { if(this.hasExtendedAttribute("Ref",member.extAttrs)) { this.cppC.write(this.outBufCPP,"&"); } this.cppC.write(this.outBufCPP,`(*self ${this.unquote(Operator.rhs.value)} ${this.getWithRefs(member.arguments[0])})`); } else { this.cppC.write(this.outBufCPP,`${this.unquote(Operator.rhs.value)} self`); } } if(wrappedCReturnValue) { this.endWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); } if(Value) { this.cppC.write(this.outBufCPP,`, &temp)`); } this.cppC.write(this.outBufCPP,`;`); this.cppC.write(this.outBufCPP,`};`); this.cppC.newLine(this.outBufCPP); } else if(member.type == "attribute") { this.cppC.write(this.outBufCPP,`export extern "C" ${this.idlTypeToCType(member.idlType,member.extAttrs,true)} ${this.mangleIndexerName(member,node.name,false)}(${Prefix}${node.name}* self) {`); this.cppC.write(this.outBufCPP,`return `); this.startWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); if(this.hasExtendedAttribute("Value",member.extAttrs)) { this.cppC.write(this.outBufCPP,"&"); } this.cppC.write(this.outBufCPP,`self->${member.name}`); this.endWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); this.cppC.writeLn(this.outBufCPP,`; };`); this.cppC.write(this.outBufCPP,`export extern "C" void ${this.mangleIndexerName(member,node.name,true)}(${Prefix}${node.name}* self,${this.idlTypeToCType(member.idlType,member.extAttrs,true)} val) {`); this.cppC.write(this.outBufCPP,`self->${member.name} = `); if(this.hasExtendedAttribute("Value",member.extAttrs)) { this.cppC.write(this.outBufCPP,"*"); } this.startWrappedCValue(this.outBufCPP,member.idlType,member.extAttrs); this.cppC.write(this.outBufCPP,`val`); this.endWrappedCValue(this.outBufCPP,member.idlType,member.extAttrs); this.cppC.writeLn(this.outBufCPP,`; };`); } } this.cppC.write(this.outBufCPP,`export extern "C" void ${this.mangleFunctionName("_delete",node.name)}(${Prefix}${node.name}* self) {`); if(!this.hasExtendedAttribute("NoDelete",node.extAttrs)) { this.cppC.write(this.outBufCPP,`delete self;`); } else { this.cppC.write(this.outBufCPP,`/* no op */`); } this.cppC.writeLn(this.outBufCPP,`};`); } walkNamespaceLua(node: webidl.NamespaceType) { let JsImpl = this.getExtendedAttribute("JSImplementation",node.extAttrs) || this.getExtendedAttribute("LuaImplementation",node.extAttrs); this.luaC.write(this.outBufLua,`__BINDINGS__.${node.name} = __BINDER__.createNamespace()`); this.luaC.indent(); this.luaC.newLine(this.outBufLua); let funcSig: {[ident: string]: number[]} = {}; for(let i=0;i < node.members.length;i++) { let member = node.members[i]; if(member.type == "operation") { funcSig[member.name] = funcSig[member.name] || [] for(let otherSig of funcSig[member.name]) { if(otherSig == member.arguments.length) { throw new SemanticError(`Function ${node.name}::${member.name} has incompatible overloaded signatures`); } } funcSig[member.name].push(member.arguments.length); } } for(let i=0;i < node.members.length;i++) { let member = node.members[i]; if(member.type == "operation") { this.luaC.write(this.outBufLua,`function __BINDINGS__.${node.name}.${member.name}`); if(funcSig[member.name].length > 1) { this.luaC.write(this.outBufLua,`__internal${member.arguments.length}`); } this.luaC.write(this.outBufLua,`(`); this.writeLuaArgs(this.outBufLua,member.arguments,false,ETypeConversion.NONE); this.luaC.write(this.outBufLua,`)`); if(JsImpl) { this.luaC.write(this.outBufLua,`error("Unimplemented -> ${node.name}::${member.name}()")`); } else { for(let j=0;j < member.arguments.length;j++) { this.convertLuaToCPP_Pre(this.outBufLua,member.arguments[j],j); } this.luaC.write(this.outBufLua,`local ret = `); this.luaC.write(this.outBufLua,`${this.symbolResolver(this.mangleFunctionName(member,node.name))}(`); this.writeLuaArgs(this.outBufLua,member.arguments,false,ETypeConversion.LUA_TO_CPP); this.luaC.write(this.outBufLua,")"); for(let j=0;j < member.arguments.length;j++) { this.convertLuaToCPP_Post(this.outBufLua,member.arguments[j],j); } this.convertCPPToLuaReturn(this.outBufLua,member.idlType,member.extAttrs,"ret"); } this.luaC.write(this.outBufLua," end"); this.luaC.newLine(this.outBufLua); if(JsImpl) { this.luaC.write(this.outBufLua,`function __CFUNCS__.${this.mangleFunctionName(member,node.name,true)}(`); this.writeLuaArgs(this.outBufLua,member.arguments,false,ETypeConversion.NONE); this.luaC.write(this.outBufLua,`)`); for(let j=0;j < member.arguments.length;j++) { this.convertLuaToCPP_Pre(this.outBufLua,member.arguments[j],j); } this.luaC.write(this.outBufLua,`local ret = __BINDINGS__.${node.name}.${member.name}(`); this.writeLuaArgs(this.outBufLua,member.arguments,false,ETypeConversion.CPP_TO_LUA); this.luaC.write(this.outBufLua,`)`); for(let j=0;j < member.arguments.length;j++) { this.convertLuaToCPP_Post(this.outBufLua,member.arguments[j],j); } this.convertLuaToCPPReturn(this.outBufLua,member.idlType,member.extAttrs,"ret"); this.luaC.write(this.outBufLua," end"); this.luaC.newLine(this.outBufLua); } } else if(member.type == "attribute") { this.luaC.write(this.outBufLua,`function __BINDINGS__.${node.name}.__specialIndex.${member.name}(self,k) `); this.luaC.write(this.outBufLua,`local ret = ${this.symbolResolver(this.mangleIndexerName(member,node.name,false))}()`); this.convertCPPToLuaReturn(this.outBufLua,member.idlType,member.extAttrs,"ret"); this.luaC.writeLn(this.outBufLua,` end`); this.luaC.write(this.outBufLua,`function __BINDINGS__.${node.name}.__specialNewIndex.${member.name}(self,k,v) `); if(!member.readonly || this.hasExtendedAttribute("OverrideCanWrite",member.extAttrs)) { this.convertLuaToCPP_Pre(this.outBufLua,{name: "v",idlType: member.idlType,extAttrs: member.extAttrs},0); this.luaC.write(this.outBufLua,`${this.symbolResolver(this.mangleIndexerName(member,node.name,true))}(`); this.convertLuaToCPP_Arg(this.outBufLua,{name: "v",idlType: member.idlType,extAttrs: member.extAttrs},0); this.luaC.write(this.outBufLua,`)`); this.convertLuaToCPP_Post(this.outBufLua,{name: "v",idlType: member.idlType,extAttrs: member.extAttrs},0); } else { this.luaC.write(this.outBufLua,`error("Cannot modify read-only attribute ${node.name}::${member.name}")`); } this.luaC.writeLn(this.outBufLua,` end`); } } for(let ident in funcSig) { let memberData = funcSig[ident]; if(memberData.length > 1) { // needs resolution this.luaC.write(this.outBufLua,`function __BINDINGS__.${node.name}.${ident}(`); let maxArg = Math.max(...memberData); for(let i=0;i < maxArg;i++) { this.luaC.write(this.outBufLua,`arg${i}`); if((i+1) !== maxArg) { this.luaC.write(this.outBufLua,","); } } this.luaC.write(this.outBufLua,") "); memberData.sort().reverse(); // I'm lazy this.luaC.write(this.outBufLua,"if "); for(let i=0;i < memberData.length;i++) { if(memberData[i] != 0) { this.luaC.write(this.outBufLua,`arg${memberData[i]-1} ~= nil then `); } this.luaC.write(this.outBufLua,`return __BINDINGS__.${node.name}.${ident}__internal${memberData[i]}(`); for(let j=0;j < memberData[i];j++) { this.luaC.write(this.outBufLua,`arg${j}`); if((j+1) !== memberData[i]) { this.luaC.write(this.outBufLua,","); } } this.luaC.write(this.outBufLua,") "); if((i+1) !== memberData.length) { if(memberData[i+1] != 0) { this.luaC.write(this.outBufLua,"elseif "); } else { this.luaC.write(this.outBufLua,"else "); } } } this.luaC.writeLn(this.outBufLua,"end end"); } } this.luaC.outdent(this.outBufLua); this.luaC.newLine(this.outBufLua); } walkNamespaceCPP(node: webidl.NamespaceType) { let JsImpl = this.getExtendedAttribute("JSImplementation",node.extAttrs) || this.getExtendedAttribute("LuaImplementation",node.extAttrs); if(JsImpl) { for(let i=0;i < node.members.length;i++) { let member = node.members[i]; if(member.type == "operation") { this.cppC.write(this.outBufCPP,`extern "C" ${this.idlTypeToCType(member.idlType,node.extAttrs,true)} ${this.mangleFunctionName(member,node.name,true)}(`); this.writeCArgs(this.outBufCPP,member.arguments,true,false); this.cppC.writeLn(this.outBufCPP,`) __CFUNC(${this.mangleFunctionName(member,node.name,true)});`); } } if(node.name !== "global") { this.cppC.write(this.outBufCPP,`namespace ${node.name} {`); } this.cppC.indent(); this.cppC.newLine(this.outBufCPP); for(let i=0;i < node.members.length;i++) { let member = node.members[i]; if(member.type == "operation") { this.cppC.write(this.outBufCPP,`${this.idlTypeToCType(member.idlType,node.extAttrs,true)} `); this.cppC.write(this.outBufCPP,`${member.name}(`); this.writeCArgs(this.outBufCPP,member.arguments,true,false,false,false); this.cppC.write(this.outBufCPP,`) {`); if(member.idlType.idlType !== "void") { this.cppC.write(this.outBufCPP,"return"); } this.cppC.write(this.outBufCPP,` `); if(member.idlType.idlType !== "void") { this.startWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); } this.cppC.write(this.outBufCPP,`${this.mangleFunctionName(member,node.name,true)}(`); this.writeCArgs(this.outBufCPP,member.arguments,false,false,true,false); this.cppC.write(this.outBufCPP,")"); if(member.idlType.idlType !== "void") { this.endWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); } this.cppC.write(this.outBufCPP,"; };"); this.cppC.newLine(this.outBufCPP); } } this.cppC.outdent(this.outBufCPP) if(node.name !== "global") { this.cppC.write(this.outBufCPP,"};"); } this.cppC.newLine(this.outBufCPP); } else { for(let i=0;i < node.members.length;i++) { let member = node.members[i]; if(member.type == "operation") { let Value = this.getExtendedAttribute("Value",member.extAttrs); this.cppC.write(this.outBufCPP,`export extern "C" ${this.idlTypeToCType(member.idlType,member.extAttrs,true)} ${this.mangleFunctionName(member,node.name)}(`); this.writeCArgs(this.outBufCPP,member.arguments,true,false); this.cppC.write(this.outBufCPP,`) {`); let wrappedCReturnValue = true; if(Value) { this.cppC.write(this.outBufCPP,`static ${this.idlTypeToCType(member.idlType,[],false,true)} temp; return (temp = `); this.cppC.write(this.outBufCPP,` `); this.startWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); } else if(member.idlType.idlType !== "void") { this.cppC.write(this.outBufCPP,"return"); this.cppC.write(this.outBufCPP,` `); this.startWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); } else { wrappedCReturnValue = false; this.cppC.write(this.outBufCPP,` `); } if(node.name === "global") { this.cppC.write(this.outBufCPP,`${member.name}`); } else { this.cppC.write(this.outBufCPP,`${node.name}::${member.name}`); } this.cppC.write(this.outBufCPP,`(`); this.writeCArgs(this.outBufCPP,member.arguments,false,false,true); this.cppC.write(this.outBufCPP,`) `); if(wrappedCReturnValue) { this.endWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); } if(Value) { this.cppC.write(this.outBufCPP,`, &temp)`); } this.cppC.write(this.outBufCPP,`;`); this.cppC.write(this.outBufCPP,`};`); this.cppC.newLine(this.outBufCPP); } else if(member.type == "attribute") { this.cppC.write(this.outBufCPP,`export extern "C" ${this.idlTypeToCType(member.idlType,member.extAttrs,true)} ${this.mangleIndexerName(member,node.name,false)}(${node.name}* self) {`); this.cppC.write(this.outBufCPP,`return `); this.startWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); if(this.hasExtendedAttribute("Value",member.extAttrs)) { this.cppC.write(this.outBufCPP,"&"); } if(node.name === "global") { this.cppC.write(this.outBufCPP,`${member.name}`); } else { this.cppC.write(this.outBufCPP,`${node.name}::${member.name}`); } this.endWrappedCReturnValue(this.outBufCPP,member.idlType,member.extAttrs); this.cppC.write(this.outBufCPP,`; `); this.cppC.writeLn(this.outBufCPP,`};`); if(!member.readonly || this.hasExtendedAttribute("OverrideCanWrite",member.extAttrs)) { this.cppC.write(this.outBufCPP,`export extern "C" void ${this.mangleIndexerName(member,node.name,true)}(${node.name}* self,${this.idlTypeToCType(member.idlType,member.extAttrs,true)} val) {`); if(node.name === "global") { this.cppC.write(this.outBufCPP,`${member.name}`); } else { this.cppC.write(this.outBufCPP,`${node.name}::${member.name}`); } this.cppC.write(this.outBufCPP,` = `); this.startWrappedCValue(this.outBufCPP,member.idlType,member.extAttrs); if(this.hasExtendedAttribute("Value",member.extAttrs)) { this.cppC.write(this.outBufCPP,"*"); } this.cppC.write(this.outBufCPP,`val`); this.endWrappedCValue(this.outBufCPP,member.idlType,member.extAttrs); this.cppC.writeLn(this.outBufCPP,`; };`); } } } } } } // let infile = process.argv[2] || (__dirname + "/../test/test.idl"); // let outfile_lua = process.argv[3] || (__dirname + "/../test/test_bind.lua"); // let outfile_cpp = process.argv[3] || (__dirname + "/../test/test_bind.cpp"); // let idl = fs.readFileSync(infile); // // console.log(JSON.stringify(ast,null,4)); // let inst = new WebIDLBinder(idl.toString(),BinderMode.WEBIDL_LUA,true); // inst.buildOut() // fs.writeFileSync(outfile_lua,inst.outBufLua.join("")); // fs.writeFileSync(outfile_cpp,inst.outBufCPP.join(""));
the_stack
import { ClientDocumentSnapshot, IFieldValue, } from "@/types/ClientDocumentSnapshot"; import { getParentPath, newId, prettifyPath } from "@/utils/common"; import { deserializeDocumentSnapshotArray, serializeQuerySnapshot, } from "firestore-serializers"; import firebase from "firebase/app"; import { differenceBy, uniq, uniqBy, uniqueId } from "lodash"; import { changedDocAtom, collectionAtom, deletedDocsAtom, docAtom, docsLibraryAtom, collectionHasBeenDeleteAtom, newDocsAtom, parseFSUrl, pathExpanderPureAtom, fieldAtom, buildFSUrl, } from "./firestore"; import { getRecoilExternalLoadable, IRecoilUpdateCommand, resetRecoilExternalState, setRecoilBatchUpdate, setRecoilExternalState, } from "./RecoilExternalStatePortal"; import * as immutable from "object-path-immutable"; import { navigatorPathAtom, queryVersionAtom } from "./navigator"; import { actionGoTo } from "./navigator.action"; import { notifyErrorPromise } from "./ui.action"; import { convertFSValue } from "@/utils/fieldConverter"; export const actionStoreDocs = ( { added = [], modified = [], removed = [], }: { added?: ClientDocumentSnapshot[]; modified?: ClientDocumentSnapshot[]; removed?: ClientDocumentSnapshot[]; }, override = false ): void => { const batches: any[] = []; added.forEach((doc) => { if (override) { batches.push({ atom: docAtom(doc.ref.path), valOrUpdater: doc, }); } else { batches.push({ atom: docAtom(doc.ref.path), valOrUpdater: (curDoc) => { if (curDoc?.isChanged()) { return curDoc; } return doc; }, }); } }); modified.forEach((doc) => { batches.push({ atom: docAtom(doc.ref.path), valOrUpdater: doc, }); }); batches.push({ // Synchronize data with docsLibraryAtom. Why I need to do it manually ?_? atom: docsLibraryAtom, valOrUpdater: (curPath) => uniq([...curPath, ...[...added, ...modified].map((doc) => doc.ref.path)]), }); removed.forEach((doc) => { batches.push({ atom: docAtom(doc.ref.path), valOrUpdater: null, }); }); setRecoilBatchUpdate(batches); }; // This is trigger from user export const actionDeleteDoc = async (docPath: string) => { const doc = await getRecoilExternalLoadable(docAtom(docPath)).toPromise(); if (doc) { resetRecoilExternalState(docAtom(docPath)); if (doc.isNew) { // Ignore if the doc is new and haven't commit to db return true; } setRecoilExternalState(deletedDocsAtom, (docs) => uniqBy([...docs, doc], (doc) => doc.ref.path) ); } return true; }; // This is trigger from server. It will irevertable export const actionRemoveDocs = ( docs: ClientDocumentSnapshot[], override = false ): void => { docs.forEach(async (doc) => { // TODO: What if user already modified the deleted one resetRecoilExternalState(docAtom(doc.ref.path)); setRecoilExternalState(deletedDocsAtom, (deletedDocs) => differenceBy(deletedDocs, docs, (doc) => doc.ref.path) ); }); }; // This is trigger from user export const actionDeleteCollection = async (path: string): Promise<void> => { console.log(`start delete collection ${path}`); // Marks all docs as delete const docsInCollection = await getRecoilExternalLoadable( collectionAtom(path) ).toPromise(); const updater: any[] = docsInCollection.map((doc) => ({ atom: docAtom(doc.ref.path), valOrUpdater: null, })); updater.push({ atom: deletedDocsAtom, valOrUpdater: (docs) => uniqBy([...docs, ...docsInCollection], (doc) => doc.ref.path), }); updater.push({ atom: collectionHasBeenDeleteAtom, valOrUpdater: (paths) => uniq([...paths, path]), }); requestAnimationFrame(() => { setRecoilBatchUpdate(updater); }); }; export const actionUpdateDoc = (doc: ClientDocumentSnapshot): void => { setRecoilExternalState(docAtom(doc.ref.path), doc); }; export const actionUpdateFieldKey = async ( oldPath: string, newField: string ): Promise<void> => { const { path, field: oldField } = parseFSUrl(oldPath); const curDocAtom = docAtom(path); const doc = await getRecoilExternalLoadable(curDocAtom).toPromise(); if (doc) { const docData = immutable.wrap(doc.data()); const oldFieldData = immutable.get(doc.data(), oldField); const newData = docData.del(oldField).set(newField, oldFieldData); const newDoc = doc.clone(newData.value()); newDoc.addChange([oldField, newField]); setRecoilExternalState(docAtom(path), newDoc); } }; export const actionRemoveFieldKey = async (oldPath: string): Promise<void> => { const { path, field: oldField } = parseFSUrl(oldPath); const curDocAtom = docAtom(path); const doc = await getRecoilExternalLoadable(curDocAtom).toPromise(); if (doc) { const newDoc = doc.clone().removeField(oldField); setRecoilExternalState(docAtom(path), newDoc); } }; export const actionCommitChange = async (): Promise<boolean> => { const docsChange = await getRecoilExternalLoadable( changedDocAtom ).toPromise(); const newDocs = await getRecoilExternalLoadable(newDocsAtom).toPromise(); const allDeletedDocs = await getRecoilExternalLoadable( deletedDocsAtom ).toPromise(); const deletedCollections = await getRecoilExternalLoadable( collectionHasBeenDeleteAtom ).toPromise(); const deletedDocs = allDeletedDocs.filter( (doc) => !deletedCollections.find((collection) => doc.ref.path.startsWith(collection) ) ); window .send("fs.updateDocs", { docs: serializeQuerySnapshot({ docs: docsChange }), }) .catch(notifyErrorPromise); window .send("fs.addDocs", { docs: serializeQuerySnapshot({ docs: newDocs }), }) .catch(notifyErrorPromise); window .send("fs.deleteDocs", { docs: deletedDocs.map((doc) => doc.ref.path), }) .then(() => { resetRecoilExternalState(deletedDocsAtom); }) .catch(notifyErrorPromise); window .send("fs.deleteCollections", { collections: deletedCollections, }) .then(() => { resetRecoilExternalState(collectionHasBeenDeleteAtom); setRecoilExternalState(pathExpanderPureAtom, (paths) => paths.filter( (path) => !deletedCollections.find((collection) => path.startsWith(collection) ) ) ); }) .catch(notifyErrorPromise); return true; }; export const actionReverseChange = async (): Promise<any> => { // TODO: Confirm box to reload window.location.reload(); // const docsChange = await getRecoilExternalLoadable( // changedDocAtom // ).toPromise(); // return window // .send("fs.getDocs", { // docs: docsChange.map((doc) => doc.ref.path), // }) // .then((response) => { // const data = deserializeDocumentSnapshotArray( // response, // firebase.firestore.GeoPoint, // firebase.firestore.Timestamp // ); // actionStoreDocs(ClientDocumentSnapshot.transformFromFirebase(data), true); // }); }; export const actionReverseDocChange = async ( docPath: string, type: "new" | "modified" | "deleted" ): Promise<any> => { const { queryVersion } = await getRecoilExternalLoadable( queryVersionAtom ).toPromise(); // TODO: Do we really need to fetch the data again? if (type === "new") { resetRecoilExternalState(docAtom(docPath)); return; } return window .send("fs.getDocs", { docs: [docPath], }) .then((response) => { const data = deserializeDocumentSnapshotArray( response, firebase.firestore.GeoPoint, firebase.firestore.Timestamp ); actionStoreDocs( { added: ClientDocumentSnapshot.transformFromFirebase( data, queryVersion ), }, true ); setRecoilExternalState(deletedDocsAtom, (docs) => docs.filter((doc) => doc.ref.path !== docPath) ); }) .catch(notifyErrorPromise); }; export const actionGetDocs = async (paths: string[]) => { const { queryVersion } = await getRecoilExternalLoadable( queryVersionAtom ).toPromise(); return window .send("fs.getDocs", { docs: paths, }) .then((response) => { const data = deserializeDocumentSnapshotArray( response, firebase.firestore.GeoPoint, firebase.firestore.Timestamp ); actionStoreDocs( { added: ClientDocumentSnapshot.transformFromFirebase( data, queryVersion ), }, false ); }); }; export const actionAddPathExpander = (paths: string[]) => { setRecoilExternalState(pathExpanderPureAtom, (currentValue) => uniq([...currentValue, ...paths.map((path) => prettifyPath(path))]) ); }; export const actionDuplicateDoc = async (path: string) => { const doc = await getRecoilExternalLoadable(docAtom(path)).toPromise(); if (!doc) { // TODO: Throw error here return; } const newDocId = newId(); const newDoc = doc.clone(doc.data(), newDocId); setRecoilExternalState(docAtom(newDoc.ref.path), newDoc); actionGoTo(newDoc.ref.path); }; interface IActionImportDocsOption { idField?: string; autoParseJSON?: boolean; } export const actionImportDocs = async ( path: string, docs: any[], option: IActionImportDocsOption ) => { console.log({ docs, path, option, }); // TODO: Check if path is collection return window.send("fs.importDocs", { docs, path, option, }); }; export const actionNewDocument = async ( collectionPath: string, id?: string ) => { // const newDocId = uniqueId(NEW_DOC_PREFIX); // TODO: Sort new document to the bottom of table const newDocId = id || newId(); const newPath = prettifyPath(`${collectionPath}/${newDocId}`); const { queryVersion } = await getRecoilExternalLoadable( queryVersionAtom ).toPromise(); setRecoilExternalState( docAtom(newPath), new ClientDocumentSnapshot({}, newDocId, newPath, queryVersion, true) ); setRecoilExternalState(navigatorPathAtom, newPath); }; export const actionSetFieldValue = async ( docPath: string, field: string, fieldType: RefiFS.IFieldType ) => { const fieldPath = buildFSUrl({ path: docPath, field }); const instanceValue = await getRecoilExternalLoadable( fieldAtom(fieldPath) ).toPromise(); const newValue = convertFSValue(instanceValue, fieldType); setRecoilExternalState(fieldAtom(fieldPath), newValue); };
the_stack
import 'mocha'; import { strictEqual } from 'assert'; const { format } = require('assertion-error-formatter'); // eslint-disable-line @typescript-eslint/no-var-requires import { AssertionError } from '../../src/errors'; import { ErrorSerialiser, parse } from '../../src/io'; import { expect } from '../expect'; describe ('ErrorSerialiser', () => { describe('when serialising errors to JSON', () => { /** @test {ErrorSerialiser} */ it('works with Error objects', () => { const error = thrown(new Error(`Something happened`)); expect(ErrorSerialiser.serialise(error)).to.equal(JSON.stringify({ name: 'Error', stack: error.stack, message: 'Something happened', })); }); /** @test {ErrorSerialiser} */ it('serialises all fields of custom objects that extend Error', () => { const error = thrown(new AssertionError(`Expected false to equal true`, true, false)); const serialised = ErrorSerialiser.serialise(error), deserialised = parse(serialised); expect(deserialised.name).to.equal('AssertionError'); expect(deserialised.message).to.equal('Expected false to equal true'); expect(deserialised.expected).to.equal(true); expect(deserialised.actual).to.equal(false); expect(deserialised.stack).to.equal(error.stack); }); /** @test {ErrorSerialiser} */ it('serialises all fields of a Node.js AssertionError', () => { const error = caught(() => strictEqual(true, false)); const serialised = ErrorSerialiser.serialise(error), deserialised = parse(serialised); expect(deserialised.name).to.equal('AssertionError'); expect(deserialised.message).to.equal('Expected values to be strictly equal:\n\ntrue !== false\n'); expect(deserialised.expected).to.equal(false); expect(deserialised.actual).to.equal(true); expect(deserialised.stack).to.equal(error.stack); }); }); describe('when deserialising errors from JSON', () => { /** @test {ErrorSerialiser} */ it('deserialises an Error', () => { const stack = [ 'Error: Something happened', ' at /app/index.js:38:20', ' at Generator.next (<anonymous>)', ].join('\n'); const error = ErrorSerialiser.deserialise(JSON.stringify({ name: 'Error', message: 'Something happened', stack, })); expect(error).to.be.instanceOf(Error); expect(error.name).to.equal(`Error`); expect(error.message).to.equal(`Something happened`); expect(error.stack).to.equal(stack); }); /** @test {ErrorSerialiser} */ it('deserialises a custom AssertionError to Serenity/JS AssertionError, including all its fields', () => { const stack = [ 'AssertionError: Expected false to equal true', ' at /app/index.js:38:20', ' at Generator.next (<anonymous>)', ].join('\n'); const error = ErrorSerialiser.deserialise(JSON.stringify({ name: 'AssertionError', message: 'Expected false to equal true', expected: true, actual: false, stack, })) as AssertionError; expect(error).to.be.instanceOf(AssertionError); expect(error.name).to.equal(`AssertionError`); expect(error.message).to.equal(`Expected false to equal true`); expect(error.expected).to.equal(true); expect(error.actual).to.equal(false); expect(error.stack).to.equal(stack); }); /** @test {ErrorSerialiser} */ it('deserialises Node.js AssertionError as Serenity/JS AssertionError', () => { const error = caught(() => strictEqual(true, false)); const deserialised = ErrorSerialiser.deserialise(ErrorSerialiser.serialise(error)) as AssertionError; expect(deserialised).to.be.instanceOf(AssertionError); expect(deserialised.name).to.equal(`AssertionError`); expect(deserialised.message).to.match(/Expected.*strictly equal/); expect(deserialised.expected).to.equal(false); expect(deserialised.actual).to.equal(true); }); }); describe('when deserialising errors from stack trace', () => { /** @test {ErrorSerialiser} */ it('works with standard Error objects (Cucumber event protocol)', () => { const stack = `Error: Something's wrong\n at World.<anonymous> (features/step_definitions/synchronous.steps.ts:9:15)`; const error: Error = ErrorSerialiser.deserialiseFromStackTrace(stack); expect(error).to.be.instanceOf(Error); expect(error.name).to.equal(`Error`); expect(error.message).to.equal(`Something's wrong`); expect(error.stack).to.equal(stack); }); /** @test {ErrorSerialiser} */ it('instantiates an Error object from a string (Cucumber event protocol)', () => { const stack = `function has 2 arguments, should have 3 (if synchronous or returning a promise) or 4 (if accepting a callback)`; const error: Error = ErrorSerialiser.deserialiseFromStackTrace(stack); expect(error).to.be.instanceOf(Error); expect(error.name).to.equal(`Error`); expect(error.message).to.equal(`function has 2 arguments, should have 3 (if synchronous or returning a promise) or 4 (if accepting a callback)`); }); /** @test {ErrorSerialiser} */ it('instantiates a Serenity/JS AssertionError from an AssertionError-like stack trace, as well as it can', () => { const error = caught(() => strictEqual(true, false)); const deserialised = ErrorSerialiser.deserialiseFromStackTrace(error.stack) as AssertionError; expect(deserialised).to.be.instanceOf(AssertionError); expect(deserialised.name).to.equal(`AssertionError`); expect(deserialised.message).to.match(/Expected.*strictly equal/); // todo: we have no way of knowing either of those two fields from the stack trace alone expect(deserialised.actual).to.equal(undefined); expect(deserialised.expected).to.equal(undefined); }); }); // Cucumber.js 7 Message Protocol emits pretty-printed stack traces - see https://github.com/cucumber/cucumber-js/issues/1453 describe(`when deserialising a stack trace decorated by Cucumber's assertion-error-formatter`, () => { it('instantiates a standard Error', () => { const error = thrown(new Error('Boom')); const message = format(error); const deserialised = ErrorSerialiser.deserialiseFromStackTrace(message); expect(deserialised).to.be.instanceof(Error); expect(deserialised.message).to.equal(error.message); expect(deserialised.stack).to.equal(error.stack); }); it('instantiates a Serenity/JS AssertionError based on Chai AssertionError, to the best of its ability', () => { const error = caught(() => expect(true).to.equal(false)); const message = format(error); const deserialised = ErrorSerialiser.deserialiseFromStackTrace(message) as AssertionError; expect(deserialised).to.be.instanceof(AssertionError); expect(deserialised.message).to.equal(`+ expected - actual\n\n -true\n +false`); // todo: we have no way of knowing either of those two fields from the stack trace alone expect(deserialised.expected).to.equal(undefined); expect(deserialised.actual).to.equal(undefined); }); it('instantiates a Serenity/JS AssertionError based on Node.js AssertionError, to the best of its ability', () => { const error = caught(() => strictEqual(false, true)); const message = format(error); const deserialised = ErrorSerialiser.deserialiseFromStackTrace(message) as AssertionError; expect(deserialised).to.be.instanceof(AssertionError); expect(deserialised.message).to.equal(`[ERR_ASSERTION]: Expected values to be strictly equal:\n\nfalse !== true\n\n + expected - actual\n\n -false\n +true`); // todo: we have no way of knowing either of those two fields from the stack trace alone expect(deserialised.expected).to.equal(undefined); expect(deserialised.actual).to.equal(undefined); }); it('instantiates a Serenity/JS AssertionError, to the best of its ability', () => { const error = caught(() => { throw new AssertionError('Expected true to equal false', true, false)}) as AssertionError; const message = format(error); const deserialised = ErrorSerialiser.deserialiseFromStackTrace(message) as AssertionError; expect(deserialised).to.be.instanceof(AssertionError); expect(deserialised.message).to.equal(`Expected true to equal false\n + expected - actual\n\n -false\n +true`); // todo: we have no way of knowing either of those two fields from the stack trace alone expect(deserialised.expected).to.equal(undefined); expect(deserialised.actual).to.equal(undefined); }); }); }); function thrown<T>(throwable: T): T { try { throw throwable; } catch (error) { return error; } } function caught(fn: () => void) { try { fn(); } catch (error) { return error; } }
the_stack
import type { Color as MuiColorShades } from '@material-ui/core'; import type { PartialDeep, Merge } from 'type-fest' declare global { type BreakpointName = "xs"|"sm"|"md"|"lg"|"xl"|"tiny" type ColorString = string; type ThemeGreyscale = MuiColorShades & { 0: ColorString, 1000: ColorString, 10: ColorString, 20: ColorString, 25: ColorString, 30: ColorString, 40: ColorString, 55: ColorString, 60: ColorString, 110: ColorString, 120: ColorString, 140: ColorString, 250: ColorString, 310: ColorString, 315: ColorString, 320: ColorString, 340: ColorString, 410: ColorString, 550: ColorString, 620: ColorString, 650: ColorString, 680: ColorString, } type ThemeShadePalette = { grey: MuiColorShades, greyAlpha: (alpha: number) => ColorString, boxShadowColor: (alpha: number) => ColorString, greyBorder: (thickness: string, alpha: number) => string, fonts: { sansSerifStack: string, serifStack: string, }, // Used by material-UI for picking some of its own colors, and also by site // themes type: "light"|"dark", } type ThemeComponentPalette = { primary: { main: ColorString, light: ColorString, dark: ColorString, contrastText: ColorString }, secondary: { main: ColorString, light: ColorString, dark: ColorString, //UNUSED contrastText: ColorString }, lwTertiary: { main: ColorString, dark: ColorString }, error: { main: ColorString, light: ColorString, dark: ColorString contrastText: ColorString, //UNUSED }, text: { primary: ColorString, secondary: ColorString normal: ColorString, maxIntensity: ColorString, slightlyIntense: ColorString, slightlyIntense2: ColorString, slightlyDim: ColorString, slightlyDim2: ColorString, dim: ColorString, dim2: ColorString, dim3: ColorString, dim4: ColorString, dim40: ColorString, dim45: ColorString, dim55: ColorString, dim60: ColorString, grey: ColorString, dim700: ColorString, spoilerBlockNotice: ColorString, notificationCount: ColorString, notificationLabel: ColorString, eventType: ColorString, tooltipText: ColorString, negativeKarmaRed: ColorString, moderationGuidelinesEasygoing: ColorString, moderationGuidelinesNormEnforcing: ColorString, moderationGuidelinesReignOfTerror: ColorString, charsAdded: ColorString, charsRemoved: ColorString, invertedBackgroundText: ColorString, invertedBackgroundText2: ColorString, invertedBackgroundText3: ColorString, invertedBackgroundText4: ColorString, error: ColorString, error2: ColorString, red: ColorString, sequenceIsDraft: ColorString, sequenceTitlePlaceholder: ColorString, reviewUpvote: ColorString, reviewDownvote: ColorString, aprilFools: { orange: ColorString, yellow: ColorString, green: ColorString, }, }, linkHover: { dim: ColorString, }, link: { unmarked: ColorString, dim: ColorString, dim2: ColorString, dim3: ColorString, grey800: ColorString, tocLink: ColorString, tocLinkHighlighted: ColorString, }, icon: { normal: ColorString, maxIntensity: ColorString, slightlyDim: ColorString, slightlyDim2: ColorString, slightlyDim3: ColorString, slightlyDim4: ColorString, dim: ColorString, dim2: ColorString, dim3: ColorString, dim4: ColorString, dim5: ColorString, dim6: ColorString, dim600: ColorString, dim700: ColorString, dim55: ColorString, tooltipUserMetric: ColorString, loadingDots: ColorString, loadingDotsAlternate: ColorString, horizRuleDots: ColorString, greenCheckmark: ColorString, onTooltip: ColorString, inverted: ColorString, topAuthor: ColorString, navigationSidebarIcon: ColorString, commentsBubble: { commentCount: ColorString, noUnread: ColorString, newPromoted: ColorString, }, }, border: { normal: string, itemSeparatorBottom: string, slightlyFaint: string, extraFaint: string, slightlyIntense: string, slightlyIntense2: string, slightlyIntense3: string, intense: string, faint: string, grey300: string, grey400: string, maxIntensity: string, tableHeadingDivider: string, table: string, tableCell: string, transparent: string, emailHR: string, sunshineNewUsersInfoHR: string, appBarSubtitleDivider: string, commentBorder: string, answerBorder: string, tooltipHR: string, }, panelBackground: { default: ColorString, translucent: ColorString, translucent2: ColorString, translucent3: ColorString, hoverHighlightGrey: ColorString, postsItemHover: ColorString, formErrors: ColorString, darken02: ColorString, darken03: ColorString, darken04: ColorString, darken05: ColorString, darken08: ColorString, darken10: ColorString, darken15: ColorString, darken20: ColorString, darken25: ColorString, darken40: ColorString, adminHomeRecentLogins: ColorString, adminHomeAllUsers: ColorString, deletedComment: ColorString, newCommentFormModerationGuidelines: ColorString, commentNodeEven: ColorString, commentNodeOdd: ColorString, commentModeratorHat: ColorString, commentHighlightAnimation: ColorString, postsItemExpandedComments: ColorString, metaculusBackground: ColorString, spoilerBlock: ColorString, revealedSpoilerBlock: ColorString, tableHeading: ColorString, notificationMenuTabBar: ColorString, recentDiscussionThread: ColorString, tooltipBackground: ColorString, tenPercent: ColorString, sunshineReportedContent: ColorString, sunshineFlaggedUser: ColorString, sunshineNewPosts: ColorString, sunshineNewComments: ColorString, sunshineNewTags: ColorString, sunshineWarningHighlight: ColorString, mobileNavFooter: ColorString, singleLineComment: ColorString, singleLineCommentHovered: ColorString, singleLineCommentOddHovered: ColorString, sequenceImageGradient: string, sequencesBanner: ColorString, }, boxShadow: { default: string, moreFocused: string, faint: string, notificationsDrawer: string, appBar: string, sequencesGridItemHover: string, eventCard: string, mozillaHubPreview: string, featuredResourcesCard: string, spreadsheetPage1: string, spreadsheetPage2: string, collectionsCardHover: string, comment: string, sunshineSidebarHoverInfo: string, sunshineSendMessage: string, lwCard: string, searchResults: string, recentDiscussionMeetupsPoke: string, }, buttons: { hoverGrayHighlight: ColorString, startReadingButtonBackground: ColorString, recentDiscussionSubscribeButtonText: ColorString, featuredResourceCTAtext: ColorString, primaryDarkText: ColorString, feedExpandButton: { background: ColorString, plusSign: ColorString, border: string, }, notificationsBellOpen: { background: ColorString, icon: ColorString, }, groupTypesMultiselect: { background: ColorString, hoverBackground: ColorString, }, imageUpload: { background: ColorString, hoverBackground: ColorString, }, bookCheckoutButton: ColorString, eventCardTag: ColorString, }, tag: { background: ColorString, border: string, coreTagBorder: string, text: ColorString, boxShadow: string, hollowTagBackground: ColorString, addTagButtonBackground: ColorString, }, geosuggest: { dropdownBackground: ColorString, dropdownText: ColorString, dropdownActiveBackground: ColorString, dropdownActiveText: ColorString, dropdownHoveredBackground: ColorString, dropdownActiveHoveredBackground: ColorString, }, review: { activeProgress: ColorString, progressBar: ColorString, adminButton: ColorString, }, background: { default: ColorString paper: ColorString, pageActiveAreaBackground: ColorString, diffInserted: ColorString, diffDeleted: ColorString, usersListItem: ColorString, }, header: { text: ColorString, background: ColorString, }, datePicker: { selectedDate: ColorString, }, intercom?: { //Optional. If omitted, use defaults from library. buttonBackground: ColorString, }, group: ColorString, contrastText: ColorString, individual: ColorString, event: ColorString, commentParentScrollerHover: ColorString, tocScrollbarColors: string, eventsHomeLoadMoreHover: ColorString, eaForumGroupsMobileImg: ColorString, }; type ThemePalette = Merge<ThemeShadePalette,ThemeComponentPalette> type ThemeType = { breakpoints: { down: (breakpoint: BreakpointName|number)=>string, up: (breakpoint: BreakpointName|number)=>string, values: Record<BreakpointName,number>, }, spacing: { unit: number, titleDividerSpacing: number, }, palette: ThemePalette, typography: { fontFamily: string, fontDownloads: string[], postStyle: JssStyles, commentStyle: JssStyles, commentStyles: JssStyles, commentBlockquote: JssStyles, commentHeader: JssStyles, errorStyle: JssStyles, title: JssStyles, subtitle: JssStyles, li: JssStyles, display0: JssStyles, display1: JssStyles, display2: JssStyles, display3: JssStyles, display4: JssStyles, body1: JssStyles, body2: JssStyles, headline: JssStyles, subheading: JssStyles, headerStyle: JssStyles, code: JssStyles, codeblock: JssStyles, contentNotice: JssStyles, uiSecondary: JssStyles, smallFont: JssStyles, smallText: JssStyles, tinyText: JssStyles, caption: JssStyles, blockquote: JssStyles, uiStyle: JssStyles, }, zIndexes: any, overrides: any, postImageStyles: JssStyles, voting: {strongVoteDelay: number}, secondary: any, // Used by material-UI. Not used by us directly (for our styles use // `theme.palette.boxShadow` which defines shadows semantically rather than // with an arbitrary darkness number) shadows: string[], rawCSS: string[], }; type BaseThemeSpecification = { shadePalette: ThemeShadePalette, componentPalette: (shadePalette: ThemeShadePalette) => ThemeComponentPalette, make: (palette: ThemePalette) => PartialDeep<Omit<ThemeType,"palette">> }; type SiteThemeSpecification = { shadePalette?: PartialDeep<ThemeShadePalette>, componentPalette?: (shadePalette: ThemeShadePalette) => PartialDeep<ThemeComponentPalette>, make?: (palette: ThemePalette) => PartialDeep<Omit<ThemeType,"palette">> }; type UserThemeSpecification = { shadePalette?: PartialDeep<ThemeShadePalette>, componentPalette?: (shadePalette: ThemeShadePalette) => PartialDeep<ThemeComponentPalette>, make?: (palette: ThemePalette) => PartialDeep<Omit<ThemeType,"palette">> }; }
the_stack
import bezierEasing from 'bezier-easing' import { Keyframe, KeyframeValueTypes } from '../Entity' import ColorRGB from '../Values/ColorRGB' import ColorRGBA from '../Values/ColorRGBA' import { AnyParameterTypeDescriptor, TypeDescriptor } from '../PluginSupport/TypeDescriptor' import { AssetPointer } from '../Values' interface KeyFrameLink<T extends KeyframeValueTypes> { previous: Keyframe<T> | null active: Keyframe<T> next: Keyframe<T> | null } export interface KeyframeParamValueSequence { [frame: number]: KeyframeValueTypes } export function calcKeyframesAt( frame: number, clipPlacedFrame: number, descriptor: TypeDescriptor, keyframes: { [paramName: string]: ReadonlyArray<Keyframe> }, ): { [paramName: string]: KeyframeValueTypes } { return descriptor.properties .map<[string, KeyframeValueTypes]>(desc => { return [desc.paramName, calcKeyframeAt(frame, clipPlacedFrame, desc, keyframes[desc.paramName] || [])] }) .reduce((values, entry) => { values[entry[0]] = entry[1] return values }, Object.create(null)) } export function calcKeyframeAt( frame: number, clipPlacedFrame: number, desc: AnyParameterTypeDescriptor, keyframes: ReadonlyArray<Keyframe>, ): KeyframeValueTypes { switch (desc.type) { // case 'POINT_2D': // return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcPoint2dKeyFrames)[frame] // case 'POINT_3D': // return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcPoint3dKeyFrames)[frame] // case 'SIZE_2D': // return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcSize2dKeyFrames)[frame] // case 'SIZE_3D': // return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcSize3dKeyFrames)[frame] case 'COLOR_RGB': return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcColorRgbKeyFrames)[frame] case 'COLOR_RGBA': return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcColorRgbaKeyFrames)[frame] case 'BOOL': return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcBoolKeyFrames)[frame] case 'STRING': return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcStringKeyFrames)[frame] case 'NUMBER': return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcNumberKeyFrames)[frame] case 'FLOAT': return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcFloatKeyFrames)[frame] case 'ENUM': return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcEnumKeyFrames)[frame] case 'CODE': return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcNonAnimatableKeyframes)[frame] // case 'CLIP': // return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcNoAnimatable)[frame] // case 'PULSE': // return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcPulseKeyFrames)[frame] // case 'ARRAY': // return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcArrayOfKeyFrames)[frame] case 'ASSET': return calcKeyframe(desc, keyframes, clipPlacedFrame, frame, 1, calcAssetKeyFrames)[frame] default: throw new Error('Unsupported parameter type') } } export function calcKeyframesInRange( paramTypes: TypeDescriptor | AnyParameterTypeDescriptor[], keyFrames: { [paramName: string]: ReadonlyArray<Keyframe> }, clipPlacedFrame: number, beginFrame: number, calcFrames: number, ): { [paramName: string]: KeyframeParamValueSequence } { const tables: { [paramName: string]: KeyframeParamValueSequence } = {} const params = paramTypes instanceof TypeDescriptor ? paramTypes.properties : paramTypes for (const paramDesc of params) { const { paramName } = paramDesc const propSequence = keyFrames[paramName] || [] switch (paramDesc.type) { // case 'POINT_2D': // tables[paramName] = calcKeyframe(propDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcPoint2dKeyFrames) // break // case 'POINT_3D': // tables[paramName] = calcKeyframe(propDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcPoint3dKeyFrames) // break // case 'SIZE_2D': // tables[paramName] = calcKeyframe(propDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcSize2dKeyFrames) // break // case 'SIZE_3D': // tables[paramName] = calcKeyframe(propDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcSize3dKeyFrames) // break case 'COLOR_RGB': tables[paramName] = calcKeyframe( paramDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcColorRgbKeyFrames, ) break case 'COLOR_RGBA': tables[paramName] = calcKeyframe( paramDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcColorRgbaKeyFrames, ) break case 'BOOL': tables[paramName] = calcKeyframe( paramDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcBoolKeyFrames, ) break case 'STRING': tables[paramName] = calcKeyframe( paramDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcStringKeyFrames, ) break case 'NUMBER': tables[paramName] = calcKeyframe( paramDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcNumberKeyFrames, ) break case 'FLOAT': tables[paramName] = calcKeyframe( paramDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcFloatKeyFrames, ) break case 'ENUM': tables[paramName] = calcKeyframe( paramDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcEnumKeyFrames, ) break // case 'CLIP': // tables[paramName] = calcKeyframe(propDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcNoAnimatable) // break // case 'PULSE': // tables[paramName] = calcKeyframe(propDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcPulseKeyFrames) // break // case 'ARRAY': // tables[paramName] = calcKeyframe(propDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcArrayOfKeyFrames) // break case 'ASSET': tables[paramName] = calcKeyframe( paramDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcAssetKeyFrames, ) break case 'CODE': tables[paramName] = calcKeyframe( paramDesc, propSequence, clipPlacedFrame, beginFrame, calcFrames, calcNonAnimatableKeyframes, ) break } } return tables } function calcKeyframe( propDesc: AnyParameterTypeDescriptor, keyFrameSequense: ReadonlyArray<Keyframe>, clipPlacedFrame: number, beginFrame: number, calcFrames: number, transformer: (rate: number, frame: number, keyFrameLink: KeyFrameLink<KeyframeValueTypes>) => any, ): KeyframeParamValueSequence { const orderedSequense: Keyframe[] = keyFrameSequense.slice(0).sort((kfA, kfB) => kfA.frameOnClip - kfB.frameOnClip) const linkedSequense: KeyFrameLink<KeyframeValueTypes>[] = _buildLinkedKeyFrame(orderedSequense) const table: KeyframeParamValueSequence = {} for (let frame = beginFrame, end = beginFrame + calcFrames; frame <= end; frame++) { const activeKeyFrame: KeyFrameLink<KeyframeValueTypes> | null = activeKeyFrameOfFrame( linkedSequense, clipPlacedFrame, frame, ) if (activeKeyFrame == null) { // 0 10 20 // | | | // -> if keyframes empty use defaultValue table[frame] = propDesc.defaultValue?.() ?? null continue } if (activeKeyFrame.previous == null && frame < clipPlacedFrame + activeKeyFrame.active.frameOnClip) { // [0] 10 20 // ◇ ◇ // -> use 10frame's value at frame 0 table[frame] = activeKeyFrame.active.value continue } if (activeKeyFrame.next == null && frame >= clipPlacedFrame + activeKeyFrame.active.frameOnClip) { // 0 [10] // ◇ | // -> use 0frame's value at frame 10 table[frame] = activeKeyFrame.active.value continue } const currentKeyEaseOut = activeKeyFrame.active.easeOutParam ? activeKeyFrame.active.easeOutParam : [0, 0] const nextKeyEaseIn = activeKeyFrame.next ? activeKeyFrame.next.easeInParam || [1, 1] : [1, 2] // TODO: Cache Bezier instance between change active keyframe const bezier = bezierEasing(currentKeyEaseOut[0], currentKeyEaseOut[1], nextKeyEaseIn[0], nextKeyEaseIn[1]) const progressRate = activeKeyFrame.next ? (frame - (clipPlacedFrame + activeKeyFrame.active.frameOnClip)) / (clipPlacedFrame + activeKeyFrame.next.frameOnClip - (clipPlacedFrame + activeKeyFrame.active.frameOnClip)) : 1 table[frame] = transformer(bezier(progressRate), frame, activeKeyFrame) if (propDesc.animatable === false) { break } } return table } function _buildLinkedKeyFrame(orderedKeyFrameSeq: Keyframe[]): KeyFrameLink<KeyframeValueTypes>[] { const linked = [] const placedFrames = (Object.keys(orderedKeyFrameSeq) as any[]) as number[] for (let idx = 0, l = placedFrames.length; idx < l; idx++) { linked.push({ previous: orderedKeyFrameSeq[placedFrames[idx - 1]], active: orderedKeyFrameSeq[placedFrames[idx]], next: orderedKeyFrameSeq[placedFrames[idx + 1]], }) } return linked } function activeKeyFrameOfFrame( linkedKeyFrameSeq: KeyFrameLink<KeyframeValueTypes>[], clipPlacedFrame: number, frame: number, ): KeyFrameLink<KeyframeValueTypes> | null { if (linkedKeyFrameSeq.length === 1) { return linkedKeyFrameSeq[0] } for (const keyFrameLink of linkedKeyFrameSeq) { if ( keyFrameLink.next == null || (clipPlacedFrame + keyFrameLink.active.frameOnClip <= frame && frame < clipPlacedFrame + keyFrameLink.next.frameOnClip) || (keyFrameLink.previous == null && frame < clipPlacedFrame + keyFrameLink.active.frameOnClip) ) { return keyFrameLink } } return null } // // Typed keyframe calculators // // function calcPoint2dKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<Point2D>): {x: number, y: number} // { // const xVector = keyFrameLink.next!.value!.x - keyFrameLink.active.value!.x // const yVector = keyFrameLink.next!.value!.y - keyFrameLink.active.value!.y // return { // x: keyFrameLink.active.value!.x + (xVector * rate), // y: keyFrameLink.active.value!.y + (yVector * rate), // } // } // function calcPoint3dKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<Point3D>): {x: number, y: number, z: number} // { // const xVector = keyFrameLink.next!.value!.x - keyFrameLink.active.value!.x // const yVector = keyFrameLink.next!.value!.y - keyFrameLink.active.value!.y // const zVector = keyFrameLink.next!.value!.z - keyFrameLink.active.value!.z // return { // x: keyFrameLink.active.value!.x + (xVector * rate), // y: keyFrameLink.active.value!.y + (yVector * rate), // z: keyFrameLink.active.value!.z + (zVector * rate), // } // } // function calcSize2dKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<Size2D>): {width: number, height: number} // { // const widthVector = keyFrameLink.next!.value!.width - keyFrameLink.active.value!.width // const heightVector = keyFrameLink.next!.value!.height - keyFrameLink.active.value!.height // return { // width: keyFrameLink.active.value!.width + (widthVector * rate), // height: keyFrameLink.active.value!.height + (heightVector * rate), // } // } // function calcSize3dKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<Size3D>): {width: number, height: number, depth: number} // { // const widthVector = keyFrameLink.next!.value!.width - keyFrameLink.active.value!.width // const heightVector = keyFrameLink.next!.value!.height - keyFrameLink.active.value!.height // const depthVector = keyFrameLink.next!.value!.depth - keyFrameLink.active.value!.depth // return { // width: keyFrameLink.active.value!.width + (widthVector * rate), // height: keyFrameLink.active.value!.height + (heightVector * rate), // depth: keyFrameLink.active.value!.depth + (depthVector * rate), // } // } function calcColorRgbKeyFrames( rate: number, frame: number, keyFrameLink: KeyFrameLink<ColorRGB>, ): { red: number; green: number; blue: number } { const redVector = keyFrameLink.next!.value!.red - keyFrameLink.active.value!.red const greenVector = keyFrameLink.next!.value!.green - keyFrameLink.active.value!.green const blueVector = keyFrameLink.next!.value!.blue - keyFrameLink.active.value!.blue return new ColorRGB( keyFrameLink.active.value!.red + redVector * rate, keyFrameLink.active.value!.green + greenVector * rate, keyFrameLink.active.value!.blue + blueVector * rate, ) } function calcColorRgbaKeyFrames( rate: number, frame: number, keyFrameLink: KeyFrameLink<ColorRGBA>, ): { red: number; green: number; blue: number; alpha: number } { const redVector = keyFrameLink.next!.value!.red - keyFrameLink.active.value!.red const greenVector = keyFrameLink.next!.value!.green - keyFrameLink.active.value!.green const blueVector = keyFrameLink.next!.value!.blue - keyFrameLink.active.value!.blue const alphaVector = keyFrameLink.next!.value!.alpha - keyFrameLink.active.value!.alpha return new ColorRGBA( keyFrameLink.active.value!.red + redVector * rate, keyFrameLink.active.value!.green + greenVector * rate, keyFrameLink.active.value!.blue + blueVector * rate, keyFrameLink.active.value!.alpha + alphaVector * rate, ) } function calcBoolKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<boolean>): boolean { return keyFrameLink.previous ? !!keyFrameLink.previous.value : !!keyFrameLink.active.value } function calcStringKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<string>): string { return keyFrameLink.active!.value as string } function calcNumberKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<number>): number { const numVector = (keyFrameLink.next!.value as number) - (keyFrameLink.active!.value as number) return Math.round((keyFrameLink.active!.value as number) + numVector * rate) } function calcFloatKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<number>): number { const floatVector = (keyFrameLink.next!.value as number) - (keyFrameLink.active!.value! as number) return (keyFrameLink.active.value as number) + floatVector * rate } function calcPulseKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<any>): boolean { return keyFrameLink.active.frameOnClip === frame ? true : false } function calcEnumKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<string>): any { return keyFrameLink.previous ? keyFrameLink.previous.value : keyFrameLink.active.value } // function calcClipKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink): any // TODO: Typing // { // return keyFrameLink.previous ? keyFrameLink.previous.value : keyFrameLink.active.value // } function calcAssetKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink<AssetPointer>): AssetPointer { return keyFrameLink.previous ? (keyFrameLink.previous.value! as AssetPointer) : (keyFrameLink.active!.value as AssetPointer) } function calcNonAnimatableKeyframes(rate: number, frame: number, keyFrameLink: KeyFrameLink<any>): any { return keyFrameLink.active.value } // function calcArrayOfKeyFrames(rate: number, frame: number, keyFrameLink: KeyFrameLink): any // TODO: Typing // { // }
the_stack
module android.widget { import R = android.R; import Resources = android.content.res.Resources; import Context = android.content.Context; import PixelFormat = android.graphics.PixelFormat; import Rect = android.graphics.Rect; import Drawable = android.graphics.drawable.Drawable; import StateListDrawable = android.graphics.drawable.StateListDrawable; import Gravity = android.view.Gravity; import KeyEvent = android.view.KeyEvent; import MotionEvent = android.view.MotionEvent; import View = android.view.View; import OnTouchListener = android.view.View.OnTouchListener; import ViewGroup = android.view.ViewGroup; import ViewTreeObserver = android.view.ViewTreeObserver; import OnScrollChangedListener = android.view.ViewTreeObserver.OnScrollChangedListener; import WindowManager = android.view.WindowManager; import Window = android.view.Window; import Animation = android.view.animation.Animation; import WeakReference = java.lang.ref.WeakReference; import Integer = java.lang.Integer; import FrameLayout = android.widget.FrameLayout; import Spinner = android.widget.Spinner; import TextView = android.widget.TextView; import AnimationUtils = android.view.animation.AnimationUtils; /** * <p>A popup window that can be used to display an arbitrary view. The popup * window is a floating container that appears on top of the current * activity.</p> * * @see android.widget.AutoCompleteTextView * @see android.widget.Spinner */ export class PopupWindow implements Window.Callback{ /** * Mode for {@link #setInputMethodMode(int)}: the requirements for the * input method should be based on the focusability of the popup. That is * if it is focusable than it needs to work with the input method, else * it doesn't. */ static INPUT_METHOD_FROM_FOCUSABLE:number = 0; /** * Mode for {@link #setInputMethodMode(int)}: this popup always needs to * work with an input method, regardless of whether it is focusable. This * means that it will always be displayed so that the user can also operate * the input method while it is shown. */ static INPUT_METHOD_NEEDED:number = 1; /** * Mode for {@link #setInputMethodMode(int)}: this popup never needs to * work with an input method, regardless of whether it is focusable. This * means that it will always be displayed to use as much space on the * screen as needed, regardless of whether this covers the input method. */ static INPUT_METHOD_NOT_NEEDED:number = 2; private static DEFAULT_ANCHORED_GRAVITY:number = Gravity.TOP | Gravity.START; private mContext:Context; private mWindowManager:WindowManager; private mIsShowing:boolean; private mIsDropdown:boolean; private mContentView:View; private mPopupView:View; private mPopupWindow:Window; private mFocusable:boolean; private mInputMethodMode:number = PopupWindow.INPUT_METHOD_FROM_FOCUSABLE; //private mSoftInputMode:number = WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED; private mTouchable:boolean = true; private mOutsideTouchable:boolean = false; //private mClippingEnabled:boolean = true; private mSplitTouchEnabled:number = -1; //private mLayoutInScreen:boolean; private mClipToScreen:boolean; private mAllowScrollingAnchorParent:boolean = true; //private mLayoutInsetDecor:boolean = false; private mNotTouchModal:boolean; private mTouchInterceptor:OnTouchListener; private mWidthMode:number; private mWidth:number; private mLastWidth:number; private mHeightMode:number; private mHeight:number; private mLastHeight:number; private mPopupWidth:number; private mPopupHeight:number; private mDrawingLocation:number[] = [0, 0]; private mScreenLocation:number[] = [0, 0]; private mTempRect:Rect = new Rect(); private mBackground:Drawable; private mAboveAnchorBackgroundDrawable:Drawable; private mBelowAnchorBackgroundDrawable:Drawable; private mAboveAnchor:boolean; private mWindowLayoutType:number = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL; private mOnDismissListener:PopupWindow.OnDismissListener; //private mIgnoreCheekPress:boolean = false; private mDefaultDropdownAboveEnterAnimation = R.anim.grow_fade_in_from_bottom; private mDefaultDropdownBelowEnterAnimation = R.anim.grow_fade_in; private mDefaultDropdownAboveExitAnimation = R.anim.shrink_fade_out_from_bottom; private mDefaultDropdownBelowExitAnimation = R.anim.shrink_fade_out; private mEnterAnimation:Animation; private mExitAnimation:Animation; //private static ABOVE_ANCHOR_STATE_SET:number[] = [ com.android.internal.R.attr.state_above_anchor ]; private mAnchor:WeakReference<View>; private mOnScrollChangedListener:ViewTreeObserver.OnScrollChangedListener = (()=>{ const inner_this=this; class _Inner implements ViewTreeObserver.OnScrollChangedListener { onScrollChanged():void { let anchor:View = inner_this.mAnchor != null ? inner_this.mAnchor.get() : null; if (anchor != null && inner_this.mPopupView != null) { let p:WindowManager.LayoutParams = <WindowManager.LayoutParams> inner_this.mPopupView.getLayoutParams(); inner_this.updateAboveAnchor(inner_this.findDropDownPosition(anchor, p, inner_this.mAnchorXoff, inner_this.mAnchorYoff, inner_this.mAnchoredGravity)); inner_this.update(p.x, p.y, -1, -1, true); } } } return new _Inner(); })(); private mAnchorXoff:number; private mAnchorYoff:number; private mAnchoredGravity:number; private mPopupViewInitialLayoutDirectionInherited:boolean; /** * <p>Create a new popup window which can display the <tt>contentView</tt>. * The dimension of the window must be passed to this constructor.</p> * * <p>The popup does not provide any background. This should be handled * by the content view.</p> * * @param contentView the popup's content * @param width the popup's width * @param height the popup's height * @param focusable true if the popup can be focused, false otherwise */ constructor(contentView:View, width?:number, height?:number, focusable?:boolean); /** * <p>Create a new, empty, non focusable popup window of dimension (0,0).</p> * * <p>The popup does not provide a background.</p> */ constructor(context:Context, styleAttr?:Map<string, string>); constructor(...args) { if(args[0] instanceof Context) { let context = <Context>args[0]; let styleAttr = args.length==1 ? R.attr.popupWindowStyle : args[1]; this.mContext = context; this.mWindowManager = context.getWindowManager();//<WindowManager> context.getSystemService(Context.WINDOW_SERVICE); this.mPopupWindow = new Window(context); this.mPopupWindow.setCallback(this); let a = context.obtainStyledAttributes(null, styleAttr); this.mBackground = a.getDrawable('popupBackground'); this.mEnterAnimation = AnimationUtils.loadAnimation(context, a.getAttrValue('popupEnterAnimation')); this.mExitAnimation = AnimationUtils.loadAnimation(context, a.getAttrValue('popupExitAnimation')); // at least one other drawable, intended for the 'below-anchor state'. //if (this.mBackground instanceof StateListDrawable) { // let background:StateListDrawable = <StateListDrawable> this.mBackground; // // Find the above-anchor view - this one's easy, it should be labeled as such. // let aboveAnchorStateIndex:number = background.getStateDrawableIndex(PopupWindow.ABOVE_ANCHOR_STATE_SET); // // Now, for the below-anchor view, look for any other drawable specified in the // // StateListDrawable which is not for the above-anchor state and use that. // let count:number = background.getStateCount(); // let belowAnchorStateIndex:number = -1; // for (let i:number = 0; i < count; i++) { // if (i != aboveAnchorStateIndex) { // belowAnchorStateIndex = i; // break; // } // } // // to null so that we'll just use refreshDrawableState. // if (aboveAnchorStateIndex != -1 && belowAnchorStateIndex != -1) { // this.mAboveAnchorBackgroundDrawable = background.getStateDrawable(aboveAnchorStateIndex); // this.mBelowAnchorBackgroundDrawable = background.getStateDrawable(belowAnchorStateIndex); // } else { // this.mBelowAnchorBackgroundDrawable = null; // this.mAboveAnchorBackgroundDrawable = null; // } //} //a.recycle(); }else{ let [contentView=null, width=0, height=0, focusable=false] = args; if (contentView != null) { this.mContext = contentView.getContext(); this.mWindowManager = this.mContext.getWindowManager();//<WindowManager> this.mContext.getSystemService(Context.WINDOW_SERVICE); this.mPopupWindow = new Window(this.mContext); this.mPopupWindow.setCallback(this); } this.setContentView(contentView); this.setWidth(width); this.setHeight(height); this.setFocusable(focusable); } } /** * <p>Return the drawable used as the popup window's background.</p> * * @return the background drawable or null */ getBackground():Drawable { return this.mBackground; } /** * <p>Change the background drawable for this popup window. The background * can be set to null.</p> * * @param background the popup's background */ setBackgroundDrawable(background:Drawable):void { this.mBackground = background; } /** * <p>Return the animation style to use the popup appears</p> */ getEnterAnimation():Animation { return this.mEnterAnimation; } /** * <p>Return the animation style to use the popup appears</p> */ getExitAnimation():Animation { return this.mExitAnimation; } ///** // * Set the flag on popup to ignore cheek press eventt; by default this flag // * is set to false // * which means the pop wont ignore cheek press dispatch events. // * // * <p>If the popup is showing, calling this method will take effect only // * the next time the popup is shown or through a manual call to one of // * the {@link #update()} methods.</p> // * // * @see #update() // */ //setIgnoreCheekPress():void { // this.mIgnoreCheekPress = true; //} /** * <p>Change the animation style resource for this popup.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @param animationStyle animation style to use when the popup appears * and disappears. Set to -1 for the default animation, 0 for no * animation, or a resource identifier for an explicit animation. * * @see #update() */ setWindowAnimation(enterAnimation:Animation, exitAnimation:Animation):void { this.mEnterAnimation = enterAnimation; this.mExitAnimation = exitAnimation; } /** * <p>Return the view used as the content of the popup window.</p> * * @return a {@link android.view.View} representing the popup's content * * @see #setContentView(android.view.View) */ getContentView():View { return this.mContentView; } /** * <p>Change the popup's content. The content is represented by an instance * of {@link android.view.View}.</p> * * <p>This method has no effect if called when the popup is showing.</p> * * @param contentView the new content for the popup * * @see #getContentView() * @see #isShowing() */ setContentView(contentView:View):void { if (this.isShowing()) { return; } this.mContentView = contentView; if (this.mContext == null && this.mContentView != null) { this.mContext = this.mContentView.getContext(); } if (this.mWindowManager == null && this.mContentView != null) { this.mWindowManager = this.mContext.getWindowManager();//<WindowManager> this.mContext.getSystemService(Context.WINDOW_SERVICE); } if(this.mPopupWindow==null && this.mContext!=null){ this.mPopupWindow = new Window(this.mContext); this.mPopupWindow.setCallback(this); } } /** * Set a callback for all touch events being dispatched to the popup * window. */ setTouchInterceptor(l:OnTouchListener):void { this.mTouchInterceptor = l; } /** * <p>Indicate whether the popup window can grab the focus.</p> * * @return true if the popup is focusable, false otherwise * * @see #setFocusable(boolean) */ isFocusable():boolean { return this.mFocusable; } /** * <p>Changes the focusability of the popup window. When focusable, the * window will grab the focus from the current focused widget if the popup * contains a focusable {@link android.view.View}. By default a popup * window is not focusable.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @param focusable true if the popup should grab focus, false otherwise. * * @see #isFocusable() * @see #isShowing() * @see #update() */ setFocusable(focusable:boolean):void { this.mFocusable = focusable; } /** * Return the current value in {@link #setInputMethodMode(int)}. * * @see #setInputMethodMode(int) */ getInputMethodMode():number { return this.mInputMethodMode; } /** * Control how the popup operates with an input method: one of * {@link #INPUT_METHOD_FROM_FOCUSABLE}, {@link #INPUT_METHOD_NEEDED}, * or {@link #INPUT_METHOD_NOT_NEEDED}. * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @see #getInputMethodMode() * @see #update() */ setInputMethodMode(mode:number):void { this.mInputMethodMode = mode; } ///** // * Sets the operating mode for the soft input area. // * // * @param mode The desired mode, see // * {@link android.view.WindowManager.LayoutParams#softInputMode} // * for the full list // * // * @see android.view.WindowManager.LayoutParams#softInputMode // * @see #getSoftInputMode() // */ //setSoftInputMode(mode:number):void { // this.mSoftInputMode = mode; //} // ///** // * Returns the current value in {@link #setSoftInputMode(int)}. // * // * @see #setSoftInputMode(int) // * @see android.view.WindowManager.LayoutParams#softInputMode // */ //getSoftInputMode():number { // return this.mSoftInputMode; //} /** * <p>Indicates whether the popup window receives touch events.</p> * * @return true if the popup is touchable, false otherwise * * @see #setTouchable(boolean) */ isTouchable():boolean { return this.mTouchable; } /** * <p>Changes the touchability of the popup window. When touchable, the * window will receive touch events, otherwise touch events will go to the * window below it. By default the window is touchable.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @param touchable true if the popup should receive touch events, false otherwise * * @see #isTouchable() * @see #isShowing() * @see #update() */ setTouchable(touchable:boolean):void { this.mTouchable = touchable; } /** * <p>Indicates whether the popup window will be informed of touch events * outside of its window.</p> * * @return true if the popup is outside touchable, false otherwise * * @see #setOutsideTouchable(boolean) */ isOutsideTouchable():boolean { return this.mOutsideTouchable; } /** * <p>Controls whether the pop-up will be informed of touch events outside * of its window. This only makes sense for pop-ups that are touchable * but not focusable, which means touches outside of the window will * be delivered to the window behind. The default is false.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @param touchable true if the popup should receive outside * touch events, false otherwise * * @see #isOutsideTouchable() * @see #isShowing() * @see #update() */ setOutsideTouchable(touchable:boolean):void { this.mOutsideTouchable = touchable; } ///** // * <p>Indicates whether clipping of the popup window is enabled.</p> // * // * @return true if the clipping is enabled, false otherwise // * // * @see #setClippingEnabled(boolean) // */ //isClippingEnabled():boolean { // return this.mClippingEnabled; //} // ///** // * <p>Allows the popup window to extend beyond the bounds of the screen. By default the // * window is clipped to the screen boundaries. Setting this to false will allow windows to be // * accurately positioned.</p> // * // * <p>If the popup is showing, calling this method will take effect only // * the next time the popup is shown or through a manual call to one of // * the {@link #update()} methods.</p> // * // * @param enabled false if the window should be allowed to extend outside of the screen // * @see #isShowing() // * @see #isClippingEnabled() // * @see #update() // */ //setClippingEnabled(enabled:boolean):void { // this.mClippingEnabled = enabled; //} /** * Clip this popup window to the screen, but not to the containing window. * * @param enabled True to clip to the screen. * @hide */ setClipToScreenEnabled(enabled:boolean):void { this.mClipToScreen = enabled; //this.setClippingEnabled(!enabled); } /** * Allow PopupWindow to scroll the anchor's parent to provide more room * for the popup. Enabled by default. * * @param enabled True to scroll the anchor's parent when more room is desired by the popup. */ private setAllowScrollingAnchorParent(enabled:boolean):void { this.mAllowScrollingAnchorParent = enabled; } /** * <p>Indicates whether the popup window supports splitting touches.</p> * * @return true if the touch splitting is enabled, false otherwise * * @see #setSplitTouchEnabled(boolean) */ isSplitTouchEnabled():boolean { if (this.mSplitTouchEnabled < 0 && this.mContext != null) { return true;//this.mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB; } return this.mSplitTouchEnabled == 1; } /** * <p>Allows the popup window to split touches across other windows that also * support split touch. When this flag is false, the first pointer * that goes down determines the window to which all subsequent touches * go until all pointers go up. When this flag is true, each pointer * (not necessarily the first) that goes down determines the window * to which all subsequent touches of that pointer will go until that * pointer goes up thereby enabling touches with multiple pointers * to be split across multiple windows.</p> * * @param enabled true if the split touches should be enabled, false otherwise * @see #isSplitTouchEnabled() */ setSplitTouchEnabled(enabled:boolean):void { this.mSplitTouchEnabled = enabled ? 1 : 0; } ///** // * <p>Indicates whether the popup window will be forced into using absolute screen coordinates // * for positioning.</p> // * // * @return true if the window will always be positioned in screen coordinates. // * @hide // */ //isLayoutInScreenEnabled():boolean { // return this.mLayoutInScreen; //} // ///** // * <p>Allows the popup window to force the flag // * {@link WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN}, overriding default behavior. // * This will cause the popup to be positioned in absolute screen coordinates.</p> // * // * @param enabled true if the popup should always be positioned in screen coordinates // * @hide // */ //setLayoutInScreenEnabled(enabled:boolean):void { // this.mLayoutInScreen = enabled; //} ///** // * Allows the popup window to force the flag // * {@link WindowManager.LayoutParams#FLAG_LAYOUT_INSET_DECOR}, overriding default behavior. // * This will cause the popup to inset its content to account for system windows overlaying // * the screen, such as the status bar. // * // * <p>This will often be combined with {@link #setLayoutInScreenEnabled(boolean)}. // * // * @param enabled true if the popup's views should inset content to account for system windows, // * the way that decor views behave for full-screen windows. // * @hide // */ //setLayoutInsetDecor(enabled:boolean):void { // this.mLayoutInsetDecor = enabled; //} /** * Set the layout type for this window. Should be one of the TYPE constants defined in * {@link WindowManager.LayoutParams}. * * @param layoutType Layout type for this window. * @hide */ setWindowLayoutType(layoutType:number):void { this.mWindowLayoutType = layoutType; } /** * @return The layout type for this window. * @hide */ getWindowLayoutType():number { return this.mWindowLayoutType; } /** * Set whether this window is touch modal or if outside touches will be sent to * other windows behind it. * @hide */ setTouchModal(touchModal:boolean):void { this.mNotTouchModal = !touchModal; } /** * <p>Change the width and height measure specs that are given to the * window manager by the popup. By default these are 0, meaning that * the current width or height is requested as an explicit size from * the window manager. You can supply * {@link ViewGroup.LayoutParams#WRAP_CONTENT} or * {@link ViewGroup.LayoutParams#MATCH_PARENT} to have that measure * spec supplied instead, replacing the absolute width and height that * has been set in the popup.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown.</p> * * @param widthSpec an explicit width measure spec mode, either * {@link ViewGroup.LayoutParams#WRAP_CONTENT}, * {@link ViewGroup.LayoutParams#MATCH_PARENT}, or 0 to use the absolute * width. * @param heightSpec an explicit height measure spec mode, either * {@link ViewGroup.LayoutParams#WRAP_CONTENT}, * {@link ViewGroup.LayoutParams#MATCH_PARENT}, or 0 to use the absolute * height. */ setWindowLayoutMode(widthSpec:number, heightSpec:number):void { this.mWidthMode = widthSpec; this.mHeightMode = heightSpec; } /** * <p>Return this popup's height MeasureSpec</p> * * @return the height MeasureSpec of the popup * * @see #setHeight(int) */ getHeight():number { return this.mHeight; } /** * <p>Change the popup's height MeasureSpec</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown.</p> * * @param height the height MeasureSpec of the popup * * @see #getHeight() * @see #isShowing() */ setHeight(height:number):void { this.mHeight = height; } /** * <p>Return this popup's width MeasureSpec</p> * * @return the width MeasureSpec of the popup * * @see #setWidth(int) */ getWidth():number { return this.mWidth; } /** * <p>Change the popup's width MeasureSpec</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown.</p> * * @param width the width MeasureSpec of the popup * * @see #getWidth() * @see #isShowing() */ setWidth(width:number):void { this.mWidth = width; } /** * <p>Indicate whether this popup window is showing on screen.</p> * * @return true if the popup is showing, false otherwise */ isShowing():boolean { return this.mIsShowing; } /** * <p> * Display the content view in a popup window at the specified location. If the popup window * cannot fit on screen, it will be clipped. See {@link android.view.WindowManager.LayoutParams} * for more information on how gravity and the x and y parameters are related. Specifying * a gravity of {@link android.view.Gravity#NO_GRAVITY} is similar to specifying * <code>Gravity.LEFT | Gravity.TOP</code>. * </p> * * @param parent a parent view to get the {@link android.view.View#getWindowToken()} token from * @param gravity the gravity which controls the placement of the popup window * @param x the popup's x location offset * @param y the popup's y location offset */ showAtLocation(parent:View, gravity:number, x:number, y:number):void { if (this.isShowing() || this.mContentView == null) { return; } this.unregisterForScrollChanged(); this.mIsShowing = true; this.mIsDropdown = false; let p:WindowManager.LayoutParams = this.createPopupLayout(); p.enterAnimation = this.computeWindowEnterAnimation(); p.exitAnimation = this.computeWindowExitAnimation(); this.preparePopup(p); if (gravity == Gravity.NO_GRAVITY) { gravity = Gravity.TOP | Gravity.START; } p.gravity = gravity; p.x = x; p.y = y; if (this.mHeightMode < 0) p.height = this.mLastHeight = this.mHeightMode; if (this.mWidthMode < 0) p.width = this.mLastWidth = this.mWidthMode; this.invokePopup(p); } /** * <p>Display the content view in a popup window anchored to the bottom-left * corner of the anchor view offset by the specified x and y coordinates. * If there is not enough room on screen to show * the popup in its entirety, this method tries to find a parent scroll * view to scroll. If no parent scroll view can be scrolled, the bottom-left * corner of the popup is pinned at the top left corner of the anchor view.</p> * <p>If the view later scrolls to move <code>anchor</code> to a different * location, the popup will be moved correspondingly.</p> * * @param anchor the view on which to pin the popup window * @param xoff A horizontal offset from the anchor in pixels * @param yoff A vertical offset from the anchor in pixels * @param gravity Alignment of the popup relative to the anchor * * @see #dismiss() */ showAsDropDown(anchor:View, xoff=0, yoff=0, gravity=PopupWindow.DEFAULT_ANCHORED_GRAVITY):void { if (this.isShowing() || this.mContentView == null) { return; } this.registerForScrollChanged(anchor, xoff, yoff, gravity); this.mIsShowing = true; this.mIsDropdown = true; let p:WindowManager.LayoutParams = this.createPopupLayout(); this.preparePopup(p); this.updateAboveAnchor(this.findDropDownPosition(anchor, p, xoff, yoff, gravity)); if (this.mHeightMode < 0) p.height = this.mLastHeight = this.mHeightMode; if (this.mWidthMode < 0) p.width = this.mLastWidth = this.mWidthMode; p.enterAnimation = this.computeWindowEnterAnimation(); p.exitAnimation = this.computeWindowExitAnimation(); this.invokePopup(p); } private updateAboveAnchor(aboveAnchor:boolean):void { if (aboveAnchor != this.mAboveAnchor) { this.mAboveAnchor = aboveAnchor; if (this.mBackground != null) { // do the job. if (this.mAboveAnchorBackgroundDrawable != null) { if (this.mAboveAnchor) { this.mPopupView.setBackgroundDrawable(this.mAboveAnchorBackgroundDrawable); } else { this.mPopupView.setBackgroundDrawable(this.mBelowAnchorBackgroundDrawable); } } else { this.mPopupView.refreshDrawableState(); } } } } /** * Indicates whether the popup is showing above (the y coordinate of the popup's bottom * is less than the y coordinate of the anchor) or below the anchor view (the y coordinate * of the popup is greater than y coordinate of the anchor's bottom). * * The value returned * by this method is meaningful only after {@link #showAsDropDown(android.view.View)} * or {@link #showAsDropDown(android.view.View, int, int)} was invoked. * * @return True if this popup is showing above the anchor view, false otherwise. */ isAboveAnchor():boolean { return this.mAboveAnchor; } /** * <p>Prepare the popup by embedding in into a new ViewGroup if the * background drawable is not null. If embedding is required, the layout * parameters' height is mnodified to take into account the background's * padding.</p> * * @param p the layout parameters of the popup's content view */ private preparePopup(p:WindowManager.LayoutParams):void { if (this.mContentView == null || this.mContext == null || this.mWindowManager == null) { throw Error(`new IllegalStateException("You must specify a valid content view by " + "calling setContentView() before attempting to show the popup.")`); } //if (this.mBackground != null) { // const layoutParams:ViewGroup.LayoutParams = this.mContentView.getLayoutParams(); // let height:number = ViewGroup.LayoutParams.MATCH_PARENT; // if (layoutParams != null && layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT) { // height = ViewGroup.LayoutParams.WRAP_CONTENT; // } // // when a background is available, we embed the content view // // within another view that owns the background drawable // let popupViewContainer:PopupWindow.PopupViewContainer = new PopupWindow.PopupViewContainer(this.mContext, this); // let listParams = new PopupWindow.PopupViewContainer.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, height); // popupViewContainer.setBackgroundDrawable(this.mBackground); // popupViewContainer.addView(this.mContentView, listParams); // this.mPopupView = popupViewContainer; //} else { // this.mPopupView = this.mContentView; //} this.mPopupWindow.setContentView(this.mContentView); this.mPopupWindow.setFloating(true); this.mPopupWindow.setBackgroundColor(android.graphics.Color.TRANSPARENT); this.mPopupWindow.setDimAmount(0); this.mPopupView = this.mPopupWindow.getDecorView(); if (this.mBackground != null) { this.mPopupView.setBackground(this.mBackground) } this.mPopupViewInitialLayoutDirectionInherited = false;//(this.mPopupView.getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT); this.mPopupWidth = p.width; this.mPopupHeight = p.height; } /** * <p>Invoke the popup window by adding the content view to the window * manager.</p> * * <p>The content view must be non-null when this method is invoked.</p> * * @param p the layout parameters of the popup's content view */ private invokePopup(p:WindowManager.LayoutParams):void { //if (this.mContext != null) { // p.packageName = this.mContext.getPackageName(); //} //this.mPopupView.setFitsSystemWindows(this.mLayoutInsetDecor); this.setLayoutDirectionFromAnchor(); this.mWindowManager.addWindow(this.mPopupWindow); } private setLayoutDirectionFromAnchor():void { if (this.mAnchor != null) { let anchor:View = this.mAnchor.get(); if (anchor != null && this.mPopupViewInitialLayoutDirectionInherited) { this.mPopupView.setLayoutDirection(anchor.getLayoutDirection()); } } } /** * <p>Generate the layout parameters for the popup window.</p> * * @param token the window token used to bind the popup's window * * @return the layout parameters to pass to the window manager */ private createPopupLayout():WindowManager.LayoutParams { // generates the layout parameters for the drop down // we want a fixed size view located at the bottom left of the anchor let p:WindowManager.LayoutParams = this.mPopupWindow.getAttributes(); // these gravity settings put the view at the top left corner of the // screen. The view is then positioned to the appropriate location // by setting the x and y offsets to match the anchor's bottom // left corner p.gravity = Gravity.START | Gravity.TOP; p.width = this.mLastWidth = this.mWidth; p.height = this.mLastHeight = this.mHeight; //if (this.mBackground != null) { // p.format = this.mBackground.getOpacity(); //} else { // p.format = PixelFormat.TRANSLUCENT; //} p.flags = this.computeFlags(p.flags); p.type = this.mWindowLayoutType; //p.token = token; //p.softInputMode = this.mSoftInputMode; p.setTitle("PopupWindow"); return p; } private computeFlags(curFlags:number):number { curFlags &= ~( //WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | //WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | //WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS | //WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM | WindowManager.LayoutParams.FLAG_SPLIT_TOUCH); //if (this.mIgnoreCheekPress) { // curFlags |= WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES; //} if (!this.mFocusable) { curFlags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; //if (this.mInputMethodMode == PopupWindow.INPUT_METHOD_NEEDED) { // curFlags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; //} } //else if (this.mInputMethodMode == PopupWindow.INPUT_METHOD_NOT_NEEDED) { // curFlags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; //} if (!this.mTouchable) { curFlags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; } if (this.mOutsideTouchable) { curFlags |= WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH; } //if (!this.mClippingEnabled) { // curFlags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; //} if (this.isSplitTouchEnabled()) { curFlags |= WindowManager.LayoutParams.FLAG_SPLIT_TOUCH; } //if (this.mLayoutInScreen) { // curFlags |= WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN; //} //if (this.mLayoutInsetDecor) { // curFlags |= WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR; //} if (this.mNotTouchModal) { curFlags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL; } return curFlags; } private computeWindowEnterAnimation():Animation { if (this.mEnterAnimation == null) { if (this.mIsDropdown) { return this.mAboveAnchor ? this.mDefaultDropdownAboveEnterAnimation : this.mDefaultDropdownBelowEnterAnimation; } return null; } return this.mEnterAnimation; } private computeWindowExitAnimation():Animation { if (this.mExitAnimation == null) { if (this.mIsDropdown) { return this.mAboveAnchor ? this.mDefaultDropdownAboveExitAnimation : this.mDefaultDropdownBelowExitAnimation; } return null; } return this.mExitAnimation; } /** * <p>Positions the popup window on screen. When the popup window is too * tall to fit under the anchor, a parent scroll view is seeked and scrolled * up to reclaim space. If scrolling is not possible or not enough, the * popup window gets moved on top of the anchor.</p> * * <p>The height must have been set on the layout parameters prior to * calling this method.</p> * * @param anchor the view on which the popup window must be anchored * @param p the layout parameters used to display the drop down * * @return true if the popup is translated upwards to fit on screen */ private findDropDownPosition(anchor:View, p:WindowManager.LayoutParams, xoff:number, yoff:number, gravity:number):boolean { const anchorHeight:number = anchor.getHeight(); anchor.getLocationInWindow(this.mDrawingLocation); p.x = this.mDrawingLocation[0] + xoff; p.y = this.mDrawingLocation[1] + anchorHeight + yoff; const hgrav:number = Gravity.getAbsoluteGravity(gravity, anchor.getLayoutDirection()) & Gravity.HORIZONTAL_GRAVITY_MASK; if (hgrav == Gravity.RIGHT) { // Flip the location to align the right sides of the popup and anchor instead of left p.x -= this.mPopupWidth - anchor.getWidth(); } let onTop:boolean = false; p.gravity = Gravity.LEFT | Gravity.TOP; anchor.getLocationOnScreen(this.mScreenLocation); const displayFrame:Rect = new Rect(); anchor.getWindowVisibleDisplayFrame(displayFrame); let screenY:number = this.mScreenLocation[1] + anchorHeight + yoff; const root:View = anchor.getRootView(); if (screenY + this.mPopupHeight > displayFrame.bottom || p.x + this.mPopupWidth - root.getWidth() > 0) { // the edit box if (this.mAllowScrollingAnchorParent) { let scrollX:number = anchor.getScrollX(); let scrollY:number = anchor.getScrollY(); let r:Rect = new Rect(scrollX, scrollY, scrollX + this.mPopupWidth + xoff, scrollY + this.mPopupHeight + anchor.getHeight() + yoff); anchor.requestRectangleOnScreen(r, true); } // now we re-evaluate the space available, and decide from that // whether the pop-up will go above or below the anchor. anchor.getLocationInWindow(this.mDrawingLocation); p.x = this.mDrawingLocation[0] + xoff; p.y = this.mDrawingLocation[1] + anchor.getHeight() + yoff; // Preserve the gravity adjustment if (hgrav == Gravity.RIGHT) { p.x -= this.mPopupWidth - anchor.getWidth(); } // determine whether there is more space above or below the anchor anchor.getLocationOnScreen(this.mScreenLocation); onTop = (displayFrame.bottom - this.mScreenLocation[1] - anchor.getHeight() - yoff) < (this.mScreenLocation[1] - yoff - displayFrame.top); if (onTop) { p.gravity = Gravity.LEFT | Gravity.BOTTOM; p.y = root.getHeight() - this.mDrawingLocation[1] + yoff; } else { p.y = this.mDrawingLocation[1] + anchor.getHeight() + yoff; } } if (this.mClipToScreen) { const displayFrameWidth:number = displayFrame.right - displayFrame.left; let right:number = p.x + p.width; if (right > displayFrameWidth) { p.x -= right - displayFrameWidth; } if (p.x < displayFrame.left) { p.x = displayFrame.left; p.width = Math.min(p.width, displayFrameWidth); } if (onTop) { let popupTop:number = this.mScreenLocation[1] + yoff - this.mPopupHeight; if (popupTop < 0) { p.y += popupTop; } } else { p.y = Math.max(p.y, displayFrame.top); } } p.gravity |= Gravity.DISPLAY_CLIP_VERTICAL; return onTop; } /** * Returns the maximum height that is available for the popup to be * completely shown, optionally ignoring any bottom decorations such as * the input method. It is recommended that this height be the maximum for * the popup's height, otherwise it is possible that the popup will be * clipped. * * @param anchor The view on which the popup window must be anchored. * @param yOffset y offset from the view's bottom edge * @param ignoreBottomDecorations if true, the height returned will be * all the way to the bottom of the display, ignoring any * bottom decorations * @return The maximum available height for the popup to be completely * shown. * * @hide Pending API council approval. */ getMaxAvailableHeight(anchor:View, yOffset=0, ignoreBottomDecorations=false):number { const displayFrame:Rect = new Rect(); anchor.getWindowVisibleDisplayFrame(displayFrame); const anchorPos:number[] = this.mDrawingLocation; anchor.getLocationOnScreen(anchorPos); let bottomEdge:number = displayFrame.bottom; if (ignoreBottomDecorations) { let res:Resources = anchor.getContext().getResources(); bottomEdge = res.getDisplayMetrics().heightPixels; } const distanceToBottom:number = bottomEdge - (anchorPos[1] + anchor.getHeight()) - yOffset; const distanceToTop:number = anchorPos[1] - displayFrame.top + yOffset; // anchorPos[1] is distance from anchor to top of screen let returnedHeight:number = Math.max(distanceToBottom, distanceToTop); if (this.mBackground != null) { this.mBackground.getPadding(this.mTempRect); returnedHeight -= this.mTempRect.top + this.mTempRect.bottom; } return returnedHeight; } /** * <p>Dispose of the popup window. This method can be invoked only after * {@link #showAsDropDown(android.view.View)} has been executed. Failing that, calling * this method will have no effect.</p> * * @see #showAsDropDown(android.view.View) */ dismiss():void { if (this.isShowing() && this.mPopupView != null) { this.mIsShowing = false; this.unregisterForScrollChanged(); try { this.mWindowManager.removeWindow(this.mPopupWindow); } finally { if (this.mPopupView != this.mContentView && this.mPopupView instanceof ViewGroup) { (<ViewGroup> this.mPopupView).removeView(this.mContentView); } this.mPopupView = null; if (this.mOnDismissListener != null) { this.mOnDismissListener.onDismiss(); } } } } /** * Sets the listener to be called when the window is dismissed. * * @param onDismissListener The listener. */ setOnDismissListener(onDismissListener:PopupWindow.OnDismissListener):void { this.mOnDismissListener = onDismissListener; } /** * Updates the state of the popup window, if it is currently being displayed, * from the currently set state. This include: * {@link #setClippingEnabled(boolean)}, {@link #setFocusable(boolean)}, * {@link #setIgnoreCheekPress()}, {@link #setInputMethodMode(int)}, * {@link #setTouchable(boolean)}, and {@link #setAnimationStyle(int)}. */ update():void; /** * <p>Updates the dimension of the popup window. Calling this function * also updates the window with the current popup state as described * for {@link #update()}.</p> * * @param width the new width * @param height the new height */ update(width:number, height:number):void; /** * <p>Updates the position and the dimension of the popup window. Calling this * function also updates the window with the current popup state as described * for {@link #update()}.</p> * * @param anchor the popup's anchor view * @param width the new width, can be -1 to ignore * @param height the new height, can be -1 to ignore */ update(anchor:View, width:number, height:number):void; /** * <p>Updates the position and the dimension of the popup window. Width and * height can be set to -1 to update location only. Calling this function * also updates the window with the current popup state as * described for {@link #update()}.</p> * * @param x the new x location * @param y the new y location * @param width the new width, can be -1 to ignore * @param height the new height, can be -1 to ignore * @param force reposition the window even if the specified position * already seems to correspond to the LayoutParams */ update(x:number, y:number, width:number, height:number, force?:boolean):void; /** * <p>Updates the position and the dimension of the popup window. Width and * height can be set to -1 to update location only. Calling this function * also updates the window with the current popup state as * described for {@link #update()}.</p> * * <p>If the view later scrolls to move <code>anchor</code> to a different * location, the popup will be moved correspondingly.</p> * * @param anchor the popup's anchor view * @param xoff x offset from the view's left edge * @param yoff y offset from the view's bottom edge * @param width the new width, can be -1 to ignore * @param height the new height, can be -1 to ignore */ update(anchor:View, xoff:number, yoff:number, width:number, height:number):void; update(...args):void{ if(args.length==0){ this._update(); }else if(args.length==2){ this._update_w_h(args[0], args[1]); }else if(args.length==3){ this._update_a_w_h(args[0], args[1], args[2]); }else if(args.length == 4){ this._update_x_y_w_h_f(args[0], args[1], args[2], args[3]); }else if(args.length == 5){ if(args[0] instanceof View) this._update_a_x_y_w_h(args[0], args[1], args[2], args[3], args[4]); else this._update_x_y_w_h_f(args[0], args[1], args[2], args[3], args[4]); } } private _update():void { if (!this.isShowing() || this.mContentView == null) { return; } let p:WindowManager.LayoutParams = <WindowManager.LayoutParams> this.mPopupView.getLayoutParams(); let update:boolean = false; const enterAnim = this.computeWindowEnterAnimation(); const exitAnim = this.computeWindowExitAnimation(); if (enterAnim != p.enterAnimation) { p.enterAnimation = enterAnim; update = true; } if (exitAnim != p.exitAnimation) { p.exitAnimation = exitAnim; update = true; } const newFlags:number = this.computeFlags(p.flags); if (newFlags != p.flags) { p.flags = newFlags; update = true; } if (update) { this.setLayoutDirectionFromAnchor(); this.mWindowManager.updateWindowLayout(this.mPopupWindow, p); } } private _update_w_h(width:number, height:number):void { let p:WindowManager.LayoutParams = <WindowManager.LayoutParams> this.mPopupView.getLayoutParams(); this.update(p.x, p.y, width, height, false); } private _update_x_y_w_h_f(x:number, y:number, width:number, height:number, force=false):void { if (width != -1) { this.mLastWidth = width; this.setWidth(width); } if (height != -1) { this.mLastHeight = height; this.setHeight(height); } if (!this.isShowing() || this.mContentView == null) { return; } let p:WindowManager.LayoutParams = <WindowManager.LayoutParams> this.mPopupView.getLayoutParams(); let update:boolean = force; const finalWidth:number = this.mWidthMode < 0 ? this.mWidthMode : this.mLastWidth; if (width != -1 && p.width != finalWidth) { p.width = this.mLastWidth = finalWidth; update = true; } const finalHeight:number = this.mHeightMode < 0 ? this.mHeightMode : this.mLastHeight; if (height != -1 && p.height != finalHeight) { p.height = this.mLastHeight = finalHeight; update = true; } if (p.x != x) { p.x = x; update = true; } if (p.y != y) { p.y = y; update = true; } const enterAnim = this.computeWindowEnterAnimation(); const exitAnim = this.computeWindowExitAnimation(); if (enterAnim != p.enterAnimation) { p.enterAnimation = enterAnim; update = true; } if (exitAnim != p.exitAnimation) { p.exitAnimation = exitAnim; update = true; } const newFlags:number = this.computeFlags(p.flags); if (newFlags != p.flags) { p.flags = newFlags; update = true; } if (update) { this.setLayoutDirectionFromAnchor(); this.mWindowManager.updateWindowLayout(this.mPopupWindow, p); } } private _update_a_w_h(anchor:View, width:number, height:number):void { this._update_all_args(anchor, false, 0, 0, true, width, height, this.mAnchoredGravity); } private _update_a_x_y_w_h(anchor:View, xoff:number, yoff:number, width:number, height:number):void { this._update_all_args(anchor, true, xoff, yoff, true, width, height, this.mAnchoredGravity); } private _update_all_args(anchor:View, updateLocation:boolean, xoff:number, yoff:number, updateDimension:boolean, width:number, height:number, gravity:number):void { if (!this.isShowing() || this.mContentView == null) { return; } let oldAnchor:WeakReference<View> = this.mAnchor; const needsUpdate:boolean = updateLocation && (this.mAnchorXoff != xoff || this.mAnchorYoff != yoff); if (oldAnchor == null || oldAnchor.get() != anchor || (needsUpdate && !this.mIsDropdown)) { this.registerForScrollChanged(anchor, xoff, yoff, gravity); } else if (needsUpdate) { // No need to register again if this is a DropDown, showAsDropDown already did. this.mAnchorXoff = xoff; this.mAnchorYoff = yoff; this.mAnchoredGravity = gravity; } let p:WindowManager.LayoutParams = <WindowManager.LayoutParams> this.mPopupView.getLayoutParams(); if (updateDimension) { if (width == -1) { width = this.mPopupWidth; } else { this.mPopupWidth = width; } if (height == -1) { height = this.mPopupHeight; } else { this.mPopupHeight = height; } } let x:number = p.x; let y:number = p.y; if (updateLocation) { this.updateAboveAnchor(this.findDropDownPosition(anchor, p, xoff, yoff, gravity)); } else { this.updateAboveAnchor(this.findDropDownPosition(anchor, p, this.mAnchorXoff, this.mAnchorYoff, this.mAnchoredGravity)); } this.update(p.x, p.y, width, height, x != p.x || y != p.y); } private unregisterForScrollChanged():void { let anchorRef:WeakReference<View> = this.mAnchor; let anchor:View = null; if (anchorRef != null) { anchor = anchorRef.get(); } if (anchor != null) { let vto:ViewTreeObserver = anchor.getViewTreeObserver(); vto.removeOnScrollChangedListener(this.mOnScrollChangedListener); } this.mAnchor = null; } private registerForScrollChanged(anchor:View, xoff:number, yoff:number, gravity:number):void { this.unregisterForScrollChanged(); this.mAnchor = new WeakReference<View>(anchor); let vto:ViewTreeObserver = anchor.getViewTreeObserver(); if (vto != null) { vto.addOnScrollChangedListener(this.mOnScrollChangedListener); } this.mAnchorXoff = xoff; this.mAnchorYoff = yoff; this.mAnchoredGravity = gravity; } //androidui add: onTouchEvent(event:MotionEvent):boolean { //if (this.mPopupWindow.shouldCloseOnTouch(this.mContext, event)) { // this.dismiss(); // return true; //} const x:number = Math.floor(event.getX()); const y:number = Math.floor(event.getY()); if ((event.getAction() == MotionEvent.ACTION_DOWN) && ((x < 0) || (x >= this.mPopupView.getWidth()) || (y < 0) || (y >= this.mPopupView.getHeight()))) { this.dismiss(); return true; } else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { this.dismiss(); return true; } else if(this.mPopupView){ return this.mPopupView.onTouchEvent(event); } return false; } onGenericMotionEvent(event:MotionEvent):boolean { return false; } onWindowAttributesChanged(params:WindowManager.LayoutParams):void { if (this.mPopupWindow != null) { this.mWindowManager.updateWindowLayout(this.mPopupWindow, params); } } onContentChanged():void { } onWindowFocusChanged(hasFocus:boolean):void { } onAttachedToWindow():void { } onDetachedFromWindow():void { } dispatchKeyEvent(event:KeyEvent):boolean { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if (this.mPopupView.getKeyDispatcherState() == null) { return this.mPopupWindow.superDispatchKeyEvent(event); } if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { let state:KeyEvent.DispatcherState = this.mPopupView.getKeyDispatcherState(); if (state != null) { state.startTracking(event, this); } return true; } else if (event.getAction() == KeyEvent.ACTION_UP) { let state:KeyEvent.DispatcherState = this.mPopupView.getKeyDispatcherState(); if (state != null && state.isTracking(event) && !event.isCanceled()) { this.dismiss(); return true; } } return this.mPopupWindow.superDispatchKeyEvent(event); } else { return this.mPopupWindow.superDispatchKeyEvent(event); } } dispatchTouchEvent(ev:MotionEvent):boolean { if (this.mTouchInterceptor != null && this.mTouchInterceptor.onTouch(this.mPopupView, ev)) { return true; } if(this.mPopupWindow.superDispatchTouchEvent(ev)){ return true; } return this.onTouchEvent(ev); } dispatchGenericMotionEvent(ev:MotionEvent):boolean { if (this.mPopupWindow.superDispatchGenericMotionEvent(ev)) { return true; } return this.onGenericMotionEvent(ev); } } export module PopupWindow{ /** * Listener that is called when this popup window is dismissed. */ export interface OnDismissListener { /** * Called when this popup window is dismissed. */ onDismiss():void; } //export class PopupViewContainer extends FrameLayout { // private static TAG:string = "PopupWindow.PopupViewContainer"; // // _PopupWindow_this:any; // constructor(context:Context, arg:PopupWindow){ // super(context); // this._PopupWindow_this = arg; // } // // // //onCreateDrawableState(extraSpace:number):number[] { // // if (this._PopupWindow_this.mAboveAnchor) { // // // 1 more needed for the above anchor state // // const drawableState:number[] = super.onCreateDrawableState(extraSpace + 1); // // View.mergeDrawableStates(drawableState, PopupWindow.ABOVE_ANCHOR_STATE_SET); // // return drawableState; // // } else { // // return super.onCreateDrawableState(extraSpace); // // } // //} // // dispatchKeyEvent(event:KeyEvent):boolean { // if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { // if (this.getKeyDispatcherState() == null) { // return super.dispatchKeyEvent(event); // } // if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { // let state:KeyEvent.DispatcherState = this.getKeyDispatcherState(); // if (state != null) { // state.startTracking(event, this); // } // return true; // } else if (event.getAction() == KeyEvent.ACTION_UP) { // let state:KeyEvent.DispatcherState = this.getKeyDispatcherState(); // if (state != null && state.isTracking(event) && !event.isCanceled()) { // this._PopupWindow_this.dismiss(); // return true; // } // } // return super.dispatchKeyEvent(event); // } else { // return super.dispatchKeyEvent(event); // } // } // // dispatchTouchEvent(ev:MotionEvent):boolean { // if (this._PopupWindow_this.mTouchInterceptor != null && this._PopupWindow_this.mTouchInterceptor.onTouch(this, ev)) { // return true; // } // return super.dispatchTouchEvent(ev); // } // // onTouchEvent(event:MotionEvent):boolean { // const x:number = Math.floor(event.getX()); // const y:number = Math.floor(event.getY()); // if ((event.getAction() == MotionEvent.ACTION_DOWN) && ((x < 0) || (x >= this.getWidth()) || (y < 0) || (y >= this.getHeight()))) { // this._PopupWindow_this.dismiss(); // return true; // } else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { // this._PopupWindow_this.dismiss(); // return true; // } else { // return super.onTouchEvent(event); // } // } // // sendAccessibilityEvent(eventType:number):void { // // clinets are interested in the content not the container, make it event source // if (this._PopupWindow_this.mContentView != null) { // this._PopupWindow_this.mContentView.sendAccessibilityEvent(eventType); // } else { // super.sendAccessibilityEvent(eventType); // } // } //} } }
the_stack
import * as fs from "fs"; import * as path from "path"; import { Client } from "ssh2"; import { SocksClient, SocksClientOptions } from "./socks/client/socksclient"; import { Reader, ProgressFunc, IMountList, ProgressResult } from "../../common/Reader"; import { File } from "../../common/File"; import { Logger } from "../../common/Logger"; import { Transform } from "stream"; import { convertAttrToStatMode, FileReader } from "../FileReader"; import { Socket } from "net"; import { Crypto } from "../../common/Crypto"; import Configure from "../../config/Configure"; import { T } from "../../common/Translation"; const log = Logger("SftpReader"); const convertAttr = ( stats: fs.Stats ): string => { const fileMode: string[] = "----------".split(""); fileMode[0] = stats.isSocket() ? "s" : fileMode[0]; fileMode[0] = stats.isBlockDevice() ? "b" : fileMode[0]; fileMode[0] = stats.isCharacterDevice() ? "c" : fileMode[0]; fileMode[0] = stats.isFIFO() ? "p" : fileMode[0]; fileMode[0] = stats.isDirectory() ? "d" : fileMode[0]; fileMode[0] = stats.isSymbolicLink() ? "l" : fileMode[0]; fileMode[1] = stats.mode & 256 ? "r" : "-"; fileMode[2] = stats.mode & 128 ? "w" : "-"; fileMode[3] = stats.mode & 64 ? "x" : "-"; fileMode[4] = stats.mode & 32 ? "r" : "-"; fileMode[5] = stats.mode & 16 ? "w" : "-"; fileMode[6] = stats.mode & 8 ? "x" : "-"; fileMode[7] = stats.mode & 4 ? "r" : "-"; fileMode[8] = stats.mode & 2 ? "w" : "-"; fileMode[9] = stats.mode & 1 ? "x" : "-"; return fileMode.join(""); }; export interface IConnectionInfoBase { protocol?: "SFTP" | "SSH" | "SFTP_SSH"; host?: string; port?: number; // default 22 username?: string; password?: string; privateKey?: string; // key file path proxyInfo?: { host?: string; port?: number; type?: 4 | 5; username?: string; password?: string; }; } export interface IConnectionInfo { name?: string; info?: IConnectionInfoBase[]; } // https://github.com/mscdex/ssh2#client-events export interface ssh2ConnectionInfo { host: string; port?: number; // default 22 forceIPv4?: string; forceIPv6?: string; localAddress?: string; hostHash?: string; hostVerifier?: ( hostkey: string, callback?: () => boolean) => void; username?: string; password?: string; agent?: string; agentForward?: boolean; privateKey?: string | Buffer; // Buffer or string that contains a private key for either key-based or hostbased user authentication (OpenSSH format) passphrase?: string; // For an encrypted private key localHostname?: string; localUsername?: string; // tryKeyboard?: boolean; // Disallow option // authHandler?: (methodsLeft, partialSuccess, callback) => void; // Disallow option keepaliveInterval?: number; keepaliveCountMax?: number; readyTimeout?: number; sock?: Socket; strictVendor?: boolean; algorithms?: { kex: any[]; cipher: any[]; serverHostKey: any[]; hmac: any[]; compress: any[]; }; compress?: boolean | "force"; debug?: () => void; proxyInfo?: SocksClientOptions; } export class SftpReader extends Reader { private client = null; private sftp = null; protected _readerFsType = "sftp"; private homeDirFile: File = null; private currentPath: File = null; private option: ssh2ConnectionInfo = null; private connSessionInfo: IConnectionInfoBase = null; private connInfo: IConnectionInfo = null; private _isEachConnect: boolean = false; constructor() { super(); this.init(); } public destory() { this.disconnect(); } public init() { this.disconnect(); this.client = new Client(); } public disconnect() { if ( this.client ) { log.info( "DISCONNECT: %s", this.getConnectInfo() ); this.sftp = null; this.client.end(); this.client.destroy(); this.client = null; } } public getSSH2Client() { return this.client; } public isSFTPSession() { return !!this.sftp; } public getConnectInfo(): string { const { host, username, port } = this.option || {}; if ( this.isSFTPSession() ) { return `sftp://${username}@${host}:${port}`; } return `ssh://${username}@${host}:${port}`; } public getConnSessionInfo(): IConnectionInfoBase { return this.connSessionInfo; } public getConnInfoConfig(): IConnectionInfo { return this.connInfo; } public isEachConnect() { return this._isEachConnect; } private decryptConnectionInfo( option: ssh2ConnectionInfo ): ssh2ConnectionInfo { const result = { ...option }; result.password = Crypto.decrypt(option.password) || ""; if (result.proxyInfo && result.proxyInfo.proxy ) { result.proxyInfo.proxy.password = Crypto.decrypt(option.proxyInfo.proxy.password) || ""; } return result; } public convertConnectionInfo(connInfo: IConnectionInfo, protocol: RegExp ): ssh2ConnectionInfo { const info: IConnectionInfoBase = connInfo.info.find( item => item.protocol.match( protocol ) ); if ( !info ) { return null; } log.debug( "convertConnectionInfo: ", info ); let proxyInfo: SocksClientOptions = null; if ( info.proxyInfo ) { proxyInfo = { command: "connect", destination: { host: info.host, port: info.port }, proxy: { host: info.proxyInfo.host, port: info.proxyInfo.port, type: info.proxyInfo.type, userId: info.proxyInfo.username, password: info.proxyInfo.password }, timeout: Configure.instance().getOpensshOption("proxyDefaultTimeout"), }; } return { host: info.host, port: info.port, username: info.username, password: info.password, privateKey: info.privateKey, algorithms: Configure.instance().getOpensshOption("algorithms"), keepaliveInterval: Configure.instance().getOpensshOption("keepaliveInterval"), keepaliveCountMax: Configure.instance().getOpensshOption("keepaliveCountMax"), readyTimeout: Configure.instance().getOpensshOption("readyTimeout"), proxyInfo: proxyInfo /* debug: ( ...args: any[] ) => { log.debug( "SFTP DBG: %s", args.join(" ") ); } */ }; } public async connect(connInfo: IConnectionInfo, connectionErrorFunc: ( errInfo: any ) => void ): Promise<string> { let option = this.convertConnectionInfo(connInfo, /SFTP/ ); const sshOption = this.convertConnectionInfo(connInfo, /SSH/ ); let connectionOnly = false; if ( !option && sshOption ) { connectionOnly = true; option = sshOption; } const result = await this.sessionConnect( option, connectionErrorFunc, connectionOnly ); this.connInfo = connInfo; this._isEachConnect = !connInfo.info.find( item => item.protocol === "SFTP_SSH" ); return result; } public sessionConnect( option: ssh2ConnectionInfo, connectionErrorFunc: ( errInfo: any ) => void, connectionOnly: boolean = false ): Promise<string> { log.debug( "CONNECTION INFO: %s", JSON.stringify(option, null, 2) ); // eslint-disable-next-line no-async-promise-executor return new Promise( async (resolve, reject) => { if ( !option ) { reject( "Empty Connection Configuration !!!" ); return; } const decryptOption = this.decryptConnectionInfo(option); if ( !decryptOption.password || (decryptOption.proxyInfo && !decryptOption.proxyInfo.proxy.password) ) { reject( T("Message.PasswordEmpty") ); return; } if ( decryptOption.proxyInfo ) { try { const { socket } = await SocksClient.createConnection(decryptOption.proxyInfo); log.info( "PROXY CONNECT OK: [%s][%d]", socket.remoteAddress, socket.remotePort ); decryptOption.sock = socket; } catch( err ) { log.error( "Proxy CONNECTION ERROR - ERORR: %s", err ); reject( err ); return; } } const onceReady = (err) => { if ( err ) { log.error( "Ready - ERORR: %s", err ); this.client.removeListener("error", onceReady); reject( err ); return; } if ( !connectionOnly ) { this.client.sftp( async (err, sftp) => { if ( err ) { log.error( "SFTP SESSION - ERORR: %s", err ); reject( err ); return; } this.sftp = sftp; log.info( "SFTP connected !!!" ); this.client.on("error", (err) => { log.error( "SFTP client error: %s", err); connectionErrorFunc(err); }); this.client.on("close", (err) => { log.error( "SFTP client close", err); this.disconnect(); connectionErrorFunc("close"); }); try { this.homeDirFile = await this.convertFile( await this.sftpRealPath(".") ); this.currentPath = this.homeDirFile; } catch( e ) { log.error( "GET HOME ERROR [%s]", e ); } resolve("SFTP"); }); } else { resolve("SESSION_CLIENT"); } }; this.client.once( "ready", onceReady ); this.client.once( "error", (err) => { if ( err && err.level === "client-authentication" ) { reject( T("Message.AuthenticationFailed" ) ); return; } log.error( "Client ERORR: %s %j", err.level, err ); this.client.removeListener("ready", onceReady); reject( err ); } ); // log.debug("connect option : %j", option ); log.info( "Client connect - [%s:%d] - [%s]", option.host, option.port || 22, option.username ); this.option = option; this.client.connect( decryptOption ); }); } private sftpRealPath(path: string): Promise<string> { if ( !this.sftp ) { throw new Error("disconnected sftp"); } return new Promise( (resolve, reject) => { try { this.sftp.realpath(path, (err, absPath) => { if ( err ) { log.error(`realpath error ${err.message} code: ${err.code}`); reject( err ); return; } resolve( absPath ); }); } catch( e ) { log.error( "realpath exception: %s - %s", e, path ); reject( e ); } }); } private sftpStat(path: string): Promise<any> { if ( !this.sftp ) { throw new Error("disconnected sftp"); } return new Promise( (resolve, reject) => { try { this.sftp.stat(path, (err, stats) => { if ( err ) { log.error(`sftp lstat error ${err.message} code: ${err.code} - path: ${path}`); reject( err ); return; } resolve(stats); }); } catch ( e ) { log.error( "sftpStat exception: %s", e); reject( e ); } }); } async convertFile(pathStr: string, _option?: any): Promise<File> { if ( !this.sftp ) { throw new Error("disconnected sftp"); } if ( pathStr === "~" ) { return await this.homeDir(); } else if ( pathStr === "." ) { return this.currentPath.clone(); } else if ( pathStr === ".." ) { pathStr = this.currentPath.dirname; } else if ( pathStr[0] === "~" ) { pathStr = pathStr.replace("~", (await this.homeDir()).fullname); } else if ( pathStr[0] !== "/" ) { pathStr = this.currentPath.fullname + this.sep() + pathStr; } const file = new File(); file.root = this.getConnectInfo(); file.fstype = this._readerFsType; file.fullname = await this.sftpRealPath( pathStr ); file.name = path.basename(file.fullname); const stat = await this.sftpStat( file.fullname ); file.attr = convertAttr( stat ); file.dir = stat.isDirectory(); file.size = stat.size; file.attr = convertAttr( stat ); file.uid = stat.uid; file.gid = stat.gid; file.ctime = new Date(stat.mtime * 1000); file.mtime = new Date(stat.mtime * 1000); file.atime = new Date(stat.atime * 1000); return file; } private convertFileForReadDir(item: any, baseDir: File ): File { /* { "filename":".viminfo", "longname":"-rw------- 1 1000967 10099999 3343 16 Jul 02:49 .viminfo", "attrs": { "mode":33152, "permissions":33152, "uid":1000967, "gid":10099999, "size":3343, "atime":1594835386, "mtime":1594835386 } } */ const file = new File(); file.root = this.getConnectInfo(); file.fstype = this._readerFsType; file.fullname = baseDir.fullname + (baseDir.fullname !== "/" ? this.sep() : "") + item.filename; file.name = path.basename(file.fullname); const longInfo = item.longname.split(" ").filter( item => item.length > 0 ); if ( longInfo.length > 3) { const attrs = item.attrs; file.owner = longInfo[2]; file.group = longInfo[3]; file.attr = longInfo[0]; file.dir = file.attr[0] === "d"; file.size = attrs.size; file.uid = attrs.uid; file.gid = attrs.gid; file.ctime = new Date(attrs.mtime * 1000); file.mtime = new Date(attrs.mtime * 1000); file.atime = new Date(attrs.atime * 1000); } else { return null; } return file; } readdir(dir: File, _option?: { isExcludeHiddenFile?: boolean; noChangeDir?: boolean }): Promise<File[]> { if ( !this.sftp ) { throw new Error("disconnected sftp"); } return new Promise( (resolve, reject) => { try { log.debug( "READDIR: %s", dir.fullname ); this.sftp.readdir(dir.fullname, async (err, fileList: any[]) => { if ( err ) { log.error( "error readdir [%s]", err ); reject( err ); return; } const result: File[] = []; for ( const item of fileList ) { try { log.debug( "READDIR LIST: [%j]", item ); const file = this.convertFileForReadDir( item, dir ); if ( file ) { result.push( file ); } } catch( e ) { log.error( "readdir - %j", e ); } } this.currentPath = dir; resolve( result ); }); } catch( err ) { log.error( "readdir error: [%s]", err ); reject( err ); } }); } async homeDir(): Promise<File> { return this.homeDirFile || await this.rootDir(); } async rootDir(): Promise<File> { return await this.convertFile("/"); } mountList(): Promise<IMountList[]> { throw new Error("Unsupport sftp mountlist()"); } async changeDir(_dirFile: File): Promise<void> { log.warning( "unsupport change dir" ); } async currentDir(): Promise<File> { return await this.convertFile("."); } sep(): string { return "/"; } async exist(source: string | File): Promise<boolean> { log.info( "SFTP EXIST : %s", source); const src = source instanceof File ? source.fullname : source; try { const result = await this.sftpStat( src ); return !!result; } catch( e ) { log.error( "exist exception: %s", e ); return false; } } async newFile( file: string | File, progress?: ProgressFunc ): Promise<void> { if ( !this.sftp ) { throw new Error("disconnected sftp"); } const name = path instanceof File ? path.fullname : path; return new Promise( (resolve, reject) => { const result: fs.WriteStream = this.sftp.createWriteStream(name, { mode: 0o644, encoding: null, flags: "w", autoClose: true }); result.write( "", (err) => { if ( result ) { result.close(); } if ( err ) { log.error("NEWFILE ERROR: %s", err); reject( err ); } else { log.debug("NEWFILE: %s", name); resolve(); } }); }); } async mkdir(path: string | File, _progress?: ProgressFunc): Promise<void> { if ( !this.sftp ) { throw new Error("disconnected sftp"); } const name = path instanceof File ? path.fullname : path; return new Promise( (resolve, reject) => { this.sftp.mkdir( name, (err) => { if ( err ) { log.error("MKDIR ERROR: %s", err); reject( err ); } else { log.debug("MKDIR: %s", name); resolve(); } }); }); } rename(source: File, rename: string, _progress?: ProgressFunc): Promise<void> { if ( !this.sftp ) { throw new Error("disconnected sftp"); } return new Promise( (resolve, reject) => { this.sftp.rename( source.fullname, rename, (err) => { if ( err ) { log.error("RENAME ERROR: %s", err); reject( err ); } else { log.debug( "RENAME : %s => %s", source.fullname, rename ); resolve(); } }); }); } copy(source: File | File[], _sourceBaseDir: File, targetDir: File, progress?: ProgressFunc): Promise<void> { if ( !this.sftp ) { throw new Error("disconnected sftp"); } return new Promise( ( resolve, reject ) => { if ( Array.isArray(source) ) { reject( "Unsupport file array type !!!" ); return; } if ( source.fstype === targetDir.fstype ) { reject( `Unsupport file type !!! source: ${source.fstype}, target ${targetDir.fstype}` ); return; } const srcFile = source.link ? source.link.file : source; if ( srcFile.dir || targetDir.dir ) { reject("Unable to copy from a source directory."); return; } /* const fileMode = { mode: null // convertAttrToStatMode(srcFile) || 0o644 }; const step = ( total_transfered: number, chunk: number, total: number ) => { progress && progress( srcFile, total_transfered, srcFile.size, chunk ); log.debug( "Copy to: %s => %s (%d / %d)", srcFile.fullname, targetDir.fullname, total_transfered, srcFile.size ); }; if ( srcFile.fstype === "file" ) { this.sftp.fastPut( srcFile.fullname, targetDir.fullname, { step, mode: fileMode.mode }, (err) => { if ( err ) { reject( err ); } else { resolve(); } }); } else { this.sftp.fastGet( srcFile.fullname, targetDir.fullname, { step, mode: fileMode.mode }, (err) => { if ( err ) { reject( err ); } else { resolve(); } }); } */ let rejectCalled = false; try { const fileMode = { mode: convertAttrToStatMode(srcFile) || 0o644 }; let chunkCopyLength = 0; const rd = srcFile.fstype === "file" ? fs.createReadStream(srcFile.fullname) : this.sftp.createReadStream(srcFile.fullname); const wr = targetDir.fstype === "file" ? fs.createWriteStream(targetDir.fullname, fileMode) : this.sftp.createWriteStream(targetDir.fullname, { ...fileMode, encoding: null, flags: "w", autoClose: true }); const rejectFunc = (err) => { if ( rejectCalled ) { log.debug( "reject called !!!"); return; } rejectCalled = true; try { log.error( "COPY ERROR - %s", err ); rd.destroy(); wr.end(() => { try { if ( targetDir.fstype === "file" ) { fs.unlinkSync( targetDir.fullname ); } else { this.sftp?.unlink( targetDir.fullname ); } } catch( e ) { console.log( err ); } }); } catch( e ) { log.error( "COPY ERROR - " + e ); } finally { reject(err); } }; rd.on("error", rejectFunc); wr.on("error", rejectFunc); wr.on("finish", () => { log.debug( "Copy to: %s %s => %s %s (%d / %d) - FINISH !!!", srcFile.fstype, srcFile.fullname, targetDir.fstype, targetDir.fullname, chunkCopyLength, srcFile.size ); resolve(); }); this.client.on("close", () => { this.disconnect(); rejectFunc("connection close."); }); const sftp = this.sftp; const reportProgress = new Transform({ transform(chunk: Buffer, encoding, callback) { chunkCopyLength += chunk.length; const result = progress && progress( srcFile, chunkCopyLength, srcFile.size, chunk.length ); log.debug( "Copy to: %s %s => %s %s (%d / %d)", srcFile.fstype, srcFile.fullname, targetDir.fstype, targetDir.fullname, chunkCopyLength, srcFile.size ); if ( result === ProgressResult.USER_CANCELED ) { try { rd.destroy(); wr.end(() => { try { if ( targetDir.fstype === "file" ) { fs.unlinkSync( targetDir.fullname ); } else { sftp.unlink( targetDir.fullname ); } } catch( e ) { log.error( e ); } }); } catch( e ) { log.error( e ); } log.debug( "COPY - CANCEL" ); reject( "USER_CANCEL" ); return; } callback( null, chunk ); } }); rd.pipe( reportProgress ).pipe(wr); } catch( e ) { log.error( "COPY Exception !!! - %s", e ); reject( e ); } }); } remove(source: File, _progress?: ProgressFunc): Promise<void> { if ( !this.sftp ) { throw new Error("disconnected sftp"); } return new Promise( (resolve, reject) => { if ( source.dir ) { this.sftp.rmdir( source.fullname, (err) => { if ( err ) { reject( err ); } else { log.debug( "REMOVE : %s", source.fullname ); resolve(); } }); } else { this.sftp.unlink( source.fullname, (err) => { if ( err ) { reject( err ); } else { log.debug( "REMOVE : %s", source.fullname ); resolve(); } }); } }); } async viewer( file: File, progress?: ProgressFunc ): Promise<{ orgFile: File; tmpFile: File; endFunc: () => void }> { if ( !this.sftp ) { throw new Error("disconnected sftp"); } if ( file.dir ) { log.debug( "Unable to view the directory in the viewer."); return null; } if ( file.root !== this.getConnectInfo() ) { throw new Error("viewer file is not SftpReader"); } const tmpFileDirName = path.join((global as any).fsTmpDir, "viewer"); if ( !fs.existsSync( tmpFileDirName ) ) { fs.mkdirSync( tmpFileDirName ); } const tmpFile = await FileReader.convertFile( path.join(tmpFileDirName, file.name), { virtualFile: true } ); await this.copy( file, null, tmpFile, progress ); const endFunc = () => { try { fs.rmdirSync( path.join((global as any).fsTmpDir, "viewer"), { recursive: true } ); } catch( e ) { log.error( e ); } return; }; return { orgFile: file, tmpFile, endFunc }; } }
the_stack
import {Constants} from "../../scripts/constants"; import {TooltipType} from "../../scripts/clipperUI/tooltipType"; import {TooltipHelper} from "../../scripts/extensions/tooltipHelper"; import {Storage} from "../../scripts/storage/storage"; import {ClipperStorageKeys} from "../../scripts/storage/clipperStorageKeys"; import {MockStorage} from "../storage/mockStorage"; import {TestModule} from "../testModule"; export class TooltipHelperTests extends TestModule { private tooltipHelper: TooltipHelper; private mockStorage: Storage; private testType = TooltipType.Pdf; private validTypes = [TooltipType.Pdf, TooltipType.Product, TooltipType.Recipe, TooltipType.Video]; private baseTime = new Date("09/27/2016 00:00:00 PM").getTime(); protected module() { return "tooltipHelper"; } protected beforeEach() { this.mockStorage = new MockStorage(); this.tooltipHelper = new TooltipHelper(this.mockStorage); } protected tests() { // undefined clipped time, undefined lastSeenTime should return 0 // null clipped time, null lastSeenTime test("Null or undefined passed to getTooltipInformation should throw an Error", () => { /* tslint:disable:no-null-keyword */ throws(() => { this.tooltipHelper.getTooltipInformation(undefined, undefined); }); throws(() => { this.tooltipHelper.getTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, undefined); }); throws(() => { this.tooltipHelper.getTooltipInformation(undefined, this.testType); }); throws(() => { this.tooltipHelper.getTooltipInformation(null, null); }); throws(() => { this.tooltipHelper.getTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, null); }); throws(() => { this.tooltipHelper.getTooltipInformation(null, this.testType); }); /* tslint:enable:no-null-keyword */ }); test("getTooltipInformation should return 0 for a value that is not in storage", () => { let value = this.tooltipHelper.getTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, this.testType); strictEqual(value, 0); }); test("getTooltipInformation should return 0 for an invalid value", () => { let storageKey = TooltipHelper.getStorageKeyForTooltip(ClipperStorageKeys.lastSeenTooltipTimeBase, this.testType); let expected = "blah"; this.mockStorage.setValue(storageKey, expected); let value = this.tooltipHelper.getTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, this.testType); strictEqual(value, 0); }); test("getTooltipInformation should return correct information for a value that is in storage", () => { let storageKey = TooltipHelper.getStorageKeyForTooltip(ClipperStorageKeys.lastSeenTooltipTimeBase, this.testType); let expected = 1234; this.mockStorage.setValue(storageKey, expected.toString()); let value = this.tooltipHelper.getTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, this.testType); strictEqual(value, expected); }); test("Null or undefined passed to setTooltipInformation should throw an Error", () => { /* tslint:disable:no-null-keyword */ throws(() => { this.tooltipHelper.setTooltipInformation(undefined, undefined, ""); }); throws(() => { this.tooltipHelper.setTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, undefined, ""); }); throws(() => { this.tooltipHelper.setTooltipInformation(undefined, this.testType, ""); }); throws(() => { this.tooltipHelper.setTooltipInformation(null, null, ""); }); throws(() => { this.tooltipHelper.setTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, null, ""); }); throws(() => { this.tooltipHelper.setTooltipInformation(null, this.testType, ""); }); /* tslint:enable:no-null-keyword */ }); test("setTooltipInformation should correctly set the key and value when given valid arguments", () => { let val = 4134134; this.tooltipHelper.setTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, this.testType, val.toString()); let actual = this.tooltipHelper.getTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, this.testType); strictEqual(actual, val); }); test("Null or undefined passed to tooltipDelayIsOver should throw an Error", () => { /* tslint:disable:no-null-keyword */ throws(() => { this.tooltipHelper.tooltipDelayIsOver(undefined, null); }); throws(() => { this.tooltipHelper.tooltipDelayIsOver(null, null); }); /* tslint:enable:no-null-keyword */ }); test("tooltipHasBeenSeenInLastTimePeriod should return FALSE when nothing is in storage", () => { ok(!this.tooltipHelper.tooltipHasBeenSeenInLastTimePeriod(this.baseTime, this.testType, Constants.Settings.timeBetweenSameTooltip)); }); test("tooltipHasBeenSeenInLastTimePeriod should return FALSE when a value is in storage but it is outside the time period", () => { this.setSeenTimeOutsideOfRange(this.testType, Constants.Settings.timeBetweenSameTooltip); ok(!this.tooltipHelper.tooltipHasBeenSeenInLastTimePeriod(this.baseTime, this.testType, Constants.Settings.timeBetweenSameTooltip)); }); test("tooltipHasBeenSeenInLastTimePeriod should return TRUE when a value is in storage and is within the time period", () => { this.setSeenTimeWithinRange(this.testType, Constants.Settings.timeBetweenSameTooltip); ok(this.tooltipHelper.tooltipHasBeenSeenInLastTimePeriod(this.testType, this.baseTime, Constants.Settings.timeBetweenSameTooltip)); }); test("hasAnyTooltipBeenSeenInLastTimePeriod should return FALSE when nothing is in storage", () => { ok(!this.tooltipHelper.hasAnyTooltipBeenSeenInLastTimePeriod(this.baseTime, this.validTypes, Constants.Settings.timeBetweenDifferentTooltips)); }); test("hasAnyTooltipBeenSeenInLastTimePeriod should return TRUE if at least one of the tooltips has a lastSeenTooltipTime in Storage within the time period", () => { this.setSeenTimeWithinRange(this.testType, Constants.Settings.timeBetweenDifferentTooltips); ok(this.tooltipHelper.hasAnyTooltipBeenSeenInLastTimePeriod(this.baseTime, this.validTypes, Constants.Settings.timeBetweenDifferentTooltips)); }); test("tooltipDelayIsOver should return TRUE when nothing in in storage", () => { ok(this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); }); // Have they clipped this content? If so, return FALSE test("tooltipDelayIsOver should return FALSE when the user has clipped this content type regardless of when they Clipped it and the rest of the values in storage", () => { this.setClipTimeWithinRange(); ok(!this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); this.setClipTimeOutsideOfRange(); ok(!this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); }); // Have they seen ANY content? If so, return FALSE test("tooltipDelayIsOver should return FALSE when they have seen a tooltip in the last Constants.Settings.timeBetweenSameTooltip period", () => { this.setSeenTimeWithinRange(this.testType, Constants.Settings.timeBetweenSameTooltip); ok(!this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); }); test("tooltipDelayIsOver should return FALSE when they have seen a tooltip (not the same one) in the last Constants.Settings.timeBetweenDifferentTooltipsPeriod", () => { this.setSeenTimeWithinRange(TooltipType.Pdf, Constants.Settings.timeBetweenDifferentTooltips); ok(!this.tooltipHelper.tooltipDelayIsOver(TooltipType.Product, this.baseTime)); }); test("tooltipDelayIsOver should return TRUE if they have NOT seen a different tooltip in the last Constants.Settings.timeBetweenDifferentTooltipsPeriod", () => { this.setSeenTimeOutsideOfRange(TooltipType.Product, Constants.Settings.timeBetweenDifferentTooltips); ok(this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); }); // Has the user has seen the tooltip more than maxTooltipsShown times? If so, return FALSE test("tooltipDelayIsOVer should return FALSE when the user has seen this tooltip more than maxTooltipsShown times", () => { this.setNumTimesTooltipHasBeenSeen(Constants.Settings.maximumNumberOfTimesToShowTooltips); ok(!this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); }); test("tooltipDelayIsOver should return TRUE when the user hasn't seen a tooltip in a while, they've never clipped this content, and they haven't gone over the max number of times to see the tooltip", () => { this.setSeenTimeOutsideOfRange(this.testType, Constants.Settings.timeBetweenSameTooltip); ok(this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); }); test("tooltipDelayIsOver should return FALSE when the user has seen a tooltip in the last Constants.Settings.timeBetweenSameTooltip period, no matter the value of lastClippedTime", () => { this.setSeenTimeWithinRange(this.testType, Constants.Settings.timeBetweenSameTooltip); ok(!this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); this.setClipTimeOutsideOfRange(); ok(!this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); this.setClipTimeWithinRange(); ok(!this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); }); test("tooltipDelayIsOver should return FALSE when the user has clipped a tooltip, no matter the value of lastSeenTime", () => { this.setClipTimeWithinRange(); ok(!this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); this.setSeenTimeOutsideOfRange(this.testType, Constants.Settings.timeBetweenSameTooltip); ok(!this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); this.setSeenTimeWithinRange(this.testType, Constants.Settings.timeBetweenSameTooltip); ok(!this.tooltipHelper.tooltipDelayIsOver(this.testType, this.baseTime)); }); } private setClipTimeWithinRange() { let timeToSet = this.baseTime - Constants.Settings.timeBetweenSameTooltip + 5000; this.tooltipHelper.setTooltipInformation(ClipperStorageKeys.lastClippedTooltipTimeBase, this.testType, timeToSet.toString()); } private setClipTimeOutsideOfRange() { let timeToSet = this.baseTime - Constants.Settings.timeBetweenSameTooltip - 5000; this.tooltipHelper.setTooltipInformation(ClipperStorageKeys.lastClippedTooltipTimeBase, this.testType, timeToSet.toString()); } private setSeenTimeWithinRange(tooltipType: TooltipType, timePeriod: number) { let timeToSet = this.baseTime - timePeriod + 5000; this.tooltipHelper.setTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, tooltipType, timeToSet.toString()); } private setSeenTimeOutsideOfRange(tooltipType: TooltipType, timePeriod: number) { let timeToSet = this.baseTime - timePeriod - 5000; this.tooltipHelper.setTooltipInformation(ClipperStorageKeys.lastSeenTooltipTimeBase, tooltipType, timeToSet.toString()); } private setNumTimesTooltipHasBeenSeen(times: number) { this.tooltipHelper.setTooltipInformation(ClipperStorageKeys.numTimesTooltipHasBeenSeenBase, this.testType, times.toString()); } } (new TooltipHelperTests()).runTests();
the_stack
import { ensurePercent, formatPercent, parseCSSFunction, cssFunction, formatFloat, toFloat } from './utils/formatting'; import { roundFloat, round } from './utils/math'; import { StringType } from './types'; import { ColorProperty } from 'csstype'; const RGB = 'rgb', HSL = 'hsl'; const converters = { [RGB + HSL]: RGBtoHSL, [HSL + RGB]: HSLtoRGB }; /** * Describe the ceiling for each color channel for each format */ const maxChannelValues = { r: 255, g: 255, b: 255, h: 360, s: 1, l: 1, a: 1 } /** * Creates a color from a hex color code or named color. * e.g. color('red') or color('#FF0000') or color('#F00')) */ export function color(value: ColorProperty): ColorHelper { return parseHexCode(value) || parseColorFunction(value) || rgb(255, 0, 0)!; } /** * Creates a color from hue, saturation, and lightness. Alpha is automatically set to 100% * @param hue The hue of the color. This should be a number between 0-360. * @param saturation The saturation of the color. This should be a number between 0-1 or a percentage string between 0%-100%. * @param lightness The lightness of the color. This should be a number between 0-1 or a percentage string between 0%-100%. * @param alpha The alpha of the color. This should be a number between 0-1 or a percentage string between 0%-100%. If not specified, this defaults to 1. */ export function hsl(hue: number, saturation: string | number, lightness: string | number, alpha?: string | number): ColorHelper { return new ColorHelper( HSL, modDegrees(hue), ensurePercent(saturation), ensurePercent(lightness), (alpha === undefined ? 1 : ensurePercent(alpha)), alpha !== undefined /* hasAlpha*/); } /** * Creates a color from hue, saturation, lightness, and alpha * @param hue The hue of the color. This should be a number between 0-360. * @param saturation The saturation of the color. This should be a number between 0-1 or a percentage string between 0%-100%. * @param lightness The lightness of the color. This should be a number between 0-1 or a percentage string between 0%-100%. * @param alpha The alpha of the color. This should be a number between 0-1 or a percentage string between 0%-100%. */ export function hsla(hue: number, saturation: string | number, lightness: string | number, alpha: string | number): ColorHelper { return new ColorHelper(HSL, modDegrees(hue), ensurePercent(saturation), ensurePercent(lightness), ensurePercent(alpha), true); } /** * Creates a color form the red, blue, and green color space. Alpha is automatically set to 100% * @param red The red channel of the color. This should be a number between 0-255. * @param blue The blue channel of the color. This should be a number between 0-255. * @param green The green channel of the color. This should be a number between 0-255. * @param alpha The alpha of the color. This should be a number between 0-1 or a percentage string between 0%-100%. If not specified, this defaults to 1. */ export function rgb(red: number, blue: number, green: number, alpha?: string | number): ColorHelper { return new ColorHelper( RGB, red, blue, green, (alpha === undefined ? 1 : ensurePercent(alpha)), alpha !== undefined /* hasAlpha*/); } /** * Creates a color form the red, blue, green, and alpha in the color space * @param red The red channel of the color. This should be a number between 0-255. * @param blue The blue channel of the color. This should be a number between 0-255. * @param green The green channel of the color. This should be a number between 0-255. * @param alpha The alpha of the color. This should be a number between 0-1 or a percentage string between 0%-100%. */ export function rgba(red: number, blue: number, green: number, alpha: string | number): ColorHelper { return new ColorHelper(RGB, red, blue, green, ensurePercent(alpha), true); } function convertHelper(toFormat: 'rgb' | 'hsl', helper: ColorHelper | any, forceAlpha?: boolean): ColorHelper { const { f: fromFormat, r, g, b, a } = helper; const newAlpha = forceAlpha === undefined ? helper.o : forceAlpha; if (fromFormat !== toFormat) { return converters[fromFormat + toFormat](r, g, b, a, newAlpha); } return forceAlpha === undefined ? helper : new ColorHelper(fromFormat, r, g, b, a, newAlpha); } /** * A CSS Color. Includes utilities for converting between color types */ export class ColorHelper implements StringType<ColorProperty> { /** * Format of the color * @private */ private f: 'rgb' | 'hsl'; /** * True if the color should output opacity in the formatted result * @private */ private o: boolean; /** * Channel 0 * @private */ private r: number; /** * Channel 1 * @private */ private g: number; /** * Channel 2 * @private */ private b: number; /** * Channel Alpha * @private */ private a: number; constructor(format: 'rgb' | 'hsl', r: number, g: number, b: number, a: number, hasAlpha: boolean) { const self = this; self.f = format; self.o = hasAlpha; const isHSL = format === HSL; self.r = clampColor(isHSL ? 'h': 'r', r); self.g = clampColor(isHSL ? 's': 'g', g); self.b = clampColor(isHSL ? 'l': 'b', b); self.a = clampColor('a', a); } /** * Converts the stored color into string form (which is used by Free Style) */ public toString(): ColorProperty { const { o: hasAlpha, f: format, r, g, b, a } = this; let fnName: string; let params: (number | string)[]; // find function name and resolve first three channels if (format === RGB) { fnName = hasAlpha ? 'rgba' : RGB; params = [round(r), round(g), round(b)]; } else if (format === HSL) { fnName = hasAlpha ? 'hsla' : HSL; params = [round(r), formatPercent(roundFloat(g, 100)), formatPercent(roundFloat(b, 100))]; } else { throw new Error('Invalid color format'); } // add alpha channel if needed if (hasAlpha) { params.push(formatFloat(roundFloat(a, 100000))); } // return as a string return cssFunction(fnName, params); } /** * Converts to hex rgb(255, 255, 255) to #FFFFFF */ public toHexString(): string { const color = convertHelper(RGB, this); return '#' + (toHex(color.r) + toHex(color.g) + toHex(color.b)).toUpperCase(); } /** * Converts to the Hue, Saturation, Lightness color space */ public toHSL(): ColorHelper { return convertHelper(HSL, this, false); } /** * Converts to the Hue, Saturation, Lightness color space and adds an alpha channel */ public toHSLA(): ColorHelper { return convertHelper(HSL, this, true); } /** * Converts to the Red, Green, Blue color space */ public toRGB(): ColorHelper { return convertHelper(RGB, this, false); } /** * Converts to the Red, Green, Blue color space and adds an alpha channel */ public toRGBA(): ColorHelper { return convertHelper(RGB, this, true); } public red(): number { const _ = this; return (_.f === RGB ? _ : _.toRGB()).r; } public green(): number { const _ = this; return (_.f === RGB ? _ : _.toRGB()).g; } public blue(): number { const _ = this; return (_.f === RGB ? _ : _.toRGB()).b; } public hue(): number { const _ = this; return (_.f === HSL ? _ : _.toHSL()).r; } public saturation(): number { const _ = this; return (_.f === HSL ? _ : _.toHSL()).g; } public lightness(): number { const _ = this; return (_.f === HSL ? _ : _.toHSL()).b; } public alpha(): number { return this.a; } public opacity(): number { return this.a; } public invert(): ColorHelper { const _ = this; const color2 = convertHelper(RGB, _); return convertHelper(_.f, new ColorHelper(RGB, 255 - color2.r, 255 - color2.g, 255 - color2.b, _.a, _.o)); } public lighten(percent: string | number, relative?: boolean): ColorHelper { const _ = this; const color2 = convertHelper(HSL, _); const max = maxChannelValues.l; const l = color2.b + (relative ? max - color2.b : max) * ensurePercent(percent); return convertHelper(_.f, new ColorHelper(HSL, color2.r, color2.g, l, _.a, _.o)); } public darken(percent: string | number, relative?: boolean): ColorHelper { const _ = this; const color2 = convertHelper(HSL, _); const l = color2.b - (relative ? color2.b : maxChannelValues.l) * ensurePercent(percent); return convertHelper(_.f, new ColorHelper(HSL, color2.r, color2.g, l, _.a, _.o)); } public saturate(percent: string | number, relative?: boolean): ColorHelper { const _ = this; const color2 = convertHelper(HSL, _); const max = maxChannelValues.s; const s = color2.g + (relative ? max - color2.g : max) * ensurePercent(percent); return convertHelper(_.f, new ColorHelper(HSL, color2.r, s, color2.b, _.a, _.o)); } public desaturate(percent: string | number, relative?: boolean): ColorHelper { const _ = this; const color2 = convertHelper(HSL, _); const max = maxChannelValues.s; const s = color2.g - (relative ? color2.g : max) * ensurePercent(percent); return convertHelper(_.f, new ColorHelper(HSL, color2.r, s, color2.b, _.a, _.o)); } public grayscale() { return this.desaturate(1); } public fade(percent: string | number): ColorHelper { const _ = this; const a = clampColor('a', ensurePercent(percent)); return convertHelper(_.f, new ColorHelper(_.f, _.r, _.g, _.b, a, true)); } public fadeOut(percent: string | number, relative?: boolean): ColorHelper { const _ = this; const max = 1; const a = clampColor('a', _.a - (relative ? _.a : max) * ensurePercent(percent)); return convertHelper(_.f, new ColorHelper(_.f, _.r, _.g, _.b, a, true)); } public fadeIn(percent: string | number, relative?: boolean): ColorHelper { const _ = this; const max = 1; const a = clampColor('a', _.a + (relative ? _.a : max) * ensurePercent(percent)); return convertHelper(_.f, new ColorHelper(_.f, _.r, _.g, _.b, a, true)); } public mix(mixin: string | ColorHelper, weight?: number): ColorHelper { const _ = this; const color2 = ensureColor(mixin); const g = convertHelper(RGB, _); const b = convertHelper(RGB, color2); const p = weight === undefined ? 0.5 : weight; const w = 2 * p - 1; const a = Math.abs(g.a- b.a); const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0; const w2 = 1 - w1; const helper = new ColorHelper( RGB, round(g.r * w1 + b.r * w2), round(g.g * w1 + b.g * w2), round(g.b * w1 + b.b * w2), g.a * p + b.a * (1 - p), _.o || color2.o ); return convertHelper(this.f, helper); } public tint(weight: number): ColorHelper { return rgb(255, 255, 255).mix(this, weight); } public shade(weight: number): ColorHelper { return rgb(0, 0, 0).mix(this, weight); } public spin(degrees: number): ColorHelper { const _ = this; const color2 = convertHelper(HSL, _); return convertHelper(_.f, new ColorHelper(HSL, modDegrees(color2.r + degrees), color2.g, color2.b, _.a, _.o)); } } function toHex(n: number): string { const i = round(n); return (i < 16 ? '0' : '') + i.toString(16); } function modDegrees(n: number): number { // note: maybe there is a way to simplify this return ((n < 0 ? 360 : 0) + n % 360) % 360; } function RGBtoHSL(r: number, g: number, b: number, a: number, hasAlpha: boolean): ColorHelper { const newR = r / 255; const newG = g / 255; const newB = b / 255; const min = Math.min(newR, newG, newB); const max = Math.max(newR, newG, newB); const l = (min + max) / 2; const delta = max - min; let h: number; if (max === min) { h = 0; } else if (newR === max) { h = (newG - newB) / delta; } else if (newG === max) { h = 2 + (newB - newR) / delta; } else if (newB === max) { h = 4 + (newR - newG) / delta; } else { h = 0; } h = Math.min(h * 60, 360); if (h < 0) { h += 360; } let s: number; if (max === min) { s = 0; } else if (l <= 0.5) { s = delta / (max + min); } else { s = delta / (2 - max - min); } return new ColorHelper(HSL, h, s, l, a, hasAlpha); } function HSLtoRGB(r: number, g: number, b: number, a: number, hasAlpha: boolean): ColorHelper { const newH = r / 360; const newS = g; const newL = b; if (newS === 0) { const val = newL * 255; return new ColorHelper(RGB, val, val, val, a, hasAlpha); } const t2 = newL < 0.5 ? newL * (1 + newS) : newL + newS - newL * newS; const t1 = 2 * newL - t2; let newR = 0, newG = 0, newB = 0; for (let i = 0; i < 3; i++) { let t3 = newH + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } let val: number; if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } val *= 255; // manually set variables instead of using an array if (i === 0) { newR = val; } else if (i === 1) { newG = val; } else { newB = val; } } return new ColorHelper(RGB, newR, newG, newB, a, hasAlpha); } function clampColor(channel: keyof typeof maxChannelValues, value: number): number { const min = 0; const max = maxChannelValues[channel]; return value < min ? min : value > max ? max : value; } function ensureColor(c: string | ColorHelper): ColorHelper { return c instanceof ColorHelper ? (c as ColorHelper) : color(c as string); } function parseHexCode(stringValue: string): ColorHelper | undefined { const match = stringValue.match(/#(([a-f0-9]{6})|([a-f0-9]{3}))$/i); if (!match) { return undefined; } const hex = match[1]; const hexColor = parseInt(hex.length === 3 ? hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2] : hex, 16); const r = (hexColor >> 16) & 0xff; const b = (hexColor >> 8) & 0xff; const g = hexColor & 0xff; return new ColorHelper(RGB, r, b, g, 1, false); } function parseColorFunction(colorString: string): ColorHelper | undefined { const cssParts = parseCSSFunction(colorString); if (!cssParts || !(cssParts.length === 4 || cssParts.length === 5)) { return undefined; } const fn = cssParts[0]; const isRGBA = fn === 'rgba'; const isHSLA = fn === 'hsla'; const isRGB = fn === RGB; const isHSL = fn === HSL; const hasAlpha = isHSLA || isRGBA; let type: 'rgb' | 'hsl'; if (isRGB || isRGBA) { type = RGB; } else if (isHSL || isHSLA) { type = HSL; } else { throw new Error('unsupported color string'); } const r = toFloat(cssParts[1]); const g = isRGB || isRGBA ? toFloat(cssParts[2]) : ensurePercent(cssParts[2]); const b = isRGB || isRGBA ? toFloat(cssParts[3]) : ensurePercent(cssParts[3]); const a = hasAlpha ? toFloat(cssParts[4]) : 1; return new ColorHelper(type, r, g, b, a, hasAlpha); }
the_stack
export interface ExpressionBuilder { e: NewExpression } type TypeExpressionMap = { new: NewExpression unknown: UnknownExpression boolean: BooleanExpression number: NumberExpression string: StringExpression array: ArrayExpression json: JSONExpression row: RowExpression table: TableExpression } type TypePrimitiveMap = { new: never unknown: null boolean: boolean number: number string: string array: any[] json: null | number | boolean | string | any[] | { [key: string]: any } row: never table: never } type TypeInferenceMap = { [key in Types]: TypeExpressionMap[key] | TypePrimitiveMap[key] } type InferOrUnknown<T extends Types> = null | UnknownExpression | TypeInferenceMap[T] type TypeCompatibilityMap = { new: never unknown: Arg boolean: InferOrUnknown<'boolean'> number: InferOrUnknown<'number'> string: InferOrUnknown<'string'> array: InferOrUnknown<'array'> json: InferOrUnknown<'json'> row: InferOrUnknown<'row'> table: TypeInferenceMap['table'] } type Types = keyof TypeExpressionMap type ExpressionTypes = TypeExpressionMap[Types] type PrimitiveTypes = TypePrimitiveMap[Types] type ArgTypes = Exclude<Types, 'new'> type Arg = TypeExpressionMap[ArgTypes] | PrimitiveTypes type Compatible<T extends Types> = TypeCompatibilityMap[T] type CompatibleArray<T extends Types> = Compatible<T>[] | null | UnknownExpression | ArrayExpression type Infer<T extends Arg> = T extends TypeInferenceMap['new'] ? 'new' : T extends TypeInferenceMap['unknown'] ? 'unknown' : T extends TypeInferenceMap['boolean'] ? 'boolean' : T extends TypeInferenceMap['number'] ? 'number' : T extends TypeInferenceMap['string'] ? 'string' : T extends TypeInferenceMap['array'] ? 'array' : T extends TypeInferenceMap['row'] ? 'row' : T extends TypeInferenceMap['table'] ? 'table' : T extends TypeInferenceMap['json'] ? 'json' : never // json must be last due to structural typing type InferCompatible<T extends Arg> = Compatible<Infer<T>> type UnknownArgument = TypeCompatibilityMap['unknown'] type BooleanArgument = TypeCompatibilityMap['boolean'] type NumberArgument = TypeCompatibilityMap['number'] type StringArgument = TypeCompatibilityMap['string'] type ArrayArgument = TypeCompatibilityMap['array'] type RowArgument = TypeCompatibilityMap['row'] type TableArgument = TypeCompatibilityMap['table'] type JSONArgument = TypeCompatibilityMap['json'] type CompatibleTypes<T extends Types> = T | 'new' | 'unknown' type BooleanTypes = CompatibleTypes<'boolean'> type NumberTypes = CompatibleTypes<'number'> type StringTypes = CompatibleTypes<'string'> type ArrayTypes = CompatibleTypes<'array'> type RowTypes = CompatibleTypes<'row'> type TableTypes = CompatibleTypes<'table'> type JSONTypes = CompatibleTypes<'json'> interface Expression<T extends Types> extends ComparisonOperations<T> { type: T _build(): string } // // Expressions // interface AllOperations<T extends 'new' | 'unknown'> extends ValueOperations<T>, ArgOperations, LogicalOperations<T>, MathOperations<T>, StringOperations<T>, ArrayOperations<T>, RowOperations<T>, TableOperations<T> {} interface NewExpression extends Expression<'new'>, AllOperations<'new'> {} interface UnknownExpression extends Expression<'unknown'>, AllOperations<'unknown'> {} interface BooleanExpression extends Expression<'boolean'>, LogicalOperations<'boolean'> {} interface NumberExpression extends Expression<'number'>, MathOperations<'number'> {} interface StringExpression extends Expression<'string'>, StringOperations<'string'> {} interface ArrayExpression extends Expression<'array'>, ArrayOperations<'array'> {} interface RowExpression extends Expression<'row'> {} interface TableExpression extends Expression<'table'>, TableOperations<'table'>, ValueOperations<'table'> {} interface JSONExpression extends Expression<'json'>, JSONOperations<'json'> {} // // Operations // interface ArgOperations { (strings: TemplateStringsArray, ...args: any[]): UnknownExpression <T extends Arg>(arg: T): TypeArgChainMap[Infer<T>] (...arg: Arg[]): RowExpression } type TypeArgChainMap = { unknown: ArgUnknownChain boolean: ArgBooleanChain number: ArgNumberChain string: ArgStringChain array: ArgArrayChain json: ArgJSONChain row: ArgRowChain table: ArgTableChain } interface ArgChain { (strings: TemplateStringsArray, ...args: any[]): RowExpression (...arg: Arg[]): RowExpression } interface ArgUnknownChain extends ArgChain, UnknownExpression {} interface ArgBooleanChain extends ArgChain, BooleanExpression {} interface ArgNumberChain extends ArgChain, NumberExpression {} interface ArgStringChain extends ArgChain, StringExpression {} interface ArgArrayChain extends ArgChain, ArrayExpression {} interface ArgJSONChain extends ArgChain, JSONExpression {} interface ArgRowChain extends ArgChain, RowExpression {} interface ArgTableChain extends ArgChain, TableExpression {} interface ValueOperations<T extends Types> { unknown: T extends 'new' ? UnknownChain : UnknownExpression boolean: T extends 'new' ? BooleanChain : BooleanExpression number: T extends 'new' ? NumberChain : NumberExpression string: T extends 'new' ? StringChain : StringExpression array: T extends 'new' ? ArrayChain : ArrayExpression json: T extends 'new' ? JSONChain : JSONExpression row: T extends 'new' ? RowChain : RowExpression table: T extends 'new' ? TableChain : TableExpression } interface UnknownChain { (strings: TemplateStringsArray, ...args: any[]): UnknownExpression (unknown: UnknownArgument): UnknownExpression } interface BooleanChain { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (boolean: BooleanArgument): BooleanExpression } interface NumberChain { (strings: TemplateStringsArray, ...args: any[]): NumberExpression (number: NumberArgument): NumberExpression } interface StringChain { (strings: TemplateStringsArray, ...args: any[]): StringExpression (string: StringArgument): StringExpression } interface ArrayChain { (strings: TemplateStringsArray, ...args: any[]): ArrayExpression (array: ArrayArgument): ArrayExpression } interface JSONChain { (strings: TemplateStringsArray, ...args: any[]): JSONExpression (json: JSONArgument): JSONExpression } interface RowChain { (strings: TemplateStringsArray, ...args: any[]): RowExpression (row: RowArgument): RowExpression (...arg: Arg[]): RowExpression } interface TableChain { (strings: TemplateStringsArray, ...args: any[]): TableExpression (table: TableArgument): TableExpression } // // Logical Operations // interface LogicalOperations<T extends BooleanTypes> { // logical and: T extends 'new' ? And : AndChain or: T extends 'new' ? Or : OrChain not: T extends 'new' ? Not : BooleanExpression // comparison isTrue: T extends 'new' ? IsTrue : BooleanExpression isNotTrue: T extends 'new' ? IsNotTrue : BooleanExpression isFalse: T extends 'new' ? IsFalse : BooleanExpression isNotFalse: T extends 'new' ? IsNotFalse : BooleanExpression isUnknown: T extends 'new' ? IsUnknown : BooleanExpression isNotUnknown: T extends 'new' ? IsNotUnknown : BooleanExpression } interface And { (text: TemplateStringsArray, ...args: any[]): AndChain (...args: BooleanArgument[]): AndChain } interface AndChain extends And, BooleanExpression {} interface Or { (text: TemplateStringsArray, ...args: any[]): OrChain (...args: BooleanArgument[]): OrChain } interface OrChain extends Or, BooleanExpression {} interface Not { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg: BooleanArgument): BooleanExpression } interface IsTrue { (arg1: Arg): BooleanExpression } interface IsNotTrue { (arg1: Arg): BooleanExpression } interface IsFalse { (arg1: Arg): BooleanExpression } interface IsNotFalse { (arg1: Arg): BooleanExpression } interface IsUnknown { (arg1: BooleanArgument): BooleanExpression } interface IsNotUnknown { (arg1: BooleanArgument): BooleanExpression } // // Comparison Operations // interface ComparisonOperations<T extends Types> { // binary comparison eq: T extends 'new' ? Eq : EqChain<T> neq: T extends 'new' ? Neq : NeqChain<T> lt: T extends 'new' ? Lt : LtChain<T> gt: T extends 'new' ? Gt : GtChain<T> lte: T extends 'new' ? Lte : LteChain<T> gte: T extends 'new' ? Gte : GteChain<T> // misc between: T extends 'new' ? Between : BetweenChain1<T> notBetween: T extends 'new' ? NotBetween : NotBetweenChain1<T> isDistinctFrom: T extends 'new' ? IsDistinctFrom : IsDistinctFromChain<T> isNotDistinctFrom: T extends 'new' ? IsNotDistinctFrom : IsNotDistinctFromChain<T> isNull: T extends 'new' ? IsNull : BooleanExpression isNotNull: T extends 'new' ? IsNotNull : BooleanExpression in: T extends 'new' ? In : InChain<T> notIn: T extends 'new' ? NotIn : NotInChain<T> // quantified any eqAny: T extends 'new' ? EqAny : EqAnyChain<T> neqAny: T extends 'new' ? NeqAny : NeqAnyChain<T> ltAny: T extends 'new' ? LtAny : LtAnyChain<T> gtAny: T extends 'new' ? GtAny : GtAnyChain<T> lteAny: T extends 'new' ? LteAny : LteAnyChain<T> gteAny: T extends 'new' ? GteAny : GteAnyChain<T> // quantified all eqAll: T extends 'new' ? EqAll : EqAllChain<T> neqAll: T extends 'new' ? NeqAll : NeqAllChain<T> ltAll: T extends 'new' ? LtAll : LtAllChain<T> gtAll: T extends 'new' ? GtAll : GtAllChain<T> lteAll: T extends 'new' ? LteAll : LteAllChain<T> gteAll: T extends 'new' ? GteAll : GteAllChain<T> } interface Eq { (text: TemplateStringsArray, ...args: any[]): EqChain<'unknown'> <T extends Arg>(arg1: T): EqChain<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>): BooleanExpression } interface EqChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: Compatible<T>): BooleanExpression } interface Neq { (strings: TemplateStringsArray, ...args: any[]): NeqChain<'unknown'> <T extends Arg>(arg1: T): NeqChain<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>): BooleanExpression } interface NeqChain<T extends Types> { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: Compatible<T>): BooleanExpression } interface Lt { (strings: TemplateStringsArray, ...args: any[]): LtChain<'unknown'> <T extends Arg>(arg1: T): LtChain<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>): BooleanExpression } interface LtChain<T extends Types> { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: Compatible<T>): BooleanExpression } interface Gt { (strings: TemplateStringsArray, ...args: any[]): GtChain<'unknown'> <T extends Arg>(arg1: T): GtChain<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>): BooleanExpression } interface GtChain<T extends Types> { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: Compatible<T>): BooleanExpression } interface Lte { (strings: TemplateStringsArray, ...args: any[]): LteChain<'unknown'> <T extends Arg>(arg1: T): LteChain<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>): BooleanExpression } interface LteChain<T extends Types> { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: Compatible<T>): BooleanExpression } interface Gte { (strings: TemplateStringsArray, ...args: any[]): GteChain<'unknown'> <T extends Arg>(arg1: T): GteChain<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>): BooleanExpression } interface GteChain<T extends Types> { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: Compatible<T>): BooleanExpression } interface Between { (strings: TemplateStringsArray, ...args: any[]): BetweenChain1<'unknown'> <T extends Arg>(arg1: T): BetweenChain1<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>): BetweenChain2<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>, arg3: InferCompatible<T>): BooleanExpression } interface BetweenChain1<T extends Types> { (strings: TemplateStringsArray, ...args: any[]): BetweenChain2<T> (arg2: Compatible<T>): BetweenChain2<T> (arg2: Compatible<T>, arg3: Compatible<T>): BooleanExpression } interface BetweenChain2<T extends Types> { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg3: Compatible<T>): BooleanExpression } interface NotBetween { (strings: TemplateStringsArray, ...args: any[]): NotBetweenChain1<'unknown'> <T extends Arg>(arg1: T): NotBetweenChain1<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>): NotBetweenChain2<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>, arg3: InferCompatible<T>): BooleanExpression } interface NotBetweenChain1<T extends Types> { (strings: TemplateStringsArray, ...args: any[]): NotBetweenChain2<T> (arg2: Compatible<T>): NotBetweenChain2<T> (arg2: Compatible<T>, arg3: Compatible<T>): BooleanExpression } interface NotBetweenChain2<T extends Types> { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg3: Compatible<T>): BooleanExpression } interface IsDistinctFrom { (text: TemplateStringsArray, ...args: any[]): IsDistinctFromChain<'unknown'> <T extends Arg>(arg1: T): IsDistinctFromChain<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>): BooleanExpression } interface IsDistinctFromChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: Compatible<T>): BooleanExpression } interface IsNotDistinctFrom { (text: TemplateStringsArray, ...args: any[]): IsNotDistinctFromChain<'unknown'> <T extends Arg>(arg1: T): IsNotDistinctFromChain<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>): BooleanExpression } interface IsNotDistinctFromChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: Compatible<T>): BooleanExpression } interface IsNull { (arg1: Arg): BooleanExpression } interface IsNotNull { (arg1: Arg): BooleanExpression } interface EqAny { (text: TemplateStringsArray, ...args: any[]): EqAnyChain<'unknown'> <T extends Arg>(arg1: T): EqAnyChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface EqAnyChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface NeqAny { (text: TemplateStringsArray, ...args: any[]): NeqAnyChain<'unknown'> <T extends Arg>(arg1: T): NeqAnyChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface NeqAnyChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface LtAny { (text: TemplateStringsArray, ...args: any[]): LtAnyChain<'unknown'> <T extends Arg>(arg1: T): LtAnyChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface LtAnyChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface GtAny { (text: TemplateStringsArray, ...args: any[]): GtAnyChain<'unknown'> <T extends Arg>(arg1: T): GtAnyChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface GtAnyChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface LteAny { (text: TemplateStringsArray, ...args: any[]): LteAnyChain<'unknown'> <T extends Arg>(arg1: T): LteAnyChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface LteAnyChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface GteAny { (text: TemplateStringsArray, ...args: any[]): GteAnyChain<'unknown'> <T extends Arg>(arg1: T): GteAnyChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface GteAnyChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface EqSome { (text: TemplateStringsArray, ...args: any[]): EqSomeChain<'unknown'> <T extends Arg>(arg1: T): EqSomeChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface EqSomeChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface NeqSome { (text: TemplateStringsArray, ...args: any[]): NeqSomeChain<'unknown'> <T extends Arg>(arg1: T): NeqSomeChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface NeqSomeChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface LtSome { (text: TemplateStringsArray, ...args: any[]): LtSomeChain<'unknown'> <T extends Arg>(arg1: T): LtSomeChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface LtSomeChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface GtSome { (text: TemplateStringsArray, ...args: any[]): GtSomeChain<'unknown'> <T extends Arg>(arg1: T): GtSomeChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface GtSomeChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface LteSome { (text: TemplateStringsArray, ...args: any[]): LteSomeChain<'unknown'> <T extends Arg>(arg1: T): LteSomeChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface LteSomeChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface GteSome { (text: TemplateStringsArray, ...args: any[]): GteSomeChain<'unknown'> <T extends Arg>(arg1: T): GteSomeChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface GteSomeChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface EqAll { (text: TemplateStringsArray, ...args: any[]): EqAllChain<'unknown'> <T extends Arg>(arg1: T): EqAllChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface EqAllChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface NeqAll { (text: TemplateStringsArray, ...args: any[]): NeqAllChain<'unknown'> <T extends Arg>(arg1: T): NeqAllChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface NeqAllChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface LtAll { (text: TemplateStringsArray, ...args: any[]): LtAllChain<'unknown'> <T extends Arg>(arg1: T): LtAllChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface LtAllChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface GtAll { (text: TemplateStringsArray, ...args: any[]): GtAllChain<'unknown'> <T extends Arg>(arg1: T): GtAllChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface GtAllChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface LteAll { (text: TemplateStringsArray, ...args: any[]): LteAllChain<'unknown'> <T extends Arg>(arg1: T): LteAllChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface LteAllChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface GteAll { (text: TemplateStringsArray, ...args: any[]): GteAllChain<'unknown'> <T extends Arg>(arg1: T): GteAllChain<Infer<T>> <T extends Arg>(arg1: T, arg2: CompatibleArray<Infer<T>>): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface GteAllChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<T>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface In { (text: TemplateStringsArray, ...args: any[]): InChain<'unknown'> <T extends Arg>(arg1: T): InChain<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>[]): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface InChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: Compatible<T>[]): BooleanExpression (arg2: TableArgument): BooleanExpression } interface NotIn { (text: TemplateStringsArray, ...args: any[]): NotInChain<'unknown'> <T extends Arg>(arg1: T): NotInChain<Infer<T>> <T extends Arg>(arg1: T, arg2: InferCompatible<T>[]): BooleanExpression <T extends Arg>(arg1: T, arg2: TableArgument): BooleanExpression } interface NotInChain<T extends Types> { (text: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: Compatible<T>[]): BooleanExpression (arg2: TableArgument): BooleanExpression } // // Number Operations // interface MathOperations<T extends NumberTypes> { add: T extends 'new' ? Add : AddChain sub: T extends 'new' ? Sub : SubChain mul: T extends 'new' ? Mul : MulChain div: T extends 'new' ? Div : DivChain mod: T extends 'new' ? Mod : ModChain exp: T extends 'new' ? Exp : ExpChain sqrt: T extends 'new'? Sqrt : NumberExpression cbrt: T extends 'new'? Cbrt : NumberExpression fact: T extends 'new' ? Fact : NumberExpression abs: T extends 'new'? Abs : NumberExpression } interface Add { (text: TemplateStringsArray, ...args: any[]): AddChain (arg1: NumberArgument): AddChain (arg1: NumberArgument, arg2: NumberArgument): NumberExpression } interface AddChain { (text: TemplateStringsArray, ...args: any[]): NumberExpression (arg2: NumberArgument): NumberExpression } interface Sub { (text: TemplateStringsArray, ...args: any[]): SubChain (arg1: NumberArgument): SubChain (arg1: NumberArgument, arg2: NumberArgument): NumberExpression } interface SubChain { (text: TemplateStringsArray, ...args: any[]): NumberExpression (arg2: NumberArgument): NumberExpression } interface Mul { (text: TemplateStringsArray, ...args: any[]): MulChain (arg1: NumberArgument): MulChain (arg1: NumberArgument, arg2: NumberArgument): NumberExpression } interface MulChain { (text: TemplateStringsArray, ...args: any[]): NumberExpression (arg2: NumberArgument): NumberExpression } interface Div { (text: TemplateStringsArray, ...args: any[]): DivChain (arg1: NumberArgument): DivChain (arg1: NumberArgument, arg2: NumberArgument): NumberExpression } interface DivChain { (text: TemplateStringsArray, ...args: any[]): NumberExpression (arg2: NumberArgument): NumberExpression } interface Mod { (text: TemplateStringsArray, ...args: any[]): ModChain (arg1: NumberArgument): ModChain (arg1: NumberArgument, arg2: NumberArgument): NumberExpression } interface ModChain { (text: TemplateStringsArray, ...args: any[]): NumberExpression (arg2: NumberArgument): NumberExpression } interface Exp { (text: TemplateStringsArray, ...args: any[]): ExpChain (arg1: NumberArgument): ExpChain (arg1: NumberArgument, arg2: NumberArgument): NumberExpression } interface ExpChain { (text: TemplateStringsArray, ...args: any[]): NumberExpression (arg2: NumberArgument): NumberExpression } interface Sqrt { (text: TemplateStringsArray, ...args: any[]): NumberExpression (arg1: NumberArgument): NumberExpression } interface Cbrt { (text: TemplateStringsArray, ...args: any[]): NumberExpression (arg1: NumberArgument): NumberExpression } interface Fact { (text: TemplateStringsArray, ...args: any[]): NumberExpression (arg1: NumberArgument): NumberExpression } interface Abs { (text: TemplateStringsArray, ...args: any[]): NumberExpression (arg1: NumberArgument): NumberExpression } // // String Operations // interface StringOperations<T extends StringTypes> { like: T extends 'new' ? Like : LikeChain notLike: T extends 'new' ? NotLike : NotLikeChain // any likeAny: T extends 'new' ? LikeAny : LikeAnyChain notLikeAny: T extends 'new' ? NotLikeAny : NotLikeAnyChain // all likeAll: T extends 'new' ? LikeAll : LikeAllChain notLikeAll: T extends 'new' ? NotLikeAll : NotLikeAllChain concat: T extends 'new' ? Concat : ConcatChain similarTo: T extends 'new' ? SimilarTo : SimilarToChain notSimilarTo: T extends 'new' ? NotSimilarTo : NotSimilarToChain lower: T extends 'new' ? Lower : StringExpression upper: T extends 'new' ? Upper : StringExpression } interface Concat { (strings: TemplateStringsArray, ...args: any[]): ConcatChain (...args: StringArgument[]): ConcatChain } interface ConcatChain extends Concat, StringExpression {} interface Like { (strings: TemplateStringsArray, ...args: any[]): LikeChain (arg1: StringArgument): LikeChain (arg1: StringArgument, arg2: StringArgument): LikeEscape } interface LikeChain { (strings: TemplateStringsArray, ...args: any[]): LikeEscape (arg2: StringArgument): LikeEscape } interface LikeEscape extends BooleanExpression { escape(strings: TemplateStringsArray, ...args: any[]): BooleanExpression escape(character: StringArgument): BooleanExpression } interface NotLike { (strings: TemplateStringsArray, ...args: any[]): NotLikeChain (arg1: StringArgument): NotLikeChain (arg1: StringArgument, arg2: StringArgument): LikeEscape } interface NotLikeChain { (strings: TemplateStringsArray, ...args: any[]): LikeEscape (arg2: StringArgument): LikeEscape } interface LikeAny { (strings: TemplateStringsArray, ...args: any[]): LikeAnyChain (arg1: StringArgument): LikeAnyChain (arg1: StringArgument, arg2: CompatibleArray<'string'>): BooleanExpression (arg1: StringArgument, arg2: TableArgument): BooleanExpression } interface LikeAnyChain { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<'string'>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface LikeAll { (strings: TemplateStringsArray, ...args: any[]): LikeAllChain (arg1: StringArgument): LikeAllChain (arg1: StringArgument, arg2: CompatibleArray<'string'>): BooleanExpression (arg1: StringArgument, arg2: TableArgument): BooleanExpression } interface LikeAllChain { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<'string'>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface NotLikeAny { (strings: TemplateStringsArray, ...args: any[]): NotLikeAnyChain (arg1: StringArgument): NotLikeAnyChain (arg1: StringArgument, arg2: CompatibleArray<'string'>): BooleanExpression (arg1: StringArgument, arg2: TableArgument): BooleanExpression } interface NotLikeAnyChain { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<'string'>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface NotLikeAll { (strings: TemplateStringsArray, ...args: any[]): NotLikeAllChain (arg1: StringArgument): NotLikeAllChain (arg1: StringArgument, arg2: CompatibleArray<'string'>): BooleanExpression (arg1: StringArgument, arg2: TableArgument): BooleanExpression } interface NotLikeAllChain { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: CompatibleArray<'string'>): BooleanExpression (arg2: TableArgument): BooleanExpression } interface SimilarTo { (strings: TemplateStringsArray, ...args: any[]): SimilarToChain (arg1: StringArgument): SimilarToChain (arg1: StringArgument, arg2: StringArgument): BooleanExpression } interface SimilarToChain { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: StringArgument): BooleanExpression } interface NotSimilarTo { (strings: TemplateStringsArray, ...args: any[]): NotSimilarToChain (arg1: StringArgument): NotSimilarToChain (arg1: StringArgument, arg2: StringArgument): BooleanExpression } interface NotSimilarToChain { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg2: StringArgument): BooleanExpression } interface Lower { (strings: TemplateStringsArray, ...args: any[]): StringExpression (arg: StringArgument): StringExpression } interface Upper { (strings: TemplateStringsArray, ...args: any[]): StringExpression (arg: StringArgument): StringExpression } // // Array Operations // interface ArrayOperations<T extends ArrayTypes> { unnest: T extends 'new' ? Unnest : UnnestChain arrayGet: T extends 'new' ? ArrayGet : ArrayGetChain arrayAppend: T extends 'new' ? ArrayAppend : ArrayAppendChain arrayCat: T extends 'new' ? ArrayCat : ArrayCatChain } interface Unnest { (text: TemplateStringsArray, ...args: any[]): UnnestChain (...args: ArrayArgument[]): UnnestChain } interface UnnestChain extends Unnest, TableExpression {} interface ArrayGet { (strings: TemplateStringsArray, ...args: any[]): ArrayGetChain (array: ArrayArgument): ArrayGetChain (array: ArrayArgument, index: NumberArgument): UnknownExpression } interface ArrayGetChain { (strings: TemplateStringsArray, ...args: any[]): UnknownExpression (index: NumberArgument): UnknownExpression } interface ArrayAppend { (strings: TemplateStringsArray, ...args: any[]): ArrayAppendChain (array: ArrayArgument): ArrayAppendChain (array: ArrayArgument, element: UnknownArgument): ArrayExpression } interface ArrayAppendChain { (strings: TemplateStringsArray, ...args: any[]): ArrayExpression (element: UnknownArgument): ArrayExpression } interface ArrayCat { (strings: TemplateStringsArray, ...args: any[]): ArrayCatChain (array1: ArrayArgument): ArrayCatChain (array1: ArrayArgument, array2: ArrayArgument): ArrayExpression } interface ArrayCatChain { (strings: TemplateStringsArray, ...args: any[]): ArrayExpression (array2: ArrayArgument): ArrayExpression } // // Row Operations // interface RowOperations<T extends RowTypes> { } // // table Operations // interface TableOperations<T extends TableTypes> { exists: T extends 'new' ? Exists : BooleanExpression notExists: T extends 'new' ? NotExists : BooleanExpression } interface Exists { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg: TableArgument): BooleanExpression } interface NotExists { (strings: TemplateStringsArray, ...args: any[]): BooleanExpression (arg: TableArgument): BooleanExpression } // // JSON Operations // interface JSONOperations<T extends JSONTypes> {}
the_stack
import * as gregor1 from '../gregor1'; export declare type HasServerKeysRes = { hasServerKeys: boolean; }; export declare type APIRes = { status: string; body: string; httpStatus: number; appStatus: string; }; export declare enum MobileAppState { FOREGROUND = "foreground", BACKGROUND = "background", INACTIVE = "inactive", BACKGROUNDACTIVE = "backgroundactive" } export declare enum MobileNetworkState { NONE = "none", WIFI = "wifi", CELLULAR = "cellular", UNKNOWN = "unknown", NOTAVAILABLE = "notavailable" } export declare enum BoxAuditAttemptResult { FAILURE_RETRYABLE = "failure_retryable", FAILURE_MALICIOUS_SERVER = "failure_malicious_server", OK_VERIFIED = "ok_verified", OK_NOT_ATTEMPTED_ROLE = "ok_not_attempted_role", OK_NOT_ATTEMPTED_OPENTEAM = "ok_not_attempted_openteam", OK_NOT_ATTEMPTED_SUBTEAM = "ok_not_attempted_subteam" } export declare type AvatarUrl = string; export declare type AvatarFormat = string; export declare enum BlockType { DATA = "data", MD = "md", GIT = "git" } export declare type ChallengeInfo = { now: number; challenge: string; }; export declare enum BlockStatus { UNKNOWN = "unknown", LIVE = "live", ARCHIVED = "archived" } export declare type BlockRefNonce = string | null; export declare type BlockPingResponse = {}; export declare type UsageStatRecord = { write: number; archive: number; read: number; mdWrite: number; gitWrite: number; gitArchive: number; }; export declare type BotToken = string; export declare type Time = number; export declare type UnixTime = number; export declare type DurationSec = number; export declare type DurationMsec = number; export declare type StringKVPair = { key: string; value: string; }; export declare type UID = string; export declare type VID = string; export declare type DeviceID = string; export declare type SigID = string; export declare type LeaseID = string; export declare type KID = string; export declare type PhoneNumber = string; export declare type RawPhoneNumber = string; export declare type LinkID = string; export declare type BinaryLinkID = Buffer; export declare type BinaryKID = Buffer; export declare type TLFID = string; export declare type TeamID = string; export declare type UserOrTeamID = string; export declare type GitRepoName = string; export declare type HashMeta = Buffer; export declare enum TeamType { NONE = "none", LEGACY = "legacy", MODERN = "modern" } export declare enum TLFVisibility { ANY = "any", PUBLIC = "public", PRIVATE = "private" } export declare type Seqno = number; export declare enum SeqType { NONE = "none", PUBLIC = "public", PRIVATE = "private", SEMIPRIVATE = "semiprivate", USER_PRIVATE_HIDDEN = "user_private_hidden", TEAM_PRIVATE_HIDDEN = "team_private_hidden" } export declare type Bytes32 = string | null; export declare type Text = { data: string; markup: boolean; }; export declare type PGPIdentity = { username: string; comment: string; email: string; }; export declare enum DeviceType { DESKTOP = "desktop", MOBILE = "mobile" } export declare type DeviceTypeV2 = string; export declare type Stream = { fd: number; }; export declare enum LogLevel { NONE = "none", DEBUG = "debug", INFO = "info", NOTICE = "notice", WARN = "warn", ERROR = "error", CRITICAL = "critical", FATAL = "fatal" } export declare enum ClientType { NONE = "none", CLI = "cli", GUI_MAIN = "gui_main", KBFS = "kbfs", GUI_HELPER = "gui_helper" } export declare type KBFSPathInfo = { standardPath: string; deeplinkPath: string; platformAfterMountPath: string; }; export declare type PerUserKeyGeneration = number; export declare enum UserOrTeamResult { USER = "user", TEAM = "team" } export declare enum MerkleTreeID { MASTER = "master", KBFS_PUBLIC = "kbfs_public", KBFS_PRIVATE = "kbfs_private", KBFS_PRIVATETEAM = "kbfs_privateteam" } /** * SocialAssertionService is a service that can be used to assert proofs for a * user. */ export declare type SocialAssertionService = string; export declare type FullName = string; export declare enum FullNamePackageVersion { V0 = "v0", V1 = "v1", V2 = "v2" } export declare type ImageCropRect = { x0: number; y0: number; x1: number; y1: number; }; export declare enum IdentityVisibility { PRIVATE = "private", PUBLIC = "public" } export declare type SizedImage = { path: string; width: number; }; export declare enum OfflineAvailability { NONE = "none", BEST_EFFORT = "best_effort" } export declare type UserReacji = { name: string; customAddr?: string; customAddrNoAnim?: string; }; export declare enum ReacjiSkinTone { NONE = "none", SKINTONE1 = "skintone1", SKINTONE2 = "skintone2", SKINTONE3 = "skintone3", SKINTONE4 = "skintone4", SKINTONE5 = "skintone5" } export declare enum WotStatusType { NONE = "none", PROPOSED = "proposed", ACCEPTED = "accepted", REJECTED = "rejected", REVOKED = "revoked" } export declare type SessionStatus = { sessionFor: string; loaded: boolean; cleared: boolean; saltOnly: boolean; expired: boolean; }; export declare type PlatformInfo = { os: string; osVersion: string; arch: string; goVersion: string; }; export declare type LoadDeviceErr = { where: string; desc: string; }; export declare type DirSizeInfo = { numFiles: number; name: string; humanSize: string; }; export declare type KbClientStatus = { version: string; }; export declare type KbServiceStatus = { version: string; running: boolean; pid: string; log: string; ekLog: string; perfLog: string; }; export declare type KBFSStatus = { version: string; installedVersion: string; running: boolean; pid: string; log: string; perfLog: string; mount: string; }; export declare type DesktopStatus = { version: string; running: boolean; log: string; }; export declare type UpdaterStatus = { log: string; }; export declare type StartStatus = { log: string; }; export declare type GitStatus = { log: string; perfLog: string; }; export declare type LogSendID = string; export declare type AllProvisionedUsernames = { defaultUsername: string; provisionedUsernames: string[] | null; hasProvisionedUser: boolean; }; export declare enum ForkType { NONE = "none", AUTO = "auto", WATCHDOG = "watchdog", LAUNCHD = "launchd", SYSTEMD = "systemd" } export declare type ConfigValue = { isNull: boolean; b?: boolean; i?: number; f?: number; s?: string; o?: string; }; export declare type OutOfDateInfo = { upgradeTo: string; upgradeUri: string; customMessage: string; criticalClockSkew: number; }; export declare enum UpdateInfoStatus { UP_TO_DATE = "up_to_date", NEED_UPDATE = "need_update", CRITICALLY_OUT_OF_DATE = "critically_out_of_date" } export declare enum UpdateInfoStatus2 { OK = "ok", SUGGESTED = "suggested", CRITICAL = "critical" } export declare type UpdateDetails = { message: string; }; export declare enum ProxyType { No_Proxy = "no_proxy", HTTP_Connect = "http_connect", Socks = "socks" } export declare enum StatusCode { SCOk = "scok", SCInputError = "scinputerror", SCAssertionParseError = "scassertionparseerror", SCLoginRequired = "scloginrequired", SCBadSession = "scbadsession", SCBadLoginUserNotFound = "scbadloginusernotfound", SCBadLoginPassword = "scbadloginpassword", SCNotFound = "scnotfound", SCThrottleControl = "scthrottlecontrol", SCDeleted = "scdeleted", SCGeneric = "scgeneric", SCAlreadyLoggedIn = "scalreadyloggedin", SCExists = "scexists", SCCanceled = "sccanceled", SCInputCanceled = "scinputcanceled", SCBadUsername = "scbadusername", SCOffline = "scoffline", SCReloginRequired = "screloginrequired", SCResolutionFailed = "scresolutionfailed", SCProfileNotPublic = "scprofilenotpublic", SCIdentifyFailed = "scidentifyfailed", SCTrackingBroke = "sctrackingbroke", SCWrongCryptoFormat = "scwrongcryptoformat", SCDecryptionError = "scdecryptionerror", SCInvalidAddress = "scinvalidaddress", SCWrongCryptoMsgType = "scwrongcryptomsgtype", SCNoSession = "scnosession", SCAccountReset = "scaccountreset", SCIdentifiesFailed = "scidentifiesfailed", SCNoSpaceOnDevice = "scnospaceondevice", SCMerkleClientError = "scmerkleclienterror", SCMerkleUpdateRoot = "scmerkleupdateroot", SCBadEmail = "scbademail", SCRateLimit = "scratelimit", SCBadSignupUsernameTaken = "scbadsignupusernametaken", SCDuplicate = "scduplicate", SCBadInvitationCode = "scbadinvitationcode", SCBadSignupUsernameReserved = "scbadsignupusernamereserved", SCBadSignupTeamName = "scbadsignupteamname", SCFeatureFlag = "scfeatureflag", SCEmailTaken = "scemailtaken", SCEmailAlreadyAdded = "scemailalreadyadded", SCEmailLimitExceeded = "scemaillimitexceeded", SCEmailCannotDeletePrimary = "scemailcannotdeleteprimary", SCEmailUnknown = "scemailunknown", SCBotSignupTokenNotFound = "scbotsignuptokennotfound", SCNoUpdate = "scnoupdate", SCMissingResult = "scmissingresult", SCKeyNotFound = "sckeynotfound", SCKeyCorrupted = "sckeycorrupted", SCKeyInUse = "sckeyinuse", SCKeyBadGen = "sckeybadgen", SCKeyNoSecret = "sckeynosecret", SCKeyBadUIDs = "sckeybaduids", SCKeyNoActive = "sckeynoactive", SCKeyNoSig = "sckeynosig", SCKeyBadSig = "sckeybadsig", SCKeyBadEldest = "sckeybadeldest", SCKeyNoEldest = "sckeynoeldest", SCKeyDuplicateUpdate = "sckeyduplicateupdate", SCSibkeyAlreadyExists = "scsibkeyalreadyexists", SCDecryptionKeyNotFound = "scdecryptionkeynotfound", SCVerificationKeyNotFound = "scverificationkeynotfound", SCKeyNoPGPEncryption = "sckeynopgpencryption", SCKeyNoNaClEncryption = "sckeynonaclencryption", SCKeySyncedPGPNotFound = "sckeysyncedpgpnotfound", SCKeyNoMatchingGPG = "sckeynomatchinggpg", SCKeyRevoked = "sckeyrevoked", SCSigCannotVerify = "scsigcannotverify", SCSigWrongKey = "scsigwrongkey", SCSigOldSeqno = "scsigoldseqno", SCSigCreationDisallowed = "scsigcreationdisallowed", SCSigMissingRatchet = "scsigmissingratchet", SCSigBadTotalOrder = "scsigbadtotalorder", SCBadTrackSession = "scbadtracksession", SCDeviceBadName = "scdevicebadname", SCDeviceBadStatus = "scdevicebadstatus", SCDeviceNameInUse = "scdevicenameinuse", SCDeviceNotFound = "scdevicenotfound", SCDeviceMismatch = "scdevicemismatch", SCDeviceRequired = "scdevicerequired", SCDevicePrevProvisioned = "scdeviceprevprovisioned", SCDeviceNoProvision = "scdevicenoprovision", SCDeviceProvisionViaDevice = "scdeviceprovisionviadevice", SCRevokeCurrentDevice = "screvokecurrentdevice", SCRevokeLastDevice = "screvokelastdevice", SCDeviceProvisionOffline = "scdeviceprovisionoffline", SCRevokeLastDevicePGP = "screvokelastdevicepgp", SCStreamExists = "scstreamexists", SCStreamNotFound = "scstreamnotfound", SCStreamWrongKind = "scstreamwrongkind", SCStreamEOF = "scstreameof", SCStreamUnknown = "scstreamunknown", SCGenericAPIError = "scgenericapierror", SCAPINetworkError = "scapinetworkerror", SCTimeout = "sctimeout", SCKBFSClientTimeout = "sckbfsclienttimeout", SCProofError = "scprooferror", SCIdentificationExpired = "scidentificationexpired", SCSelfNotFound = "scselfnotfound", SCBadKexPhrase = "scbadkexphrase", SCNoUIDelegation = "scnouidelegation", SCNoUI = "scnoui", SCGPGUnavailable = "scgpgunavailable", SCInvalidVersionError = "scinvalidversionerror", SCOldVersionError = "scoldversionerror", SCInvalidLocationError = "scinvalidlocationerror", SCServiceStatusError = "scservicestatuserror", SCInstallError = "scinstallerror", SCLoadKextError = "scloadkexterror", SCLoadKextPermError = "scloadkextpermerror", SCGitInternal = "scgitinternal", SCGitRepoAlreadyExists = "scgitrepoalreadyexists", SCGitInvalidRepoName = "scgitinvalidreponame", SCGitCannotDelete = "scgitcannotdelete", SCGitRepoDoesntExist = "scgitrepodoesntexist", SCLoginStateTimeout = "scloginstatetimeout", SCChatInternal = "scchatinternal", SCChatRateLimit = "scchatratelimit", SCChatConvExists = "scchatconvexists", SCChatUnknownTLFID = "scchatunknowntlfid", SCChatNotInConv = "scchatnotinconv", SCChatBadMsg = "scchatbadmsg", SCChatBroadcast = "scchatbroadcast", SCChatAlreadySuperseded = "scchatalreadysuperseded", SCChatAlreadyDeleted = "scchatalreadydeleted", SCChatTLFFinalized = "scchattlffinalized", SCChatCollision = "scchatcollision", SCIdentifySummaryError = "scidentifysummaryerror", SCNeedSelfRekey = "scneedselfrekey", SCNeedOtherRekey = "scneedotherrekey", SCChatMessageCollision = "scchatmessagecollision", SCChatDuplicateMessage = "scchatduplicatemessage", SCChatClientError = "scchatclienterror", SCChatNotInTeam = "scchatnotinteam", SCChatStalePreviousState = "scchatstalepreviousstate", SCChatEphemeralRetentionPolicyViolatedError = "scchatephemeralretentionpolicyviolatederror", SCChatUsersAlreadyInConversationError = "scchatusersalreadyinconversationerror", SCChatBadConversationError = "scchatbadconversationerror", SCTeamBadMembership = "scteambadmembership", SCTeamSelfNotOwner = "scteamselfnotowner", SCTeamNotFound = "scteamnotfound", SCTeamExists = "scteamexists", SCTeamReadError = "scteamreaderror", SCTeamWritePermDenied = "scteamwritepermdenied", SCTeamBadGeneration = "scteambadgeneration", SCNoOp = "scnoop", SCTeamInviteBadCancel = "scteaminvitebadcancel", SCTeamInviteBadToken = "scteaminvitebadtoken", SCTeamBadNameReservedDB = "scteambadnamereserveddb", SCTeamTarDuplicate = "scteamtarduplicate", SCTeamTarNotFound = "scteamtarnotfound", SCTeamMemberExists = "scteammemberexists", SCTeamNotReleased = "scteamnotreleased", SCTeamPermanentlyLeft = "scteampermanentlyleft", SCTeamNeedRootId = "scteamneedrootid", SCTeamHasLiveChildren = "scteamhaslivechildren", SCTeamDeleteError = "scteamdeleteerror", SCTeamBadRootTeam = "scteambadrootteam", SCTeamNameConflictsWithUser = "scteamnameconflictswithuser", SCTeamDeleteNoUpPointer = "scteamdeletenouppointer", SCTeamNeedOwner = "scteamneedowner", SCTeamNoOwnerAllowed = "scteamnoownerallowed", SCTeamImplicitNoNonSbs = "scteamimplicitnononsbs", SCTeamImplicitBadHash = "scteamimplicitbadhash", SCTeamImplicitBadName = "scteamimplicitbadname", SCTeamImplicitClash = "scteamimplicitclash", SCTeamImplicitDuplicate = "scteamimplicitduplicate", SCTeamImplicitBadOp = "scteamimplicitbadop", SCTeamImplicitBadRole = "scteamimplicitbadrole", SCTeamImplicitNotFound = "scteamimplicitnotfound", SCTeamBadAdminSeqnoType = "scteambadadminseqnotype", SCTeamImplicitBadAdd = "scteamimplicitbadadd", SCTeamImplicitBadRemove = "scteamimplicitbadremove", SCTeamInviteTokenReused = "scteaminvitetokenreused", SCTeamKeyMaskNotFound = "scteamkeymasknotfound", SCTeamBanned = "scteambanned", SCTeamInvalidBan = "scteaminvalidban", SCTeamShowcasePermDenied = "scteamshowcasepermdenied", SCTeamProvisionalCanKey = "scteamprovisionalcankey", SCTeamProvisionalCannotKey = "scteamprovisionalcannotkey", SCTeamFTLOutdated = "scteamftloutdated", SCTeamStorageWrongRevision = "scteamstoragewrongrevision", SCTeamStorageBadGeneration = "scteamstoragebadgeneration", SCTeamStorageNotFound = "scteamstoragenotfound", SCTeamContactSettingsBlock = "scteamcontactsettingsblock", SCEphemeralKeyBadGeneration = "scephemeralkeybadgeneration", SCEphemeralKeyUnexpectedBox = "scephemeralkeyunexpectedbox", SCEphemeralKeyMissingBox = "scephemeralkeymissingbox", SCEphemeralKeyWrongNumberOfKeys = "scephemeralkeywrongnumberofkeys", SCEphemeralKeyMismatchedKey = "scephemeralkeymismatchedkey", SCEphemeralPairwiseMACsMissingUIDs = "scephemeralpairwisemacsmissinguids", SCEphemeralDeviceAfterEK = "scephemeraldeviceafterek", SCEphemeralMemberAfterEK = "scephemeralmemberafterek", SCEphemeralDeviceStale = "scephemeraldevicestale", SCEphemeralUserStale = "scephemeraluserstale", SCStellarError = "scstellarerror", SCStellarBadInput = "scstellarbadinput", SCStellarWrongRevision = "scstellarwrongrevision", SCStellarMissingBundle = "scstellarmissingbundle", SCStellarBadPuk = "scstellarbadpuk", SCStellarMissingAccount = "scstellarmissingaccount", SCStellarBadPrev = "scstellarbadprev", SCStellarWrongPrimary = "scstellarwrongprimary", SCStellarUnsupportedCurrency = "scstellarunsupportedcurrency", SCStellarNeedDisclaimer = "scstellarneeddisclaimer", SCStellarDeviceNotMobile = "scstellardevicenotmobile", SCStellarMobileOnlyPurgatory = "scstellarmobileonlypurgatory", SCStellarIncompatibleVersion = "scstellarincompatibleversion", SCNISTWrongSize = "scnistwrongsize", SCNISTBadMode = "scnistbadmode", SCNISTHashWrongSize = "scnisthashwrongsize", SCNISTSigWrongSize = "scnistsigwrongsize", SCNISTSigBadInput = "scnistsigbadinput", SCNISTSigBadUID = "scnistsigbaduid", SCNISTSigBadDeviceID = "scnistsigbaddeviceid", SCNISTSigBadNonce = "scnistsigbadnonce", SCNISTNoSigOrHash = "scnistnosigorhash", SCNISTExpired = "scnistexpired", SCNISTSigRevoked = "scnistsigrevoked", SCNISTKeyRevoked = "scnistkeyrevoked", SCNISTUserDeleted = "scnistuserdeleted", SCNISTNoDevice = "scnistnodevice", SCNISTSigCannot_verify = "scnistsigcannot_verify", SCNISTReplay = "scnistreplay", SCNISTSigBadLifetime = "scnistsigbadlifetime", SCNISTNotFound = "scnistnotfound", SCNISTBadClock = "scnistbadclock", SCNISTSigBadCtime = "scnistsigbadctime", SCBadSignupUsernameDeleted = "scbadsignupusernamedeleted", SCPhoneNumberUnknown = "scphonenumberunknown", SCPhoneNumberAlreadyVerified = "scphonenumberalreadyverified", SCPhoneNumberVerificationCodeExpired = "scphonenumberverificationcodeexpired", SCPhoneNumberWrongVerificationCode = "scphonenumberwrongverificationcode", SCPhoneNumberLimitExceeded = "scphonenumberlimitexceeded", SCNoPaperKeys = "scnopaperkeys", SCTeambotKeyGenerationExists = "scteambotkeygenerationexists", SCTeambotKeyOldBoxedGeneration = "scteambotkeyoldboxedgeneration", SCTeambotKeyBadGeneration = "scteambotkeybadgeneration", SCAirdropRegisterFailedMisc = "scairdropregisterfailedmisc", SCSimpleFSNameExists = "scsimplefsnameexists", SCSimpleFSDirNotEmpty = "scsimplefsdirnotempty", SCSimpleFSNotExist = "scsimplefsnotexist", SCSimpleFSNoAccess = "scsimplefsnoaccess" } export declare type ED25519PublicKey = string | null; export declare type ED25519Signature = string | null; export declare type EncryptedBytes32 = string | null; export declare type BoxNonce = string | null; export declare type BoxPublicKey = string | null; export declare type RegisterAddressRes = { type: string; family: string; }; export declare enum ExitCode { OK = "ok", NOTOK = "notok", RESTART = "restart" } export declare enum DbType { MAIN = "main", CHAT = "chat", FS_BLOCK_CACHE = "fs_block_cache", FS_BLOCK_CACHE_META = "fs_block_cache_meta", FS_SYNC_BLOCK_CACHE = "fs_sync_block_cache", FS_SYNC_BLOCK_CACHE_META = "fs_sync_block_cache_meta" } export declare type DbValue = Buffer; export declare enum OnLoginStartupStatus { UNKNOWN = "unknown", DISABLED = "disabled", ENABLED = "enabled" } export declare type FirstStepResult = { valPlusTwo: number; }; export declare type EkGeneration = number; export declare enum TeamEphemeralKeyType { TEAM = "team", TEAMBOT = "teambot" } export declare enum FolderType { UNKNOWN = "unknown", PRIVATE = "private", PUBLIC = "public", TEAM = "team" } export declare enum FolderConflictType { NONE = "none", IN_CONFLICT = "in_conflict", IN_CONFLICT_AND_STUCK = "in_conflict_and_stuck", CLEARED_CONFLICT = "cleared_conflict" } export declare enum ConflictStateType { NormalView = "normalview", ManualResolvingLocalView = "manualresolvinglocalview" } export declare type FeaturedBot = { botAlias: string; description: string; extendedDescription: string; extendedDescriptionRaw: string; botUsername: string; ownerTeam?: string; ownerUser?: string; rank: number; isPromoted: boolean; }; export declare type File = { path: string; }; export declare type RepoID = string; export declare enum GitLocalMetadataVersion { V1 = "v1" } export declare enum GitPushType { DEFAULT = "default", CREATEREPO = "createrepo", RENAMEREPO = "renamerepo" } export declare enum GitRepoResultState { ERR = "err", OK = "ok" } export declare type GitTeamRepoSettings = { channelName?: string; chatDisabled: boolean; }; export declare type SelectKeyRes = { keyId: string; doSecretPush: boolean; }; export declare enum PushReason { NONE = "none", RECONNECTED = "reconnected", NEW_DATA = "new_data" } export declare type HomeScreenItemID = string; export declare enum HomeScreenItemType { TODO = "todo", PEOPLE = "people", ANNOUNCEMENT = "announcement" } export declare enum AppLinkType { NONE = "none", PEOPLE = "people", CHAT = "chat", FILES = "files", WALLET = "wallet", GIT = "git", DEVICES = "devices", SETTINGS = "settings", TEAMS = "teams" } export declare type HomeScreenAnnouncementID = number; export declare type HomeScreenAnnouncementVersion = number; export declare enum HomeScreenTodoType { NONE = "none", BIO = "bio", PROOF = "proof", DEVICE = "device", FOLLOW = "follow", CHAT = "chat", PAPERKEY = "paperkey", TEAM = "team", FOLDER = "folder", GIT_REPO = "git_repo", TEAM_SHOWCASE = "team_showcase", AVATAR_USER = "avatar_user", AVATAR_TEAM = "avatar_team", ADD_PHONE_NUMBER = "add_phone_number", VERIFY_ALL_PHONE_NUMBER = "verify_all_phone_number", VERIFY_ALL_EMAIL = "verify_all_email", LEGACY_EMAIL_VISIBILITY = "legacy_email_visibility", ADD_EMAIL = "add_email", ANNONCEMENT_PLACEHOLDER = "annoncement_placeholder" } export declare enum HomeScreenPeopleNotificationType { FOLLOWED = "followed", FOLLOWED_MULTI = "followed_multi", CONTACT = "contact", CONTACT_MULTI = "contact_multi" } export declare type Pics = { square40: string; square200: string; square360: string; }; export declare type Identify3Assertion = string; export declare type Identify3GUIID = string; export declare enum Identify3RowState { CHECKING = "checking", VALID = "valid", ERROR = "error", WARNING = "warning", REVOKED = "revoked" } export declare enum Identify3RowColor { BLUE = "blue", RED = "red", BLACK = "black", GREEN = "green", GRAY = "gray", YELLOW = "yellow", ORANGE = "orange" } export declare enum Identify3ResultType { OK = "ok", BROKEN = "broken", NEEDS_UPGRADE = "needs_upgrade", CANCELED = "canceled" } export declare type TrackToken = string; export declare type SigVersion = number; export declare enum TrackDiffType { NONE = "none", ERROR = "error", CLASH = "clash", REVOKED = "revoked", UPGRADED = "upgraded", NEW = "new", REMOTE_FAIL = "remote_fail", REMOTE_WORKING = "remote_working", REMOTE_CHANGED = "remote_changed", NEW_ELDEST = "new_eldest", NONE_VIA_TEMPORARY = "none_via_temporary" } /** * TrackStatus is a summary of this track before the track is approved by the * user. * NEW_*: New tracks * UPDATE_*: Update to an existing track * NEW_OK: Everything ok * NEW_ZERO_PROOFS: User being tracked has no proofs * NEW_FAIL_PROOFS: User being tracked has some failed proofs * UPDATE_BROKEN: Previous tracking statement broken, this one will fix it. * UPDATE_NEW_PROOFS: Previous tracking statement ok, but there are new proofs since previous tracking statement generated * UPDATE_OK: No changes to previous tracking statement */ export declare enum TrackStatus { NEW_OK = "new_ok", NEW_ZERO_PROOFS = "new_zero_proofs", NEW_FAIL_PROOFS = "new_fail_proofs", UPDATE_BROKEN_FAILED_PROOFS = "update_broken_failed_proofs", UPDATE_NEW_PROOFS = "update_new_proofs", UPDATE_OK = "update_ok", UPDATE_BROKEN_REVOKED = "update_broken_revoked" } export declare enum IdentifyReasonType { NONE = "none", ID = "id", TRACK = "track", ENCRYPT = "encrypt", DECRYPT = "decrypt", VERIFY = "verify", RESOURCE = "resource", BACKGROUND = "background" } export declare type SigHint = { remoteId: string; humanUrl: string; apiUrl: string; checkText: string; }; export declare enum CheckResultFreshness { FRESH = "fresh", AGED = "aged", RANCID = "rancid" } export declare type ConfirmResult = { identityConfirmed: boolean; remoteConfirmed: boolean; expiringLocal: boolean; autoConfirmed: boolean; }; export declare enum DismissReasonType { NONE = "none", HANDLED_ELSEWHERE = "handled_elsewhere" } export declare enum IncomingShareType { FILE = "file", TEXT = "text", IMAGE = "image", VIDEO = "video" } /** * Install status describes state of install for a component or service. */ export declare enum InstallStatus { UNKNOWN = "unknown", ERROR = "error", NOT_INSTALLED = "not_installed", INSTALLED = "installed" } export declare enum InstallAction { UNKNOWN = "unknown", NONE = "none", UPGRADE = "upgrade", REINSTALL = "reinstall", INSTALL = "install" } export declare type FuseMountInfo = { path: string; fstype: string; output: string; }; export declare type InviteCounts = { inviteCount: number; percentageChange: number; showNumInvites: boolean; showFire: boolean; tooltipMarkdown: string; }; export declare type EmailInvites = { commaSeparatedEmailsFromUser?: string; emailsFromContacts?: EmailAddress[] | null; }; export declare enum FSStatusCode { START = "start", FINISH = "finish", ERROR = "error" } export declare enum FSNotificationType { ENCRYPTING = "encrypting", DECRYPTING = "decrypting", SIGNING = "signing", VERIFYING = "verifying", REKEYING = "rekeying", CONNECTION = "connection", MD_READ_SUCCESS = "md_read_success", FILE_CREATED = "file_created", FILE_MODIFIED = "file_modified", FILE_DELETED = "file_deleted", FILE_RENAMED = "file_renamed", INITIALIZED = "initialized", SYNC_CONFIG_CHANGED = "sync_config_changed" } export declare enum FSErrorType { ACCESS_DENIED = "access_denied", USER_NOT_FOUND = "user_not_found", REVOKED_DATA_DETECTED = "revoked_data_detected", NOT_LOGGED_IN = "not_logged_in", TIMEOUT = "timeout", REKEY_NEEDED = "rekey_needed", BAD_FOLDER = "bad_folder", NOT_IMPLEMENTED = "not_implemented", OLD_VERSION = "old_version", OVER_QUOTA = "over_quota", NO_SIG_CHAIN = "no_sig_chain", TOO_MANY_FOLDERS = "too_many_folders", EXDEV_NOT_SUPPORTED = "exdev_not_supported", DISK_LIMIT_REACHED = "disk_limit_reached", DISK_CACHE_ERROR_LOG_SEND = "disk_cache_error_log_send", OFFLINE_ARCHIVED = "offline_archived", OFFLINE_UNSYNCED = "offline_unsynced" } export declare type FSSyncStatusRequest = { requestId: number; }; export declare type PassphraseStream = { passphraseStream: Buffer; generation: number; }; export declare type SessionToken = string; export declare type CsrfToken = string; export declare type HelloRes = string; export declare type KVGetResult = { teamName: string; namespace: string; entryKey: string; entryValue?: string | null; revision: number; }; export declare type KVPutResult = { teamName: string; namespace: string; entryKey: string; revision: number; }; export declare type EncryptedKVEntry = { v: number; e: Buffer; n: Buffer; }; export declare type KVListNamespaceResult = { teamName: string; namespaces: string[] | null; }; export declare type KVListEntryKey = { entryKey: string; revision: number; }; export declare type KVDeleteEntryResult = { teamName: string; namespace: string; entryKey: string; revision: number; }; export declare enum ResetPromptType { COMPLETE = "complete", ENTER_NO_DEVICES = "enter_no_devices", ENTER_FORGOT_PW = "enter_forgot_pw", ENTER_RESET_PW = "enter_reset_pw" } export declare type ResetPromptInfo = { hasWallet: boolean; }; export declare enum ResetPromptResponse { NOTHING = "nothing", CANCEL_RESET = "cancel_reset", CONFIRM_RESET = "confirm_reset" } export declare enum PassphraseRecoveryPromptType { ENCRYPTED_PGP_KEYS = "encrypted_pgp_keys" } export declare enum ResetMessage { ENTERED_VERIFIED = "entered_verified", ENTERED_PASSWORDLESS = "entered_passwordless", REQUEST_VERIFIED = "request_verified", NOT_COMPLETED = "not_completed", CANCELED = "canceled", COMPLETED = "completed", RESET_LINK_SENT = "reset_link_sent" } export declare type KBFSRootHash = Buffer; export declare type MerkleStoreSupportedVersion = number; export declare type MerkleStoreKitHash = string; export declare type MerkleStoreKit = string; export declare type MerkleStoreEntryString = string; export declare type KeyBundle = { version: number; bundle: Buffer; }; export declare type MerkleRoot = { version: number; root: Buffer; }; export declare type LockID = number; export declare type MDPriority = number; export declare type RekeyRequest = { folderId: string; revision: number; }; export declare enum NetworkSource { LOCAL = "local", REMOTE = "remote" } export declare type ChatConversationID = Buffer; export declare type DeletedTeamInfo = { teamName: string; deletedBy: string; id: gregor1.MsgID; }; export declare type WalletAccountInfo = { accountId: string; numUnread: number; }; export declare type NotificationChannels = { session: boolean; users: boolean; kbfs: boolean; kbfsdesktop: boolean; kbfslegacy: boolean; kbfssubscription: boolean; tracking: boolean; favorites: boolean; paperkeys: boolean; keyfamily: boolean; service: boolean; app: boolean; chat: boolean; pgp: boolean; kbfsrequest: boolean; badges: boolean; reachability: boolean; team: boolean; ephemeral: boolean; teambot: boolean; chatkbfsedits: boolean; chatdev: boolean; chatemoji: boolean; chatemojicross: boolean; deviceclone: boolean; chatattachments: boolean; wallet: boolean; audit: boolean; runtimestats: boolean; featuredBots: boolean; saltpack: boolean; }; export declare enum StatsSeverityLevel { NORMAL = "normal", WARNING = "warning", SEVERE = "severe" } export declare enum ProcessType { MAIN = "main", KBFS = "kbfs" } export declare enum PerfEventType { NETWORK = "network", TEAMBOXAUDIT = "teamboxaudit", TEAMAUDIT = "teamaudit", USERCHAIN = "userchain", TEAMCHAIN = "teamchain", CLEARCONV = "clearconv", CLEARINBOX = "clearinbox", TEAMTREELOAD = "teamtreeload" } export declare enum SaltpackOperationType { ENCRYPT = "encrypt", DECRYPT = "decrypt", SIGN = "sign", VERIFY = "verify" } export declare type HttpSrvInfo = { address: string; token: string; }; export declare type TeamChangeSet = { membershipChanged: boolean; keyRotated: boolean; renamed: boolean; misc: boolean; }; export declare enum AvatarUpdateType { NONE = "none", USER = "user", TEAM = "team" } export declare enum RuntimeGroup { UNKNOWN = "unknown", LINUXLIKE = "linuxlike", DARWINLIKE = "darwinlike", WINDOWSLIKE = "windowslike" } export declare type Feature = { allow: boolean; defaultValue: boolean; readonly: boolean; label: string; }; export declare enum PassphraseType { NONE = "none", PAPER_KEY = "paper_key", PASS_PHRASE = "pass_phrase", VERIFY_PASS_PHRASE = "verify_pass_phrase" } export declare type GetPassphraseRes = { passphrase: string; storeSecret: boolean; }; export declare enum SignMode { ATTACHED = "attached", DETACHED = "detached", CLEAR = "clear" } export declare type PGPEncryptOptions = { recipients: string[] | null; noSign: boolean; noSelf: boolean; binaryOut: boolean; keyQuery: string; }; export declare type PGPDecryptOptions = { assertSigned: boolean; signedBy: string; }; export declare type PGPVerifyOptions = { signedBy: string; signature: Buffer; }; export declare type KeyInfo = { fingerprint: string; key: string; desc: string; }; export declare type PGPQuery = { secret: boolean; query: string; exactMatch: boolean; }; /** * Export all pgp keys in lksec, then if doPurge is true, remove the keys from lksec. */ export declare type PGPPurgeRes = { filenames: string[] | null; }; export declare enum FileType { UNKNOWN = "unknown", DIRECTORY = "directory", FILE = "file" } export declare enum ProofState { NONE = "none", OK = "ok", TEMP_FAILURE = "temp_failure", PERM_FAILURE = "perm_failure", LOOKING = "looking", SUPERSEDED = "superseded", POSTED = "posted", REVOKED = "revoked", DELETED = "deleted", UNKNOWN_TYPE = "unknown_type", SIG_HINT_MISSING = "sig_hint_missing", UNCHECKED = "unchecked" } /** * 3: It's been found in the hunt, but not proven yet * 1xx: Retryable soft errors; note that this will be put in the proof_cache, but won't * be returned from the proof cache in most cases. Their freshness will always be * RANCID. * 2xx: Will likely result in a hard error, if repeated enough * 3xx: Hard final errors */ export declare enum ProofStatus { NONE = "none", OK = "ok", LOCAL = "local", FOUND = "found", BASE_ERROR = "base_error", HOST_UNREACHABLE = "host_unreachable", PERMISSION_DENIED = "permission_denied", FAILED_PARSE = "failed_parse", DNS_ERROR = "dns_error", AUTH_FAILED = "auth_failed", HTTP_429 = "http_429", HTTP_500 = "http_500", TIMEOUT = "timeout", INTERNAL_ERROR = "internal_error", UNCHECKED = "unchecked", MISSING_PVL = "missing_pvl", BASE_HARD_ERROR = "base_hard_error", NOT_FOUND = "not_found", CONTENT_FAILURE = "content_failure", BAD_USERNAME = "bad_username", BAD_REMOTE_ID = "bad_remote_id", TEXT_NOT_FOUND = "text_not_found", BAD_ARGS = "bad_args", CONTENT_MISSING = "content_missing", TITLE_NOT_FOUND = "title_not_found", SERVICE_ERROR = "service_error", TOR_SKIPPED = "tor_skipped", TOR_INCOMPATIBLE = "tor_incompatible", HTTP_300 = "http_300", HTTP_400 = "http_400", HTTP_OTHER = "http_other", EMPTY_JSON = "empty_json", DELETED = "deleted", SERVICE_DEAD = "service_dead", BAD_SIGNATURE = "bad_signature", BAD_API_URL = "bad_api_url", UNKNOWN_TYPE = "unknown_type", NO_HINT = "no_hint", BAD_HINT_TEXT = "bad_hint_text", INVALID_PVL = "invalid_pvl" } export declare enum ProofType { NONE = "none", KEYBASE = "keybase", TWITTER = "twitter", GITHUB = "github", REDDIT = "reddit", COINBASE = "coinbase", HACKERNEWS = "hackernews", FACEBOOK = "facebook", GENERIC_SOCIAL = "generic_social", GENERIC_WEB_SITE = "generic_web_site", DNS = "dns", PGP = "pgp", ROOTER = "rooter" } export declare type SelectorEntry = { isIndex: boolean; index: number; isKey: boolean; key: string; isAll: boolean; isContents: boolean; }; export declare type ParamProofUsernameConfig = { re: string; min: number; max: number; }; export declare type ServiceDisplayConfig = { creationDisabled: boolean; priority: number; key: string; group?: string; new: boolean; logoKey: string; }; export declare enum PromptOverwriteType { SOCIAL = "social", SITE = "site" } export declare enum ProvisionMethod { DEVICE = "device", PAPER_KEY = "paper_key", PASSPHRASE = "passphrase", GPG_IMPORT = "gpg_import", GPG_SIGN = "gpg_sign" } export declare enum GPGMethod { GPG_NONE = "gpg_none", GPG_IMPORT = "gpg_import", GPG_SIGN = "gpg_sign" } export declare enum ChooseType { EXISTING_DEVICE = "existing_device", NEW_DEVICE = "new_device" } /** * SecretResponse should be returned by DisplayAndPromptSecret. Use either secret or phrase. */ export declare type SecretResponse = { secret: Buffer; phrase: string; }; export declare enum Reachable { UNKNOWN = "unknown", YES = "yes", NO = "no" } export declare enum Outcome { NONE = "none", FIXED = "fixed", IGNORED = "ignored" } export declare enum RekeyEventType { NONE = "none", NOT_LOGGED_IN = "not_logged_in", API_ERROR = "api_error", NO_PROBLEMS = "no_problems", LOAD_ME_ERROR = "load_me_error", CURRENT_DEVICE_CAN_REKEY = "current_device_can_rekey", DEVICE_LOAD_ERROR = "device_load_error", HARASS = "harass", NO_GREGOR_MESSAGES = "no_gregor_messages" } export declare type SHA512 = Buffer; export declare enum ResetType { NONE = "none", RESET = "reset", DELETE = "delete" } export declare enum AuthenticityType { SIGNED = "signed", REPUDIABLE = "repudiable", ANONYMOUS = "anonymous" } export declare type SaltpackDecryptOptions = { interactive: boolean; forceRemoteCheck: boolean; usePaperKey: boolean; }; export declare type SaltpackSignOptions = { detached: boolean; binary: boolean; saltpackVersion: number; }; export declare type SaltpackVerifyOptions = { signedBy: string; signature: Buffer; }; export declare type SaltpackEncryptResult = { usedUnresolvedSbs: boolean; unresolvedSbsAssertion: string; }; export declare type SaltpackFrontendEncryptOptions = { recipients: string[] | null; signed: boolean; includeSelf: boolean; }; export declare type SaltpackEncryptStringResult = { usedUnresolvedSbs: boolean; unresolvedSbsAssertion: string; ciphertext: string; }; export declare type SaltpackEncryptFileResult = { usedUnresolvedSbs: boolean; unresolvedSbsAssertion: string; filename: string; }; export declare enum SaltpackSenderType { NOT_TRACKED = "not_tracked", UNKNOWN = "unknown", ANONYMOUS = "anonymous", TRACKING_BROKE = "tracking_broke", TRACKING_OK = "tracking_ok", SELF = "self", REVOKED = "revoked", EXPIRED = "expired" } export declare type SecretEntryArg = { desc: string; prompt: string; err: string; cancel: string; ok: string; reason: string; showTyping: boolean; }; export declare type SecretEntryRes = { text: string; canceled: boolean; storeSecret: boolean; }; export declare type NaclSigningKeyPublic = string | null; export declare type NaclSigningKeyPrivate = string | null; export declare type NaclDHKeyPublic = string | null; export declare type NaclDHKeyPrivate = string | null; export declare type SignupRes = { passphraseOk: boolean; postOk: boolean; writeOk: boolean; paperKey: string; }; export declare type SigTypes = { track: boolean; proof: boolean; cryptocurrency: boolean; isSelf: boolean; }; export declare type OpID = string | null; export declare type KBFSRevision = number; export declare enum KBFSArchivedType { REVISION = "revision", TIME = "time", TIME_STRING = "time_string", REL_TIME_STRING = "rel_time_string" } export declare enum PathType { LOCAL = "local", KBFS = "kbfs", KBFS_ARCHIVED = "kbfs_archived" } export declare enum DirentType { FILE = "file", DIR = "dir", SYM = "sym", EXEC = "exec" } export declare enum PrefetchStatus { NOT_STARTED = "not_started", IN_PROGRESS = "in_progress", COMPLETE = "complete" } export declare enum RevisionSpanType { DEFAULT = "default", LAST_FIVE = "last_five" } export declare type ErrorNum = number; export declare enum OpenFlags { READ = "read", REPLACE = "replace", EXISTING = "existing", WRITE = "write", APPEND = "append", DIRECTORY = "directory" } export declare type Progress = number; export declare enum AsyncOps { LIST = "list", LIST_RECURSIVE = "list_recursive", READ = "read", WRITE = "write", COPY = "copy", MOVE = "move", REMOVE = "remove", LIST_RECURSIVE_TO_DEPTH = "list_recursive_to_depth", GET_REVISIONS = "get_revisions" } export declare enum ListFilter { NO_FILTER = "no_filter", FILTER_ALL_HIDDEN = "filter_all_hidden", FILTER_SYSTEM_HIDDEN = "filter_system_hidden" } export declare type SimpleFSQuotaUsage = { usageBytes: number; archiveBytes: number; limitBytes: number; gitUsageBytes: number; gitArchiveBytes: number; gitLimitBytes: number; }; export declare enum FolderSyncMode { DISABLED = "disabled", ENABLED = "enabled", PARTIAL = "partial" } export declare enum KbfsOnlineStatus { OFFLINE = "offline", TRYING = "trying", ONLINE = "online" } export declare type FSSettings = { spaceAvailableNotificationThreshold: number; sfmiBannerDismissed: boolean; syncOnCellular: boolean; }; export declare enum SubscriptionTopic { FAVORITES = "favorites", JOURNAL_STATUS = "journal_status", ONLINE_STATUS = "online_status", DOWNLOAD_STATUS = "download_status", FILES_TAB_BADGE = "files_tab_badge", OVERALL_SYNC_STATUS = "overall_sync_status", SETTINGS = "settings", UPLOAD_STATUS = "upload_status" } export declare enum PathSubscriptionTopic { CHILDREN = "children", STAT = "stat" } export declare enum FilesTabBadge { NONE = "none", UPLOADING_STUCK = "uploading_stuck", AWAITING_UPLOAD = "awaiting_upload", UPLOADING = "uploading" } export declare enum GUIViewType { DEFAULT = "default", TEXT = "text", IMAGE = "image", AUDIO = "audio", VIDEO = "video", PDF = "pdf" } export declare type SimpleFSSearchHit = { path: string; }; export declare type TeambotKeyGeneration = number; export declare enum TeamRole { NONE = "none", READER = "reader", WRITER = "writer", ADMIN = "admin", OWNER = "owner", BOT = "bot", RESTRICTEDBOT = "restrictedbot" } export declare enum TeamApplication { KBFS = "kbfs", CHAT = "chat", SALTPACK = "saltpack", GIT_METADATA = "git_metadata", SEITAN_INVITE_TOKEN = "seitan_invite_token", STELLAR_RELAY = "stellar_relay", KVSTORE = "kvstore" } export declare enum TeamStatus { NONE = "none", LIVE = "live", DELETED = "deleted", ABANDONED = "abandoned" } export declare enum AuditMode { STANDARD = "standard", JUST_CREATED = "just_created", SKIP = "skip", STANDARD_NO_HIDDEN = "standard_no_hidden" } export declare type PerTeamKeyGeneration = number; export declare enum PTKType { READER = "reader" } export declare enum PerTeamSeedCheckVersion { V1 = "v1" } export declare type PerTeamSeedCheckValue = Buffer; export declare type PerTeamSeedCheckValuePostImage = Buffer; export declare type MaskB64 = Buffer; export declare type TeamInviteID = string; export declare type TeamInviteMaxUses = number; export declare type PerTeamKeySeed = string | null; export declare enum TeamMemberStatus { ACTIVE = "active", RESET = "reset", DELETED = "deleted" } export declare type UserVersionPercentForm = string; export declare enum RatchetType { MAIN = "main", BLINDED = "blinded", SELF = "self", UNCOMMITTED = "uncommitted" } export declare enum AuditVersion { V0 = "v0", V1 = "v1", V2 = "v2", V3 = "v3", V4 = "v4" } export declare enum TeamInviteCategory { NONE = "none", UNKNOWN = "unknown", KEYBASE = "keybase", EMAIL = "email", SBS = "sbs", SEITAN = "seitan", PHONE = "phone", INVITELINK = "invitelink" } export declare type TeamInviteSocialNetwork = string; export declare type TeamInviteName = string; export declare type TeamInviteDisplayName = string; export declare type TeamEncryptedKBFSKeyset = { v: number; e: Buffer; n: Buffer; }; export declare type TeamEncryptedKBFSKeysetHash = string; export declare type BoxSummaryHash = string; export declare type TeamNamePart = string; export declare type SeitanAKey = string; export declare type SeitanIKey = string; export declare type SeitanIKeyInvitelink = string; export declare type SeitanPubKey = string; export declare type SeitanIKeyV2 = string; export declare enum SeitanKeyAndLabelVersion { V1 = "v1", V2 = "v2", Invitelink = "invitelink" } export declare enum SeitanKeyLabelType { SMS = "sms", GENERIC = "generic" } export declare type SeitanKeyLabelSms = { f: string; n: string; }; export declare type SeitanKeyLabelGeneric = { l: string; }; export declare type TeamBotSettings = { cmds: boolean; mentions: boolean; triggers: string[] | null; convs: string[] | null; }; export declare type TeamRequestAccessResult = { open: boolean; }; export declare type TeamAcceptOrRequestResult = { wasToken: boolean; wasSeitan: boolean; wasTeamName: boolean; wasOpenTeam: boolean; }; export declare type BulkRes = { malformed: string[] | null; }; export declare type ConflictGeneration = number; export declare type TeamOperation = { manageMembers: boolean; manageSubteams: boolean; createChannel: boolean; chat: boolean; deleteChannel: boolean; renameChannel: boolean; renameTeam: boolean; editChannelDescription: boolean; editTeamDescription: boolean; setTeamShowcase: boolean; setMemberShowcase: boolean; setRetentionPolicy: boolean; setMinWriterRole: boolean; changeOpenTeam: boolean; leaveTeam: boolean; joinTeam: boolean; setPublicityAny: boolean; listFirst: boolean; changeTarsDisabled: boolean; deleteChatHistory: boolean; deleteOtherEmojis: boolean; deleteOtherMessages: boolean; deleteTeam: boolean; pinMessage: boolean; manageBots: boolean; manageEmojis: boolean; }; export declare type ProfileTeamLoadRes = { loadTimeNsec: number; }; export declare enum RotationType { VISIBLE = "visible", HIDDEN = "hidden", CLKR = "clkr" } export declare type MemberEmail = { email: string; role: string; }; export declare type MemberUsername = { username: string; role: string; }; export declare type UserTeamVersion = number; export declare enum TeamTreeMembershipStatus { OK = "ok", ERROR = "error", HIDDEN = "hidden" } export declare type TeamTreeError = { message: string; willSkipSubtree: boolean; willSkipAncestors: boolean; }; export declare type TeamTreeInitial = { guid: number; }; /** * Result from calling test(..). */ export declare type Test = { reply: string; }; export declare enum TLFIdentifyBehavior { UNSET = "unset", CHAT_CLI = "chat_cli", CHAT_GUI = "chat_gui", REMOVED_AND_UNUSED = "removed_and_unused", KBFS_REKEY = "kbfs_rekey", KBFS_QR = "kbfs_qr", CHAT_SKIP = "chat_skip", SALTPACK = "saltpack", CLI = "cli", GUI = "gui", DEFAULT_KBFS = "default_kbfs", KBFS_CHAT = "kbfs_chat", RESOLVE_AND_CHECK = "resolve_and_check", GUI_PROFILE = "gui_profile", KBFS_INIT = "kbfs_init", FS_GUI = "fs_gui" } export declare type CanonicalTlfName = string; export declare enum PromptDefault { NONE = "none", YES = "yes", NO = "no" } export declare enum KeyType { NONE = "none", NACL = "nacl", PGP = "pgp" } export declare enum UPK2MinorVersion { V0 = "v0", V1 = "v1", V2 = "v2", V3 = "v3", V4 = "v4", V5 = "v5", V6 = "v6" } export declare type PGPFingerprint = string | null; export declare enum UPAKVersion { V1 = "v1", V2 = "v2" } export declare enum UPKLiteMinorVersion { V0 = "v0" } export declare type TrackProof = { proofType: string; proofName: string; idString: string; }; export declare type WebProof = { hostname: string; protocols: string[] | null; }; export declare type EmailAddress = string; /** * PassphraseState values are used in .config.json, so should not be changed without a migration strategy */ export declare enum PassphraseState { KNOWN = "known", RANDOM = "random" } export declare enum UserBlockType { CHAT = "chat", FOLLOW = "follow" } export declare type UserBlockArg = { username: string; setChatBlock?: boolean; setFollowBlock?: boolean; }; export declare type APIUserServiceID = string; export declare type ImpTofuSearchResult = { assertion: string; assertionValue: string; assertionKey: string; label: string; prettyName: string; keybaseUsername: string; }; export declare type EmailOrPhoneNumberSearchResult = { input: string; assertion: string; assertionValue: string; assertionKey: string; foundUser: boolean; username: string; fullName: string; }; export declare type UsernameVerificationType = string; export declare enum WotReactionType { ACCEPT = "accept", REJECT = "reject" } export declare type LockdownHistory = { status: boolean; ctime: Time; deviceId: DeviceID; deviceName: string; }; export declare type TeamContactSettings = { teamId: TeamID; enabled: boolean; }; export declare type AirdropDetails = { uid: UID; kid: BinaryKID; vid: VID; vers: string; time: Time; }; export declare type BoxAuditAttempt = { ctime: UnixTime; error?: string; result: BoxAuditAttemptResult; generation?: PerTeamKeyGeneration; rotated: boolean; }; export declare type LoadAvatarsRes = { picmap: { [key: string]: { [key: string]: AvatarUrl; }; }; }; export declare type AvatarClearCacheMsg = { name: string; formats: AvatarFormat[] | null; typ: AvatarUpdateType; }; export declare type BlockIdCombo = { blockHash: string; chargedTo: UserOrTeamID; blockType: BlockType; }; export declare type GetBlockRes = { blockKey: string; buf: Buffer; size: number; status: BlockStatus; }; export declare type GetBlockSizesRes = { sizes: number[] | null; statuses: BlockStatus[] | null; }; export declare type UsageStat = { bytes: UsageStatRecord; blocks: UsageStatRecord; mtime: Time; }; export declare type BotTokenInfo = { botToken: BotToken; ctime: Time; }; export declare type Status = { code: number; name: string; desc: string; fields: StringKVPair[] | null; }; export declare type UserVersion = { uid: UID; eldestSeqno: Seqno; }; export declare type CompatibilityTeamID = { typ: TeamType.LEGACY; LEGACY: TLFID; } | { typ: TeamType.MODERN; MODERN: TeamID; } | { typ: Exclude<TeamType, TeamType.LEGACY | TeamType.MODERN>; }; export declare type TeamIDWithVisibility = { teamId: TeamID; visibility: TLFVisibility; }; export declare type PublicKey = { kid: KID; pgpFingerprint: string; pgpIdentities: PGPIdentity[] | null; isSibkey: boolean; isEldest: boolean; parentId: string; deviceId: DeviceID; deviceDescription: string; deviceType: DeviceTypeV2; cTime: Time; eTime: Time; isRevoked: boolean; }; export declare type KeybaseTime = { unix: Time; chain: Seqno; }; export declare type User = { uid: UID; username: string; }; export declare type Device = { type: DeviceTypeV2; name: string; deviceId: DeviceID; deviceNumberOfType: number; cTime: Time; mTime: Time; lastUsedTime: Time; encryptKey: KID; verifyKey: KID; status: number; }; export declare type UserVersionVector = { id: number; sigHints: number; sigChain: number; cachedAt: Time; }; export declare type PerUserKey = { gen: number; seqno: Seqno; sigKid: KID; encKid: KID; signedByKid: KID; }; export declare type UserOrTeamLite = { id: UserOrTeamID; name: string; }; export declare type RemoteTrack = { username: string; uid: UID; linkId: LinkID; }; /** * SocialAssertion contains a service and username for that service, that * together form an assertion about a user. It can either be a social * assertion (like "facebook" or "twitter") or a server trust assertion (like * "phone" or "email"). * * If the assertion is for social network, resolving an assertion requires * that the user posts a Keybase proof on the asserted service as the asserted * user. * * For server trust assertion, we have to trust the server. */ export declare type SocialAssertion = { user: string; service: SocialAssertionService; }; export declare type FullNamePackage = { version: FullNamePackageVersion; fullName: FullName; eldestSeqno: Seqno; status: StatusCode; cachedAt: Time; }; export declare type PhoneLookupResult = { uid: UID; username: string; ctime: UnixTime; }; export declare type UserReacjis = { topReacjis: UserReacji[] | null; skinTone: ReacjiSkinTone; }; export declare type ClientDetails = { pid: number; clientType: ClientType; argv: string[] | null; desc: string; version: string; }; export declare type Config = { serverUri: string; socketFile: string; label: string; runMode: string; gpgExists: boolean; gpgPath: string; version: string; path: string; binaryRealpath: string; configPath: string; versionShort: string; versionFull: string; isAutoForked: boolean; forkType: ForkType; }; export declare type UpdateInfo = { status: UpdateInfoStatus; message: string; }; export declare type UpdateInfo2 = { status: UpdateInfoStatus2.OK; } | { status: UpdateInfoStatus2.SUGGESTED; SUGGESTED: UpdateDetails; } | { status: UpdateInfoStatus2.CRITICAL; CRITICAL: UpdateDetails; } | { status: Exclude<UpdateInfoStatus2, UpdateInfoStatus2.OK | UpdateInfoStatus2.SUGGESTED | UpdateInfoStatus2.CRITICAL>; }; export declare type ProxyData = { addressWithPort: string; proxyType: ProxyType; certPinning: boolean; }; export declare type ContactComponent = { label: string; phoneNumber?: RawPhoneNumber; email?: EmailAddress; }; export declare type ED25519SignatureInfo = { sig: ED25519Signature; publicKey: ED25519PublicKey; }; export declare type CiphertextBundle = { kid: KID; ciphertext: EncryptedBytes32; nonce: BoxNonce; publicKey: BoxPublicKey; }; export declare type UnboxAnyRes = { kid: KID; plaintext: Bytes32; index: number; }; export declare type DbKey = { dbType: DbType; objType: number; key: string; }; export declare type EmailLookupResult = { email: EmailAddress; uid?: UID; }; export declare type EmailAddressVerifiedMsg = { email: EmailAddress; }; export declare type EmailAddressChangedMsg = { email: EmailAddress; }; export declare type DeviceEkMetadata = { deviceEphemeralDhPublic: KID; hashMeta: HashMeta; generation: EkGeneration; ctime: Time; deviceCtime: Time; }; export declare type UserEkMetadata = { userEphemeralDhPublic: KID; hashMeta: HashMeta; generation: EkGeneration; ctime: Time; }; export declare type UserEkBoxMetadata = { box: string; recipientGeneration: EkGeneration; recipientDeviceId: DeviceID; }; export declare type TeamEkMetadata = { teamEphemeralDhPublic: KID; hashMeta: HashMeta; generation: EkGeneration; ctime: Time; }; export declare type TeamEkBoxMetadata = { box: string; recipientGeneration: EkGeneration; recipientUid: UID; }; export declare type TeambotEkMetadata = { teambotDhPublic: KID; generation: EkGeneration; uid: UID; userEkGeneration: EkGeneration; hashMeta: HashMeta; ctime: Time; }; export declare type FolderHandle = { name: string; folderType: FolderType; created: boolean; }; export declare type FeaturedBotsRes = { bots: FeaturedBot[] | null; isLastPage: boolean; }; export declare type SearchRes = { bots: FeaturedBot[] | null; isLastPage: boolean; }; export declare type ListResult = { files: File[] | null; }; export declare type EncryptedGitMetadata = { v: number; e: Buffer; n: BoxNonce; gen: PerTeamKeyGeneration; }; export declare type GitLocalMetadataV1 = { repoName: GitRepoName; }; export declare type GitCommit = { commitHash: string; message: string; authorName: string; authorEmail: string; ctime: Time; }; export declare type GitServerMetadata = { ctime: Time; mtime: Time; lastModifyingUsername: string; lastModifyingDeviceId: DeviceID; lastModifyingDeviceName: string; }; export declare type GPGKey = { algorithm: string; keyId: string; creation: string; expiration: string; identities: PGPIdentity[] | null; }; export declare type HomeScreenAnnouncement = { id: HomeScreenAnnouncementID; version: HomeScreenAnnouncementVersion; appLink: AppLinkType; confirmLabel: string; dismissable: boolean; iconUrl: string; text: string; url: string; }; /** * Most of TODO items do not carry additional data, but some do. e.g. TODO * item to tell user to verify their email address will carry that email * address. * * All new TODO data bundle types should be records rather than single fields * to support adding new data to existing TODOs. If a legacy TODO (such as * VERIFY_ALL_EMAIL) uses a single field, the "TodoExt" field should be used to * introduce more data to the payload. */ export declare type HomeScreenTodo = { t: HomeScreenTodoType.VERIFY_ALL_PHONE_NUMBER; VERIFY_ALL_PHONE_NUMBER: PhoneNumber; } | { t: HomeScreenTodoType.VERIFY_ALL_EMAIL; VERIFY_ALL_EMAIL: EmailAddress; } | { t: HomeScreenTodoType.LEGACY_EMAIL_VISIBILITY; LEGACY_EMAIL_VISIBILITY: EmailAddress; } | { t: Exclude<HomeScreenTodoType, HomeScreenTodoType.VERIFY_ALL_PHONE_NUMBER | HomeScreenTodoType.VERIFY_ALL_EMAIL | HomeScreenTodoType.LEGACY_EMAIL_VISIBILITY>; }; export declare type VerifyAllEmailTodoExt = { lastVerifyEmailDate: UnixTime; }; export declare type HomeScreenPeopleNotificationContact = { resolveTime: Time; username: string; description: string; resolvedContactBlob: string; }; export declare type HomeUserSummary = { uid: UID; username: string; bio: string; fullName: string; pics?: Pics; }; export declare type Identify3RowMeta = { color: Identify3RowColor; label: string; }; export declare type Identify3Summary = { guiId: Identify3GUIID; numProofsToCheck: number; }; export declare type TrackDiff = { type: TrackDiffType; displayMarkup: string; }; export declare type TrackSummary = { username: string; time: Time; isRemote: boolean; }; export declare type TrackOptions = { localOnly: boolean; bypassConfirm: boolean; forceRetrack: boolean; expiringLocal: boolean; forPgpPull: boolean; sigVersion?: SigVersion; }; export declare type IdentifyReason = { type: IdentifyReasonType; reason: string; resource: string; }; export declare type RemoteProof = { proofType: ProofType; key: string; value: string; displayMarkup: string; sigId: SigID; mTime: Time; }; export declare type ProofResult = { state: ProofState; status: ProofStatus; desc: string; }; export declare type Cryptocurrency = { rowId: number; pkhash: Buffer; address: string; sigId: SigID; type: string; family: string; }; export declare type StellarAccount = { accountId: string; federationAddress: string; sigId: SigID; hidden: boolean; }; export declare type UserTeamShowcase = { fqName: string; open: boolean; teamIsShowcased: boolean; description: string; role: TeamRole; publicAdmins: string[] | null; numMembers: number; }; export declare type DismissReason = { type: DismissReasonType; reason: string; resource: string; }; export declare type IncomingShareItem = { type: IncomingShareType; originalPath: string; originalSize: number; scaledPath?: string; scaledSize?: number; thumbnailPath?: string; content?: string; }; export declare type KBFSTeamSettings = { tlfId: TLFID; }; export declare type FSNotification = { filename: string; status: string; statusCode: FSStatusCode; notificationType: FSNotificationType; errorType: FSErrorType; params: { [key: string]: string; }; writerUid: UID; localTime: Time; folderType: FolderType; }; export declare type FSFolderWriterEdit = { filename: string; notificationType: FSNotificationType; serverTime: Time; }; export declare type FSPathSyncStatus = { folderType: FolderType; path: string; syncingBytes: number; syncingOps: number; syncedBytes: number; }; export declare type FSSyncStatus = { totalSyncingBytes: number; syncingPaths: string[] | null; endEstimate?: Time; }; export declare type GcOptions = { maxLooseRefs: number; pruneMinLooseObjects: number; pruneExpireTime: Time; maxObjectPacks: number; }; export declare type Hello2Res = { encryptionKey: KID; sigPayload: HelloRes; deviceEkKid: KID; }; export declare type PerUserKeyBox = { generation: PerUserKeyGeneration; box: string; receiverKid: KID; }; export declare type KVEntryID = { teamId: TeamID; namespace: string; entryKey: string; }; export declare type KVListEntryResult = { teamName: string; namespace: string; entryKeys: KVListEntryKey[] | null; }; export declare type ConfiguredAccount = { username: string; fullname: FullName; hasStoredSecret: boolean; isCurrent: boolean; }; export declare type ResetPrompt = { t: ResetPromptType.COMPLETE; COMPLETE: ResetPromptInfo; } | { t: Exclude<ResetPromptType, ResetPromptType.COMPLETE>; }; export declare type KBFSRoot = { treeId: MerkleTreeID; root: KBFSRootHash; }; export declare type MerkleStoreEntry = { hash: MerkleStoreKitHash; entry: MerkleStoreEntryString; }; export declare type KeyHalf = { user: UID; deviceKid: KID; key: Buffer; }; export declare type MDBlock = { version: number; timestamp: Time; block: Buffer; }; export declare type PingResponse = { timestamp: Time; }; export declare type KeyBundleResponse = { writerBundle: KeyBundle; readerBundle: KeyBundle; }; export declare type LockContext = { requireLockId: LockID; releaseAfterSuccess: boolean; }; export declare type FindNextMDResponse = { kbfsRoot: MerkleRoot; merkleNodes: Buffer[] | null; rootSeqno: Seqno; rootHash: HashMeta; }; export declare type InstrumentationStat = { tag: string; numCalls: number; ctime: Time; mtime: Time; avgDur: DurationMsec; maxDur: DurationMsec; minDur: DurationMsec; totalDur: DurationMsec; avgSize: number; maxSize: number; minSize: number; totalSize: number; }; export declare type TeamMemberOutReset = { teamId: TeamID; teamname: string; username: string; uid: UID; id: gregor1.MsgID; }; export declare type ResetState = { endTime: Time; active: boolean; }; export declare type WotUpdate = { voucher: string; vouchee: string; status: WotStatusType; }; export declare type BadgeConversationInfo = { convId: ChatConversationID; badgeCount: number; unreadMessages: number; }; export declare type DbStats = { type: DbType; memCompActive: boolean; tableCompActive: boolean; }; export declare type ProcessRuntimeStats = { type: ProcessType; cpu: string; resident: string; virt: string; free: string; goheap: string; goheapsys: string; goreleased: string; cpuSeverity: StatsSeverityLevel; residentSeverity: StatsSeverityLevel; }; export declare type PerfEvent = { message: string; ctime: Time; eventType: PerfEventType; }; export declare type GUIEntryFeatures = { showTyping: Feature; }; export declare type PGPSignOptions = { keyQuery: string; mode: SignMode; binaryIn: boolean; binaryOut: boolean; }; export declare type PGPCreateUids = { useDefault: boolean; ids: PGPIdentity[] | null; }; /** * Phone number support for TOFU chats. */ export declare type UserPhoneNumber = { phoneNumber: PhoneNumber; verified: boolean; superseded: boolean; visibility: IdentityVisibility; ctime: UnixTime; }; export declare type PhoneNumberLookupResult = { phoneNumber: RawPhoneNumber; coercedPhoneNumber: PhoneNumber; err?: string; uid?: UID; }; export declare type PhoneNumberChangedMsg = { phone: PhoneNumber; }; export declare type FileDescriptor = { name: string; type: FileType; }; export declare type CheckProofStatus = { found: boolean; status: ProofStatus; proofText: string; state: ProofState; }; export declare type StartProofResult = { sigId: SigID; }; export declare type ParamProofJSON = { sigHash: SigID; kbUsername: string; }; export declare type ParamProofServiceConfig = { version: number; domain: string; displayName: string; description: string; username: ParamProofUsernameConfig; brandColor: string; prefillUrl: string; profileUrl: string; checkUrl: string; checkPath: SelectorEntry[] | null; avatarPath: SelectorEntry[] | null; }; export declare type ProveParameters = { logoFull: SizedImage[] | null; logoBlack: SizedImage[] | null; logoWhite: SizedImage[] | null; title: string; subtext: string; suffix: string; buttonLabel: string; }; export declare type VerifySessionRes = { uid: UID; sid: string; generated: number; lifetime: number; }; export declare type Reachability = { reachable: Reachable; }; export declare type TLF = { id: TLFID; name: string; writers: string[] | null; readers: string[] | null; isPrivate: boolean; }; export declare type RekeyEvent = { eventType: RekeyEventType; interruptType: number; }; export declare type ResetMerkleRoot = { hashMeta: HashMeta; seqno: Seqno; }; export declare type ResetPrev = { eldestKid?: KID; publicSeqno: Seqno; reset: SHA512; }; export declare type SaltpackEncryptOptions = { recipients: string[] | null; teamRecipients: string[] | null; authenticityType: AuthenticityType; useEntityKeys: boolean; useDeviceKeys: boolean; usePaperKeys: boolean; noSelfEncrypt: boolean; binary: boolean; saltpackVersion: number; noForcePoll: boolean; useKbfsKeysOnlyForTesting: boolean; }; export declare type SaltpackSender = { uid: UID; username: string; fullname: string; senderType: SaltpackSenderType; }; export declare type SecretKeys = { signing: NaclSigningKeyPrivate; encryption: NaclDHKeyPrivate; }; export declare type Session = { uid: UID; username: string; token: string; deviceSubkeyKid: KID; deviceSibkeyKid: KID; }; export declare type Sig = { seqno: Seqno; sigId: SigID; sigIdDisplay: string; type: string; cTime: Time; revoked: boolean; active: boolean; key: string; body: string; }; export declare type SigListArgs = { sessionId: number; username: string; allKeys: boolean; types?: SigTypes; filterx: string; verbose: boolean; revoked: boolean; }; export declare type KBFSArchivedParam = { KBFSArchivedType: KBFSArchivedType.REVISION; REVISION: KBFSRevision; } | { KBFSArchivedType: KBFSArchivedType.TIME; TIME: Time; } | { KBFSArchivedType: KBFSArchivedType.TIME_STRING; TIME_STRING: string; } | { KBFSArchivedType: KBFSArchivedType.REL_TIME_STRING; REL_TIME_STRING: string; } | { KBFSArchivedType: Exclude<KBFSArchivedType, KBFSArchivedType.REVISION | KBFSArchivedType.TIME | KBFSArchivedType.TIME_STRING | KBFSArchivedType.REL_TIME_STRING>; }; export declare type KBFSPath = { path: string; identifyBehavior?: TLFIdentifyBehavior; }; export declare type PrefetchProgress = { start: Time; endEstimate: Time; bytesTotal: number; bytesFetched: number; }; export declare type FileContent = { data: Buffer; progress: Progress; }; export declare type OpProgress = { start: Time; endEstimate: Time; opType: AsyncOps; bytesTotal: number; bytesRead: number; bytesWritten: number; filesTotal: number; filesRead: number; filesWritten: number; }; export declare type FolderSyncConfig = { mode: FolderSyncMode; paths: string[] | null; }; export declare type DownloadState = { downloadId: string; progress: number; endEstimate: Time; localPath: string; error: string; done: boolean; canceled: boolean; }; export declare type GUIFileContext = { viewType: GUIViewType; contentType: string; url: string; }; export declare type SimpleFSSearchResults = { hits: SimpleFSSearchHit[] | null; nextResult: number; }; export declare type IndexProgressRecord = { endEstimate: Time; bytesTotal: number; bytesSoFar: number; }; export declare type TeambotKeyMetadata = { teambotDhPublic: KID; generation: TeambotKeyGeneration; uid: UID; pukGeneration: PerUserKeyGeneration; application: TeamApplication; }; export declare type PerTeamSeedCheck = { version: PerTeamSeedCheckVersion; value: PerTeamSeedCheckValue; }; export declare type PerTeamSeedCheckPostImage = { h: PerTeamSeedCheckValuePostImage; v: PerTeamSeedCheckVersion; }; export declare type TeamApplicationKey = { application: TeamApplication; keyGeneration: PerTeamKeyGeneration; key: Bytes32; }; export declare type ReaderKeyMask = { application: TeamApplication; generation: PerTeamKeyGeneration; mask: MaskB64; }; export declare type PerTeamKey = { gen: PerTeamKeyGeneration; seqno: Seqno; sigKid: KID; encKid: KID; }; export declare type TeamMember = { uid: UID; role: TeamRole; eldestSeqno: Seqno; status: TeamMemberStatus; botSettings?: TeamBotSettings; }; export declare type TeamMemberRole = { uid: UID; username: string; fullName: FullName; role: TeamRole; }; export declare type TeamUsedInvite = { inviteId: TeamInviteID; uv: UserVersionPercentForm; }; export declare type LinkTriple = { seqno: Seqno; seqType: SeqType; linkId: LinkID; }; export declare type UpPointer = { ourSeqno: Seqno; parentId: TeamID; parentSeqno: Seqno; deletion: boolean; }; export declare type DownPointer = { id: TeamID; nameComponent: string; isDeleted: boolean; }; export declare type Signer = { e: Seqno; k: KID; u: UID; }; export declare type Audit = { time: Time; mms: Seqno; mcs: Seqno; mhs: Seqno; mmp: Seqno; }; export declare type Probe = { i: number; t: Seqno; h: Seqno; }; export declare type TeamInviteType = { c: TeamInviteCategory.UNKNOWN; UNKNOWN: string; } | { c: TeamInviteCategory.SBS; SBS: TeamInviteSocialNetwork; } | { c: Exclude<TeamInviteCategory, TeamInviteCategory.UNKNOWN | TeamInviteCategory.SBS>; }; export declare type TeamGetLegacyTLFUpgrade = { encryptedKeyset: string; teamGeneration: PerTeamKeyGeneration; legacyGeneration: number; appType: TeamApplication; }; export declare type TeamLegacyTLFUpgradeChainInfo = { keysetHash: TeamEncryptedKBFSKeysetHash; teamGeneration: PerTeamKeyGeneration; legacyGeneration: number; appType: TeamApplication; }; export declare type TeamNameLogPoint = { lastPart: TeamNamePart; seqno: Seqno; }; export declare type TeamName = { parts: TeamNamePart[] | null; }; export declare type TeamCLKRResetUser = { uid: UID; userEldest: Seqno; memberEldest: Seqno; }; export declare type TeamResetUser = { username: string; uid: UID; eldestSeqno: Seqno; isDelete: boolean; }; export declare type TeamChangeRow = { id: TeamID; name: string; keyRotated: boolean; membershipChanged: boolean; latestSeqno: Seqno; latestHiddenSeqno: Seqno; latestOffchainVersion: Seqno; implicitTeam: boolean; misc: boolean; removedResetUsers: boolean; }; export declare type TeamExitRow = { id: TeamID; }; export declare type TeamNewlyAddedRow = { id: TeamID; name: string; }; export declare type TeamInvitee = { inviteId: TeamInviteID; uid: UID; eldestSeqno: Seqno; role: TeamRole; }; export declare type TeamAccessRequest = { uid: UID; eldestSeqno: Seqno; }; export declare type SeitanKeyLabel = { t: SeitanKeyLabelType.SMS; SMS: SeitanKeyLabelSms; } | { t: SeitanKeyLabelType.GENERIC; GENERIC: SeitanKeyLabelGeneric; } | { t: Exclude<SeitanKeyLabelType, SeitanKeyLabelType.SMS | SeitanKeyLabelType.GENERIC>; }; export declare type TeamSeitanRequest = { inviteId: TeamInviteID; uid: UID; eldestSeqno: Seqno; akey: SeitanAKey; role: TeamRole; ctime: number; }; export declare type TeamKBFSKeyRefresher = { generation: number; appType: TeamApplication; }; export declare type ImplicitRole = { role: TeamRole; ancestor: TeamID; }; export declare type TeamJoinRequest = { name: string; username: string; fullName: FullName; ctime: UnixTime; }; export declare type TeamCreateResult = { teamId: TeamID; chatSent: boolean; creatorAdded: boolean; }; export declare type TeamSettings = { open: boolean; joinAs: TeamRole; }; export declare type TeamShowcase = { isShowcased: boolean; description?: string; setByUid?: UID; anyMemberShowcase: boolean; }; export declare type UserRolePair = { assertion: string; role: TeamRole; botSettings?: TeamBotSettings; }; export declare type TeamMemberToRemove = { username: string; email: string; inviteId: TeamInviteID; allowInaction: boolean; }; export declare type UntrustedTeamExistsResult = { exists: boolean; status: StatusCode; }; export declare type Invitelink = { ikey: SeitanIKeyInvitelink; url: string; }; export declare type ImplicitTeamConflictInfo = { generation: ConflictGeneration; time: Time; }; export declare type TeamRolePair = { role: TeamRole; implicitRole: TeamRole; }; export declare type UserTeamVersionUpdate = { version: UserTeamVersion; }; export declare type TeamTreeMembershipValue = { role: TeamRole; joinTime?: Time; teamId: TeamID; }; export declare type TeamTreeMembershipsDoneResult = { expectedCount: number; targetTeamId: TeamID; targetUsername: string; guid: number; }; export declare type TeamSearchItem = { id: TeamID; name: string; description?: string; memberCount: number; lastActive: Time; isDemoted: boolean; inTeam: boolean; }; export declare type CryptKey = { keyGeneration: number; key: Bytes32; }; export declare type TLFQuery = { tlfName: string; identifyBehavior: TLFIdentifyBehavior; }; export declare type MerkleRootV2 = { seqno: Seqno; hashMeta: HashMeta; }; export declare type SigChainLocation = { seqno: Seqno; seqType: SeqType; }; export declare type UserSummary = { uid: UID; username: string; fullName: string; linkId?: LinkID; }; export declare type Email = { email: EmailAddress; isVerified: boolean; isPrimary: boolean; visibility: IdentityVisibility; lastVerifyEmailDate: UnixTime; }; export declare type InterestingPerson = { uid: UID; username: string; fullname: string; serviceMap: { [key: string]: string; }; }; export declare type CanLogoutRes = { canLogout: boolean; reason: string; passphraseState: PassphraseState; }; export declare type UserPassphraseStateMsg = { state: PassphraseState; }; export declare type UserBlockedRow = { blockUid: UID; blockUsername: string; chat?: boolean; follow?: boolean; }; export declare type UserBlockState = { blockType: UserBlockType; blocked: boolean; }; export declare type UserBlock = { username: string; chatBlocked: boolean; followBlocked: boolean; createTime?: Time; modifyTime?: Time; }; export declare type TeamBlock = { fqName: string; ctime: Time; }; export declare type APIUserKeybaseResult = { username: string; uid: UID; pictureUrl?: string; fullName?: string; rawScore: number; stellar?: string; isFollowee: boolean; }; export declare type APIUserServiceResult = { serviceName: APIUserServiceID; username: string; pictureUrl: string; bio: string; location: string; fullName: string; confirmed?: boolean; }; export declare type APIUserServiceSummary = { serviceName: APIUserServiceID; username: string; }; export declare type WotProof = { proofType: ProofType; nameOmitempty: string; usernameOmitempty: string; protocolOmitempty: string; hostnameOmitempty: string; domainOmitempty: string; }; export declare type GetLockdownResponse = { history: LockdownHistory[] | null; status: boolean; }; export declare type ContactSettings = { version?: number; allowFolloweeDegrees: number; allowGoodTeams: boolean; enabled: boolean; teams: TeamContactSettings[] | null; }; export declare type BlockReference = { bid: BlockIdCombo; nonce: BlockRefNonce; chargedTo: UserOrTeamID; }; export declare type BlockIdCount = { id: BlockIdCombo; liveCount: number; }; export declare type FolderUsageStat = { folderId: string; stats: UsageStat; }; export declare type TeamIDAndName = { id: TeamID; name: TeamName; }; export declare type RevokedKey = { key: PublicKey; time: KeybaseTime; by: KID; }; export declare type CurrentStatus = { configured: boolean; registered: boolean; loggedIn: boolean; sessionIsValid: boolean; user?: User; deviceName: string; }; export declare type ClientStatus = { details: ClientDetails; connectionId: number; notificationChannels: NotificationChannels; }; export declare type BootstrapStatus = { registered: boolean; loggedIn: boolean; uid: UID; username: string; deviceId: DeviceID; deviceName: string; fullname: FullName; userReacjis: UserReacjis; httpSrvInfo?: HttpSrvInfo; }; export declare type Contact = { name: string; components: ContactComponent[] | null; }; export declare type ProcessedContact = { contactIndex: number; contactName: string; component: ContactComponent; resolved: boolean; uid: UID; username: string; fullName: string; following: boolean; serviceMap: { [key: string]: string; }; assertion: string; displayName: string; displayLabel: string; }; export declare type DeviceDetail = { device: Device; eldest: boolean; provisioner?: Device; provisionedAt?: Time; revokedAt?: Time; revokedBy: KID; revokedByDevice?: Device; currentDevice: boolean; }; export declare type DeviceEkStatement = { currentDeviceEkMetadata: DeviceEkMetadata; }; export declare type DeviceEk = { seed: Bytes32; metadata: DeviceEkMetadata; }; export declare type UserEkStatement = { currentUserEkMetadata: UserEkMetadata; }; export declare type UserEkBoxed = { box: string; deviceEkGeneration: EkGeneration; metadata: UserEkMetadata; }; export declare type UserEk = { seed: Bytes32; metadata: UserEkMetadata; }; export declare type UserEkReboxArg = { userEkBoxMetadata: UserEkBoxMetadata; deviceId: DeviceID; deviceEkStatementSig: string; }; export declare type TeamEkStatement = { currentTeamEkMetadata: TeamEkMetadata; }; export declare type TeamEkBoxed = { box: string; userEkGeneration: EkGeneration; metadata: TeamEkMetadata; }; export declare type TeamEk = { seed: Bytes32; metadata: TeamEkMetadata; }; export declare type TeambotEkBoxed = { box: string; metadata: TeambotEkMetadata; }; export declare type TeambotEk = { seed: Bytes32; metadata: TeambotEkMetadata; }; export declare type GitLocalMetadataVersioned = { version: GitLocalMetadataVersion.V1; V1: GitLocalMetadataV1; } | { version: Exclude<GitLocalMetadataVersion, GitLocalMetadataVersion.V1>; }; export declare type GitRefMetadata = { refName: string; commits: GitCommit[] | null; moreCommitsAvailable: boolean; isDelete: boolean; }; export declare type HomeScreenTodoExt = { t: HomeScreenTodoType.VERIFY_ALL_EMAIL; VERIFY_ALL_EMAIL: VerifyAllEmailTodoExt; } | { t: Exclude<HomeScreenTodoType, HomeScreenTodoType.VERIFY_ALL_EMAIL>; }; export declare type HomeScreenPeopleNotificationFollowed = { followTime: Time; followedBack: boolean; user: UserSummary; }; export declare type HomeScreenPeopleNotificationContactMulti = { contacts: HomeScreenPeopleNotificationContact[] | null; numOthers: number; }; export declare type Identify3Row = { guiId: Identify3GUIID; key: string; value: string; priority: number; siteUrl: string; siteIcon: SizedImage[] | null; siteIconDarkmode: SizedImage[] | null; siteIconFull: SizedImage[] | null; siteIconFullDarkmode: SizedImage[] | null; proofUrl: string; sigId: SigID; ctime: Time; state: Identify3RowState; metas: Identify3RowMeta[] | null; color: Identify3RowColor; kid?: KID; }; export declare type IdentifyOutcome = { username: string; status?: Status; warnings: string[] | null; trackUsed?: TrackSummary; trackStatus: TrackStatus; numTrackFailures: number; numTrackChanges: number; numProofFailures: number; numRevoked: number; numProofSuccesses: number; revoked: TrackDiff[] | null; trackOptions: TrackOptions; forPgpPull: boolean; reason: IdentifyReason; }; export declare type IdentifyRow = { rowId: number; proof: RemoteProof; trackDiff?: TrackDiff; }; export declare type IdentifyKey = { pgpFingerprint: Buffer; kid: KID; trackDiff?: TrackDiff; breaksTracking: boolean; sigId: SigID; }; export declare type RevokedProof = { proof: RemoteProof; diff: TrackDiff; snoozed: boolean; }; export declare type CheckResult = { proofResult: ProofResult; time: Time; freshness: CheckResultFreshness; }; export declare type UserCard = { unverifiedNumFollowing: number; unverifiedNumFollowers: number; uid: UID; fullName: string; location: string; bio: string; bioDecorated: string; website: string; twitter: string; teamShowcase: UserTeamShowcase[] | null; registeredForAirdrop: boolean; stellarHidden: boolean; blocked: boolean; hidFromFollowers: boolean; }; export declare type ServiceStatus = { version: string; label: string; pid: string; lastExitStatus: string; bundleVersion: string; installStatus: InstallStatus; installAction: InstallAction; status: Status; }; export declare type FuseStatus = { version: string; bundleVersion: string; kextId: string; path: string; kextStarted: boolean; installStatus: InstallStatus; installAction: InstallAction; mountInfos: FuseMountInfo[] | null; status: Status; }; export declare type ComponentResult = { name: string; status: Status; exitCode: number; }; export declare type FSFolderWriterEditHistory = { writerName: string; edits: FSFolderWriterEdit[] | null; deletes: FSFolderWriterEdit[] | null; }; export declare type FolderSyncStatus = { localDiskBytesAvailable: number; localDiskBytesTotal: number; prefetchStatus: PrefetchStatus; prefetchProgress: PrefetchProgress; storedBytesTotal: number; outOfSyncSpace: boolean; }; export declare type MerkleRootAndTime = { root: MerkleRootV2; updateTime: Time; fetchTime: Time; }; export declare type MetadataResponse = { folderId: string; mdBlocks: MDBlock[] | null; }; export declare type BadgeState = { newTlfs: number; rekeysNeeded: number; newFollowers: number; inboxVers: number; homeTodoItems: number; unverifiedEmails: number; unverifiedPhones: number; smallTeamBadgeCount: number; bigTeamBadgeCount: number; newTeamAccessRequestCount: number; newDevices: DeviceID[] | null; revokedDevices: DeviceID[] | null; conversations: BadgeConversationInfo[] | null; newGitRepoGlobalUniqueIDs: string[] | null; newTeams: TeamID[] | null; deletedTeams: DeletedTeamInfo[] | null; teamsWithResetUsers: TeamMemberOutReset[] | null; unreadWalletAccounts: WalletAccountInfo[] | null; wotUpdates: { [key: string]: WotUpdate; }; resetState: ResetState; }; export declare type RuntimeStats = { processStats: ProcessRuntimeStats[] | null; dbStats: DbStats[] | null; perfEvents: PerfEvent[] | null; convLoaderActive: boolean; selectiveSyncActive: boolean; }; export declare type GUIEntryArg = { windowTitle: string; prompt: string; username: string; submitLabel: string; cancelLabel: string; retryLabel: string; type: PassphraseType; features: GUIEntryFeatures; }; /** * PGPSigVerification is returned by pgpDecrypt and pgpVerify with information * about the signature verification. If isSigned is false, there was no * signature, and the rest of the fields should be ignored. */ export declare type PGPSigVerification = { isSigned: boolean; verified: boolean; signer: User; signKey: PublicKey; warnings: string[] | null; }; export declare type Process = { pid: string; command: string; fileDescriptors: FileDescriptor[] | null; }; export declare type ExternalServiceConfig = { schemaVersion: number; display?: ServiceDisplayConfig; config?: ParamProofServiceConfig; }; export declare type ProblemTLF = { tlf: TLF; score: number; solutionKids: KID[] | null; }; export declare type RevokeWarning = { endangeredTlFs: TLF[] | null; }; export declare type ResetLink = { ctime: UnixTime; merkleRoot: ResetMerkleRoot; prev: ResetPrev; resetSeqno: Seqno; type: ResetType; uid: UID; }; export declare type ResetSummary = { ctime: UnixTime; merkleRoot: ResetMerkleRoot; resetSeqno: Seqno; eldestSeqno: Seqno; type: ResetType; }; export declare type SaltpackEncryptedMessageInfo = { devices: Device[] | null; numAnonReceivers: number; receiverIsAnon: boolean; sender: SaltpackSender; }; export declare type SaltpackVerifyResult = { signingKid: KID; sender: SaltpackSender; plaintext: string; verified: boolean; }; export declare type SaltpackVerifyFileResult = { signingKid: KID; sender: SaltpackSender; verifiedFilename: string; verified: boolean; }; export declare type KBFSArchivedPath = { path: string; archivedParam: KBFSArchivedParam; identifyBehavior?: TLFIdentifyBehavior; }; export declare type Dirent = { time: Time; size: number; name: string; direntType: DirentType; lastWriterUnverified: User; writable: boolean; prefetchStatus: PrefetchStatus; prefetchProgress: PrefetchProgress; symlinkTarget: string; }; export declare type SimpleFSStats = { processStats: ProcessRuntimeStats; blockCacheDbStats: string[] | null; syncCacheDbStats: string[] | null; runtimeDbStats: DbStats[] | null; }; export declare type DownloadInfo = { downloadId: string; path: KBFSPath; filename: string; startTime: Time; isRegularDownload: boolean; }; export declare type DownloadStatus = { regularDownloadIDs: string[] | null; states: DownloadState[] | null; }; export declare type UploadState = { uploadId: string; targetPath: KBFSPath; error?: string; canceled: boolean; }; export declare type TeambotKeyBoxed = { box: string; metadata: TeambotKeyMetadata; }; export declare type TeambotKey = { seed: Bytes32; metadata: TeambotKeyMetadata; }; export declare type PerTeamKeyAndCheck = { ptk: PerTeamKey; check: PerTeamSeedCheckPostImage; }; export declare type PerTeamKeySeedItem = { seed: PerTeamKeySeed; generation: PerTeamKeyGeneration; seqno: Seqno; check?: PerTeamSeedCheck; }; export declare type TeamMembers = { owners: UserVersion[] | null; admins: UserVersion[] | null; writers: UserVersion[] | null; readers: UserVersion[] | null; bots: UserVersion[] | null; restrictedBots: UserVersion[] | null; }; export declare type TeamMemberDetails = { uv: UserVersion; username: string; fullName: FullName; needsPuk: boolean; status: TeamMemberStatus; joinTime?: Time; }; export declare type UntrustedTeamInfo = { name: TeamName; inTeam: boolean; open: boolean; description: string; publicAdmins: string[] | null; numMembers: number; publicMembers: TeamMemberRole[] | null; }; export declare type TeamChangeReq = { owners: UserVersion[] | null; admins: UserVersion[] | null; writers: UserVersion[] | null; readers: UserVersion[] | null; bots: UserVersion[] | null; restrictedBots: { [key: string]: TeamBotSettings; }; none: UserVersion[] | null; completedInvites: { [key: string]: UserVersionPercentForm; }; usedInvites: TeamUsedInvite[] | null; }; export declare type TeamPlusApplicationKeys = { id: TeamID; name: string; implicit: boolean; public: boolean; application: TeamApplication; writers: UserVersion[] | null; onlyReaders: UserVersion[] | null; onlyRestrictedBots: UserVersion[] | null; applicationKeys: TeamApplicationKey[] | null; }; export declare type LinkTripleAndTime = { triple: LinkTriple; time: Time; }; export declare type FastTeamSigChainState = { id: TeamID; public: boolean; rootAncestor: TeamName; nameDepth: number; last?: LinkTriple; perTeamKeys: { [key: string]: PerTeamKey; }; perTeamKeySeedsVerified: { [key: string]: PerTeamKeySeed; }; downPointers: { [key: string]: DownPointer; }; lastUpPointer?: UpPointer; perTeamKeyCTime: UnixTime; linkIDs: { [key: string]: LinkID; }; merkleInfo: { [key: string]: MerkleRootV2; }; }; export declare type AuditHistory = { id: TeamID; public: boolean; priorMerkleSeqno: Seqno; version: AuditVersion; audits: Audit[] | null; preProbes: { [key: string]: Probe; }; postProbes: { [key: string]: Probe; }; tails: { [key: string]: LinkID; }; hiddenTails: { [key: string]: LinkID; }; preProbesToRetry: Seqno[] | null; postProbesToRetry: Seqno[] | null; skipUntil: Time; }; export declare type TeamInvite = { role: TeamRole; id: TeamInviteID; type: TeamInviteType; name: TeamInviteName; inviter: UserVersion; maxUses?: TeamInviteMaxUses; etime?: UnixTime; }; export declare type TeamUsedInviteLogPoint = { uv: UserVersion; logPoint: number; }; export declare type SubteamLogPoint = { name: TeamName; seqno: Seqno; }; export declare type TeamCLKRMsg = { teamId: TeamID; generation: PerTeamKeyGeneration; score: number; resetUsers: TeamCLKRResetUser[] | null; }; export declare type TeamMemberOutFromReset = { teamId: TeamID; teamName: string; resetUser: TeamResetUser; }; export declare type TeamSBSMsg = { teamId: TeamID; score: number; invitees: TeamInvitee[] | null; }; export declare type TeamOpenReqMsg = { teamId: TeamID; tars: TeamAccessRequest[] | null; }; export declare type SeitanKeyAndLabelVersion1 = { i: SeitanIKey; l: SeitanKeyLabel; }; export declare type SeitanKeyAndLabelVersion2 = { k: SeitanPubKey; l: SeitanKeyLabel; }; export declare type SeitanKeyAndLabelInvitelink = { i: SeitanIKeyInvitelink; l: SeitanKeyLabel; }; export declare type TeamSeitanMsg = { teamId: TeamID; seitans: TeamSeitanRequest[] | null; }; export declare type TeamOpenSweepMsg = { teamId: TeamID; resetUsers: TeamCLKRResetUser[] | null; }; /** * * TeamRefreshData are needed or wanted data requirements that, if unmet, will cause * * a refresh of the cache. */ export declare type TeamRefreshers = { needKeyGeneration: PerTeamKeyGeneration; needApplicationsAtGenerations: { [key: string]: TeamApplication[] | null; }; needApplicationsAtGenerationsWithKbfs: { [key: string]: TeamApplication[] | null; }; wantMembers: UserVersion[] | null; wantMembersRole: TeamRole; needKbfsKeyGeneration: TeamKBFSKeyRefresher; }; export declare type FastTeamLoadArg = { id: TeamID; public: boolean; assertTeamName?: TeamName; applications: TeamApplication[] | null; keyGenerationsNeeded: PerTeamKeyGeneration[] | null; needLatestKey: boolean; forceRefresh: boolean; hiddenChainIsOptional: boolean; }; export declare type FastTeamLoadRes = { name: TeamName; applicationKeys: TeamApplicationKey[] | null; }; export declare type MemberInfo = { uid: UID; teamId: TeamID; fqName: string; isImplicitTeam: boolean; isOpenTeam: boolean; role: TeamRole; implicit?: ImplicitRole; memberCount: number; allowProfilePromote: boolean; isMemberShowcased: boolean; }; export declare type AnnotatedMemberInfo = { uid: UID; teamId: TeamID; username: string; fullName: string; fqName: string; isImplicitTeam: boolean; implicitTeamDisplayName: string; isOpenTeam: boolean; role: TeamRole; implicit?: ImplicitRole; needsPuk: boolean; memberCount: number; memberEldestSeqno: Seqno; allowProfilePromote: boolean; isMemberShowcased: boolean; status: TeamMemberStatus; }; export declare type TeamAddMemberResult = { invited: boolean; user?: User; chatSending: boolean; }; export declare type TeamAddMembersResult = { notAdded: User[] | null; }; export declare type TeamTreeEntry = { name: TeamName; admin: boolean; }; export declare type SubteamListEntry = { name: TeamName; teamId: TeamID; memberCount: number; }; export declare type TeamAndMemberShowcase = { teamShowcase: TeamShowcase; isMemberShowcased: boolean; }; export declare type TeamRemoveMembersResult = { failures: TeamMemberToRemove[] | null; }; export declare type TeamEditMembersResult = { failures: UserRolePair[] | null; }; export declare type InviteLinkDetails = { inviteId: TeamInviteID; inviterUid: UID; inviterUsername: string; inviterResetOrDel: boolean; teamIsOpen: boolean; teamId: TeamID; teamDesc: string; teamName: TeamName; teamNumMembers: number; teamAvatars: { [key: string]: AvatarUrl; }; }; export declare type ImplicitTeamUserSet = { keybaseUsers: string[] | null; unresolvedUsers: SocialAssertion[] | null; }; export declare type TeamProfileAddEntry = { teamId: TeamID; teamName: TeamName; open: boolean; disabledReason: string; }; export declare type TeamRoleMapAndVersion = { teams: { [key: string]: TeamRolePair; }; userTeamVersion: UserTeamVersion; }; export declare type TeamTreeMembershipResult = { s: TeamTreeMembershipStatus.OK; OK: TeamTreeMembershipValue; } | { s: TeamTreeMembershipStatus.ERROR; ERROR: TeamTreeError; } | { s: TeamTreeMembershipStatus.HIDDEN; } | { s: Exclude<TeamTreeMembershipStatus, TeamTreeMembershipStatus.OK | TeamTreeMembershipStatus.ERROR | TeamTreeMembershipStatus.HIDDEN>; }; export declare type TeamSearchExport = { items: { [key: string]: TeamSearchItem; }; suggested: TeamID[] | null; }; export declare type TeamSearchRes = { results: TeamSearchItem[] | null; }; export declare type MerkleTreeLocation = { leaf: UserOrTeamID; loc: SigChainLocation; }; export declare type SignatureMetadata = { signingKid: KID; prevMerkleRootSigned: MerkleRootV2; firstAppearedUnverified: Seqno; time: Time; sigChainLocation: SigChainLocation; }; export declare type Proofs = { social: TrackProof[] | null; web: WebProof[] | null; publicKeys: PublicKey[] | null; }; export declare type UserSummarySet = { users: UserSummary[] | null; time: Time; version: number; }; export declare type UserSettings = { emails: Email[] | null; phoneNumbers: UserPhoneNumber[] | null; }; export declare type ProofSuggestion = { key: string; belowFold: boolean; profileText: string; profileIcon: SizedImage[] | null; profileIconDarkmode: SizedImage[] | null; pickerText: string; pickerSubtext: string; pickerIcon: SizedImage[] | null; pickerIconDarkmode: SizedImage[] | null; metas: Identify3RowMeta[] | null; }; export declare type NextMerkleRootRes = { res?: MerkleRootV2; }; export declare type UserBlockedBody = { blocks: UserBlockedRow[] | null; blockerUid: UID; blockerUsername: string; }; export declare type UserBlockedSummary = { blocker: string; blocks: { [key: string]: UserBlockState[] | null; }; }; export declare type Confidence = { usernameVerifiedViaOmitempty: UsernameVerificationType; proofsOmitempty: WotProof[] | null; otherOmitempty: string; }; export declare type BlockReferenceCount = { ref: BlockReference; liveCount: number; }; export declare type ReferenceCountRes = { counts: BlockIdCount[] | null; }; export declare type BlockQuotaInfo = { folders: FolderUsageStat[] | null; total: UsageStat; limit: number; gitLimit: number; }; export declare type UserPlusKeys = { uid: UID; username: string; eldestSeqno: Seqno; status: StatusCode; deviceKeys: PublicKey[] | null; revokedDeviceKeys: RevokedKey[] | null; pgpKeyCount: number; uvv: UserVersionVector; deletedDeviceKeys: PublicKey[] | null; perUserKeys: PerUserKey[] | null; resets: ResetSummary[] | null; }; export declare type ExtendedStatus = { standalone: boolean; passphraseStreamCached: boolean; tsecCached: boolean; deviceSigKeyCached: boolean; deviceEncKeyCached: boolean; paperSigKeyCached: boolean; paperEncKeyCached: boolean; storedSecret: boolean; secretPromptSkip: boolean; rememberPassphrase: boolean; device?: Device; deviceErr?: LoadDeviceErr; logDir: string; session?: SessionStatus; defaultUsername: string; provisionedUsernames: string[] | null; configuredAccounts: ConfiguredAccount[] | null; clients: ClientStatus[] | null; deviceEkNames: string[] | null; platformInfo: PlatformInfo; defaultDeviceId: DeviceID; localDbStats: string[] | null; localChatDbStats: string[] | null; localBlockCacheDbStats: string[] | null; localSyncCacheDbStats: string[] | null; cacheDirSizeInfo: DirSizeInfo[] | null; uiRouterMapping: { [key: string]: number; }; }; export declare type ContactListResolutionResult = { newlyResolved: ProcessedContact[] | null; resolved: ProcessedContact[] | null; }; export declare type TeamEphemeralKey = { keyType: TeamEphemeralKeyType.TEAM; TEAM: TeamEk; } | { keyType: TeamEphemeralKeyType.TEAMBOT; TEAMBOT: TeambotEk; } | { keyType: Exclude<TeamEphemeralKeyType, TeamEphemeralKeyType.TEAM | TeamEphemeralKeyType.TEAMBOT>; }; export declare type TeamEphemeralKeyBoxed = { keyType: TeamEphemeralKeyType.TEAM; TEAM: TeamEkBoxed; } | { keyType: TeamEphemeralKeyType.TEAMBOT; TEAMBOT: TeambotEkBoxed; } | { keyType: Exclude<TeamEphemeralKeyType, TeamEphemeralKeyType.TEAM | TeamEphemeralKeyType.TEAMBOT>; }; export declare type GitLocalMetadata = { repoName: GitRepoName; refs: GitRefMetadata[] | null; pushType: GitPushType; previousRepoName: GitRepoName; }; export declare type HomeScreenItemDataExt = { t: HomeScreenItemType.TODO; TODO: HomeScreenTodoExt; } | { t: Exclude<HomeScreenItemType, HomeScreenItemType.TODO>; }; export declare type HomeScreenPeopleNotificationFollowedMulti = { followers: HomeScreenPeopleNotificationFollowed[] | null; numOthers: number; }; export declare type Identity = { status?: Status; whenLastTracked: Time; proofs: IdentifyRow[] | null; cryptocurrency: Cryptocurrency[] | null; revoked: TrackDiff[] | null; revokedDetails: RevokedProof[] | null; breaksTracking: boolean; }; export declare type LinkCheckResult = { proofId: number; proofResult: ProofResult; snoozedResult: ProofResult; torWarning: boolean; tmpTrackExpireTime: Time; cached?: CheckResult; diff?: TrackDiff; remoteDiff?: TrackDiff; hint?: SigHint; breaksTracking: boolean; }; export declare type ServicesStatus = { service: ServiceStatus[] | null; kbfs: ServiceStatus[] | null; updater: ServiceStatus[] | null; }; export declare type InstallResult = { componentResults: ComponentResult[] | null; status: Status; fatal: boolean; }; export declare type UninstallResult = { componentResults: ComponentResult[] | null; status: Status; }; /** * ProblemSet is for a particular (user,kid) that initiated a rekey problem. * This problem consists of one or more problem TLFs, which are individually scored * and have attendant solutions --- devices that if they came online can rekey and * solve the ProblemTLF. */ export declare type ProblemSet = { user: User; kid: KID; tlfs: ProblemTLF[] | null; }; export declare type SaltpackPlaintextResult = { info: SaltpackEncryptedMessageInfo; plaintext: string; signed: boolean; }; export declare type SaltpackFileResult = { info: SaltpackEncryptedMessageInfo; decryptedFilename: string; signed: boolean; }; export declare type Path = { PathType: PathType.LOCAL; LOCAL: string; } | { PathType: PathType.KBFS; KBFS: KBFSPath; } | { PathType: PathType.KBFS_ARCHIVED; KBFS_ARCHIVED: KBFSArchivedPath; } | { PathType: Exclude<PathType, PathType.LOCAL | PathType.KBFS | PathType.KBFS_ARCHIVED>; }; export declare type DirentWithRevision = { entry: Dirent; revision: KBFSRevision; }; export declare type SimpleFSListResult = { entries: Dirent[] | null; progress: Progress; }; export declare type FolderSyncConfigAndStatus = { config: FolderSyncConfig; status: FolderSyncStatus; }; export declare type TeamMembersDetails = { owners: TeamMemberDetails[] | null; admins: TeamMemberDetails[] | null; writers: TeamMemberDetails[] | null; readers: TeamMemberDetails[] | null; bots: TeamMemberDetails[] | null; restrictedBots: TeamMemberDetails[] | null; }; export declare type FastTeamData = { frozen: boolean; subversion: number; tombstoned: boolean; name: TeamName; chain: FastTeamSigChainState; perTeamKeySeedsUnverified: { [key: string]: PerTeamKeySeed; }; maxContinuousPtkGeneration: PerTeamKeyGeneration; seedChecks: { [key: string]: PerTeamSeedCheck; }; latestKeyGeneration: PerTeamKeyGeneration; readerKeyMasks: { [key: string]: { [key: string]: MaskB64; }; }; latestSeqnoHint: Seqno; cachedAt: Time; loadedLatest: boolean; }; export declare type HiddenTeamChainRatchetSet = { ratchets: { [key: string]: LinkTripleAndTime; }; }; export declare type HiddenTeamChainLink = { m: MerkleRootV2; p: LinkTriple; s: Signer; k: { [key: string]: PerTeamKeyAndCheck; }; }; export declare type UserLogPoint = { role: TeamRole; sigMeta: SignatureMetadata; }; export declare type AnnotatedTeamUsedInviteLogPoint = { username: string; teamUsedInviteLogPoint: TeamUsedInviteLogPoint; }; export declare type SeitanKeyAndLabel = { v: SeitanKeyAndLabelVersion.V1; V1: SeitanKeyAndLabelVersion1; } | { v: SeitanKeyAndLabelVersion.V2; V2: SeitanKeyAndLabelVersion2; } | { v: SeitanKeyAndLabelVersion.Invitelink; Invitelink: SeitanKeyAndLabelInvitelink; } | { v: Exclude<SeitanKeyAndLabelVersion, SeitanKeyAndLabelVersion.V1 | SeitanKeyAndLabelVersion.V2 | SeitanKeyAndLabelVersion.Invitelink>; }; export declare type LoadTeamArg = { id: TeamID; name: string; public: boolean; needAdmin: boolean; refreshUidMapper: boolean; refreshers: TeamRefreshers; forceFullReload: boolean; forceRepoll: boolean; staleOk: boolean; allowNameLookupBurstCache: boolean; skipNeedHiddenRotateCheck: boolean; auditMode: AuditMode; }; export declare type TeamList = { teams: MemberInfo[] | null; }; export declare type TeamTreeResult = { entries: TeamTreeEntry[] | null; }; export declare type SubteamListResult = { entries: SubteamListEntry[] | null; }; /** * * iTeams */ export declare type ImplicitTeamDisplayName = { isPublic: boolean; writers: ImplicitTeamUserSet; readers: ImplicitTeamUserSet; conflictInfo?: ImplicitTeamConflictInfo; }; export declare type TeamRoleMapStored = { data: TeamRoleMapAndVersion; cachedAt: Time; }; export declare type AnnotatedTeamMemberDetails = { details: TeamMemberDetails; role: TeamRole; }; export declare type TeamTreeMembership = { teamName: string; result: TeamTreeMembershipResult; targetTeamId: TeamID; targetUsername: string; guid: number; }; export declare type PublicKeyV2Base = { kid: KID; isSibkey: boolean; isEldest: boolean; cTime: Time; eTime: Time; provisioning: SignatureMetadata; revocation?: SignatureMetadata; }; export declare type ProofSuggestionsRes = { suggestions: ProofSuggestion[] | null; showMore: boolean; }; export declare type APIUserSearchResult = { score: number; keybase?: APIUserKeybaseResult; service?: APIUserServiceResult; contact?: ProcessedContact; imptofu?: ImpTofuSearchResult; servicesSummary: { [key: string]: APIUserServiceSummary; }; rawScore: number; }; export declare type NonUserDetails = { isNonUser: boolean; assertionValue: string; assertionKey: string; description: string; contact?: ProcessedContact; service?: APIUserServiceResult; siteIcon: SizedImage[] | null; siteIconDarkmode: SizedImage[] | null; siteIconFull: SizedImage[] | null; siteIconFullDarkmode: SizedImage[] | null; }; export declare type WotVouch = { status: WotStatusType; vouchProof: SigID; vouchee: UserVersion; voucheeUsername: string; voucher: UserVersion; voucherUsername: string; vouchTexts: string[] | null; vouchedAt: Time; confidence?: Confidence; }; export declare type DowngradeReferenceRes = { completed: BlockReferenceCount[] | null; failed: BlockReference; }; export declare type UserPlusAllKeys = { base: UserPlusKeys; pgpKeys: PublicKey[] | null; remoteTracks: RemoteTrack[] | null; }; export declare type FullStatus = { username: string; configPath: string; curStatus: CurrentStatus; extStatus: ExtendedStatus; client: KbClientStatus; service: KbServiceStatus; kbfs: KBFSStatus; desktop: DesktopStatus; updater: UpdaterStatus; start: StartStatus; git: GitStatus; }; export declare type FolderNormalView = { resolvingConflict: boolean; stuckInConflict: boolean; localViews: Path[] | null; }; export declare type FolderConflictManualResolvingLocalView = { normalView: Path; }; export declare type GitRepoInfo = { folder: FolderHandle; repoId: RepoID; localMetadata: GitLocalMetadata; serverMetadata: GitServerMetadata; repoUrl: string; globalUniqueId: string; canDelete: boolean; teamRepoSettings?: GitTeamRepoSettings; }; export declare type HomeScreenPeopleNotification = { t: HomeScreenPeopleNotificationType.FOLLOWED; FOLLOWED: HomeScreenPeopleNotificationFollowed; } | { t: HomeScreenPeopleNotificationType.FOLLOWED_MULTI; FOLLOWED_MULTI: HomeScreenPeopleNotificationFollowedMulti; } | { t: HomeScreenPeopleNotificationType.CONTACT; CONTACT: HomeScreenPeopleNotificationContact; } | { t: HomeScreenPeopleNotificationType.CONTACT_MULTI; CONTACT_MULTI: HomeScreenPeopleNotificationContactMulti; } | { t: Exclude<HomeScreenPeopleNotificationType, HomeScreenPeopleNotificationType.FOLLOWED | HomeScreenPeopleNotificationType.FOLLOWED_MULTI | HomeScreenPeopleNotificationType.CONTACT | HomeScreenPeopleNotificationType.CONTACT_MULTI>; }; export declare type IdentifyProofBreak = { remoteProof: RemoteProof; lcr: LinkCheckResult; }; export declare type ProblemSetDevices = { problemSet: ProblemSet; devices: Device[] | null; }; export declare type ListArgs = { opId: OpID; path: Path; filter: ListFilter; }; export declare type ListToDepthArgs = { opId: OpID; path: Path; filter: ListFilter; depth: number; }; export declare type RemoveArgs = { opId: OpID; path: Path; recursive: boolean; }; export declare type ReadArgs = { opId: OpID; path: Path; offset: number; size: number; }; export declare type WriteArgs = { opId: OpID; path: Path; offset: number; }; export declare type CopyArgs = { opId: OpID; src: Path; dest: Path; overwriteExistingFiles: boolean; }; export declare type MoveArgs = { opId: OpID; src: Path; dest: Path; overwriteExistingFiles: boolean; }; export declare type GetRevisionsArgs = { opId: OpID; path: Path; spanType: RevisionSpanType; }; export declare type GetRevisionsResult = { revisions: DirentWithRevision[] | null; progress: Progress; }; export declare type HiddenTeamChain = { id: TeamID; subversion: number; public: boolean; frozen: boolean; tombstoned: boolean; last: Seqno; lastFull: Seqno; latestSeqnoHint: Seqno; lastCommittedSeqno: Seqno; linkReceiptTimes: { [key: string]: Time; }; lastPerTeamKeys: { [key: string]: Seqno; }; outer: { [key: string]: LinkID; }; inner: { [key: string]: HiddenTeamChainLink; }; readerPerTeamKeys: { [key: string]: Seqno; }; ratchetSet: HiddenTeamChainRatchetSet; cachedAt: Time; needRotate: boolean; merkleRoots: { [key: string]: MerkleRootV2; }; }; export declare type AnnotatedTeamInvite = { invite: TeamInvite; displayName: TeamInviteDisplayName; inviterUsername: string; inviteeUv: UserVersion; teamName: string; status?: TeamMemberStatus; usedInvites: AnnotatedTeamUsedInviteLogPoint[] | null; }; export declare type TeamSigChainState = { reader: UserVersion; id: TeamID; implicit: boolean; public: boolean; rootAncestor: TeamName; nameDepth: number; nameLog: TeamNameLogPoint[] | null; lastSeqno: Seqno; lastLinkId: LinkID; lastHighSeqno: Seqno; lastHighLinkId: LinkID; parentId?: TeamID; userLog: { [key: string]: UserLogPoint[] | null; }; subteamLog: { [key: string]: SubteamLogPoint[] | null; }; perTeamKeys: { [key: string]: PerTeamKey; }; maxPerTeamKeyGeneration: PerTeamKeyGeneration; perTeamKeyCTime: UnixTime; linkIDs: { [key: string]: LinkID; }; stubbedLinks: { [key: string]: boolean; }; activeInvites: { [key: string]: TeamInvite; }; obsoleteInvites: { [key: string]: TeamInvite; }; usedInvites: { [key: string]: TeamUsedInviteLogPoint[] | null; }; open: boolean; openTeamJoinAs: TeamRole; bots: { [key: string]: TeamBotSettings; }; tlfIDs: TLFID[] | null; tlfLegacyUpgrade: { [key: string]: TeamLegacyTLFUpgradeChainInfo; }; headMerkle?: MerkleRootV2; merkleRoots: { [key: string]: MerkleRootV2; }; }; export declare type LookupImplicitTeamRes = { teamId: TeamID; name: TeamName; displayName: ImplicitTeamDisplayName; tlfId: TLFID; }; export declare type PublicKeyV2NaCl = { base: PublicKeyV2Base; parent?: KID; deviceId: DeviceID; deviceDescription: string; deviceType: DeviceTypeV2; }; export declare type PublicKeyV2PGPSummary = { base: PublicKeyV2Base; fingerprint: PGPFingerprint; identities: PGPIdentity[] | null; }; export declare type ConflictState = { conflictStateType: ConflictStateType.NormalView; NormalView: FolderNormalView; } | { conflictStateType: ConflictStateType.ManualResolvingLocalView; ManualResolvingLocalView: FolderConflictManualResolvingLocalView; } | { conflictStateType: Exclude<ConflictStateType, ConflictStateType.NormalView | ConflictStateType.ManualResolvingLocalView>; }; export declare type GitRepoResult = { state: GitRepoResultState.ERR; ERR: string; } | { state: GitRepoResultState.OK; OK: GitRepoInfo; } | { state: Exclude<GitRepoResultState, GitRepoResultState.ERR | GitRepoResultState.OK>; }; export declare type HomeScreenItemData = { t: HomeScreenItemType.TODO; TODO: HomeScreenTodo; } | { t: HomeScreenItemType.PEOPLE; PEOPLE: HomeScreenPeopleNotification; } | { t: HomeScreenItemType.ANNOUNCEMENT; ANNOUNCEMENT: HomeScreenAnnouncement; } | { t: Exclude<HomeScreenItemType, HomeScreenItemType.TODO | HomeScreenItemType.PEOPLE | HomeScreenItemType.ANNOUNCEMENT>; }; export declare type IdentifyTrackBreaks = { keys: IdentifyKey[] | null; proofs: IdentifyProofBreak[] | null; }; export declare type OpDescription = { asyncOp: AsyncOps.LIST; LIST: ListArgs; } | { asyncOp: AsyncOps.LIST_RECURSIVE; LIST_RECURSIVE: ListArgs; } | { asyncOp: AsyncOps.LIST_RECURSIVE_TO_DEPTH; LIST_RECURSIVE_TO_DEPTH: ListToDepthArgs; } | { asyncOp: AsyncOps.READ; READ: ReadArgs; } | { asyncOp: AsyncOps.WRITE; WRITE: WriteArgs; } | { asyncOp: AsyncOps.COPY; COPY: CopyArgs; } | { asyncOp: AsyncOps.MOVE; MOVE: MoveArgs; } | { asyncOp: AsyncOps.REMOVE; REMOVE: RemoveArgs; } | { asyncOp: AsyncOps.GET_REVISIONS; GET_REVISIONS: GetRevisionsArgs; } | { asyncOp: Exclude<AsyncOps, AsyncOps.LIST | AsyncOps.LIST_RECURSIVE | AsyncOps.LIST_RECURSIVE_TO_DEPTH | AsyncOps.READ | AsyncOps.WRITE | AsyncOps.COPY | AsyncOps.MOVE | AsyncOps.REMOVE | AsyncOps.GET_REVISIONS>; }; export declare type TeamDetails = { name: string; members: TeamMembersDetails; keyGeneration: PerTeamKeyGeneration; annotatedActiveInvites: { [key: string]: AnnotatedTeamInvite; }; settings: TeamSettings; showcase: TeamShowcase; }; export declare type TeamData = { v: number; frozen: boolean; tombstoned: boolean; secretless: boolean; name: TeamName; chain: TeamSigChainState; perTeamKeySeedsUnverified: { [key: string]: PerTeamKeySeedItem; }; readerKeyMasks: { [key: string]: { [key: string]: MaskB64; }; }; latestSeqnoHint: Seqno; cachedAt: Time; tlfCryptKeys: { [key: string]: CryptKey[] | null; }; }; export declare type AnnotatedTeamList = { teams: AnnotatedMemberInfo[] | null; annotatedActiveInvites: { [key: string]: AnnotatedTeamInvite; }; }; export declare type TeamDebugRes = { chain: TeamSigChainState; }; export declare type AnnotatedTeam = { teamId: TeamID; name: string; transitiveSubteamsUnverified: SubteamListResult; members: AnnotatedTeamMemberDetails[] | null; invites: AnnotatedTeamInvite[] | null; joinRequests: TeamJoinRequest[] | null; tarsDisabled: boolean; settings: TeamSettings; showcase: TeamShowcase; }; export declare type PublicKeyV2 = { keyType: KeyType.NACL; NACL: PublicKeyV2NaCl; } | { keyType: KeyType.PGP; PGP: PublicKeyV2PGPSummary; } | { keyType: Exclude<KeyType, KeyType.NACL | KeyType.PGP>; }; export declare type UserPlusKeysV2 = { uid: UID; username: string; eldestSeqno: Seqno; status: StatusCode; perUserKeys: PerUserKey[] | null; deviceKeys: { [key: string]: PublicKeyV2NaCl; }; pgpKeys: { [key: string]: PublicKeyV2PGPSummary; }; stellarAccountId?: string; remoteTracks: { [key: string]: RemoteTrack; }; reset?: ResetSummary; unstubbed: boolean; }; export declare type UPKLiteV1 = { uid: UID; username: string; eldestSeqno: Seqno; status: StatusCode; deviceKeys: { [key: string]: PublicKeyV2NaCl; }; reset?: ResetSummary; }; /** * Folder represents a favorite top-level folder in kbfs. * This type is likely to change significantly as all the various parts are * connected and tested. */ export declare type Folder = { name: string; private: boolean; created: boolean; folderType: FolderType; teamId?: TeamID; resetMembers: User[] | null; mtime?: Time; conflictState?: ConflictState; syncConfig?: FolderSyncConfig; }; export declare type HomeScreenItem = { badged: boolean; data: HomeScreenItemData; dataExt: HomeScreenItemDataExt; }; export declare type Identify2Res = { upk: UserPlusKeys; identifiedAt: Time; trackBreaks?: IdentifyTrackBreaks; }; export declare type IdentifyLiteRes = { ul: UserOrTeamLite; trackBreaks?: IdentifyTrackBreaks; }; export declare type ResolveIdentifyImplicitTeamRes = { displayName: string; teamId: TeamID; writers: UserVersion[] | null; trackBreaks: { [key: string]: IdentifyTrackBreaks; }; folderId: TLFID; }; export declare type TLFIdentifyFailure = { user: User; breaks?: IdentifyTrackBreaks; }; export declare type UserPlusKeysV2AllIncarnations = { current: UserPlusKeysV2; pastIncarnations: UserPlusKeysV2[] | null; uvv: UserVersionVector; seqnoLinkIDs: { [key: string]: LinkID; }; minorVersion: UPK2MinorVersion; stale: boolean; }; export declare type UPKLiteV1AllIncarnations = { current: UPKLiteV1; pastIncarnations: UPKLiteV1[] | null; seqnoLinkIDs: { [key: string]: LinkID; }; minorVersion: UPKLiteMinorVersion; }; export declare type FavoritesResult = { favoriteFolders: Folder[] | null; ignoredFolders: Folder[] | null; newFolders: Folder[] | null; }; export declare type HomeScreen = { lastViewed: Time; version: number; visits: number; items: HomeScreenItem[] | null; followSuggestions: HomeUserSummary[] | null; announcementsVersion: number; }; export declare type Identify2ResUPK2 = { upk: UserPlusKeysV2AllIncarnations; identifiedAt: Time; trackBreaks?: IdentifyTrackBreaks; }; export declare type FSEditListRequest = { folder: Folder; requestId: number; }; export declare type FSFolderEditHistory = { folder: Folder; serverTime: Time; history: FSFolderWriterEditHistory[] | null; }; export declare type FolderSyncConfigAndStatusWithFolder = { folder: Folder; config: FolderSyncConfig; status: FolderSyncStatus; }; export declare type FolderWithFavFlags = { folder: Folder; isFavorite: boolean; isIgnored: boolean; isNew: boolean; }; export declare type SimpleFSIndexProgress = { overallProgress: IndexProgressRecord; currFolder: Folder; currProgress: IndexProgressRecord; foldersLeft: Folder[] | null; }; export declare type TLFBreak = { breaks: TLFIdentifyFailure[] | null; }; /** * * What we're storing for each user. At first it was UPAKs, as defined * * in common.avdl. But going forward, we're going to use UserPlusKeysV2AllIncarnations. */ export declare type UPAKVersioned = { v: UPAKVersion.V1; V1: UserPlusAllKeys; } | { v: UPAKVersion.V2; V2: UserPlusKeysV2AllIncarnations; } | { v: Exclude<UPAKVersion, UPAKVersion.V1 | UPAKVersion.V2>; }; export declare type SyncConfigAndStatusRes = { folders: FolderSyncConfigAndStatusWithFolder[] | null; overallStatus: FolderSyncStatus; }; export declare type CanonicalTLFNameAndIDWithBreaks = { tlfId: TLFID; canonicalName: CanonicalTlfName; breaks: TLFBreak; }; export declare type GetTLFCryptKeysRes = { nameIdBreaks: CanonicalTLFNameAndIDWithBreaks; cryptKeys: CryptKey[] | null; };
the_stack
import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { DOWN_ARROW, ENTER, ESCAPE, TAB, UP_ARROW } from '@angular/cdk/keycodes'; import { FlexibleConnectedPositionStrategy, Overlay, OverlayConfig, OverlayRef, ViewportRuler, } from '@angular/cdk/overlay'; import { TemplatePortal } from '@angular/cdk/portal'; import { ChangeDetectorRef, Directive, ElementRef, forwardRef, Host, HostListener, Input, NgZone, OnDestroy, Optional, Provider, ViewContainerRef, } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { defer, fromEvent, merge, Observable, of, Subject, Subscription } from 'rxjs'; import { delay, filter, map, switchMap, take, tap } from 'rxjs/operators'; import { FormFieldComponent } from '../form-field'; import { _getItemScrollPosition, AutocompleteItemComponent, AutocompleteItemSelectionChange, } from './autocomplete-item.component'; import { AutocompleteComponent } from './autocomplete.component'; export const AUTOCOMPLETE_VALUE_ACCESSOR: Provider = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => AutocompleteTriggerDirective), multi: true, }; export const AUTOCOMPLETE_ITEM_HEIGHT = 24; export const AUTOCOMPLETE_PANEL_HEIGHT = 256; @Directive({ selector: 'input[gdAutocompleteTrigger]', exportAs: 'gdAutocompleteTrigger', providers: [AUTOCOMPLETE_VALUE_ACCESSOR], host: { '[attr.autocomplete]': '"off"', '[attr.role]': 'autocompleteDisabled ? null : "combobox"', '[attr.aria-autocomplete]': 'autocompleteDisabled ? null : "list"', '[attr.aria-activedescendant]': 'activeItem?.id', '[attr.aria-expanded]': 'autocompleteDisabled ? null : panelOpen.toString()', '[attr.aria-owns]': '(autocompleteDisabled || !panelOpen) ? null : autocomplete?.id', }, }) export class AutocompleteTriggerDirective implements ControlValueAccessor, OnDestroy { /* tslint:disable */ /** `View -> model callback called when value changes` */ _onChange: (value: any) => void = () => { }; /** `View -> model callback called when autocomplete has been touched` */ _onTouched = () => { }; /* tslint:enable */ @Input('gdAutocompleteTrigger') autocomplete: AutocompleteComponent; private overlayRef: OverlayRef | null = null; private portal: TemplatePortal; private componentDestroyed = false; /** Strategy that is used to position the panel. */ private positionStrategy: FlexibleConnectedPositionStrategy; /** The subscription for closing actions (some are bound to document). */ private closingActionsSubscription: Subscription; /** Subscription to viewport size changes. */ private viewportSubscription = Subscription.EMPTY; /** * Whether the autocomplete can open the next time it is focused. Used to prevent a focused, * closed autocomplete from being reopened if the user switches to another browser tab and then * comes back. */ private canOpenOnNextFocus = true; /** Stream of keyboard events that can close the panel. */ private readonly closeKeyEventStream = new Subject<void>(); private _overlayAttached: boolean = false; /** Stream of autocomplete item selections. */ private readonly itemSelections: Observable<AutocompleteItemSelectionChange> = defer(() => { if (this.autocomplete && this.autocomplete.items) { return merge(...this.autocomplete.items.map(item => item.selectionChanged)); } // If there are any subscribers before `ngAfterViewInit`, the `autocomplete` will be undefined. // Return a stream that we'll replace with the real one once everything is in place. return this.zone.onStable .asObservable() .pipe(take(1), switchMap(() => this.itemSelections)); }); constructor( private elementRef: ElementRef<HTMLInputElement>, private overlay: Overlay, private viewContainerRef: ViewContainerRef, private zone: NgZone, private changeDetectorRef: ChangeDetectorRef, private viewportRuler: ViewportRuler, @Optional() @Host() private formField: FormFieldComponent, ) { } private _autocompleteDisabled = false; /** * Whether the autocomplete is disabled. When disabled, the element will * act as a regular input and the user won't be able to open the panel. */ @Input('gdAutocompleteDisabled') get autocompleteDisabled(): boolean { return this._autocompleteDisabled; } set autocompleteDisabled(value: boolean) { this._autocompleteDisabled = coerceBooleanProperty(value); } /** Whether or not the autocomplete panel is open. */ get panelOpen(): boolean { return this._overlayAttached && this.autocomplete.showPanel; } /** The currently active item, coerced to AutocompleteItem type. */ get activeItem(): AutocompleteItemComponent | null { if (this.autocomplete && this.autocomplete._keyManager) { return this.autocomplete._keyManager.activeItem; } return null; } /** * A stream of actions that should close the autocomplete panel, including * when an item is selected, on blur, and when TAB is pressed. */ private get panelClosingActions(): Observable<AutocompleteItemSelectionChange | null> { return merge( this.itemSelections, this.autocomplete._keyManager.tabOut.pipe(filter(() => this._overlayAttached)), this.closeKeyEventStream, this.getOutsideClickStream(), this.overlayRef ? this.overlayRef.detachments().pipe(filter(() => this._overlayAttached)) : of(), ).pipe( // Normalize the output so we return a consistent type. map(event => event instanceof AutocompleteItemSelectionChange ? event : null), ); } ngOnDestroy(): void { this.viewportSubscription.unsubscribe(); this.componentDestroyed = true; this.destroyPanel(); this.closeKeyEventStream.complete(); } /** Opens the autocomplete suggestion panel. */ openPanel(): void { this.attachOverlay(); } /** Closes the autocomplete suggestion panel. */ closePanel(): void { if (!this._overlayAttached) { return; } this.autocomplete._isOpen = this._overlayAttached = false; if (this.overlayRef && this.overlayRef.hasAttached()) { this.overlayRef.detach(); this.closingActionsSubscription.unsubscribe(); } // Note that in some cases this can end up being called after the component is destroyed. // Add a check to ensure that we don't try to run change detection on a destroyed view. if (!this.componentDestroyed) { // We need to trigger change detection manually, because // `fromEvent` doesn't seem to do it at the proper time. // This ensures that the label is reset when the // user clicks outside. this.changeDetectorRef.detectChanges(); } } // Implemented as part of ControlValueAccessor. writeValue(value: any): void { Promise.resolve(null).then(() => this.setTriggerValue(value)); } // Implemented as part of ControlValueAccessor. registerOnChange(fn: (value: any) => {}): void { this._onChange = fn; } // Implemented as part of ControlValueAccessor. registerOnTouched(fn: () => {}) { this._onTouched = fn; } // Implemented as part of ControlValueAccessor. setDisabledState(isDisabled: boolean) { this.elementRef.nativeElement.disabled = isDisabled; } /** Stream of clicks outside of the autocomplete panel. */ private getOutsideClickStream(): Observable<any> { return merge( fromEvent<MouseEvent>(document, 'click'), fromEvent<TouchEvent>(document, 'touchend'), ).pipe(filter((event) => { const clickTarget = event.target as HTMLElement; const formField = this.formField ? this.formField.elementRef.nativeElement : null; return this._overlayAttached && clickTarget !== this.elementRef.nativeElement && (!formField || !formField.contains(clickTarget)) && (!!this.overlayRef && !this.overlayRef.overlayElement.contains(clickTarget)); })); } @HostListener('input') private handleInput(): void { const target = event.target as HTMLInputElement; let value: number | string | null = target.value; // Based on `NumberValueAccessor` from forms. if (target.type === 'number') { value = value === '' ? null : parseFloat(value); } this._onChange(value); if (this.canOpen()) { this.openPanel(); } } @HostListener('keydown', ['$event']) _handleKeyDown(event: KeyboardEvent): void { const keyCode = event.keyCode; // Prevent the default action on all escape key presses. This is here primarily to bring IE // in line with other browsers. By default, pressing escape on IE will cause it to revert // the input value to the one that it had on focus, however it won't dispatch any events // which means that the model value will be out of sync with the view. if (keyCode === ESCAPE) { event.preventDefault(); } if (this.activeItem && keyCode === ENTER && this.panelOpen) { this.activeItem._selectViaInteraction(); this.resetActiveItem(); event.preventDefault(); } else if (this.autocomplete) { const prevActiveItem = this.autocomplete._keyManager.activeItem; const isArrowKey = keyCode === UP_ARROW || keyCode === DOWN_ARROW; if (this.panelOpen || keyCode === TAB) { this.autocomplete._keyManager.onKeydown(event); } else if (isArrowKey && this.canOpen()) { this.openPanel(); } if (isArrowKey || this.autocomplete._keyManager.activeItem !== prevActiveItem) { this.scrollToItem(); } } } @HostListener('focusin') private handleFocus(): void { if (!this.canOpenOnNextFocus) { this.canOpenOnNextFocus = true; } else if (this.canOpen()) { this.attachOverlay(); } } private scrollToItem(): void { const index = this.autocomplete._keyManager.activeItemIndex || 0; const newScrollPosition = _getItemScrollPosition( index, AUTOCOMPLETE_ITEM_HEIGHT, this.autocomplete._getScrollTop(), AUTOCOMPLETE_PANEL_HEIGHT, ); this.autocomplete._setScrollTop(newScrollPosition); } /** * This method listens to a stream of panel closing actions and resets the * stream every time the item list changes. */ private subscribeToClosingActions(): Subscription { const firstStable = this.zone.onStable.asObservable().pipe(take(1)); const itemChanges = this.autocomplete.items.changes.pipe( tap(() => this.positionStrategy.reapplyLastPosition()), // Defer emitting to the stream until the next tick, because changing // bindings in here will cause "changed after checked" errors. delay(0), ); // When the zone is stable initially, and when the option list changes... return merge(firstStable, itemChanges) .pipe( // create a new stream of panelClosingActions, replacing any previous streams // that were created, and flatten it so our stream only emits closing events... switchMap(() => { this.resetActiveItem(); this.autocomplete._setVisibility(); if (this.panelOpen) { this.overlayRef.updatePosition(); } return this.panelClosingActions; }), // when the first closing event occurs... take(1), ) // set the value, close the panel, and complete. .subscribe(event => this.setValueAndClose(event)); } /** Destroys the autocomplete suggestion panel. */ private destroyPanel(): void { if (this.overlayRef) { this.closePanel(); this.overlayRef.dispose(); this.overlayRef = null; } } private setTriggerValue(value: any): void { const toDisplay = this.autocomplete && this.autocomplete.displayWith ? this.autocomplete.displayWith(value) : value; // Simply falling back to an empty string if the display value is falsy does not work properly. // The display value can also be the number zero and shouldn't fall back to an empty string. this.elementRef.nativeElement.value = toDisplay !== null ? toDisplay : ''; } /** * This method closes the panel, and if a value is specified, also sets the associated * control to that value. It will also mark the control as dirty if this interaction * stemmed from the user. */ private setValueAndClose(event: AutocompleteItemSelectionChange | null): void { if (event && event.source) { this.clearPreviousSelectedOption(event.source); this.setTriggerValue(event.source.value); this._onChange(event.source.value); this.elementRef.nativeElement.focus(); } this.closePanel(); } /** * Clear any previous selected option and emit a selection change event for this option */ private clearPreviousSelectedOption(skip: AutocompleteItemComponent): void { this.autocomplete.items.forEach(option => { if (option !== skip && option.selected) { option.deselect(); } }); } private attachOverlay(): void { if (!this.autocomplete) { throw new Error('You should provide autocomplete!'); } if (!this.overlayRef) { this.portal = new TemplatePortal(this.autocomplete.template, this.viewContainerRef); this.overlayRef = this.overlay.create(this.getOverlayConfig()); // Use the `keydownEvents` in order to take advantage of // the overlay event targeting provided by the CDK overlay. this.overlayRef.keydownEvents().subscribe(event => { // Close when pressing ESCAPE or ALT + UP_ARROW, based on the a11y guidelines. // See: https://www.w3.org/TR/wai-aria-practices-1.1/#textbox-keyboard-interaction if (event.keyCode === ESCAPE || (event.keyCode === UP_ARROW && event.altKey)) { this.resetActiveItem(); this.closeKeyEventStream.next(); } }); if (this.viewportRuler) { this.viewportSubscription = this.viewportRuler.change().subscribe(() => { if (this.panelOpen && this.overlayRef) { this.overlayRef.updateSize({ width: this.getPanelWidth() }); } }); } } else { // Update the panel width and direction, in case anything has changed. this.overlayRef.updateSize({ width: this.getPanelWidth() }); } if (this.overlayRef && !this.overlayRef.hasAttached()) { this.overlayRef.attach(this.portal); this.closingActionsSubscription = this.subscribeToClosingActions(); } this.autocomplete._setVisibility(); this.autocomplete._isOpen = this._overlayAttached = true; } private getOverlayConfig(): OverlayConfig { this.positionStrategy = this.overlay.position() .flexibleConnectedTo(this.elementRef) .withFlexibleDimensions(false) .withPush(false) .withDefaultOffsetY(1) .withPositions([ { originX: 'start', originY: 'bottom', overlayX: 'start', overlayY: 'top', }, { originX: 'start', originY: 'top', overlayX: 'start', overlayY: 'bottom', }, ]); return new OverlayConfig({ positionStrategy: this.positionStrategy, scrollStrategy: this.overlay.scrollStrategies.reposition(), width: this.getPanelWidth(), }); } private getPanelWidth(): number { return this.elementRef.nativeElement.getBoundingClientRect().width; } /** * Resets the active item to -1 so arrow events will activate the correct items. */ private resetActiveItem(): void { this.autocomplete._keyManager.setActiveItem(-1); } /** Determines whether the panel can be opened. */ private canOpen(): boolean { const element = this.elementRef.nativeElement; return !element.readOnly && !element.disabled && !this._autocompleteDisabled; } }
the_stack
import * as React from 'react'; import { FormGroup } from '@patternfly/react-core'; import { configure, render, waitFor } from '@testing-library/react'; import { Formik, FormikConfig } from 'formik'; import * as _ from 'lodash'; import { Provider } from 'react-redux'; import store from '@console/internal/redux'; import { DropdownField } from '@console/shared/src'; import userEvent from '../../__tests__/user-event'; import { BuildStrategyType } from '../../types'; import ImagesSection, { ImagesSectionFormData } from '../ImagesSection'; const mockImageStream = (props) => ( <FormGroup fieldId="image-stream-dropdowns" label={props.label} data-test={props.dataTest}> <DropdownField label="Project" name={`${props.formContextField}.imageStream.namespace`} title="Select Project" items={{ 'project-a': 'project-a', 'project-b': 'project-b' }} /> <DropdownField label="Image Stream" name={`${props.formContextField}.imageStream.image`} title="Select Image Stream" items={{ 'imagestream-a': 'imagestream-a', 'imagestream-b': 'imagestream-b' }} /> <DropdownField label="Tag" name={`${props.formContextField}.imageStream.tag`} title="Select tag" items={{ latest: 'latest', v1: 'v1', v2: 'v2' }} /> </FormGroup> ); jest.mock('../../../import/image-search/ImageStream', () => ({ default: (props) => mockImageStream(props), })); configure({ testIdAttribute: 'data-test' }); const Wrapper: React.FC<FormikConfig<ImagesSectionFormData>> = ({ children, ...formikConfig }) => ( <Provider store={store}> <Formik {...formikConfig}> {(formikProps) => ( <form onSubmit={formikProps.handleSubmit}> {children} <input type="submit" value="Submit" /> </form> )} </Formik> </Provider> ); const emptyInitialValues: ImagesSectionFormData = { formData: { images: { buildFrom: { type: 'none', imageStreamTag: { fromImageStreamTag: false, isSearchingForImage: false, imageStream: { namespace: '', image: '', tag: '', }, project: { name: '', }, isi: { name: '', image: {}, tag: '', status: { metadata: {}, status: '' }, ports: [], }, image: { name: '', image: {}, tag: '', status: { metadata: {}, status: '' }, ports: [], }, }, imageStreamImage: '', dockerImage: '', }, pushTo: { type: 'none', imageStreamTag: { fromImageStreamTag: false, isSearchingForImage: false, imageStream: { namespace: '', image: '', tag: '', }, project: { name: '', }, isi: { name: '', image: {}, tag: '', status: { metadata: {}, status: '' }, ports: [], }, image: { name: '', image: {}, tag: '', status: { metadata: {}, status: '' }, ports: [], }, }, imageStreamImage: '', dockerImage: '', }, }, }, }; describe('ImagesSection', () => { it('should render form without subforms', () => { const onSubmit = jest.fn(); const renderResult = render( <Wrapper initialValues={emptyInitialValues} onSubmit={onSubmit}> <ImagesSection /> </Wrapper>, ); renderResult.getByTestId('section images'); renderResult.getByText('Images'); renderResult.getByText('Build from'); renderResult.getByText('Push to'); expect(onSubmit).toHaveBeenCalledTimes(0); }); it('should provide three options for build from image (no none option until strategy is Docker)', async () => { const onSubmit = jest.fn(); const renderResult = render( <Wrapper initialValues={emptyInitialValues} onSubmit={onSubmit}> <ImagesSection /> </Wrapper>, ); // Dropdown titles renderResult.getByText('Please select'); renderResult.getByText('None'); // Open first dropdown userEvent.click(renderResult.getByText('Please select')); // Assert options const options = renderResult.container .querySelector('[data-test="build-from type"]') .parentElement.querySelectorAll('li button'); expect(Object.values(options).map((option) => option.textContent)).toEqual([ 'Image Stream Tag', 'Image Stream Image', 'Docker image', ]); expect(onSubmit).toHaveBeenCalledTimes(0); }); it('should provide four options for build from image (when build strategy is Docker)', () => { const initialValues = _.cloneDeep(emptyInitialValues); initialValues.formData.images.strategyType = BuildStrategyType.Docker; const onSubmit = jest.fn(); const renderResult = render( <Wrapper initialValues={initialValues} onSubmit={onSubmit}> <ImagesSection /> </Wrapper>, ); // Dropdown titles expect(renderResult.queryAllByText('None')).toHaveLength(2); // Open first dropdown userEvent.click(renderResult.getAllByText('None')[0]); // Assert options const options = renderResult.container .querySelector('[data-test="build-from type"]') .parentElement.querySelectorAll('li button'); expect(Object.values(options).map((option) => option.textContent)).toEqual([ 'None', 'Image Stream Tag', 'Image Stream Image', 'Docker image', ]); expect(onSubmit).toHaveBeenCalledTimes(0); }); it('should provide three options (incl. none) for push to image', () => { const onSubmit = jest.fn(); const renderResult = render( <Wrapper initialValues={emptyInitialValues} onSubmit={onSubmit}> <ImagesSection /> </Wrapper>, ); // Dropdown titles renderResult.getByText('Please select'); renderResult.getByText('None'); // Open second dropdown userEvent.click(renderResult.getByText('None')); // Assert options const options = renderResult.container .querySelector('[data-test="push-to type"]') .parentElement.querySelectorAll('li button'); expect(Object.values(options).map((option) => option.textContent)).toEqual([ 'None', 'Image Stream Tag', 'Docker image', ]); expect(onSubmit).toHaveBeenCalledTimes(0); }); it('should show a subform when user selects image stream tag', () => { const onSubmit = jest.fn(); const renderResult = render( <Wrapper initialValues={emptyInitialValues} onSubmit={onSubmit}> <ImagesSection /> </Wrapper>, ); userEvent.click(renderResult.getByText('Please select')); userEvent.click(renderResult.getByText('Image Stream Tag')); renderResult.getByText('Project'); renderResult.getByText('Image Stream'); renderResult.getByText('Tag'); expect(onSubmit).toHaveBeenCalledTimes(0); }); it('should show a subform when user selects image stream image', () => { const onSubmit = jest.fn(); const renderResult = render( <Wrapper initialValues={emptyInitialValues} onSubmit={onSubmit}> <ImagesSection /> </Wrapper>, ); userEvent.click(renderResult.getByText('Please select')); userEvent.click(renderResult.getByText('Image Stream Image')); expect(renderResult.getAllByRole('textbox')).toHaveLength(1); expect(onSubmit).toHaveBeenCalledTimes(0); }); it('should show a subform when user selects dockerfile', () => { const onSubmit = jest.fn(); const renderResult = render( <Wrapper initialValues={emptyInitialValues} onSubmit={onSubmit}> <ImagesSection /> </Wrapper>, ); userEvent.click(renderResult.getByText('Please select')); userEvent.click(renderResult.getByText('Docker image')); expect(renderResult.getAllByRole('textbox')).toHaveLength(1); expect(onSubmit).toHaveBeenCalledTimes(0); }); it('should submit right form data when user fills out an image stream tag', async () => { const onSubmit = jest.fn(); const renderResult = render( <Wrapper initialValues={emptyInitialValues} onSubmit={onSubmit}> <ImagesSection /> </Wrapper>, ); userEvent.click(renderResult.getByText('Please select')); userEvent.click(renderResult.getByText('Image Stream Tag')); // Fill form userEvent.click(renderResult.getByText('Select Project')); userEvent.click(renderResult.getByText('project-a')); userEvent.click(renderResult.getByText('Select Image Stream')); userEvent.click(renderResult.getByText('imagestream-a')); userEvent.click(renderResult.getByText('Select tag')); userEvent.click(renderResult.getByText('latest')); // Submit const submitButton = renderResult.getByRole('button', { name: 'Submit' }); userEvent.click(submitButton); await waitFor(() => { expect(onSubmit).toHaveBeenCalledTimes(1); }); const expectedFormData: ImagesSectionFormData = { formData: { images: { buildFrom: { type: 'imageStreamTag', imageStreamTag: { fromImageStreamTag: false, isSearchingForImage: false, imageStream: { namespace: 'project-a', image: 'imagestream-a', tag: 'latest', }, project: { name: '', }, isi: { name: '', image: {}, tag: '', status: { metadata: {}, status: '' }, ports: [], }, image: { name: '', image: {}, tag: '', status: { metadata: {}, status: '' }, ports: [], }, }, imageStreamImage: '', dockerImage: '', }, pushTo: { type: 'none', imageStreamTag: expect.anything(), imageStreamImage: '', dockerImage: '', }, }, }, }; expect(onSubmit).toHaveBeenLastCalledWith(expectedFormData, expect.anything()); }); it('should submit right form data when user fills out an image stream image', async () => { const onSubmit = jest.fn(); const renderResult = render( <Wrapper initialValues={emptyInitialValues} onSubmit={onSubmit}> <ImagesSection /> </Wrapper>, ); // Fill form userEvent.click(renderResult.getByText('Please select')); userEvent.click(renderResult.getByText('Image Stream Image')); userEvent.type(renderResult.getByRole('textbox'), 'my-namespace/an-image'); // Submit const submitButton = renderResult.getByRole('button', { name: 'Submit' }); userEvent.click(submitButton); await waitFor(() => { expect(onSubmit).toHaveBeenCalledTimes(1); }); const expectedFormData: ImagesSectionFormData = { formData: { images: { buildFrom: { type: 'imageStreamImage', imageStreamTag: expect.anything(), imageStreamImage: 'my-namespace/an-image', dockerImage: '', }, pushTo: { type: 'none', imageStreamTag: expect.anything(), imageStreamImage: '', dockerImage: '', }, }, }, }; expect(onSubmit).toHaveBeenLastCalledWith(expectedFormData, expect.anything()); }); it('should submit right form data when user fills out an dockerfile', async () => { const onSubmit = jest.fn(); const renderResult = render( <Wrapper initialValues={emptyInitialValues} onSubmit={onSubmit}> <ImagesSection /> </Wrapper>, ); // Fill form userEvent.click(renderResult.getByText('Please select')); userEvent.click(renderResult.getByText('Docker image')); userEvent.type(renderResult.getByRole('textbox'), 'centos'); // Submit const submitButton = renderResult.getByRole('button', { name: 'Submit' }); userEvent.click(submitButton); await waitFor(() => { expect(onSubmit).toHaveBeenCalledTimes(1); }); const expectedFormData: ImagesSectionFormData = { formData: { images: { buildFrom: { type: 'dockerImage', imageStreamTag: expect.anything(), imageStreamImage: '', dockerImage: 'centos', }, pushTo: { type: 'none', imageStreamTag: expect.anything(), imageStreamImage: '', dockerImage: '', }, }, }, }; expect(onSubmit).toHaveBeenLastCalledWith(expectedFormData, expect.anything()); }); });
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * Specifications of the Dimension of metrics. */ export interface Dimension { /** * The public facing name of the dimension. */ name?: string; /** * Localized friendly display name of the dimension. */ displayName?: string; /** * Name of the dimension as it appears in MDM. */ internalName?: string; /** * A Boolean flag indicating whether this dimension should be included for the shoebox export * scenario. */ toBeExportedForShoebox?: boolean; } /** * Specifications of the Logs for Azure Monitoring. */ export interface LogSpecification { /** * Name of the log. */ name?: string; /** * Localized friendly display name of the log. */ displayName?: string; } /** * Properties of user assigned identity. */ export interface UserAssignedIdentityProperty { /** * Get the principal id for the user assigned identity * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly principalId?: string; /** * Get the client id for the user assigned identity * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly clientId?: string; } /** * A class represent managed identities used for request and response */ export interface ManagedIdentity { /** * Represent the identity type: systemAssigned, userAssigned, None. Possible values include: * 'None', 'SystemAssigned', 'UserAssigned' */ type?: ManagedIdentityType; /** * Get or set the user assigned identities */ userAssignedIdentities?: { [propertyName: string]: UserAssignedIdentityProperty }; /** * Get the principal id for the system assigned identity. * Only be used in response. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly principalId?: string; /** * Get the tenant id for the system assigned identity. * Only be used in response * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tenantId?: string; } /** * Managed identity settings for upstream. */ export interface ManagedIdentitySettings { /** * The Resource indicating the App ID URI of the target resource. * It also appears in the aud (audience) claim of the issued token. */ resource?: string; } /** * Specifications of the Metrics for Azure Monitoring. */ export interface MetricSpecification { /** * Name of the metric. */ name?: string; /** * Localized friendly display name of the metric. */ displayName?: string; /** * Localized friendly description of the metric. */ displayDescription?: string; /** * The unit that makes sense for the metric. */ unit?: string; /** * Only provide one value for this field. Valid values: Average, Minimum, Maximum, Total, Count. */ aggregationType?: string; /** * Optional. If set to true, then zero will be returned for time duration where no metric is * emitted/published. * Ex. a metric that returns the number of times a particular error code was emitted. The error * code may not appear * often, instead of the RP publishing 0, Shoebox can auto fill in 0s for time periods where * nothing was emitted. */ fillGapWithZero?: string; /** * The name of the metric category that the metric belongs to. A metric can only belong to a * single category. */ category?: string; /** * The dimensions of the metrics. */ dimensions?: Dimension[]; } /** * Result of the request to check name availability. It contains a flag and possible reason of * failure. */ export interface NameAvailability { /** * Indicates whether the name is available or not. */ nameAvailable?: boolean; /** * The reason of the availability. Required if name is not available. */ reason?: string; /** * The message of the operation. */ message?: string; } /** * Data POST-ed to the nameAvailability action */ export interface NameAvailabilityParameters { /** * The resource type. Can be "Microsoft.SignalRService/SignalR" or * "Microsoft.SignalRService/webPubSub" */ type: string; /** * The resource name to validate. e.g."my-resource-name" */ name: string; } /** * Network ACL */ export interface NetworkACL { /** * Allowed request types. The value can be one or more of: ClientConnection, ServerConnection, * RESTAPI. */ allow?: SignalRRequestType[]; /** * Denied request types. The value can be one or more of: ClientConnection, ServerConnection, * RESTAPI. */ deny?: SignalRRequestType[]; } /** * The object that describes a operation. */ export interface OperationDisplay { /** * Friendly name of the resource provider */ provider?: string; /** * Resource type on which the operation is performed. */ resource?: string; /** * The localized friendly name for the operation. */ operation?: string; /** * The localized friendly description for the operation */ description?: string; } /** * An object that describes a specification. */ export interface ServiceSpecification { /** * Specifications of the Metrics for Azure Monitoring. */ metricSpecifications?: MetricSpecification[]; /** * Specifications of the Logs for Azure Monitoring. */ logSpecifications?: LogSpecification[]; } /** * Extra Operation properties. */ export interface OperationProperties { /** * The service specifications. */ serviceSpecification?: ServiceSpecification; } /** * REST API operation supported by resource provider. */ export interface Operation { /** * Name of the operation with format: {provider}/{resource}/{operation} */ name?: string; /** * If the operation is a data action. (for data plane rbac) */ isDataAction?: boolean; /** * The object that describes the operation. */ display?: OperationDisplay; /** * Optional. The intended executor of the operation; governs the display of the operation in the * RBAC UX and the audit logs UX. */ origin?: string; /** * Extra properties for the operation. */ properties?: OperationProperties; } /** * Private endpoint */ export interface PrivateEndpoint { /** * Full qualified Id of the private endpoint */ id?: string; } /** * ACL for a private endpoint */ export interface PrivateEndpointACL extends NetworkACL { /** * Name of the private endpoint connection */ name: string; } /** * Metadata pertaining to creation and last modification of the resource. */ export interface SystemData { /** * The identity that created the resource. */ createdBy?: string; /** * The type of identity that created the resource. Possible values include: 'User', * 'Application', 'ManagedIdentity', 'Key' */ createdByType?: CreatedByType; /** * The timestamp of resource creation (UTC). */ createdAt?: Date; /** * The identity that last modified the resource. */ lastModifiedBy?: string; /** * The type of identity that last modified the resource. Possible values include: 'User', * 'Application', 'ManagedIdentity', 'Key' */ lastModifiedByType?: CreatedByType; /** * The timestamp of resource last modification (UTC) */ lastModifiedAt?: Date; } /** * Connection state of the private endpoint connection */ export interface PrivateLinkServiceConnectionState { /** * Indicates whether the connection has been Approved/Rejected/Removed by the owner of the * service. Possible values include: 'Pending', 'Approved', 'Rejected', 'Disconnected' */ status?: PrivateLinkServiceConnectionStatus; /** * The reason for approval/rejection of the connection. */ description?: string; /** * A message indicating if changes on the service provider require any updates on the consumer. */ actionsRequired?: string; } /** * The core properties of ARM resources. */ export interface Resource extends BaseResource { /** * Fully qualified resource Id for the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the resource - e.g. "Microsoft.SignalRService/SignalR" * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The resource model definition for a ARM proxy resource. It will have everything other than * required location and tags */ export interface ProxyResource extends Resource {} /** * A private endpoint connection to an azure resource */ export interface PrivateEndpointConnection extends ProxyResource { /** * Metadata pertaining to creation and last modification of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly systemData?: SystemData; /** * Provisioning state of the private endpoint connection. Possible values include: 'Unknown', * 'Succeeded', 'Failed', 'Canceled', 'Running', 'Creating', 'Updating', 'Deleting', 'Moving' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningState; /** * Private endpoint associated with the private endpoint connection */ privateEndpoint?: PrivateEndpoint; /** * Connection state */ privateLinkServiceConnectionState?: PrivateLinkServiceConnectionState; } /** * Describes the properties of a resource type that has been onboarded to private link service */ export interface ShareablePrivateLinkResourceProperties { /** * The description of the resource type that has been onboarded to private link service */ description?: string; /** * The resource provider group id for the resource that has been onboarded to private link * service */ groupId?: string; /** * The resource provider type for the resource that has been onboarded to private link service */ type?: string; } /** * Describes a resource type that has been onboarded to private link service */ export interface ShareablePrivateLinkResourceType { /** * The name of the resource type that has been onboarded to private link service */ name?: string; /** * Describes the properties of a resource type that has been onboarded to private link service */ properties?: ShareablePrivateLinkResourceProperties; } /** * Private link resource */ export interface PrivateLinkResource extends ProxyResource { /** * Group Id of the private link resource */ groupId?: string; /** * Required members of the private link resource */ requiredMembers?: string[]; /** * Required private DNS zone names */ requiredZoneNames?: string[]; /** * The list of resources that are onboarded to private link service */ shareablePrivateLinkResourceTypes?: ShareablePrivateLinkResourceType[]; } /** * Parameters describes the request to regenerate access keys */ export interface RegenerateKeyParameters { /** * The keyType to regenerate. Must be either 'primary' or 'secondary'(case-insensitive). Possible * values include: 'Primary', 'Secondary' */ keyType?: KeyType; } /** * The billing information of the resource. */ export interface ResourceSku { /** * The name of the SKU. Required. * * Allowed values: Standard_S1, Free_F1 */ name: string; /** * Optional tier of this particular SKU. 'Standard' or 'Free'. * * `Basic` is deprecated, use `Standard` instead. Possible values include: 'Free', 'Basic', * 'Standard', 'Premium' */ tier?: SignalRSkuTier; /** * Not used. Retained for future use. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly size?: string; /** * Not used. Retained for future use. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly family?: string; /** * Optional, integer. The unit count of the resource. 1 by default. * * If present, following values are allowed: * Free: 1 * Standard: 1,2,5,10,20,50,100 */ capacity?: number; } /** * Upstream auth settings. */ export interface UpstreamAuthSettings { /** * Gets or sets the type of auth. None or ManagedIdentity is supported now. Possible values * include: 'None', 'ManagedIdentity' */ type?: UpstreamAuthType; /** * Gets or sets the managed identity settings. It's required if the auth type is set to * ManagedIdentity. */ managedIdentity?: ManagedIdentitySettings; } /** * Upstream template item settings. It defines the Upstream URL of the incoming requests. * The template defines the pattern of the event, the hub or the category of the incoming request * that matches current URL template. */ export interface UpstreamTemplate { /** * Gets or sets the matching pattern for hub names. If not set, it matches any hub. * There are 3 kind of patterns supported: * 1. "*", it to matches any hub name * 2. Combine multiple hubs with ",", for example "hub1,hub2", it matches "hub1" and "hub2" * 3. The single hub name, for example, "hub1", it matches "hub1" */ hubPattern?: string; /** * Gets or sets the matching pattern for event names. If not set, it matches any event. * There are 3 kind of patterns supported: * 1. "*", it to matches any event name * 2. Combine multiple events with ",", for example "connect,disconnect", it matches event * "connect" and "disconnect" * 3. The single event name, for example, "connect", it matches "connect" */ eventPattern?: string; /** * Gets or sets the matching pattern for category names. If not set, it matches any category. * There are 3 kind of patterns supported: * 1. "*", it to matches any category name * 2. Combine multiple categories with ",", for example "connections,messages", it matches * category "connections" and "messages" * 3. The single category name, for example, "connections", it matches the category "connections" */ categoryPattern?: string; /** * Gets or sets the Upstream URL template. You can use 3 predefined parameters {hub}, {category} * {event} inside the template, the value of the Upstream URL is dynamically calculated when the * client request comes in. * For example, if the urlTemplate is `http://example.com/{hub}/api/{event}`, with a client * request from hub `chat` connects, it will first POST to this URL: * `http://example.com/chat/api/connect`. */ urlTemplate: string; /** * Gets or sets the auth settings for an upstream. If not set, no auth is used for upstream * messages. */ auth?: UpstreamAuthSettings; } /** * The settings for the Upstream when the service is in server-less mode. */ export interface ServerlessUpstreamSettings { /** * Gets or sets the list of Upstream URL templates. Order matters, and the first matching * template takes effects. */ templates?: UpstreamTemplate[]; } /** * Describes a Shared Private Link Resource */ export interface SharedPrivateLinkResource extends ProxyResource { /** * Metadata pertaining to creation and last modification of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly systemData?: SystemData; /** * The group id from the provider of resource the shared private link resource is for */ groupId: string; /** * The resource id of the resource the shared private link resource is for */ privateLinkResourceId: string; /** * Provisioning state of the shared private link resource. Possible values include: 'Unknown', * 'Succeeded', 'Failed', 'Canceled', 'Running', 'Creating', 'Updating', 'Deleting', 'Moving' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningState; /** * The request message for requesting approval of the shared private link resource */ requestMessage?: string; /** * Status of the shared private link resource. Possible values include: 'Pending', 'Approved', * 'Rejected', 'Disconnected', 'Timeout' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly status?: SharedPrivateLinkResourceStatus; } /** * Cross-Origin Resource Sharing (CORS) settings. */ export interface SignalRCorsSettings { /** * Gets or sets the list of origins that should be allowed to make cross-origin calls (for * example: http://example.com:12345). Use "*" to allow all. If omitted, allow all by default. */ allowedOrigins?: string[]; } /** * Feature of a SignalR resource, which controls the SignalR runtime behavior. */ export interface SignalRFeature { /** * FeatureFlags is the supported features of Azure SignalR service. * - ServiceMode: Flag for backend server for SignalR service. Values allowed: "Default": have * your own backend server; "Serverless": your application doesn't have a backend server; * "Classic": for backward compatibility. Support both Default and Serverless mode but not * recommended; "PredefinedOnly": for future use. * - EnableConnectivityLogs: "true"/"false", to enable/disable the connectivity log category * respectively. * - EnableMessagingLogs: "true"/"false", to enable/disable the connectivity log category * respectively. * - EnableLiveTrace: Live Trace allows you to know what's happening inside Azure SignalR * service, it will give you live traces in real time, it will be helpful when you developing * your own Azure SignalR based web application or self-troubleshooting some issues. Please note * that live traces are counted as outbound messages that will be charged. Values allowed: * "true"/"false", to enable/disable live trace feature. Possible values include: 'ServiceMode', * 'EnableConnectivityLogs', 'EnableMessagingLogs', 'EnableLiveTrace' */ flag: FeatureFlags; /** * Value of the feature flag. See Azure SignalR service document * https://docs.microsoft.com/azure/azure-signalr/ for allowed values. */ value: string; /** * Optional properties related to this feature. */ properties?: { [propertyName: string]: string }; } /** * A class represents the access keys of the resource. */ export interface SignalRKeys { /** * The primary access key. */ primaryKey?: string; /** * The secondary access key. */ secondaryKey?: string; /** * Connection string constructed via the primaryKey */ primaryConnectionString?: string; /** * Connection string constructed via the secondaryKey */ secondaryConnectionString?: string; } /** * Network ACLs for the resource */ export interface SignalRNetworkACLs { /** * Default action when no other rule matches. Possible values include: 'Allow', 'Deny' */ defaultAction?: ACLAction; /** * ACL for requests from public network */ publicNetwork?: NetworkACL; /** * ACLs for requests from private endpoints */ privateEndpoints?: PrivateEndpointACL[]; } /** * TLS settings for the resource */ export interface SignalRTlsSettings { /** * Request client certificate during TLS handshake if enabled */ clientCertEnabled?: boolean; } /** * The resource model definition for a ARM tracked top level resource. */ export interface TrackedResource extends Resource { /** * The GEO location of the resource. e.g. West US | East US | North Central US | South Central * US. */ location?: string; /** * Tags of the service which is a list of key value pairs that describe the resource. */ tags?: { [propertyName: string]: string }; } /** * A class represent a resource. */ export interface SignalRResource extends TrackedResource { /** * The billing information of the resource.(e.g. Free, Standard) */ sku?: ResourceSku; /** * Provisioning state of the resource. Possible values include: 'Unknown', 'Succeeded', 'Failed', * 'Canceled', 'Running', 'Creating', 'Updating', 'Deleting', 'Moving' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly provisioningState?: ProvisioningState; /** * The publicly accessible IP of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly externalIP?: string; /** * FQDN of the service instance. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly hostName?: string; /** * The publicly accessible port of the resource which is designed for browser/client side usage. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly publicPort?: number; /** * The publicly accessible port of the resource which is designed for customer server side usage. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly serverPort?: number; /** * Version of the resource. Probably you need the same or higher version of client SDKs. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly version?: string; /** * Private endpoint connections to the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly privateEndpointConnections?: PrivateEndpointConnection[]; /** * The list of shared private link resources. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly sharedPrivateLinkResources?: SharedPrivateLinkResource[]; /** * TLS settings. */ tls?: SignalRTlsSettings; /** * List of the featureFlags. * * FeatureFlags that are not included in the parameters for the update operation will not be * modified. * And the response will only include featureFlags that are explicitly set. * When a featureFlag is not explicitly set, its globally default value will be used * But keep in mind, the default value doesn't mean "false". It varies in terms of different * FeatureFlags. */ features?: SignalRFeature[]; /** * Cross-Origin Resource Sharing (CORS) settings. */ cors?: SignalRCorsSettings; /** * Upstream settings when the service is in server-less mode. */ upstream?: ServerlessUpstreamSettings; /** * Network ACLs */ networkACLs?: SignalRNetworkACLs; /** * The kind of the service - e.g. "SignalR" for "Microsoft.SignalRService/SignalR". Possible * values include: 'SignalR', 'RawWebSockets' */ kind?: ServiceKind; /** * The managed identity response */ identity?: ManagedIdentity; /** * Metadata pertaining to creation and last modification of the resource. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly systemData?: SystemData; } /** * Localizable String object containing the name and a localized value. */ export interface SignalRUsageName { /** * The identifier of the usage. */ value?: string; /** * Localized name of the usage. */ localizedValue?: string; } /** * Object that describes a specific usage of the resources. */ export interface SignalRUsage { /** * Fully qualified ARM resource id */ id?: string; /** * Current value for the usage quota. */ currentValue?: number; /** * The maximum permitted value for the usage quota. If there is no limit, this value will be -1. */ limit?: number; /** * Localizable String object containing the name and a localized value. */ name?: SignalRUsageName; /** * Representing the units of the usage quota. Possible values are: Count, Bytes, Seconds, * Percent, CountPerSecond, BytesPerSecond. */ unit?: string; } /** * The resource management error additional info. */ export interface ErrorAdditionalInfo { /** * The additional info type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * The additional info. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly info?: any; } /** * The error detail. */ export interface ErrorDetail { /** * The error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * The error message. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; /** * The error target. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly target?: string; /** * The error details. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly details?: ErrorDetail[]; /** * The error additional info. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly additionalInfo?: ErrorAdditionalInfo[]; } /** * Common error response for all Azure Resource Manager APIs to return error details for failed * operations. (This also follows the OData error response format.). * @summary Error response */ export interface ErrorResponse { /** * The error object. */ error?: ErrorDetail; } /** * An interface representing SignalRManagementClientOptions. */ export interface SignalRManagementClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * Result of the request to list REST API operations. It contains a list of operations. * @extends Array<Operation> */ export interface OperationList extends Array<Operation> { /** * The URL the client should use to fetch the next page (per server side paging). * It's null for now, added for future use. */ nextLink?: string; } /** * @interface * Object that includes an array of resources and a possible link for next set. * @extends Array<SignalRResource> */ export interface SignalRResourceList extends Array<SignalRResource> { /** * The URL the client should use to fetch the next page (per server side paging). * It's null for now, added for future use. */ nextLink?: string; } /** * @interface * Object that includes an array of the resource usages and a possible link for next set. * @extends Array<SignalRUsage> */ export interface SignalRUsageList extends Array<SignalRUsage> { /** * The URL the client should use to fetch the next page (per server side paging). * It's null for now, added for future use. */ nextLink?: string; } /** * @interface * A list of private endpoint connections * @extends Array<PrivateEndpointConnection> */ export interface PrivateEndpointConnectionList extends Array<PrivateEndpointConnection> { /** * Request URL that can be used to query next page of private endpoint connections. Returned when * the total number of requested private endpoint connections exceed maximum page size. */ nextLink?: string; } /** * @interface * Contains a list of PrivateLinkResource and a possible link to query more results * @extends Array<PrivateLinkResource> */ export interface PrivateLinkResourceList extends Array<PrivateLinkResource> { /** * The URL the client should use to fetch the next page (per server side paging). * It's null for now, added for future use. */ nextLink?: string; } /** * @interface * A list of shared private link resources * @extends Array<SharedPrivateLinkResource> */ export interface SharedPrivateLinkResourceList extends Array<SharedPrivateLinkResource> { /** * Request URL that can be used to query next page of private endpoint connections. Returned when * the total number of requested private endpoint connections exceed maximum page size. */ nextLink?: string; } /** * Defines values for ACLAction. * Possible values include: 'Allow', 'Deny' * @readonly * @enum {string} */ export type ACLAction = "Allow" | "Deny"; /** * Defines values for FeatureFlags. * Possible values include: 'ServiceMode', 'EnableConnectivityLogs', 'EnableMessagingLogs', * 'EnableLiveTrace' * @readonly * @enum {string} */ export type FeatureFlags = | "ServiceMode" | "EnableConnectivityLogs" | "EnableMessagingLogs" | "EnableLiveTrace"; /** * Defines values for KeyType. * Possible values include: 'Primary', 'Secondary' * @readonly * @enum {string} */ export type KeyType = "Primary" | "Secondary"; /** * Defines values for ManagedIdentityType. * Possible values include: 'None', 'SystemAssigned', 'UserAssigned' * @readonly * @enum {string} */ export type ManagedIdentityType = "None" | "SystemAssigned" | "UserAssigned"; /** * Defines values for SignalRRequestType. * Possible values include: 'ClientConnection', 'ServerConnection', 'RESTAPI', 'Trace' * @readonly * @enum {string} */ export type SignalRRequestType = "ClientConnection" | "ServerConnection" | "RESTAPI" | "Trace"; /** * Defines values for CreatedByType. * Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key' * @readonly * @enum {string} */ export type CreatedByType = "User" | "Application" | "ManagedIdentity" | "Key"; /** * Defines values for ProvisioningState. * Possible values include: 'Unknown', 'Succeeded', 'Failed', 'Canceled', 'Running', 'Creating', * 'Updating', 'Deleting', 'Moving' * @readonly * @enum {string} */ export type ProvisioningState = | "Unknown" | "Succeeded" | "Failed" | "Canceled" | "Running" | "Creating" | "Updating" | "Deleting" | "Moving"; /** * Defines values for PrivateLinkServiceConnectionStatus. * Possible values include: 'Pending', 'Approved', 'Rejected', 'Disconnected' * @readonly * @enum {string} */ export type PrivateLinkServiceConnectionStatus = | "Pending" | "Approved" | "Rejected" | "Disconnected"; /** * Defines values for SignalRSkuTier. * Possible values include: 'Free', 'Basic', 'Standard', 'Premium' * @readonly * @enum {string} */ export type SignalRSkuTier = "Free" | "Basic" | "Standard" | "Premium"; /** * Defines values for UpstreamAuthType. * Possible values include: 'None', 'ManagedIdentity' * @readonly * @enum {string} */ export type UpstreamAuthType = "None" | "ManagedIdentity"; /** * Defines values for ServiceKind. * Possible values include: 'SignalR', 'RawWebSockets' * @readonly * @enum {string} */ export type ServiceKind = "SignalR" | "RawWebSockets"; /** * Defines values for SharedPrivateLinkResourceStatus. * Possible values include: 'Pending', 'Approved', 'Rejected', 'Disconnected', 'Timeout' * @readonly * @enum {string} */ export type SharedPrivateLinkResourceStatus = | "Pending" | "Approved" | "Rejected" | "Disconnected" | "Timeout"; /** * Contains response data for the list operation. */ export type OperationsListResponse = OperationList & { /** * 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: OperationList; }; }; /** * Contains response data for the listNext operation. */ export type OperationsListNextResponse = OperationList & { /** * 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: OperationList; }; }; /** * Contains response data for the checkNameAvailability operation. */ export type SignalRCheckNameAvailabilityResponse = NameAvailability & { /** * 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: NameAvailability; }; }; /** * Contains response data for the listBySubscription operation. */ export type SignalRListBySubscriptionResponse = SignalRResourceList & { /** * 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: SignalRResourceList; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type SignalRListByResourceGroupResponse = SignalRResourceList & { /** * 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: SignalRResourceList; }; }; /** * Contains response data for the get operation. */ export type SignalRGetResponse = SignalRResource & { /** * 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: SignalRResource; }; }; /** * Contains response data for the createOrUpdate operation. */ export type SignalRCreateOrUpdateResponse = SignalRResource & { /** * 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: SignalRResource; }; }; /** * Contains response data for the update operation. */ export type SignalRUpdateResponse = SignalRResource & { /** * 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: SignalRResource; }; }; /** * Contains response data for the listKeys operation. */ export type SignalRListKeysResponse = SignalRKeys & { /** * 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: SignalRKeys; }; }; /** * Contains response data for the regenerateKey operation. */ export type SignalRRegenerateKeyResponse = SignalRKeys & { /** * 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: SignalRKeys; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type SignalRBeginCreateOrUpdateResponse = SignalRResource & { /** * 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: SignalRResource; }; }; /** * Contains response data for the beginUpdate operation. */ export type SignalRBeginUpdateResponse = SignalRResource & { /** * 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: SignalRResource; }; }; /** * Contains response data for the beginRegenerateKey operation. */ export type SignalRBeginRegenerateKeyResponse = SignalRKeys & { /** * 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: SignalRKeys; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type SignalRListBySubscriptionNextResponse = SignalRResourceList & { /** * 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: SignalRResourceList; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type SignalRListByResourceGroupNextResponse = SignalRResourceList & { /** * 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: SignalRResourceList; }; }; /** * Contains response data for the list operation. */ export type UsagesListResponse = SignalRUsageList & { /** * 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: SignalRUsageList; }; }; /** * Contains response data for the listNext operation. */ export type UsagesListNextResponse = SignalRUsageList & { /** * 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: SignalRUsageList; }; }; /** * Contains response data for the list operation. */ export type SignalRPrivateEndpointConnectionsListResponse = PrivateEndpointConnectionList & { /** * 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: PrivateEndpointConnectionList; }; }; /** * Contains response data for the get operation. */ export type SignalRPrivateEndpointConnectionsGetResponse = PrivateEndpointConnection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; }; /** * Contains response data for the update operation. */ export type SignalRPrivateEndpointConnectionsUpdateResponse = PrivateEndpointConnection & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: PrivateEndpointConnection; }; }; /** * Contains response data for the listNext operation. */ export type SignalRPrivateEndpointConnectionsListNextResponse = PrivateEndpointConnectionList & { /** * 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: PrivateEndpointConnectionList; }; }; /** * Contains response data for the list operation. */ export type SignalRPrivateLinkResourcesListResponse = PrivateLinkResourceList & { /** * 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: PrivateLinkResourceList; }; }; /** * Contains response data for the listNext operation. */ export type SignalRPrivateLinkResourcesListNextResponse = PrivateLinkResourceList & { /** * 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: PrivateLinkResourceList; }; }; /** * Contains response data for the list operation. */ export type SignalRSharedPrivateLinkResourcesListResponse = SharedPrivateLinkResourceList & { /** * 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: SharedPrivateLinkResourceList; }; }; /** * Contains response data for the get operation. */ export type SignalRSharedPrivateLinkResourcesGetResponse = SharedPrivateLinkResource & { /** * 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: SharedPrivateLinkResource; }; }; /** * Contains response data for the createOrUpdate operation. */ export type SignalRSharedPrivateLinkResourcesCreateOrUpdateResponse = SharedPrivateLinkResource & { /** * 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: SharedPrivateLinkResource; }; }; /** * Contains response data for the beginCreateOrUpdate operation. */ export type SignalRSharedPrivateLinkResourcesBeginCreateOrUpdateResponse = SharedPrivateLinkResource & { /** * 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: SharedPrivateLinkResource; }; }; /** * Contains response data for the listNext operation. */ export type SignalRSharedPrivateLinkResourcesListNextResponse = SharedPrivateLinkResourceList & { /** * 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: SharedPrivateLinkResourceList; }; };
the_stack
import {IHaikuComponent} from './api'; import HaikuBase, {GLOBAL_LISTENER_KEY} from './HaikuBase'; import getActionsMaxTime from './helpers/getActionsMaxTime'; import getTimelineMaxTime from './helpers/getTimelineMaxTime'; import {isNumeric, tokenizeDirective} from './reflection/Tokenizer'; import assign from './vendor/assign'; const NUMBER = 'number'; const DEFAULT_OPTIONS = { // loop: Boolean // Determines whether this timeline should loop (start at its beginning when finished) loop: true, }; export const enum TimeUnit { Millisecond = 'ms', Frame = 'fr', } export const enum PlaybackFlag { ONCE = 'once', PLAY = 'play', // alias for 'once' LOOP = 'loop', STOP = 'stop', SEEK = 'seek', } const makePlaybackProc = (body: string): Function => { // tslint:disable-next-line:no-function-constructor-with-string-args return new Function('$time', body); }; const PLAYBACK_FLAGS = { once: true, play: true, // alias for 'once' loop: true, stop: true, seek: true, }; // tslint:disable:variable-name export default class HaikuTimeline extends HaikuBase { options; component: IHaikuComponent; name; private globalClockTime: number; private localElapsedTime: number; private localControlledTime: number|null; private areUpdatesFrozen: boolean; private isTimelinePlaying: boolean; private isTimelineLooping: boolean; private offsetCalculator: Function; private lastFrame: number; private numLoops: number; constructor (component: IHaikuComponent, name, options) { super(); this.component = component; this.name = name; this.assignOptions(options || {}); this.globalClockTime = 0; this.localElapsedTime = 0; this.localControlledTime = null; // Only set this to a number if time is 'controlled' this.areUpdatesFrozen = !!this.options.freeze; this.isTimelineLooping = !!this.options.loop; this.isTimelinePlaying = true; this.offsetCalculator = null; this.lastFrame = null; this.numLoops = 0; } getMs (amount: number, unit: TimeUnit): number { switch (unit) { case TimeUnit.Frame: return Math.round(this.getFrameDuration() * amount); case TimeUnit.Millisecond: default: // The only currently valid alternative to TimeUnit.Frame is TimeUnit.Millisecond. return amount; } } getFrameDuration (): number { return this.component.getClock().getFrameDuration(); } assignOptions (options) { this.options = assign(this.options || {}, DEFAULT_OPTIONS, options || {}); } ensureClockIsRunning () { const clock = this.component.getClock(); if (!clock.isRunning()) { clock.start(); } } /** * @method setComponent * @description Internal hook to allow Haiku to hot swap on-stage components during editing. */ setComponent (component) { this.component = component; } doUpdateWithGlobalClockTime ( globalClockTime, ) { if (this.isFrozen()) { return; } const prevGlobalClockTime = this.getClockTime(); const deltaGlobalClockTime = globalClockTime - prevGlobalClockTime; this.globalClockTime = globalClockTime; // If we update with the global clock time while a timeline is paused, the next // time we resume playing it will "jump forward" to the time that has elapsed. if (this.isPaused()) { return; } this.doUpdateWithTimeDelta(deltaGlobalClockTime); } doUpdateWithTimeDelta ( deltaClockTime, ) { const ceilTime = this.getCeilTime(); const prevElapsedTime = this.getElapsedTime(); const newElapsedTime = prevElapsedTime + deltaClockTime; const didLoop = HaikuTimeline.didTimeLoop(prevElapsedTime, newElapsedTime, ceilTime); this.setElapsedTime(newElapsedTime); // If we are a looping timeline, reset to zero once we've gone past our max if (this.isLooping() && didLoop) { this.numLoops++; // Avoid log DoS for too-short timelines if (this.getMaxTime() > 200) { this.component.callHook('timeline:loop', { localElapsedTime: newElapsedTime, maxExplicitlyDefinedTime: this.getMaxTime(), globalClockTime: this.getClockTime(), boundedFrame: this.getBoundedFrame(), loopCount: this.numLoops, }); } } } executePreUpdateHooks (globalClockTime: number) { this.doUpdateWithGlobalClockTime(globalClockTime); } executePostUpdateHooks (globalClockTime: number) { if (this.isFrozen() || this.isPaused()) { return; } const frame = this.getBoundedFrame(); const time = Math.round(this.getBoundedTime()); this.component.routeEventToHandlerAndEmitWithoutBubbling( GLOBAL_LISTENER_KEY, `timeline:${this.getName()}:${frame}`, [frame, time], ); // Allow users to subscribe to the 'frame' event globally this.component.routeEventToHandlerAndEmitWithoutBubbling( GLOBAL_LISTENER_KEY, 'frame', [frame, time], ); // Deprecated; please use the 'frame' event instead. This is used by the Haiku Share Page. this.emit('tick', frame, time); this.lastFrame = frame; } getLastFrame (): number { return this.lastFrame; } controlTime ( controlledTimeToSet, newGlobalClockTime, ) { this.setControlledTime(parseInt(controlledTimeToSet || 0, 10)); // Need to update the properties so that accessors like .getFrame() work after this update. this.doUpdateWithGlobalClockTime(newGlobalClockTime); } isTimeControlled () { return typeof this.getControlledTime() === NUMBER; } /** * @method getName * @description Return the name of this timeline */ getName () { return this.name; } /** * @method getMaxTime * @description Return the maximum time that this timeline will reach, in ms. */ getMaxTime () { return this.cacheFetch('getMaxTime', () => { const descriptorMax = this.getMaxKeyframeTime(); const actionsMax = this.getMaxActionsTime(); return Math.max(descriptorMax, actionsMax); }); } getMaxKeyframeTime (): number { return getTimelineMaxTime(this.getDescriptor()); } getMaxActionsTime (): number { return Math.round(getActionsMaxTime( this.name, this.component.bytecode.eventHandlers, this.getFrameDuration(), )); } getDescriptor () { return this.component.getTimelineDescriptor(this.name); } /** * @description The millisecond value for the beginning of one frame past the max. */ getCeilTime () { return this.getMaxTime() + this.getMs(1, TimeUnit.Frame); } /** * @method getClockTime * @description fseek the global clock time that this timeline is at, in ms, * whether or not our local time matches it or it has exceeded our max. * This value is ultimately managed by the clock and passed in. */ getClockTime () { return this.globalClockTime; } /** * @method getElapsedTime * @description Return the amount of time that has elapsed on this timeline since * it started updating, up to the most recent time update it received from the clock. * Note that for inactive ftimelines, this value will cease increasing as of the last update. */ getElapsedTime () { return this.localElapsedTime; } setElapsedTime (t: number) { this.localElapsedTime = t; } /** * @description If time has been explicitly set here via time control, this value will * be the number of that setting. */ getControlledTime () { return this.localControlledTime; } setControlledTime (t: number|null) { this.localControlledTime = t; } /** * @description Return the locally elapsed time, or the maximum time of this timeline, * whichever is smaller. Useful if you want to know what the "effective" time of this * timeline is, not necessarily how much has elapsed in an absolute sense. This is used * in the renderer to determine what value to calculate "now" deterministically. */ getBoundedTime () { const max = this.getMaxTime(); let time = (this.isTimeControlled()) ? this.getControlledTime() : this.getElapsedTime(); if (this.offsetCalculator) { try { time = this.offsetCalculator.call(this, time); } catch (exception) { // no-op } } if (this.isLooping()) { const looped = HaikuTimeline.modulo( Math.round(time), this.getCeilTime(), ); return looped; } // Don't allow negative time if (time < 0.000001) { time = 0; } return Math.min(time, max); } /** * @description Convenience wrapper. Currently returns the bounded time. There's an argument * that this should return the elapsed time, though. #TODO */ getTime () { return this.getBoundedTime(); } /** * @description Return the current frame up to the maximum frame available for this timeline's duration. */ getBoundedFrame () { const time = this.getTime(); // Returns the bounded time const timeStep = this.component.getClock().getFrameDuration(); return Math.round(time / timeStep); } /** * @method getUnboundedFrame * @description Return the current frame, even if it is above the maximum frame. */ getUnboundedFrame () { const time = this.getElapsedTime(); // The elapsed time can go larger than the max time; see timeline.js const timeStep = this.component.getClock().getFrameDuration(); return Math.round(time / timeStep); } /** * @method getFrame * @description Return the bounded frame. * There's an argument that this should return the absolute frame. #TODO */ getFrame () { return this.getBoundedFrame(); } /** * @method isPlaying * @description Returns T/F if the timeline is playing */ isPlaying () { return this.isTimelinePlaying; } setPlaying (isPlaying: boolean = true) { this.isTimelinePlaying = !!isPlaying; } isPaused () { return !this.isPlaying(); } /** * @method isFinished * @description Returns T/F if the timeline is finished. * If this timeline is set to loop, it is never "finished". */ isFinished () { if (this.isLooping() || this.isTimeControlled()) { return false; } return this.getElapsedTime() > this.getMaxTime(); } isUnfinished () { return !this.isFinished(); } getDuration () { return this.getMaxTime() || 0; } setRepeat (bool: boolean = true) { this.isTimelineLooping = !!bool; } getRepeat (): boolean { return this.isTimelineLooping; } isRepeating (): boolean { return this.getRepeat(); } isLooping (): boolean { return this.isRepeating(); } /** * @method isFrozen * @description Returns T/F if the timeline is frozen */ isFrozen () { return this.areUpdatesFrozen; } freeze () { this.areUpdatesFrozen = true; } unfreeze () { this.areUpdatesFrozen = false; } start () { this.startSoftly(0); this.emit('start'); } startSoftly ( maybeElapsedTime: number, ) { this.setPlaying(true); this.setElapsedTime(maybeElapsedTime || 0); } stop () { this.stopSoftly(); this.emit('stop'); } stopSoftly () { this.setPlaying(false); } pause () { this.pauseSoftly(); this.emit('pause'); } pauseSoftly () { this.setPlaying(false); } play (options: any = {}) { this.playSoftly(); if (!options || !options.skipMarkForFullFlush) { this.component.markForFullFlush(); } this.emit('play'); } playSoftly () { this.ensureClockIsRunning(); this.setPlaying(true); // When playing after exiting controlled-time mode, start from the last controlled time. if (this.isTimeControlled()) { this.setElapsedTime(this.getControlledTime()); // To properly exit controlled-time mode, we need to set controlled time to null. this.setControlledTime(null); } } seek (amount: number, unit: TimeUnit = TimeUnit.Frame) { const ms = this.getMs(amount, unit); this.seekSoftly(ms); this.component.markForFullFlush(); this.emit('seek', ms); } seekSoftly (ms: number) { this.ensureClockIsRunning(); this.controlTime(ms, this.component.getClock().getTime()); this.setElapsedTime(this.getControlledTime()); } gotoAndPlay (amount: number, unit: TimeUnit = TimeUnit.Frame) { const ms = this.getMs(amount, unit); this.seekSoftly(ms); this.play(null); } gotoAndStop (amount: number, unit: TimeUnit = TimeUnit.Frame) { this.seekSoftly(this.getMs(amount, unit)); if (this.component && this.component.context && this.component.context.tick) { this.component.context.tick(); } this.pause(); } setPlaybackStatus (input) { const { flag, time, proc, } = this.parsePlaybackStatus(input); if (flag === PlaybackFlag.LOOP) { this.setRepeat(true); } if (flag === PlaybackFlag.ONCE) { this.setRepeat(false); } // If the sending timeline is frozen, don't inadvertently unfreeze its component's guests if ( flag === PlaybackFlag.LOOP || // In the current API, loop also connotes play flag === PlaybackFlag.ONCE || flag === PlaybackFlag.PLAY ) { if (!this.isPlaying()) { this.play(); } } if (flag === PlaybackFlag.STOP) { if (this.isPlaying()) { this.stop(); } } if (flag === PlaybackFlag.SEEK) { this.seek(time || 0, TimeUnit.Millisecond); } if (typeof proc === 'function') { this.offsetCalculator = proc; } } parsePlaybackStatus (input) { if (!input) { return { flag: PlaybackFlag.LOOP, }; } // If an object, assume it takes the format of a flag payload if (typeof input === 'object') { return input; } if (typeof input === 'number' && isNumeric(input)) { return { flag: PlaybackFlag.SEEK, // Assume the input is frames and convert to our internal format, milliseconds time: this.getMs(Number(input), TimeUnit.Frame), }; } if (typeof input === 'string') { const tokens = this.cacheFetch(`getPlaybackStatusTokens:${input}`, () => { return tokenizeDirective(input).map(({value}) => value); }); // If no tokens, assume the default: A looping timeline if (tokens.length < 1) { return { flag: PlaybackFlag.LOOP, }; } // Fast-path if we got a single playback flag string if (tokens.length === 1 && PLAYBACK_FLAGS[tokens[0]]) { return { flag: tokens[0], }; } const finals = []; // Convert any known number-unit tuples in the token stream into their canonical // ms-based time value. For example [100,ms]->[100], or [10]->[166] (frames to ms). for (let i = 0; i < tokens.length; i++) { const curr = tokens[i]; const next = tokens[i + 1]; if (typeof curr === 'number') { if (next === 'ms') { finals.push(this.getMs(curr, TimeUnit.Millisecond)); i++; continue; } if (next === 'fr') { finals.push(this.getMs(curr, TimeUnit.Frame)); i++; continue; } // Frames are assumed to be the default that an end-user would write if (next !== 'fr') { finals.push(this.getMs(curr, TimeUnit.Frame)); continue; } } finals.push(curr); } if (finals.length > 1) { // E.g. if we got +100, make it loop+100 if (!PLAYBACK_FLAGS[finals[0]]) { finals.unshift(PlaybackFlag.LOOP); } } const expr = finals.map((val) => { if (PLAYBACK_FLAGS[val]) { return '$time'; } return val; }).join(' '); let proc; try { proc = makePlaybackProc(`return ${expr};`); } catch (exception) { // no-op } const out = { proc, flag: finals[0], }; return out; } return { flag: PlaybackFlag.LOOP, }; } /** * @deprecated * TODO: Please change this to a getter. */ duration (): number { return this.getDuration(); } get repeat (): boolean { return this.getRepeat(); } get time (): number { return this.getTime(); } get max (): number { return this.getMaxTime(); } get frame (): number { return this.getFrame(); } static __name__ = 'HaikuTimeline'; static all = (): HaikuTimeline[] => HaikuBase.getRegistryForClass(HaikuTimeline); static where = (criteria): HaikuTimeline[] => { const all = HaikuTimeline.all(); return all.filter((timeline) => { return timeline.matchesCriteria(criteria); }); }; static create = (component: IHaikuComponent, name, config): HaikuTimeline => { return new HaikuTimeline( component, name, config, ); }; /** * @description Modulus, but returns zero if the second number is zero, * and calculates an appropriate "cycle" if the number is negative. */ static modulo = (n: number, ceil: number): number => { if (ceil === 0) { return 0; } return ((n % ceil) + ceil) % ceil; }; /** * @description Given a previous elapsed time (a), a new elapsed time (b), and a max * time (max), determine whether the given timeline has looped between (a) and (b). * * E.g.: * 0----------100 * 62 103 true * * 0----------100 * 62 100 true * * 0----------100 * 62 99 false * * 0----------100 * 100 110 false * * 0----------100 * 101 110 false * * 0----------100 * 100 * 100 false * * 0----------100 * 0 100 false * * 0----------100 * 0 * 0 false */ static didTimeLoop = (a: number, b: number, ceil: number): boolean => { const ma = HaikuTimeline.modulo(a, ceil); const mb = HaikuTimeline.modulo(b, ceil); return mb < ma; }; }
the_stack
import { BitField } from '@typings/src/BitField'; import { Constants } from '@typings/src/Constants'; import { DataStructure } from '@typings/typings/DataStructure'; import EmojiData from 'src/Content/Util/Emoji.json'; import twemoji from 'twemoji'; import { Logger } from 'src/Logger'; import { Twitch } from 'src/Sites/twitch.tv/Util/Twitch'; import { getProviderLogo, getRunningContext } from 'src/Global/Util'; import { MainComponent } from 'src/Sites/app/MainComponent'; import React from 'react'; const TWITCH_SET_NAME = 'twitch'; const EMOJI_SET_NAME = 'emoji'; export class EmoteStore { ctx = getRunningContext(); size = 0; private cachedElements = new Map<string, JSX.Element>(); sets = new Map<string, EmoteStore.EmoteSet>(); addElement(id: string, jsx: JSX.Element): JSX.Element { this.cachedElements.set(id, jsx); return jsx; } getElement(id: string): JSX.Element | undefined { return this.cachedElements.get(id); } getEmote(nameOrID: string): EmoteStore.Emote | null { for (const set of this.sets.values()) { for (const emote of set.getEmotes()) { if (emote.name === nameOrID || emote.id === nameOrID) { return emote; } } } return null; } /** * @returns all amotes, across all sets */ getAllEmotes(providers?: DataStructure.Emote.Provider[]): EmoteStore.Emote[] { const emotes = [] as EmoteStore.Emote[]; for (const set of this.sets.values()) { emotes.push(...set.getEmotes().filter(e => !Array.isArray(providers) || providers.includes(e.provider))); } return emotes; } fromTwitchEmote(data: Twitch.ChatMessage.EmoteRef): EmoteStore.Emote { if (!this.sets.has(TWITCH_SET_NAME)) { this.sets.set(TWITCH_SET_NAME, new EmoteStore.EmoteSet(TWITCH_SET_NAME)); } const urls = [ ['1', data.images?.dark['1x'] ?? ''], ['2', data.images?.dark['2x'] ?? ''], ['3', data.images?.dark['4x'] ?? ''], ['4', data.images?.dark['4x'] ?? ''] ] as [string, string][]; const set = this.sets.get(TWITCH_SET_NAME) as EmoteStore.EmoteSet; const currentEmote = set.getEmoteByID(data.emoteID ?? ''); if (!!currentEmote) { if (currentEmote.urls.length === 0) { currentEmote.urls.push(...urls); } return currentEmote; } set.push([{ id: data.emoteID ?? '', name: data.alt, provider: 'TWITCH', visibility: 0, mime: '', urls: urls, width: [28, 56, 112, 112], height: [28, 56, 112, 112], status: Constants.Emotes.Status.LIVE, tags: [] }], false); return set.getEmoteByName(data.alt) as EmoteStore.Emote; } fromEmoji(data: HTMLImageElement): EmoteStore.Emote { if (!this.sets.has(EMOJI_SET_NAME)) { this.sets.set(EMOJI_SET_NAME, new EmoteStore.EmoteSet(EMOJI_SET_NAME)); } const set = this.sets.get(EMOJI_SET_NAME) as EmoteStore.EmoteSet; const codePoint = twemoji.convert.toCodePoint(data.alt).toUpperCase(); const emoteji = set.getEmoteByID(codePoint); if (!!emoteji) { return emoteji; } const index = EmojiData.index[twemoji.convert.toCodePoint(data.alt).toUpperCase() as keyof typeof EmojiData.index] as number; const emoji = EmojiData.list[index]; const urls = [] as [string, string][]; for (let i = 1; i <= 4; i++) { urls.push([`${i}`, data.src]); } set.push([{ id: codePoint, name: emoji?.short_name.toLowerCase() ?? '', visibility: DataStructure.Emote.Visibility.GLOBAL, tags: [], mime: '', status: Constants.Emotes.Status.LIVE, provider: 'EMOJI', width: [19.5], height: [19.5], urls }]); return set.getEmoteByID(codePoint) as EmoteStore.Emote; } defineSets(data: EmoteStore.EmoteSet.Resolved[]): void { this.sets.clear(); for (const s of data) { const set = new EmoteStore.EmoteSet(s.name).push(s.emotes); this.sets.set(set.name, set); } return undefined; } /** * Enable an emote set * * @param name the name of the set to enable * @param emotes the emotes that the set contains * @returns the emote set that was created */ enableSet(name: string, emotes: DataStructure.Emote[]): EmoteStore.EmoteSet { if (this.sets.has(name)) { return (this.sets.get(name) as EmoteStore.EmoteSet).push(emotes); } const set = new EmoteStore.EmoteSet(name).push(emotes); this.sets.set(set.name, set); Logger.Get().debug(`Enabled emote set: ${name} (${emotes.length} emotes)`); return set; } /** * Disable an emote set * * @param name the name of the set to disable * @returns nothing LULW */ disableSet(name: string): void { if (!this.sets.has(name)) { return undefined; } this.sets.delete(name); return undefined; } resolve(): EmoteStore.EmoteSet.Resolved[] { const result = [] as EmoteStore.EmoteSet.Resolved[]; for (const set of this.sets.values()) { result.push(set.resolve()); } Logger.Get().debug(`Disabled emote set: ${name}`); return result; } } export namespace EmoteStore { export class EmoteSet { private emotes = new Map<string, Emote>(); get size(): number { return this.emotes.size; } /** * A set of emotes, such as that of a channel or global * * @param name the name of the set */ constructor( public name: string ) { } /** * Push emotes to this set, overwriting any data present beforehand * * @param emotes the emotes that will be in this set * @returns this */ push(emotes: DataStructure.Emote[], override = true): EmoteSet { if (override) { this.emotes.clear(); } const arr = emotes.map(e => new Emote(e)); for (const e of arr) { this.emotes.set(e.id, e); } return this; } getEmotes(): Emote[] { const emotes = [] as Emote[]; for (const [_, emote] of this.emotes) { emotes.push(emote); } return emotes; } getEmoteByID(id: string): Emote | null { return this.emotes.get(id) ?? null; } getEmoteByName(name: string): Emote | null { for (const emote of this.emotes.values()) { if (emote.name === name) { return emote; } } return null; } deleteEmote(id: string): void { this.emotes.delete(id); } /** * Resolve this set into its data form * * @returns An object matching the EmoteSet.Resolved interface */ resolve(): EmoteSet.Resolved { return { name: this.name, emotes: this.getEmotes().map(e => e.resolve()) }; } } export namespace EmoteSet { export interface Resolved { name: string; emotes: DataStructure.Emote[]; } } export class Emote { id = ''; name = ''; mime = ''; tags = [] as string[]; width = [] as number[]; height = [] as number[]; visibility: DataStructure.Emote.Visibility = 0; owner: Partial<DataStructure.TwitchUser> | null = null; provider: DataStructure.Emote.Provider = '7TV'; urls = [] as [string, string][]; element: HTMLSpanElement | null = null; weight = 0; constructor(private data: DataStructure.Emote) { this.id = data?.id ?? ''; this.name = data?.name ?? ''; this.mime = data?.mime ?? ''; this.visibility = data?.visibility ?? 0; this.provider = data?.provider ?? '7TV'; this.width = data?.width ?? []; this.height = data?.height ?? []; if (!!data.owner) { this.owner = data?.owner; } if (Array.isArray(data?.urls)) { this.urls = data.urls; } this.defineWeight(); } /** * Get the URL to this emote * * @param size the size of the emote to return */ cdn(size: '1' | '2' | '3' | '4'): string { const url = this.urls.filter(([s]) => s === size)?.[0] ?? this.urls[this.urls.length - 1]; // Return from urls if available if (url?.length === 2) { return url[1]; } // Otherwise fallback on hardcoded provider CDNs switch (this.provider) { case 'TWITCH': return `https://static-cdn.jtvnw.net/emoticons/v2/${this.id}/default/dark/${size}.0`; default: return ''; } } setName(name: string): void { this.name = this.data.name = name; } /** * Define the wseight of the emote according to its global state and provider */ private defineWeight(): number { if (this.isGlobal()) { this.weight = 0.5; } else { this.weight = 1; if (this.provider === '7TV') { this.weight += 0.5; } else if (this.provider === 'TWITCH') { this.weight += 1; } } return this.weight; } /** * @returns whether the emote is global */ isGlobal(): boolean { return BitField.HasBits(this.visibility, DataStructure.Emote.Visibility.GLOBAL); } /** * @returns whether the emote is private */ isPrivate(): boolean { return BitField.HasBits(this.visibility, DataStructure.Emote.Visibility.PRIVATE); } isZeroWidth(): boolean { return BitField.HasBits(this.visibility, DataStructure.Emote.Visibility.ZERO_WIDTH); } isUnlisted(): boolean { return BitField.HasBits(this.visibility, DataStructure.Emote.Visibility.HIDDEN); } toElement(shouldBlurHidden = false): HTMLSpanElement { const container = document.createElement('span'); container.classList.add('seventv-emote'); if (this.isZeroWidth()) { container.classList.add('seventv-zerowidth'); } const inner = document.createElement('span'); inner.style.minWidth = `${this.width[0]}px`; inner.style.minHeight = `${this.height[0]}px`; const tooltipExtra = [] as JSX.Element[]; if (this.isGlobal()) { tooltipExtra.push(<p key='global-state' className='is-7tv-global'>Global Emote</p>); } if (this.isZeroWidth()) { tooltipExtra.push(<p key='zerowidth-state' style={{ color: '#e14bb4' }}>Zero-Width Emote</p>); } if (this.isUnlisted()) { tooltipExtra.push(<p key='unlisted-state' style={{ color: '#f23333' }}>Unlisted Emote</p>); if (shouldBlurHidden) { container.classList.add('seventv-emote-unlisted'); } } inner.addEventListener('mouseenter', event => { MainComponent.ShowTooltip.next({ event, hover: true, fields: { name: this.name, hint: !!this.owner && this.owner.login !== '*deleteduser' ? `by ${this.owner.display_name ?? this.owner.login ?? 'Unknown User'}` : '', imageURL: this.cdn('3'), providerIconURL: getProviderLogo(this.provider), extra: tooltipExtra }}); }); inner.addEventListener('mouseleave', event => { MainComponent.ShowTooltip.next({ event, hover: false }); }); const img = document.createElement('img'); img.alt = ` ${this.name} `; img.classList.add('chat-image'); img.classList.add('chat-line__message--emote'); img.src = this.cdn('1'); img.srcset = `${this.cdn('1')} 1x, ${this.cdn('2')} 2x, ${this.cdn('4')} 4x`; inner.appendChild(img); container.appendChild(inner); return this.element = container; } resolve(): DataStructure.Emote { return this.data; } } }
the_stack
function Lazy<T, TArgs extends unknown[]>(fn: (...args: TArgs) => T) { let evaluated: T | null = null; return (...a: TArgs) => (evaluated ??= fn(...a)); } var Util = (() => Lazy(() => { const { HasQueryKey, GetQueryValue, GetAllQueryValues } = Query(); let isDarkMode = (() => { // check if browser supports prefers-color-scheme if (window.matchMedia && window.matchMedia("(prefers-color-scheme)").matches) { // media query supported, check preference if (window.matchMedia("(prefers-color-scheme: dark)").matches) { // use dark mode return true; } else if (window.matchMedia("(prefers-color-scheme: light)").matches) { // use light mode return false; } } // use dark mode based on time const hour = new Date().getHours(); return hour < 7 || hour > 18; })(); function SetDarkMode(isDark: boolean) { isDarkMode = isDark; document.body.classList.remove(isDark ? "light" : "dark"); document.body.classList.add(isDark ? "dark" : "light"); } const isTestnet = HasQueryKey("testnet"); function AsyncNoParallel<TArgs extends unknown[]>(fn: (...args: TArgs) => Promise<void>) { let running = false; return async (...args: TArgs) => { if (running) { return; } try { running = true; await fn(...args); } finally { running = false; } }; } async function WaitForImageLoad(image: HTMLImageElement, src?: string) { if (src !== undefined) { image.src = src; } return await new Promise<HTMLImageElement>(resolve => { function OnLoad() { image.removeEventListener("load", OnLoad); resolve(image); } image.addEventListener("load", OnLoad); }); } async function GenerateAddressQRCode(address: string, addressType: AddressType, errorCorrectionLevel: QRCodeErrorCorrectionLevel, cellSize?: number | undefined, margin?: number | undefined) { const [data, mode] = addressType === "bech32" ? [address.toUpperCase(), "Alphanumeric"] as const : [address, "Byte"] as const; return await WorkerInterface.GenerateQRCode(data, errorCorrectionLevel, mode, cellSize, margin); } async function GenerateQRCode(data: string, errorCorrectionLevel: QRCodeErrorCorrectionLevel, mode: "Byte" | "Numeric" | "Alphanumeric" | "Kanji" = "Byte", cellSize?: number | undefined, margin?: number | undefined) { return await WorkerInterface.GenerateQRCode(data, errorCorrectionLevel, mode, cellSize, margin); } class ShowLoadingHelper { private elem: HTMLElement; private delayBeforeShow: number; private timeoutHandle: number = -1; constructor(elem: HTMLElement, delayBeforeShow: number) { this.elem = elem; this.delayBeforeShow = delayBeforeShow; } show() { if (this.delayBeforeShow === 0) { this.elem.style.display = ""; } else { this.timeoutHandle = setTimeout(() => this.elem.style.display = "", this.delayBeforeShow); } } hide() { this.elem.style.display = "none"; clearTimeout(this.timeoutHandle); this.timeoutHandle = -1; } } return { IsDarkMode: () => isDarkMode, SetDarkMode, IsTestnet: () => isTestnet, AsyncNoParallel, GenerateAddressQRCode, GenerateQRCode, WaitForImageLoad, ShowLoadingHelper }; }))(); type Result<TResult, TError> = ResultOK<TResult> | ResultErr<TError>; interface ResultOK<T> { type: "ok"; result: T; } interface ResultErr<T> { type: "err"; error: T; } declare var WorkerUtils: ReturnType<typeof INIT_WorkerUtils>; function INIT_WorkerUtils() { let entropy: number[] | null = null; function SetEntropy(values: number[]) { entropy = []; for (let value of values) { value = Math.abs(value | 0); do { entropy.push(value & 0xff); value >>>= 8; } while (value !== 0); } } let isTestnet = false; function SetIsTestnet(testnet: boolean) { isTestnet = testnet; } function IsTestnet() { return isTestnet; } function TypedArrayPush(targetArray: number[], srcArray: Uint8Array | Uint32Array) { for (let i = 0; i < srcArray.length; ++i) { targetArray.push(srcArray[i]); } } function Get32SecureRandomBytes() { if (entropy !== null) { const tempArray: number[] = []; TypedArrayPush(tempArray, self.crypto.getRandomValues(new Uint8Array(8))); tempArray.push(...entropy); const tempArray2 = CryptoHelper.SHA256(tempArray); TypedArrayPush(tempArray2, self.crypto.getRandomValues(new Uint8Array(8))); return CryptoHelper.SHA256(tempArray2); } // skipped randomness generation const bytes = self.crypto.getRandomValues(new Uint8Array(32)); const ret = new Array<number>(32); for (let i = 0; i < 32; ++i) { ret[i] = bytes[i]; } return ret; } const bn_0 = new BN(0); const bn_255 = new BN(255); function BigintToByteArray(bigint: BN) { const ret: number[] = []; while (bigint.gt(bn_0)) { ret.push(bigint.and(bn_255).toNumber()); bigint = bigint.shrn(8); } return ret; } function ByteArrayToBigint(bytes: number[] | Uint8Array) { let bigint = new BN(0); for (let i = 0; i < bytes.length; ++i) { bigint = bigint.shln(8); bigint = bigint.or(new BN(bytes[i])); } return bigint; } function BigintToBitArray(bigint: BN) { if (bigint.isNeg()) return [false]; const values: boolean[] = []; while (bigint.gt(bn_0)) { values.push(bigint.isOdd()); bigint = bigint.shrn(1); } return values.reverse(); } function ByteArrayXOR(b1: number[] | Uint8Array, b2: number[] | Uint8Array) { const ret: number[] = []; for (let i = 0; i < b1.length; ++i) ret.push(b1[i] ^ b2[i]); return ret; } function BigintToByteArrayLittleEndian32(bigint: BN) { const array = BigintToByteArray(bigint); while (array.length < 32) { array.push(0); } return array.reverse(); } const base58Characters = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; const base58CharsIndices: { [key: string]: number } = { "1": 0, "2": 1, "3": 2, "4": 3, "5": 4, "6": 5, "7": 6, "8": 7, "9": 8, "A": 9, "B": 10, "C": 11, "D": 12, "E": 13, "F": 14, "G": 15, "H": 16, "J": 17, "K": 18, "L": 19, "M": 20, "N": 21, "P": 22, "Q": 23, "R": 24, "S": 25, "T": 26, "U": 27, "V": 28, "W": 29, "X": 30, "Y": 31, "Z": 32, "a": 33, "b": 34, "c": 35, "d": 36, "e": 37, "f": 38, "g": 39, "h": 40, "i": 41, "j": 42, "k": 43, "m": 44, "n": 45, "o": 46, "p": 47, "q": 48, "r": 49, "s": 50, "t": 51, "u": 52, "v": 53, "w": 54, "x": 55, "y": 56, "z": 57, } const bn_58 = new BN(58); function Base58CheckEncode(bytes: number[] | Uint8Array) { let leading_zeroes = 0; while (bytes[leading_zeroes] === 0) { // count leading zeroes ++leading_zeroes; } // note: typescript doesn't allow using the spread operator // on Uint8Arrays, but in javascript it works fine // so here the bytes are casted to number[] for this reason bytes = [...(<number[]>bytes), ...CryptoHelper.SHA256(CryptoHelper.SHA256(bytes)).slice(0, 4)]; let bigint = new BN(0); // convert bytes to bigint for (let i = 0; i < bytes.length; ++i) { bigint = bigint.shln(8); bigint = bigint.or(new BN(bytes[i])); } bytes.reverse(); const ret: string[] = []; while (bigint.gt(bn_0)) { // get base58 character const remainder = bigint.mod(bn_58); bigint = bigint.div(bn_58); ret.push(base58Characters[remainder.toNumber()]); } for (let i = 0; i < leading_zeroes; ++i) { // add padding if necessary ret.push(base58Characters[0]); } return ret.reverse().join(""); } function Base58CheckDecode(text: string): Result<number[], string> { let newstring = text.split("").reverse(); for (let i = 0; i < text.length; ++i) { if (text[i] == base58Characters[0]) { newstring.pop(); } else { break; } } let bigint = bn_0; for (let i = newstring.length - 1; i >= 0; --i) { const charIndex = base58CharsIndices[newstring[i]]; if (charIndex === undefined) { return { type: "err", error: "invalid character: " + newstring[i] }; } bigint = (bigint.mul(bn_58)).add(new BN(charIndex)); } const bytes = BigintToByteArray(bigint); if (bytes[bytes.length - 1] == 0) { bytes.pop(); } bytes.reverse(); const checksum = bytes.slice(bytes.length - 4, bytes.length); bytes.splice(bytes.length - 4, 4); const sha_result = CryptoHelper.SHA256(CryptoHelper.SHA256(bytes)); for (var i = 0; i < 4; ++i) { if (sha_result[i] != checksum[i]) { return { type: "err", error: "invalid checksum" }; } } return { type: "ok", result: bytes }; } function GenerateQRCode(data: string, errorCorrectionLevel: QRCodeErrorCorrectionLevel, mode?: "Byte" | "Numeric" | "Alphanumeric" | "Kanji", cellSize?: number, margin?: number) { const qr = qrcode(0, errorCorrectionLevel); qr.addData(data, mode); qr.make(); return "data:image/svg+xml," + encodeURI(qr.createSvgTag(cellSize, margin)); } return { SetEntropy, SetIsTestnet, IsTestnet, Get32SecureRandomBytes, BigintToBitArray, BigintToByteArray, ByteArrayToBigint, ByteArrayXOR, BigintToByteArrayLittleEndian32, Base58CheckEncode, Base58CheckDecode, GenerateQRCode }; } type QRCodeErrorCorrectionLevel = "H" | "Q" | "M" | "L";
the_stack