text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import * as py from "@andrewhead/python-program-analysis"; import { ICodeCellModel } from "@jupyterlab/cells"; import { NotebookPanel } from "@jupyterlab/notebook"; import { PanelLayout, Widget } from "@phosphor/widgets"; import { LineHandle } from "codemirror"; /* * jQuery only used for dynamically computing element height. Use Phosphor whenever possible as the * preferred user interface toolkit. */ import * as $ from "jquery"; import { CellOutput, DefSelection, EditorDef, GatherEventData, GatherModel, GatherModelEvent, IGatherObserver, OutputSelection } from "../model"; import { LabCell } from "../model/cell"; import { log } from "../util/log"; import { NotebookElementFinder } from "./element-finder"; /** * Class for a highlighted, clickable output. */ const OUTPUT_HIGHLIGHTED_CLASS = "jp-OutputArea-highlighted"; /** * Class for parent elements of a gather button in an output area. */ const GATHER_BUTTON_PARENT_CLASS = "jp-OutputArea-gather-button-parent"; /** * Class for a selected output. */ const OUTPUT_SELECTED_CLASS = "jp-OutputArea-selected"; /** * Class for a button that lets you gather an output. */ const OUTPUT_GATHER_BUTTON_CLASS = "jp-OutputArea-gatherbutton"; /** * Class for a label on a gather button on an output. */ const OUTPUT_GATHER_LABEL_CLASS = "jp-OutputArea-gatherlabel"; /** * Class for variable definition text. */ const DEFINITION_CLASS = "jp-InputArea-editor-nametext"; /** * Class for selected variable definition text. */ const DEFINITION_SELECTED_CLASS = "jp-InputArea-editor-nametext-selected"; /** * Class for a line holding a variable definition. */ const DEFINITION_LINE_SELECTED_CLASS = "jp-InputArea-editor-nameline-selected"; /** * Class for a line with a data dependency. */ const DEPENDENCY_CLASS = "jp-InputArea-editor-dependencyline"; /** * Class for a line with a data dependency in a dirty cell. */ const DIRTY_DEPENDENCY_CLASS = "jp-InputArea-editor-dirtydependencyline"; /** * Clear existing selections in the window. */ function clearSelectionsInWindow() { if (window && window.getSelection) { window.getSelection().removeAllRanges(); } else if (document.hasOwnProperty("selection")) { (document as any).selection.empty(); } } /** * Adds and manages text markers. */ export class MarkerManager implements IGatherObserver { private _model: GatherModel; private _elementFinder: NotebookElementFinder; private _defMarkers: DefMarker[] = []; private _defLineHandles: DefLineHandle[] = []; private _outputMarkers: OutputMarker[] = []; private _dependencyLineMarkers: DependencyLineMarker[] = []; /** * Construct a new marker manager. */ constructor(model: GatherModel, notebook: NotebookPanel) { this._model = model; this._model.addObserver(this); this._elementFinder = new NotebookElementFinder(notebook); /* * XXX(andrewhead): Sometimes in Chrome or Edge, "click" events get dropped when the click * occurs on the cell. Mouseup doesn't, so we use that here. */ notebook.content.node.addEventListener("mouseup", (event: MouseEvent) => { this.handleClick(event); }); } /** * Click-handler---pass on click event to markers. */ handleClick(event: MouseEvent) { this._defMarkers.forEach(marker => { marker.handleClick(event); }); } /** * Listen for changes to the gather model. */ onModelChange(eventType: GatherModelEvent, eventData: GatherEventData, model: GatherModel) { // When a cell is executed, search for definitions and output. if (eventType == GatherModelEvent.CELL_EXECUTION_LOGGED) { let cell = eventData as py.Cell; this.clearSelectablesForCell(cell); let editor = this._elementFinder.getEditor(cell); if (editor) { this.highlightDefs(editor, cell); } let outputElements = this._elementFinder.getOutputs(cell); this.highlightOutputs(cell, outputElements); } // When a cell is deleted or edited, delete all of its def markers. if (eventType == GatherModelEvent.CELL_DELETED || eventType == GatherModelEvent.CELL_EDITED) { let cell = eventData as py.Cell; this._updateDependenceHighlightsForCell(cell); this.clearSelectablesForCell(cell); } // When definitions are found, highlight them. if (eventType == GatherModelEvent.EDITOR_DEF_FOUND) { let editorDef = eventData as EditorDef; this.highlightDef(editorDef); } // When definitions are removed from the model, deselect and remove their markers. if (eventType == GatherModelEvent.EDITOR_DEF_REMOVED) { let editorDef = eventData as EditorDef; for (let i = this._defMarkers.length - 1; i >= 0; i--) { let defMarker = this._defMarkers[i]; if (defMarker.def == editorDef.def) { let defsToDeselect = this._model.selectedDefs.filter(d => d.editorDef == editorDef); for (let defToDeselect of defsToDeselect) { this._model.deselectDef(defToDeselect); } defMarker.marker.clear(); this._defMarkers.splice(i, 1); } } } // When outputs are found, highlight them. if (eventType == GatherModelEvent.OUTPUT_FOUND) { let output = eventData as CellOutput; this.highlightOutput(output); } // When outputs are removed from the model, deselect and remove their markers. if (eventType == GatherModelEvent.OUTPUT_REMOVED) { let output = eventData as CellOutput; for (let i = this._outputMarkers.length - 1; i >= 0; i--) { let outputMarker = this._outputMarkers[i]; if (outputMarker.cell == output.cell && outputMarker.outputIndex == output.outputIndex) { this._model.deselectOutput({ cell: output.cell, outputIndex: output.outputIndex }); outputMarker.destroy(); this._outputMarkers.splice(i, 1); } } } // Whenever a definition is selected, add a marker to its line. if (eventType == GatherModelEvent.DEF_SELECTED) { let defSelection = eventData as DefSelection; let editor = defSelection.editorDef.editor; let def = defSelection.editorDef.def; let lineHandle = editor.addLineClass( def.location.first_line - 1, "background", DEFINITION_LINE_SELECTED_CLASS ); this._defLineHandles.push({ def: def, lineHandle: lineHandle }); } // Whenever a definition is deselected from outside, unhighlight it. if (eventType == GatherModelEvent.DEF_DESELECTED) { let defSelection = eventData as DefSelection; this._defMarkers .filter(marker => { return ( defSelection.editorDef.def.location == marker.location && defSelection.cell.executionEventId == marker.cell.executionEventId ); }) .forEach(marker => marker.deselect()); let editorDef = defSelection.editorDef; for (let i = this._defLineHandles.length - 1; i >= 0; i--) { let defLineHandle = this._defLineHandles[i]; if (defLineHandle.def == editorDef.def) { editorDef.editor.removeLineClass( defLineHandle.lineHandle, "background", DEFINITION_LINE_SELECTED_CLASS ); } } } // Whenever an output is deselected from outside, unhighlight it. if (eventType == GatherModelEvent.OUTPUT_DESELECTED) { let outputSelection = eventData as OutputSelection; this._outputMarkers .filter(marker => { return ( marker.outputIndex == outputSelection.outputIndex && marker.cell.executionEventId == outputSelection.cell.executionEventId ); }) .forEach(marker => marker.deselect()); } // When the chosen slices change, update which lines are highlighted in the document. if ( eventType == GatherModelEvent.SLICE_SELECTED || eventType == GatherModelEvent.SLICE_DESELECTED ) { this._clearDependencyLineMarkers(); model.selectedSlices.forEach(sliceSelection => { this.highlightDependencies(sliceSelection.slice); }); } } highlightDef(editorDef: EditorDef) { let editor = editorDef.editor; let def = editorDef.def; let doc = editor.getDoc(); // Add marker for the definition symbol. let marker = doc.markText( { line: def.location.first_line - 1, ch: def.location.first_column }, { line: def.location.last_line - 1, ch: def.location.last_column }, { className: DEFINITION_CLASS } ); let defSelection = new DefSelection({ editorDef: editorDef, cell: editorDef.cell }); let clickHandler = (_: py.Cell, __: py.Location, selected: boolean, event: MouseEvent) => { if (selected) { if (!event.shiftKey) { this._model.deselectAll(); } this._model.selectDef(defSelection); } else { this._model.deselectDef(defSelection); } }; this._defMarkers.push( new DefMarker(marker, editor, def, def.location, def.node, editorDef.cell, clickHandler) ); } highlightOutput(output: CellOutput) { let selection = { cell: output.cell, outputIndex: output.outputIndex }; let outputMarker = new OutputMarker( output.element, output.outputIndex, output.cell, (selected, event: MouseEvent) => { if (selected) { if (!event.shiftKey) { this._model.deselectAll(); } this._model.selectOutput(selection); } else { this._model.deselectOutput(selection); } if (event.shiftKey) { // Don't select cells or text when multiple outputs are clicked on event.preventDefault(); event.stopPropagation(); clearSelectionsInWindow(); } } ); this._outputMarkers.push(outputMarker); } /** * Clear all def markers that belong to this editor. */ clearSelectablesForCell(cell: py.Cell) { this._model.removeEditorDefsForCell(cell.executionEventId); this._model.deselectOutputsForCell(cell.executionEventId); } /** * Highlight all of the definitions in an editor. */ highlightDefs(editor: CodeMirror.Editor, cell: py.Cell) { /** * Fetch the cell program instead of recomputing it, as it can stall the interface if we * analyze the code here. */ let cellProgram = this._model.getCellProgram(cell); if (cellProgram !== null && !cellProgram.hasError) { for (let ref of cellProgram.defs) { if (ref.type == py.SymbolType.VARIABLE) { this._model.addEditorDef({ def: ref, editor: editor, cell: cell }); } } } log("Highlighted definitions", { numActive: this._defMarkers.length }); } /** * Highlight a list of output elements. */ highlightOutputs(cell: py.Cell, outputElements: HTMLElement[]) { for (let i = 0; i < outputElements.length; i++) { let outputElement = outputElements[i]; let output = { cell: cell, element: outputElement, outputIndex: i }; this._model.addOutput(output); } log("Highlighted outputs", { numActive: this._outputMarkers.length }); } /** * Highlight dependencies in a cell at a set of locations. */ highlightDependencies(slice: py.SlicedExecution) { let defLines: number[] = []; slice.cellSlices.forEach(cellSlice => { let loggedCell = cellSlice.cell; let sliceLocations = cellSlice.slice; let liveCellWidget = this._elementFinder.getCellWidget(loggedCell); let editor = this._elementFinder.getEditor(loggedCell); if (liveCellWidget && editor) { let liveCell = new LabCell(liveCellWidget.model as ICodeCellModel); let numLines = 0; // Batch the highlight operations for each cell to spend less time updating cell height. editor.operation(() => { sliceLocations.items.forEach((loc: py.Location) => { for ( let lineNumber = loc.first_line - 1; lineNumber <= loc.last_line - 1; lineNumber++ ) { numLines += 1; let styleClass = liveCell.dirty ? DIRTY_DEPENDENCY_CLASS : DEPENDENCY_CLASS; let lineHandle = editor.addLineClass(lineNumber, "background", styleClass); this._dependencyLineMarkers.push({ editor: editor, lineHandle: lineHandle }); } }); defLines.push(numLines); }); } }); log("Added lines for defs (may be overlapping)", { defLines }); } private _clearDependencyMarkersForLine( editor: CodeMirror.Editor, lineHandle: CodeMirror.LineHandle ) { editor.removeLineClass(lineHandle, "background", DEPENDENCY_CLASS); editor.removeLineClass(lineHandle, "background", DIRTY_DEPENDENCY_CLASS); } private _updateDependenceHighlightsForCell(cell: py.Cell) { let editor = this._elementFinder.getEditor(cell); let liveCellWidget = this._elementFinder.getCellWidget(cell); let liveCell = new LabCell(liveCellWidget.model as ICodeCellModel); this._dependencyLineMarkers .filter(marker => marker.editor == editor) .forEach(marker => { this._clearDependencyMarkersForLine(marker.editor, marker.lineHandle); let styleClass = liveCell.dirty ? DIRTY_DEPENDENCY_CLASS : DEPENDENCY_CLASS; marker.editor.addLineClass(marker.lineHandle, "background", styleClass); }); } private _clearDependencyLineMarkers() { log("Cleared all dependency line markers"); this._dependencyLineMarkers.forEach(marker => { this._clearDependencyMarkersForLine(marker.editor, marker.lineHandle); }); this._dependencyLineMarkers = []; } } type DependencyLineMarker = { editor: CodeMirror.Editor; lineHandle: CodeMirror.LineHandle; }; /** * Marker for an output. */ class OutputMarker { constructor( outputElement: HTMLElement, outputIndex: number, cell: py.Cell, onToggle: (selected: boolean, event: MouseEvent) => void ) { this._element = outputElement; this._element.classList.add(OUTPUT_HIGHLIGHTED_CLASS); this._addSelectionButton(); this.outputIndex = outputIndex; this.cell = cell; this._onToggle = onToggle; this._clickListener = (event: MouseEvent) => { let target = event.target as HTMLElement; // If the click is on a child of the output area (the actual content), then handle // that click event like normal without selecting the output. if ( !target || !( target.classList.contains(OUTPUT_HIGHLIGHTED_CLASS) || target.classList.contains(OUTPUT_GATHER_BUTTON_CLASS) || target.classList.contains(OUTPUT_GATHER_LABEL_CLASS) ) ) return; if (this._onToggle) { this._toggleSelected(); this._onToggle(this._selected, event); } log("Clicked on output area", { outputIndex, cell, toggledOn: this._selected }); }; this._element.addEventListener("click", this._clickListener); } private _relaxParentOverflowVisibility() { let parentElement = this._element; while (parent != null) { parentElement.classList.add(GATHER_BUTTON_PARENT_CLASS); if (parentElement.classList.contains("jp-OutputArea")) { break; } parentElement = parentElement.parentElement; } } private _addSelectionButton() { this._gatherButton = new Widget({ node: document.createElement("div") }); this._gatherButton.addClass(OUTPUT_GATHER_BUTTON_CLASS); this._gatherButton.layout = new PanelLayout(); this._gatherLabel = new Widget({ node: document.createElement("p") }); this._gatherLabel.addClass(OUTPUT_GATHER_LABEL_CLASS); this._gatherLabel.node.textContent = "Gather"; (this._gatherButton.layout as PanelLayout).addWidget(this._gatherLabel); this._relaxParentOverflowVisibility(); this._element.appendChild(this._gatherButton.node); var buttonHeight = -$(this._gatherButton.node).outerHeight(); this._gatherButton.node.style["top"] = buttonHeight + "px"; } private _toggleSelected() { if (this._selected) this.deselect(); else if (!this._selected) this.select(); } select() { this._selected = true; this._element.classList.add(OUTPUT_SELECTED_CLASS); } deselect() { this._selected = false; this._element.classList.remove(OUTPUT_SELECTED_CLASS); } destroy() { this.deselect(); this._element.classList.remove(OUTPUT_HIGHLIGHTED_CLASS); this._element.removeEventListener("click", this._clickListener); } readonly outputIndex: number; readonly cell: py.Cell; private _element: HTMLElement; private _gatherButton: Widget; private _gatherLabel: Widget; private _clickListener: (_: MouseEvent) => void; private _onToggle: (selected: boolean, event: MouseEvent) => void; private _selected: boolean = false; } /** * Line handle for a definition line. */ type DefLineHandle = { def: py.Ref; lineHandle: LineHandle; }; /** * Marker for a variable definition. */ class DefMarker { constructor( marker: CodeMirror.TextMarker, editor: CodeMirror.Editor, def: py.Ref, location: py.Location, statement: py.SyntaxNode, cell: py.Cell, clickHandler: ( cell: py.Cell, selection: py.Location, selected: boolean, event: MouseEvent ) => void ) { this.marker = marker; this.def = def; this.editor = editor; this.location = location; this.statement = statement; this.cell = cell; this.clickHandler = clickHandler; } handleClick(event: MouseEvent) { let editor = this.editor; if (editor.getWrapperElement().contains(event.target as Node)) { // In Chrome, if you click in the top of an editor's text area, it will trigger this // event, and is considered as a click at the start of the box. This filter for // span elements filters out those spurious clicks. let target = event.target as HTMLElement; let badTarget = !target.tagName || target.tagName != "SPAN" || !target.classList.contains(DEFINITION_CLASS); if (badTarget) return; let clickPosition: CodeMirror.Position = editor.coordsChar({ left: event.clientX, top: event.clientY }); let editorMarkers = editor.getDoc().findMarksAt(clickPosition); if (editorMarkers.indexOf(this.marker) != -1) { if (this.clickHandler) { this.toggleSelected(); log("Clicked on definition", { toggledOn: this._selected, cell: this.cell }); this.clickHandler(this.cell, this.location, this._selected, event); } event.preventDefault(); } } } toggleSelected() { if (this._selected) this.deselect(); else if (!this._selected) this.select(); } select() { this._selected = true; let markerPos = this.marker.find(); this._selectionMarker = this.editor.getDoc().markText(markerPos.from, markerPos.to, { className: DEFINITION_SELECTED_CLASS }); } deselect() { this._selected = false; if (this._selectionMarker) { this._selectionMarker.clear(); this._selectionMarker = undefined; } } private _selected: boolean = false; private _selectionMarker: CodeMirror.TextMarker = undefined; readonly marker: CodeMirror.TextMarker; readonly editor: CodeMirror.Editor; readonly def: py.Ref; readonly location: py.Location; readonly statement: py.SyntaxNode; readonly cell: py.Cell; readonly clickHandler: ( cell: py.Cell, selection: py.Location, selected: boolean, event: MouseEvent ) => void; }
the_stack
import { Component, EventEmitter, Input, Output, forwardRef, ElementRef, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms'; // Vendor import { ReplaySubject } from 'rxjs'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; // APP import { KeyCodes } from '../../utils/key-codes/KeyCodes'; import { Helpers } from '../../utils/Helpers'; import { NovoLabelService } from '../../services/novo-label-service'; import { ComponentUtils } from '../../utils/component-utils/ComponentUtils'; // Value accessor for the component (supports ngModel) const CHIPS_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => NovoChipsElement), multi: true, }; @Component({ selector: 'chip,novo-chip', template: ` <span (click)="onSelect($event)" (mouseenter)="onSelect($event)" (mouseleave)="onDeselect($event)" [ngClass]="_type"> <i *ngIf="_type" class="bhi-circle"></i> <span><ng-content></ng-content></span> </span> <i class="bhi-close" *ngIf="!disabled" (click)="onRemove($event)"></i> `, }) export class NovoChipElement { @Input() set type(type: string) { this._type = type ? type.toLowerCase() : null; } @Input() disabled: boolean = false; @Output() select: EventEmitter<any> = new EventEmitter(); @Output() remove: EventEmitter<any> = new EventEmitter(); @Output() deselect: EventEmitter<any> = new EventEmitter(); entity: string; _type: string; onRemove(e) { if (e) { e.stopPropagation(); e.preventDefault(); } this.remove.emit(e); return false; } onSelect(e) { if (e) { e.stopPropagation(); e.preventDefault(); } this.select.emit(e); return false; } onDeselect(e) { if (e) { e.stopPropagation(); e.preventDefault(); } this.deselect.emit(e); return false; } } @Component({ selector: 'chips,novo-chips', providers: [CHIPS_VALUE_ACCESSOR], template: ` <div class="novo-chip-container"> <novo-chip *ngFor="let item of _items | async" [type]="type || item?.value?.searchEntity" [class.selected]="item == selected" [disabled]="disablePickerInput" (remove)="remove($event, item)" (select)="select($event, item)" (deselect)="deselect($event, item)"> {{ item.label }} </novo-chip> </div> <div class="chip-input-container" *ngIf="!maxlength || (maxlength && items.length < maxlength)"> <novo-picker clearValueOnSelect="true" [closeOnSelect]="closeOnSelect" [config]="source" [disablePickerInput]="disablePickerInput" [placeholder]="placeholder" [(ngModel)]="itemToAdd" (select)="add($event)" (keydown)="onKeyDown($event)" (focus)="onFocus($event)" (typing)="onTyping($event)" (blur)="onTouched($event)" [selected]="items" [overrideElement]="element"> </novo-picker> </div> <div class="preview-container"> <span #preview></span> </div> <i class="bhi-search" [class.has-value]="items.length" *ngIf="!disablePickerInput"></i> <label class="clear-all" *ngIf="items.length && !disablePickerInput" (click)="clearValue()">{{ labels.clearAll }} <i class="bhi-times"></i></label> `, host: { '[class.with-value]': 'items.length > 0', '[class.disabled]': 'disablePickerInput', }, }) export class NovoChipsElement implements OnInit, ControlValueAccessor { @Input() closeOnSelect: boolean = false; @Input() placeholder: string = ''; @Input() source: any; @Input() maxlength: any; @Input() type: any; @Input() set disablePickerInput(v: boolean) { this._disablePickerInput = coerceBooleanProperty(v); } get disablePickerInput() { return this._disablePickerInput; } private _disablePickerInput: boolean = false; @Output() changed: EventEmitter<any> = new EventEmitter(); @Output() focus: EventEmitter<any> = new EventEmitter(); @Output() blur: EventEmitter<any> = new EventEmitter(); @Output() typing: EventEmitter<any> = new EventEmitter(); @ViewChild('preview', { read: ViewContainerRef }) preview: ViewContainerRef; items: Array<any> = []; selected: any = null; config: any = {}; model: any; itemToAdd: any; popup: any; // private data model _value: any = ''; _items = new ReplaySubject(1); // Placeholders for the callbacks onModelChange: Function = () => {}; onModelTouched: Function = () => {}; constructor(public element: ElementRef, private componentUtils: ComponentUtils, public labels: NovoLabelService) {} ngOnInit() { this.setItems(); } get value() { return this._value; } @Input() set value(selected) { this.itemToAdd = ''; if (selected !== this._value) { this._value = selected; this.changed.emit({ value: selected, rawValue: this.items }); this.onModelChange(selected); } } clearValue() { this.items = []; this._items.next(this.items); this.value = null; this.changed.emit({ value: this.value, rawValue: this.items }); this.onModelChange(this.value); } setItems() { this.items = []; if (this.model && Array.isArray(this.model)) { const noLabels = []; for (const value of this.model) { let label; if (this.source && this.source.format && Helpers.validateInterpolationProps(this.source.format, value)) { label = Helpers.interpolate(this.source.format, value); } if (this.source && label && label !== this.source.format) { this.items.push({ value, label, }); } else if (this.source.getLabels && typeof this.source.getLabels === 'function') { noLabels.push(value); } else if (this.source.options && Array.isArray(this.source.options)) { this.items.push(this.getLabelFromOptions(value)); } else if (this.source.categoryMap && this.source.categoryMap.size) { this.items.push(value); } else { this.items.push({ value, label: value, }); } } if (noLabels.length > 0 && this.source && this.source.getLabels && typeof this.source.getLabels === 'function') { this.source.getLabels(noLabels).then((result) => { for (const value of result) { if (value.hasOwnProperty('label')) { this.items.push({ value, label: value.label, }); } else if (this.source.options && Array.isArray(this.source.options)) { this.items.push(this.getLabelFromOptions(value)); } else { this.items.push(value); } } this._items.next(this.items); }); } } this.changed.emit({ value: this.model, rawValue: this.items }); this._items.next(this.items); } getLabelFromOptions(value) { let id = value; let optLabel = this.source.options.find((val) => val.value === value); if (!optLabel && value.hasOwnProperty('id')) { optLabel = this.source.options.find((val) => val.value === value.id); id = value.id; } return { value: id, label: optLabel ? optLabel.label : value, }; } deselectAll(event?) { this.selected = null; this.hidePreview(); } select(event?, item?) { this.blur.emit(event); this.deselectAll(); this.selected = item; this.showPreview(); } deselect(event?, item?) { this.blur.emit(event); this.deselectAll(); } onTyping(event?) { this.typing.emit(event); } onFocus(event?) { this.deselectAll(); this.element.nativeElement.classList.add('selected'); this.focus.emit(event); } add(event) { if (event && !(event instanceof Event)) { this.items.push(event); this.value = this.source && this.source.valueFormatter ? this.source.valueFormatter(this.items) : this.items.map((i) => i.value); // Set focus on the picker const input = this.element.nativeElement.querySelector('novo-picker > input'); if (input) { input.focus(); } } this._items.next(this.items); } remove(event, item) { if (event) { event.stopPropagation(); event.preventDefault(); } this.items.splice(this.items.indexOf(item), 1); this.deselectAll(); this.value = this.source && this.source.valueFormatter ? this.source.valueFormatter(this.items) : this.items.map((i) => i.value); this.changed.emit({ value: this.value.length ? this.value : '', rawValue: this.items }); this.onModelChange(this.value.length ? this.value : ''); this._items.next(this.items); } onKeyDown(event) { if (event.keyCode === KeyCodes.BACKSPACE) { if (event.target && event.target.value.length === 0 && this.items.length) { if (event) { event.stopPropagation(); event.preventDefault(); } if (this.selected) { this.remove(event, this.selected); } else { this.select(event, this.items[this.items.length - 1]); } } } } // Set touched on blur onTouched(e) { this.element.nativeElement.classList.remove('selected'); this.onModelTouched(); this.blur.emit(e); } writeValue(model: any): void { this.model = model; this.setItems(); } registerOnChange(fn: Function): void { this.onModelChange = fn; } registerOnTouched(fn: Function): void { this.onModelTouched = fn; } setDisabledState(disabled: boolean): void { this._disablePickerInput = disabled; } /** * @description This method creates an instance of the preview (called popup) and adds all the bindings to that * instance. Will reuse the popup or create a new one if it does not already exist. Will only work if there is * a previewTemplate given in the config. */ showPreview() { if (this.source.previewTemplate) { if (!this.popup) { this.popup = this.componentUtils.append(this.source.previewTemplate, this.preview); } this.popup.instance.match = this.selected; } } /** * @description - This method deletes the preview popup from the DOM. */ hidePreview() { if (this.popup) { this.popup.destroy(); this.popup = null; } } }
the_stack
import {Query} from "./Query" import {Bucket, HistogramResults, IDataSource} from "../backends/elasticsearch/Elasticsearch" import {IRelative, Time, When} from "../helpers/Time" import {Direction, TimeZone} from "./Prefs" import moment, {Moment, unitOfTime} from 'moment' import * as d3 from 'd3' interface Size { width: number height: number } interface BucketInfo { bucket: Bucket hovering: boolean date?: Date x: number y: number } export class Histogram { private margin = { left: 60, right: 30, top: 40, bottom: 40, } private heightPerTick = 20 private skipTickLabels = 4 private es: IDataSource private svg: any private g: any private svgSize: Size private innerSize: Size private chart: any private valueAxis: any private timeAxis: any private query: Query private buckets: BucketInfo[] private direction: Direction private scaleTime: any private valueScale: any private scaleBand: any private visibleRange: any private dragRange: any private visible: [Date, Date] private downloaded: [Date, Date] private drag: [Date, Date] private downloadedRange: any private tooltip: any private hoveringBucket: BucketInfo private callback: (q: Query) => void private interval: IRelative private isDragging: boolean private tz: TimeZone constructor(es: IDataSource, direction: Direction, tz: TimeZone) { this.es = es this.direction = direction this.tz = tz } setDataSource(ds: IDataSource) { this.es = ds } setCallback(f: (q: Query) => void) { this.callback = f return this } updatedQuery(q: Query) { this.callback(q) // This temporarily zooms in with the course data available until the fine data comes in, but the bars overflow past the extends, which is not too bad really. this.setVisibleRange([Time.whenToDate(this.query.startTime), Time.whenToDate(this.query.endTime)]) this.updateTimeAxis() this.updateChart() } setQuery(q: Query) { this.query = q } setDirection(direction: Direction) { this.direction = direction if (this.query !== undefined) { this.redraw() } } setTimeZone(tz: TimeZone) { this.tz = tz } setVisibleRange(range: [Date, Date]) { this.visible = range this.updateVisibleRange() } setDownloadedRange(range: [Date, Date]) { this.downloaded = range this.updateDownloadedRange() } async search(query: Query) { this.calculateSizes() const when = this.calculateBucketSize(query) this.interval = when.kind === "relative" && when as IRelative this.update(query, await this.es.histogram(query, this.interval, Intl.DateTimeFormat().resolvedOptions().timeZone)) } attach(svg: SVGElement) { this.svg = d3.select(svg) this.g = this.svg.append("g") this.downloadedRange = this.g.append("g").append("rect").attr('class', 'downloaded-range') this.visibleRange = this.g.append("g").append("rect").attr('class', 'visible-range') this.dragRange = this.g.append("g").append("rect").attr('class', 'drag-range') this.chart = this.g.append("g") this.chart = this.g.append("g") this.valueAxis = this.g.append("g") this.timeAxis = this.g.append("g") this.tooltip = d3.select("#histogram-tooltip") this.attachMouseEvents() this.attachResizeEvents() } clear() { this.buckets = [] this.updateChart() } calculateBucketSize(query: Query): When { const targetBuckets = this.innerSize.height / this.heightPerTick const ms = Time.diff(query.startTime, query.endTime).asMilliseconds() const msPerBucket = ms / targetBuckets const durations = [ [1, "ms"], [10, "ms"], [100, "ms"], [500, "ms"], [1, "s"], [10, "s"], [30, "s"], [1, "m"], [2, "m"], [5, "m"], [15, "m"], [30, "m"], [1, "h"], [2, "h"], [4, "h"], [8, "h"], [12, "h"], [1, "d"], [2, "d"], [7, "d"], [14, "d"], [1, "M"], [2, "M"], [3, "M"], [1, "y"], ] // Apply the absolute millisecond difference to the expected bucket duration. .map(i => { const dur = moment.duration(i[0], i[1] as moment.unitOfTime.Base).asMilliseconds() return [i[0], i[1], Math.abs(msPerBucket - dur)] }) // Sort by smallest delta .sort((a, b) => (a[2] > b[2]) ? 1 : -1) return Time.wrapRelative(durations[0][0] as number, durations[0][1] as unitOfTime.Base) } update(query: Query, results: HistogramResults) { this.query = query this.buckets = results.buckets.map(b => ({ bucket: b, hovering: false, x: 0, y: 0, })) this.mangleResults() this.redraw() } private redraw() { this.updateTimeAxis() this.updateValueAxis() this.updateChart() this.updateDownloadedRange() this.updateVisibleRange() this.updateDragRange() } private calculateSizes() { const rect = this.svg.node().getBoundingClientRect() this.svgSize = { width: rect.width, height: rect.height, } this.innerSize = { width: this.svgSize.width - this.margin.left - this.margin.right, height: this.svgSize.height - this.margin.top - this.margin.bottom, } } private updateTimeAxis() { this.scaleTime = (this.tz === TimeZone.UTC) ? d3.scaleUtc() : d3.scaleTime() this.scaleTime.domain([this.query.startTime, this.query.endTime].map(Time.whenToDate)).nice() if (this.direction === Direction.Down) { this.scaleTime.range([0, this.innerSize.height]) } else { this.scaleTime.range([this.innerSize.height, 0]) } const labels = d3 .axisLeft(this.scaleTime.interpolate(d3.interpolateRound)) .ticks(this.innerSize.height / this.heightPerTick / this.skipTickLabels) this.timeAxis .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`) .call(labels) let start: Moment let end: Moment if (this.buckets.length > 0) { start = moment(this.buckets[0].date) // Add an extra interval to the end for the last bar, so it doesn't overlap past the end. end = Time.whenToMoment(Time.whenAdd( this.buckets[this.buckets.length - 1].bucket.when, Time.whenToDuration(this.interval) )) } else { start = Time.whenToMoment(this.query.startTime) end = Time.whenToMoment(this.query.endTime) } if (this.tz === TimeZone.UTC) { start = start.utc() end = end.utc() } this.scaleBand = d3.scaleBand() .domain(this.buckets.map(b => b.date.toISOString())) .range([ this.scaleTime(start), this.scaleTime(end), ]) } private updateValueAxis() { this.valueScale = d3.scaleLinear() .domain([0, d3.max(this.buckets, d => d.bucket.count)]) .range([0, this.innerSize.width]) const labels = d3 .axisBottom(this.valueScale.interpolate(d3.interpolateRound)) .ticks(2) this.valueAxis .attr('transform', `translate(${this.margin.left}, ${this.margin.top + this.innerSize.height})`) .call(labels) } private updateChart() { if (this.buckets.length === 0) { const c = this.chart .selectAll("rect") .data(this.buckets) c.exit().remove() return } // For some reason d3.scaleBand overlaps bars in millisecond intervals, // so we fall back to using d3.scaleTime. const isScaleBand = (this.interval.unit !== "millisecond") const barStep = (isScaleBand) ? this.scaleBand.step() : Math.abs(this.scaleTime(this.buckets[0].date.toISOString()) - this.scaleTime(this.buckets[this.buckets.length - 1].date.toISOString())) / this.buckets.length const f = el => { el.attr('x', this.margin.left) .attr('width', d => this.valueScale(d.bucket.count)) .attr('y', d => { const scale = isScaleBand ? this.scaleBand : this.scaleTime const y = scale(d.date.toISOString()) + this.margin.top d.y = y if (this.direction === Direction.Down) { d.y += barStep } return y }) .attr('height', () => { if (isScaleBand) { return this.scaleBand.bandwidth() } else { return barStep } }) .attr('class', d => d.hovering ? 'hovering' : '') } const chart = this.chart .selectAll("rect") .data(this.buckets) .call(f) chart.enter().append("rect").call(f) chart.exit().remove() } private updateVisibleRange() { this.rangeBox(this.visibleRange, this.visible) } private updateDownloadedRange() { this.rangeBox(this.downloadedRange, this.downloaded) } private updateDragRange() { this.rangeBox(this.dragRange, this.drag) } private rangeBox(el, range?: [Date, Date]) { if (range === undefined || this.scaleTime === undefined) { el.style('visibility', 'hidden') return } const y0 = this.scaleTime(range[0]) const y1 = this.scaleTime(range[1]) const y = (y0 < y1) ? y0 : y1 const height = Math.abs(y0 - y1) el .style('visibility', 'visible') .attr('x', 0) .attr('width', this.svgSize.width) .attr('y', this.margin.top + y) // +1 to make it at least slightly visible .attr('height', height + 1) } private mangleResults() { this.buckets = this.buckets.map(r => ({ ...r, // TODO: Separate bucket from date, maybe a local map. date: Time.whenToDate(r.bucket.when), })) } private attachMouseEvents() { this.svg .on('mousemove', this.mouseMove) .on('mouseout', this.hideTooltip) .call(d3.drag() .on('start', this.dragStart) .on('drag', this.dragMove) .on('end', this.dragEndOrClick) ) } dragStart = () => { const [ts] = this.mouseEventInfo() this.drag = [ts, ts] this.updateDragRange() this.isDragging = true this.hoverBucket(undefined) } dragMove = () => { const [ts] = this.mouseEventInfo() this.drag[1] = ts this.updateDragRange() this.mouseMove() } dragEndOrClick = () => { this.isDragging = false // Check if we just clicked instead of dragged const pixelsMoved = Math.abs(this.scaleTime(this.drag[0].getTime()) - this.scaleTime(this.drag[1].getTime())) if (pixelsMoved < 3) { this.drag = undefined this.onClick() return } if (this.drag[0].getTime() > this.drag[1].getTime()) { this.drag = [this.drag[1], this.drag[0]] } this.query.startTime = Time.wrapDate(this.drag[0]) this.query.endTime = Time.wrapDate(this.drag[1]) this.drag = undefined this.updatedQuery(this.query) this.updateDragRange() } onClick = () => { const [, bucket] = this.mouseEventInfo() this.hoverBucket(bucket) this.query.startTime = this.hoveringBucket.bucket.when this.query.endTime = Time.whenAdd(this.hoveringBucket.bucket.when, Time.whenToDuration(this.interval)) this.updatedQuery(this.query) } mouseEventInfo(): [Date, BucketInfo] { if (this.scaleTime === undefined) { return [undefined, undefined] } const coordinates = d3.mouse(this.svg.node()) const relY = coordinates[1] // 3 is some sort of magic number i don't know where it's coming from // It helps align the mouse position to the actual position in the time scale const ts = this.scaleTime.invert(relY - this.margin.top - 3) const bucket = this.buckets.find(b => { const found = b.y > relY return this.direction === Direction.Down ? found : !found }) return [ts, bucket] } mouseMove = () => { const height = this.tooltip.node().getBoundingClientRect().height const [ts, bucket] = this.mouseEventInfo() if (ts === undefined) { this.tooltipVisible(false) this.hoverBucket(undefined) return } const y = this.scaleTime(ts) let text = '' if (this.isDragging) { let startDate = this.drag[0] let endDate = this.drag[1] if (this.direction === Direction.Up) { [startDate, endDate] = [endDate, startDate] } if (startDate.getTime() > endDate.getTime()) { [startDate, endDate] = [endDate, startDate] } const start = Time.wrapDate(startDate) const end = Time.wrapDate(endDate) const diff = Time.diff(start, end) const countInBuckets = this.buckets .filter(b => b.date.getTime() >= startDate.getTime() && b.date.getTime() <= endDate.getTime()) .map(b => b.bucket.count) .reduce((a, b) => a + b, 0) text = this.tooltipText(start, end, diff, countInBuckets) } else { this.hoverBucket(bucket) if (bucket === undefined) { this.tooltipVisible(false) return } const duration = Time.whenToDuration(this.interval) text = this.tooltipText(this.hoveringBucket.bucket.when, Time.whenAdd(this.hoveringBucket.bucket.when, duration), duration, this.hoveringBucket.bucket.count) } this.tooltipVisible(true) this.tooltip .style("top", `${y - height / 2 + this.margin.top}px`) .html(text) } formatDate(when: When): string { if (when.kind !== "moment") { return Time.whenToText(when) } const m = (this.tz === TimeZone.UTC) ? when.moment.utc() : when.moment return m.format("YYYY-MM-DD HH:mm:ss.SSSZZ") } tooltipText(start: When, end: When, duration: moment.Duration, count: number): string { return ` ${this.formatDate(start)}<br/> ${this.formatDate(end)}<br/> ${Time.getRangeHuman(duration, 2)} <b>${nFormatter(count, 2)}</b> ` } private hoverBucket(bucket: BucketInfo) { if (this.hoveringBucket === bucket) { return } if (this.hoveringBucket !== undefined) { // TODO: Move this out of Bucket into its own type, similar to "date". this.hoveringBucket.hovering = false } if (bucket !== undefined) { bucket.hovering = true } this.hoveringBucket = bucket this.updateChart() } hideTooltip = () => { this.tooltipVisible(false) } tooltipVisible(visible: boolean) { this.tooltip.style("display", visible ? "block" : "none") } // A resize basically needs to recalculate sizes and request new buckets. // We don't want to spam many of them so do a debounce. attachResizeEvents() { const f = () => { if (!this.query) { return } this.search(this.query) } let timer: NodeJS.Timeout window.addEventListener('resize', () => { clearTimeout(timer) timer = setTimeout(f, 500) }) } } // https://stackoverflow.com/a/9462382/11125 // Modified to keep the fixed amount of digits, except when under 1k function nFormatter(num, digits) { const si = [ {value: 1, symbol: ""}, {value: 1E3, symbol: "k"}, {value: 1E6, symbol: "M"}, {value: 1E9, symbol: "G"}, {value: 1E12, symbol: "T"}, {value: 1E15, symbol: "P"}, {value: 1E18, symbol: "E"} ] let i for (i = si.length - 1; i > 0; i--) { if (num >= si[i].value) { break } } if (i === 0) { digits = 0 } return (num / si[i].value).toFixed(digits) + si[i].symbol }
the_stack
* 音频流信息。 */ export interface AudioStreamInfo { /** * 码率,单位:bps。 */ Bitrate: number /** * 采样率,单位:hz。 */ SamplingRate: number /** * 编码格式。 */ Codec: string } /** * ModifyMaterial返回参数结构体 */ export interface ModifyMaterialResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteProject请求参数结构体 */ export interface DeleteProjectRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 项目 Id。 */ ProjectId: string /** * 操作者。填写用户的 Id,用于标识调用者及校验对项目删除操作权限。 */ Operator?: string } /** * ExportVideoByVideoSegmentationData返回参数结构体 */ export interface ExportVideoByVideoSegmentationDataResponse { /** * 任务 Id。 */ TaskId: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ImportMaterial返回参数结构体 */ export interface ImportMaterialResponse { /** * 媒体 Id。 */ MaterialId: string /** * 媒体文预处理任务 ID,如果未指定发起预处理任务则为空。 */ PreProcessTaskId: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 云转推项目输入信息。 */ export interface StreamConnectProjectInput { /** * 云转推主输入源信息。 */ MainInput?: StreamInputInfo /** * 云转推备输入源信息。 */ BackupInput?: StreamInputInfo /** * 云转推输出源信息。 */ Outputs?: Array<StreamConnectOutput> } /** * DescribeAccounts请求参数结构体 */ export interface DescribeAccountsRequest { /** * 平台唯一标识。 */ Platform: string /** * 手机号码。 */ Phone?: string /** * 分页返回的起始偏移量,默认值:0。 */ Offset?: number /** * 分页返回的记录条数,默认值:10,最大值:20。 */ Limit?: number } /** * ExportVideoByVideoSegmentationData请求参数结构体 */ export interface ExportVideoByVideoSegmentationDataRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 视频拆条项目 Id 。 */ ProjectId: string /** * 指定需要导出的智能拆条片段的组 Id 。 */ SegmentGroupId: string /** * 指定需要导出的智能拆条片段 Id 集合。 */ SegmentIds: Array<string> /** * 导出模板 Id,目前不支持自定义创建,只支持下面的预置模板 Id。 <li>10:分辨率为 480P,输出视频格式为 MP4;</li> <li>11:分辨率为 720P,输出视频格式为 MP4;</li> <li>12:分辨率为 1080P,输出视频格式为 MP4。</li> */ Definition: number /** * 导出目标。 <li>CME:云剪,即导出为云剪素材;</li> <li>VOD:云点播,即导出为云点播媒资。</li> */ ExportDestination: string /** * 导出的云剪媒体信息。当导出目标为 CME 时必填。 */ CMEExportInfo?: CMEExportInfo /** * 导出的云点播媒资信息。当导出目标为 VOD 时必填。 */ VODExportInfo?: VODExportInfo /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * 转场信息 */ export interface MediaTransitionItem { /** * 转场 Id 。暂只支持一个转场。 */ TransitionId: string /** * 转场持续时间,单位为秒,默认为2秒。进行转场处理的两个媒体片段,第二个片段在轨道上的起始时间会自动进行调整,设置为前面一个片段的结束时间减去转场的持续时间。 */ Duration?: number } /** * DescribeTeams返回参数结构体 */ export interface DescribeTeamsResponse { /** * 符合条件的记录总数。 */ TotalCount?: number /** * 团队列表。 */ TeamSet?: Array<TeamInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeTaskDetail返回参数结构体 */ export interface DescribeTaskDetailResponse { /** * 任务状态,取值有: <li>PROCESSING:处理中:</li> <li>SUCCESS:成功;</li> <li>FAIL:失败。</li> */ Status: string /** * 任务进度,取值为:0~100。 */ Progress: number /** * 错误码。 <li>0:成功;</li> <li>其他值:失败。</li> */ ErrCode: number /** * 错误信息。 */ ErrMsg: string /** * 任务类型,取值有: <li>VIDEO_EDIT_PROJECT_EXPORT:视频编辑项目导出。</li> */ TaskType: string /** * 导出项目输出信息。 注意:此字段可能返回 null,表示取不到有效值。 */ VideoEditProjectOutput: VideoEditProjectOutput /** * 创建时间,格式按照 ISO 8601 标准表示。 */ CreateTime: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ExportVideoEditProject请求参数结构体 */ export interface ExportVideoEditProjectRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 项目 Id。 */ ProjectId: string /** * 导出模板 Id,目前不支持自定义创建,只支持下面的预置模板 Id。 <li>10:分辨率为 480P,输出视频格式为 MP4;</li> <li>11:分辨率为 720P,输出视频格式为 MP4;</li> <li>12:分辨率为 1080P,输出视频格式为 MP4。</li> */ Definition: number /** * 导出目标。 <li>CME:云剪,即导出为云剪媒体;</li> <li>VOD:云点播,即导出为云点播媒资。</li> */ ExportDestination: string /** * 视频封面图片文件(如 jpeg, png 等)进行 Base64 编码后的字符串,仅支持 gif、jpeg、png 三种图片格式,原图片文件不能超过2 M大 小。 */ CoverData?: string /** * 导出的云剪媒体信息。当导出目标为 CME 时必填。 */ CMEExportInfo?: CMEExportInfo /** * 导出的云点播媒资信息。当导出目标为 VOD 时必填。 */ VODExportInfo?: VODExportInfo /** * 操作者。填写用户的 Id,用于标识调用者及校验项目导出权限。 */ Operator?: string } /** * 分类信息 */ export interface ClassInfo { /** * 归属者。 */ Owner: Entity /** * 分类路径。 */ ClassPath: string } /** * ModifyProject返回参数结构体 */ export interface ModifyProjectResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 音频轨道上的音频片段信息。 */ export interface AudioTrackItem { /** * 音频媒体来源类型,取值有: <ul> <li>VOD :素材来源于云点播文件 ;</li> <li>CME :视频来源于制作云媒体文件 ;</li> <li>EXTERNAL :视频来源于媒资绑定,如果媒体不是存储在腾讯云点播中或者云创中,都需要使用媒资绑定。</li> </ul> */ SourceType: string /** * 音频媒体,可取值为: <ul> <li>当 SourceType 为 VOD 时,参数填云点播 FileId ;</li> <li>当 SourceType 为 CME 时,参数填云剪媒体 Id;</li> <li>当 SourceType 为 EXTERNAL 时,目前仅支持外部媒体 URL(如`https://www.example.com/a.mp3`),参数填写规则请参见注意事项。</li> </ul> 注意: <li>当 SourceType 为 EXTERNAL 并且媒体 URL Scheme 为 `https` 时(如:`https://www.example.com/a.mp3`),参数为:`1000000:www.example.com/a.mp3`。</li> <li>当 SourceType 为 EXTERNAL 并且媒体 URL Scheme 为 `http` 时(如:`http://www.example.com/b.mp3`),参数为:`1000001:www.example.com/b.mp3`。</li> */ SourceMedia: string /** * 音频片段取自媒体文件的起始时间,单位为秒。0 表示从媒体开始位置截取。默认为0。 */ SourceMediaStartTime?: number /** * 音频片段的时长,单位为秒。默认和媒体本身长度一致,表示截取全部媒体。 */ Duration?: number } /** * 云转推项目信息,包含输入源、输出源、当前转推开始时间等信息。 */ export interface StreamConnectProjectInfo { /** * 转推项目状态,取值有: <li>Working :转推中;</li> <li>Idle :空闲中。</li> */ Status: string /** * 当前转推输入源,取值有: <li>Main :主输入源;</li> <li>Backup :备输入源。</li> */ CurrentInputEndpoint: string /** * 当前转推开始时间, 采用 [ISO 日期格式](https://cloud.tencent.com/document/product/266/11732#I)。仅 Status 取值 Working 时有效。 */ CurrentStartTime: string /** * 当前转推计划结束时间, 采用 [ISO 日期格式](https://cloud.tencent.com/document/product/266/11732#I)。仅 Status 取值 Working 时有效。 */ CurrentStopTime: string /** * 上一次转推结束时间, 采用 [ISO 日期格式](https://cloud.tencent.com/document/product/266/11732#I)。仅 Status 取值 Idle 时有效。 */ LastStopTime: string /** * 云转推主输入源。 注意:此字段可能返回 null,表示取不到有效值。 */ MainInput: StreamInputInfo /** * 云转推备输入源。 注意:此字段可能返回 null,表示取不到有效值。 */ BackupInput: StreamInputInfo /** * 云转推输出源。 */ OutputSet: Array<StreamConnectOutputInfo> } /** * 整型范围 */ export interface IntegerRange { /** * 按整形代表值的下限检索。 */ LowerBound: number /** * 按整形代表值的上限检索。 */ UpperBound: number } /** * SearchMaterial请求参数结构体 */ export interface SearchMaterialRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 指定搜索空间,数组长度不得超过5。 */ SearchScopes: Array<SearchScope> /** * 媒体类型,取值: <li>AUDIO:音频;</li> <li>VIDEO:视频 ;</li> <li>IMAGE:图片。</li> */ MaterialTypes?: Array<string> /** * 搜索文本,模糊匹配媒体名称或描述信息,匹配项越多,匹配度越高,排序越优先。长度限制:15个字符。 */ Text?: string /** * 按画质检索,取值为:LD/SD/HD/FHD/2K/4K。 */ Resolution?: string /** * 按媒体时长检索,单位s。 */ DurationRange?: IntegerRange /** * 按照媒体创建时间检索。 */ CreateTimeRange?: TimeRange /** * 按标签检索,填入检索的标签名。 */ Tags?: Array<string> /** * 排序方式。Sort.Field 可选值:CreateTime。指定 Text 搜索时,将根据匹配度排序,该字段无效。 */ Sort?: SortBy /** * 偏移量。默认值:0。 */ Offset?: number /** * 返回记录条数,默认值:50。 */ Limit?: number /** * 操作者。填写用户的 Id,用于标识调用者及校验媒体访问权限。 */ Operator?: string } /** * DeleteTeam返回参数结构体 */ export interface DeleteTeamResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 云转推输出源。 */ export interface StreamConnectOutput { /** * 云转推输出源标识,转推项目级别唯一。若不填则由后端生成。 */ Id?: string /** * 云转推输出源名称。 */ Name?: string /** * 云转推输出源类型,取值: <li>URL :URL类型</li> 不填默认为URL类型。 */ Type?: string /** * 云转推推流地址。 */ PushUrl?: string } /** * CopyProject请求参数结构体 */ export interface CopyProjectRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 被复制的项目 ID。 */ ProjectId: string /** * 复制后的项目名称,不填为原项目名称+"(副本)"。 */ Name?: string /** * 复制后的项目归属者,不填为原项目归属者。 */ Owner?: Entity /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * 搜索空间 */ export interface SearchScope { /** * 分类路径归属。 */ Owner: Entity /** * 按分类路径检索。 不填则默认按根分类路径检索。 */ ClassPath?: string } /** * RevokeResourceAuthorization返回参数结构体 */ export interface RevokeResourceAuthorizationResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * HandleStreamConnectProject请求参数结构体 */ export interface HandleStreamConnectProjectRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 云转推项目Id 。 */ ProjectId: string /** * 请参考 [操作类型](#Operation) */ Operation: string /** * 转推输入源操作参数。具体操作方式详见 [操作类型](#Operation) 及下文示例。 */ InputInfo?: StreamInputInfo /** * 主备输入源标识,取值有: <li> Main :主源;</li> <li> Backup :备源。</li> */ InputEndpoint?: string /** * 转推输出源操作参数。具体操作方式详见 [操作类型](#Operation) 及下文示例。 */ OutputInfo?: StreamConnectOutput /** * 云转推当前预计结束时间,采用 [ISO 日期格式](https://cloud.tencent.com/document/product/266/11732#I)。具体操作方式详见 [操作类型](#Operation) 及下文示例。 */ CurrentStopTime?: string } /** * 项目信息。 */ export interface ProjectInfo { /** * 项目 Id。 */ ProjectId: string /** * 项目名称。 */ Name: string /** * 画布宽高比。 */ AspectRatio: string /** * 项目类别,取值有: <li>VIDEO_EDIT:视频编辑。</li> <li>SWITCHER:导播台。</li> <li>VIDEO_SEGMENTATION:视频拆条。</li> <li>STREAM_CONNECT:云转推。</li> <li>RECORD_REPLAY:录制回放。</li> */ Category: string /** * 归属者。 */ Owner: Entity /** * 项目封面图片地址。 */ CoverUrl: string /** * 云转推项目信息,仅当项目类别取值 STREAM_CONNECT 时有效。 注意:此字段可能返回 null,表示取不到有效值。 */ StreamConnectProjectInfo: StreamConnectProjectInfo /** * 项目创建时间,格式按照 ISO 8601 标准表示。 */ CreateTime: string /** * 项目更新时间,格式按照 ISO 8601 标准表示。 */ UpdateTime: string } /** * 视频轨的视频片段信息。 */ export interface VideoTrackItem { /** * 视频媒体来源类型,取值有: <ul> <li>VOD :媒体来源于云点播文件 。</li> <li>CME :视频来源制作云媒体文件。</li> <li>EXTERNAL :视频来源于媒资绑定,如果媒体不是存储在腾讯云点播中或者云创中,都需要使用媒资绑定。</li> </ul> */ SourceType: string /** * 视频媒体,可取值为: <ul> <li>当 SourceType 为 VOD 时,参数填云点播 FileId ;</li> <li>当 SourceType 为 CME 时,参数填云剪媒体 Id;</li> <li>当 SourceType 为 EXTERNAL 时,目前仅支持外部媒体 URL(如`https://www.example.com/a.mp4`),参数填写规则请参见注意事项。</li> </ul> 注意: <li>当 SourceType 为 EXTERNAL 并且媒体 URL Scheme 为 `https` 时(如:`https://www.example.com/a.mp4`),参数为:`1000000:www.example.com/a.mp4`。</li> <li>当 SourceType 为 EXTERNAL 并且媒体 URL Scheme 为 `http` 时(如:`http://www.example.com/b.mp4`),参数为:`1000001:www.example.com/b.mp4`。</li> */ SourceMedia: string /** * 视频片段取自媒体文件的起始时间,单位为秒。默认为0。 */ SourceMediaStartTime?: number /** * 视频片段时长,单位为秒。默认取视频媒体文件本身长度,表示截取全部媒体文件。如果源文件是图片,Duration需要大于0。 */ Duration?: number /** * 视频片段原点距离画布原点的水平位置。支持 %、px 两种格式: <li>当字符串以 % 结尾,表示视频片段 XPos 为画布宽度指定百分比的位置,如 10% 表示 XPos 为画布口宽度的 10%。</li> <li>当字符串以 px 结尾,表示视频片段 XPos 单位为像素,如 100px 表示 XPos 为100像素。</li> 默认值:0px。 */ XPos?: string /** * 视频片段原点距离画布原点的垂直位置。支持 %、px 两种格式: <li>当字符串以 % 结尾,表示视频片段 YPos 为画布高度指定百分比的位置,如 10% 表示 YPos 为画布高度的 10%。</li> <li>当字符串以 px 结尾,表示视频片段 YPos 单位为像素,如 100px 表示 YPos 为100像素。</li> 默认值:0px。 */ YPos?: string /** * 视频原点位置,取值有: <li>Center:坐标原点为中心位置,如画布中心。</li> 默认值 :Center。 */ CoordinateOrigin?: string /** * 视频片段的高度。支持 %、px 两种格式: <li>当字符串以 % 结尾,表示视频片段 Height 为画布高度的百分比大小,如 10% 表示 Height 为画布高度的 10%;</li> <li>当字符串以 px 结尾,表示视频片段 Height 单位为像素,如 100px 表示 Height 为100像素;</li> <li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li> <li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li> <li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li> */ Height?: string /** * 视频片段的宽度。支持 %、px 两种格式: <li>当字符串以 % 结尾,表示视频片段 Width 为画布宽度的百分比大小,如 10% 表示 Width 为画布宽度的 10%;</li> <li>当字符串以 px 结尾,表示视频片段 Width 单位为像素,如 100px 表示 Width 为100像素;</li> <li>当 Width、Height 均为空,则 Width 和 Height 取视频媒体文件本身的 Width、Height;</li> <li>当 Width 为空,Height 非空,则 Width 按比例缩放;</li> <li>当 Width 非空,Height 为空,则 Height 按比例缩放。</li> */ Width?: string } /** * DeleteTeam请求参数结构体 */ export interface DeleteTeamRequest { /** * 平台名称,指定访问平台。 */ Platform: string /** * 要删除的团队 ID。 */ TeamId: string /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * DescribeTeams请求参数结构体 */ export interface DescribeTeamsRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 团队 ID 列表,限30个。若不填,则默认获取平台下所有团队。 */ TeamIds?: Array<string> /** * 分页偏移量,默认值:0。 */ Offset?: number /** * 返回记录条数,默认值:20,最大值:30。 */ Limit?: number } /** * 链接类型的素材信息 */ export interface LinkMaterial { /** * 链接类型取值: <li>CLASS: 分类链接;</li> <li> MATERIAL:素材链接。</li> */ LinkType: string /** * 链接状态取值: <li> Normal:正常 ;</li> <li>NotFound:链接目标不存在;</li> <li>Forbidden:无权限。</li> */ LinkStatus: string /** * 素材链接详细信息,当LinkType="MATERIAL"时有值。 注意:此字段可能返回 null,表示取不到有效值。 */ LinkMaterialInfo: LinkMaterialInfo /** * 分类链接目标信息,当LinkType=“CLASS”时有值。 注意:此字段可能返回 null,表示取不到有效值。 */ LinkClassInfo: ClassInfo } /** * 导播台项目输入信息 */ export interface SwitcherProjectInput { /** * 导播台停止时间,格式按照 ISO 8601 标准表示。若不填,该值默认为当前时间加七天。 */ StopTime?: string /** * 导播台主监输出配置信息。若不填,默认输出 720P。 */ PgmOutputConfig?: SwitcherPgmOutputConfig } /** * FlattenListMedia请求参数结构体 */ export interface FlattenListMediaRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 媒体分类路径,例如填写"/a/b",则代表平铺该分类路径下及其子分类路径下的媒体信息。 */ ClassPath: string /** * 媒体分类的归属者。 */ Owner: Entity /** * 分页偏移量,默认值:0。 */ Offset?: number /** * 返回记录条数,默认值:10,最大值:50。 */ Limit?: number /** * 操作者。填写用户的 Id,用于标识调用者及校验媒体访问权限。 */ Operator?: string } /** * 直播推流信息,包括推流地址有效时长,云剪后端生成直播推流地址。 */ export interface RtmpPushInputInfo { /** * 直播推流地址有效期,单位:秒 。 */ ExpiredSecond: number /** * 直播推流地址,入参不填默认由云剪生成。 */ PushUrl?: string } /** * 音频素材信息 */ export interface AudioMaterial { /** * 素材元信息。 */ MetaData: MediaMetaData /** * 素材媒体文件的播放 URL 地址。 */ MaterialUrl: string /** * 素材媒体文件的封面图片地址。 */ CoverUrl: string /** * 素材状态。 注意:此字段可能返回 null,表示取不到有效值。 */ MaterialStatus: MaterialStatus /** * 素材媒体文件的原始 URL 地址。 */ OriginalUrl: string /** * 云点播媒资 FileId。 */ VodFileId: string } /** * 添加的团队成员信息 */ export interface AddMemberInfo { /** * 团队成员 ID。 */ MemberId: string /** * 团队成员备注。 */ Remark?: string /** * 团队成员角色,不填则默认添加普通成员。可选值: <li>Admin:团队管理员;</li> <li>Member:普通成员。</li> */ Role?: string } /** * 用于描述资源的归属,归属者为个人或者团队。 */ export interface Entity { /** * 类型,取值有: <li>PERSON:个人。</li> <li>TEAM:团队。</li> */ Type: string /** * Id,当 Type=PERSON,取值为用户 Id,当 Type=TEAM,取值为团队 Id。 */ Id: string } /** * 团队信息 */ export interface TeamInfo { /** * 团队 ID。 */ TeamId: string /** * 团队名称。 */ Name: string /** * 团队成员个数 */ MemberCount?: number /** * 团队创建时间,格式按照 ISO 8601 标准表示。 */ CreateTime?: string /** * 团队最后更新时间,格式按照 ISO 8601 标准表示。 */ UpdateTime: string } /** * ExportVideoByEditorTrackData请求参数结构体 */ export interface ExportVideoByEditorTrackDataRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 导出模板 Id,目前不支持自定义创建,只支持下面的预置模板 Id。 <li>10:分辨率为 480P,输出视频格式为 MP4;</li> <li>11:分辨率为 720P,输出视频格式为 MP4;</li> <li>12:分辨率为 1080P,输出视频格式为 MP4。</li> */ Definition: number /** * 导出目标。 <li>CME:云剪,即导出为云剪素材;</li> <li>VOD:云点播,即导出为云点播媒资。</li> */ ExportDestination: string /** * 在线编辑轨道数据。轨道数据相关介绍,请查看 [视频合成协议](https://cloud.tencent.com/document/product/1156/51225)。 */ TrackData: string /** * 视频封面图片文件(如 jpeg, png 等)进行 Base64 编码后的字符串,仅支持 gif、jpeg、png 三种图片格式,原图片文件不能超过2 M大 小。 */ CoverData?: string /** * 导出的云剪媒体信息。当导出目标为 CME 时必填。 */ CMEExportInfo?: CMEExportInfo /** * 导出的云点播媒资信息。当导出目标为 VOD 时必填。 */ VODExportInfo?: VODExportInfo /** * 操作者。填写用户的 Id,用于标识调用者及校验导出操作权限。 */ Operator?: string } /** * 素材标签信息 */ export interface MaterialTagInfo { /** * 标签类型,取值为: <li>PRESET:预置标签;</li> */ Type: string /** * 标签 Id 。当标签类型为 PRESET 时,标签 Id 为预置标签 Id 。 */ Id: string /** * 标签名称。 */ Name: string } /** * 项目导出信息。 */ export interface VideoEditProjectOutput { /** * 导出的云剪素材 MaterialId,仅当导出为云剪素材时有效。 */ MaterialId: string /** * 云点播媒资 FileId。 */ VodFileId: string /** * 导出的媒资 URL。 */ URL: string /** * 元信息。 注意:此字段可能返回 null,表示取不到有效值。 */ MetaData: MediaMetaData } /** * CreateProject请求参数结构体 */ export interface CreateProjectRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 项目名称,不可超过30个字符。 */ Name: string /** * 项目归属者。 */ Owner: Entity /** * 项目类别,取值有: <li>VIDEO_EDIT:视频编辑。</li> <li>SWITCHER:导播台。</li> <li>VIDEO_SEGMENTATION:视频拆条。</li> <li>STREAM_CONNECT:云转推。</li> <li>RECORD_REPLAY:录制回放。</li> */ Category: string /** * 项目模式,一个项目可以有多种模式并相互切换。 当 Category 为 VIDEO_EDIT 时,可选模式有: <li>Default:默认模式。</li> <li>VideoEditTemplate:视频编辑模板制作模式。</li> */ Mode?: string /** * 画布宽高比。 该字段已经废弃,请使用具体项目输入中的 AspectRatio 字段。 */ AspectRatio?: string /** * 项目描述信息。 */ Description?: string /** * 导播台信息,仅当项目类型为 SWITCHER 时必填。 */ SwitcherProjectInput?: SwitcherProjectInput /** * 直播剪辑信息,暂未开放,请勿使用。 */ LiveStreamClipProjectInput?: LiveStreamClipProjectInput /** * 视频编辑信息,仅当项目类型为 VIDEO_EDIT 时必填。 */ VideoEditProjectInput?: VideoEditProjectInput /** * 视频拆条信息,仅当项目类型为 VIDEO_SEGMENTATION 时必填。 */ VideoSegmentationProjectInput?: VideoSegmentationProjectInput /** * 云转推项目信息,仅当项目类型为 STREAM_CONNECT 时必填。 */ StreamConnectProjectInput?: StreamConnectProjectInput /** * 录制回放项目信息,仅当项目类型为 RECORD_REPLAY 时必填。 */ RecordReplayProjectInput?: RecordReplayProjectInput } /** * ModifyMaterial请求参数结构体 */ export interface ModifyMaterialRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 媒体 Id。 */ MaterialId: string /** * 媒体或分类路径归属。 */ Owner?: Entity /** * 媒体名称,不能超过30个字符。 */ Name?: string /** * 媒体分类路径,例如填写"/a/b",则代表该媒体存储的路径为"/a/b"。若修改分类路径,则 Owner 字段必填。 */ ClassPath?: string /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * 授权者 */ export interface Authorizer { /** * 授权者类型,取值有: <li>PERSON:个人。</li> <li>TEAM:团队。</li> */ Type: string /** * Id,当 Type=PERSON,取值为用户 Id。当Type=TEAM,取值为团队 ID。 */ Id: string } /** * DescribePlatforms返回参数结构体 */ export interface DescribePlatformsResponse { /** * 符合搜索条件的记录总数。 */ TotalCount?: number /** * 平台信息列表。 */ PlatformInfoSet?: Array<PlatformInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeTasks请求参数结构体 */ export interface DescribeTasksRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 项目 Id。 */ ProjectId?: string /** * 任务类型集合,取值有: <li>VIDEO_EDIT_PROJECT_EXPORT:视频编辑项目导出。</li> */ TaskTypeSet?: Array<string> /** * 任务状态集合,取值有: <li>PROCESSING:处理中;</li> <li>SUCCESS:成功;</li> <li>FAIL:失败。</li> */ StatusSet?: Array<string> /** * 分页返回的起始偏移量,默认值:0。 */ Offset?: number /** * 分页返回的记录条数,默认值:10。最大值:20。 */ Limit?: number /** * 操作者。填写用户的 Id,用于标识调用者及校验对任务的访问权限。 */ Operator?: string } /** * 媒体轨道的片段信息 */ export interface MediaTrackItem { /** * 片段类型。取值有: <li>Video:视频片段;</li> <li>Audio:音频片段;</li> <li>Empty:空白片段;</li> <li>Transition:转场。</li> */ Type: string /** * 视频片段,当 Type = Video 时有效。 */ VideoItem?: VideoTrackItem /** * 音频片段,当 Type = Audio 时有效。 */ AudioItem?: AudioTrackItem /** * 空白片段,当 Type = Empty 时有效。空片段用于时间轴的占位。<li>如需要两个音频片段之间有一段时间的静音,可以用 EmptyTrackItem 来进行占位。</li> <li>使用 EmptyTrackItem 进行占位,来定位某个Item。</li> */ EmptyItem?: EmptyTrackItem /** * 转场,当 Type = Transition 时有效。 */ TransitionItem?: MediaTransitionItem } /** * 新文件生成事件 */ export interface StorageNewFileCreatedEvent { /** * 云点播文件 Id。 */ FileId: string /** * 媒体 Id。 */ MaterialId: string /** * 操作者 Id。 */ Operator: string /** * 操作类型,可取值为: <li>Upload:上传;</li> <li>PullUpload:拉取上传;</li> <li>Record:直播录制。</li> */ OperationType: string /** * 媒体归属。 */ Owner: Entity /** * 媒体分类路径。 */ ClassPath: string } /** * DescribeLoginStatus请求参数结构体 */ export interface DescribeLoginStatusRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 用户 Id 列表,N 从 0 开始取值,最大 19。 */ UserIds: Array<string> } /** * 轨道信息 */ export interface MediaTrack { /** * 轨道类型,取值有: <ul> <li>Video :视频轨道。视频轨道由以下 Item 组成:<ul><li>VideoTrackItem</li><li>EmptyTrackItem</li><li>MediaTransitionItem</li></ul> </li> <li>Audio :音频轨道。音频轨道由以下 Item 组成:<ul><li>AudioTrackItem</li><li>EmptyTrackItem</li></ul> </li> </ul> */ Type: string /** * 轨道上的媒体片段列表。 */ TrackItems: Array<MediaTrackItem> } /** * DeleteLoginStatus返回参数结构体 */ export interface DeleteLoginStatusResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 微博发布信息。 */ export interface WeiboPublishInfo { /** * 视频发布标题。 */ Title?: string /** * 视频发布描述信息。 */ Description?: string /** * 微博可见性,可取值为: <li>Public:公开,所有人可见;</li> <li>Private:私有,仅自己可见。</li> 默认为 Public,所有人可见。 */ Visible?: string } /** * 用于描述资源 */ export interface Resource { /** * 类型,取值有: <li>MATERIAL:素材。</li> <li>CLASS:分类。</li> */ Type: string /** * 资源 Id,当 Type 为 MATERIAL 时,取值为素材 Id;当 Type 为 CLASS 时,取值为分类路径 ClassPath。 */ Id: string } /** * CreateLink返回参数结构体 */ export interface CreateLinkResponse { /** * 新建链接的媒体 Id。 */ MaterialId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ExportVideoByTemplate返回参数结构体 */ export interface ExportVideoByTemplateResponse { /** * 导出任务 Id。 */ TaskId: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 输入流信息。 */ export interface StreamInputInfo { /** * 流输入类型,取值: <li>VodPull : 点播拉流;</li> <li>LivePull :直播拉流;</li> <li>RtmpPush : 直播推流。</li> */ InputType: string /** * 点播拉流信息,当 InputType = VodPull 时必填。 注意:此字段可能返回 null,表示取不到有效值。 */ VodPullInputInfo?: VodPullInputInfo /** * 直播拉流信息,当 InputType = LivePull 时必填。 注意:此字段可能返回 null,表示取不到有效值。 */ LivePullInputInfo?: LivePullInputInfo /** * 直播推流信息,当 InputType = RtmpPush 时必填。 注意:此字段可能返回 null,表示取不到有效值。 */ RtmpPushInputInfo?: RtmpPushInputInfo } /** * ListMedia返回参数结构体 */ export interface ListMediaResponse { /** * 符合条件的媒体记录总数。 */ MaterialTotalCount: number /** * 浏览分类路径下的媒体列表信息。 */ MaterialInfoSet: Array<MaterialInfo> /** * 浏览分类路径下的一级子类。 */ ClassInfoSet: Array<ClassInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * SearchMaterial返回参数结构体 */ export interface SearchMaterialResponse { /** * 符合记录总条数。 */ TotalCount: number /** * 媒体信息,仅返回基础信息。 */ MaterialInfoSet: Array<MaterialInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 云转推输出源信息,包含输出源和输出源转推状态。 */ export interface StreamConnectOutputInfo { /** * 输出源。 注意:此字段可能返回 null,表示取不到有效值。 */ StreamConnectOutput: StreamConnectOutput /** * 输出流状态: <li>On :开;</li> <li>Off :关 。</li> */ PushSwitch: string } /** * ParseEvent请求参数结构体 */ export interface ParseEventRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 回调事件内容。 */ EventContent: string } /** * 空的轨道片段,用来进行时间轴的占位。如需要两个音频片段之间有一段时间的静音,可以用 EmptyTrackItem 来进行占位。 */ export interface EmptyTrackItem { /** * 持续时间,单位为秒。 */ Duration: number } /** * 平台信息。 */ export interface PlatformInfo { /** * 平台名称。 */ Platform: string /** * 平台描述。 */ Description: string /** * 云点播子应用 Id。 */ VodSubAppId: number /** * 平台绑定的 license Id。 */ LicenseId: string /** * 平台状态,可取值为: <li>Normal:正常,可使用。;</li> <li>Stopped:已停用,暂无法使用;</li> <li>Expired:已过期,需要重新购买会员包。</li> */ Status: string /** * 创建时间,格式按照 ISO 8601 标准表示。 */ CreateTime: string /** * 更新时间,格式按照 ISO 8601 标准表示。 */ UpdateTime: string } /** * DescribeJoinTeams请求参数结构体 */ export interface DescribeJoinTeamsRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 团队成员 ID。 */ MemberId: string /** * 分页偏移量,默认值:0 */ Offset?: number /** * 返回记录条数,默认值:30,最大值:30。 */ Limit?: number } /** * 视频拆条项目的输入信息。 */ export interface VideoSegmentationProjectInput { /** * 画布宽高比,取值有: <li>16:9;</li> <li>9:16;</li> <li>2:1。</li> 默认值 16:9 。 */ AspectRatio?: string /** * 视频拆条处理模型,不填则默认为手工分割视频。取值 : <li>AI.GameHighlights.PUBG:和平精英集锦 ;</li> <li>AI.GameHighlights.Honor OfKings:王者荣耀集锦 ;</li> <li>AI.SportHighlights.Football:足球集锦 </li> <li>AI.SportHighlights.Basketball:篮球集锦 ;</li> <li>AI.PersonSegmentation:人物集锦 ;</li> <li>AI.NewsSegmentation:新闻拆条。</li> */ ProcessModel?: string } /** * DeleteMaterial请求参数结构体 */ export interface DeleteMaterialRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 媒体 Id。 */ MaterialId: string /** * 操作者。填写用户的 Id,用于标识调用者及校验媒体删除权限。 */ Operator?: string } /** * CreateProject返回参数结构体 */ export interface CreateProjectResponse { /** * 项目 Id。 */ ProjectId: string /** * 输入源推流信息。 <li> 当 Catagory 为 STREAM_CONNECT 时,数组返回长度为 2 ,第 0 个代表主输入源,第 1 个代表备输入源。只有当各自输入源类型为推流时才有有效内容。</li> */ RtmpPushInputInfoSet: Array<RtmpPushInputInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 视频编辑项目输入参数 */ export interface VideoEditProjectInput { /** * 画布宽高比,取值有: <li>16:9;</li> <li>9:16;</li> <li>2:1。</li> 默认值 16:9 。 */ AspectRatio?: string /** * 视频编辑模板媒体 ID ,通过模板媒体导入项目轨道数据时填写。 */ VideoEditTemplateId?: string /** * 输入的媒体轨道列表,包括视频、音频,等媒体组成的多个轨道信息。其中:<li>输入的多个轨道在时间轴上和输出媒体文件的时间轴对齐;</li><li>时间轴上相同时间点的各个轨道的素材进行重叠,视频或者图片按轨道顺序进行图像的叠加,轨道顺序高的素材叠加在上面,音频素材进行混音;</li><li>视频、音频,每一种类型的轨道最多支持10个。</li> 注:当从模板导入项目时(即 VideoEditTemplateId 不为空时),该参数无效。 */ InitTracks?: Array<MediaTrack> } /** * DeleteProject返回参数结构体 */ export interface DeleteProjectResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteClass请求参数结构体 */ export interface DeleteClassRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 归属者。 */ Owner: Entity /** * 分类路径。 */ ClassPath: string /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * CreateLink请求参数结构体 */ export interface CreateLinkRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 链接类型,取值有: <li>CLASS: 分类链接;</li> <li> MATERIAL:媒体文件链接。</li> */ Type: string /** * 链接名称,不能超过30个字符。 */ Name: string /** * 链接归属者。 */ Owner: Entity /** * 目标资源Id。取值: <li>当 Type 为 MATERIAL 时填媒体 ID;</li> <li>当 Type 为 CLASS 时填写分类路径。</li> */ DestinationId: string /** * 目标资源归属者。 */ DestinationOwner: Entity /** * 链接的分类路径,如填"/a/b"则代表链接属于该分类路径,不填则默认为根路径。 */ ClassPath?: string /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * CreateClass请求参数结构体 */ export interface CreateClassRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 归属者。 */ Owner: Entity /** * 分类路径。 */ ClassPath: string /** * 操作者。填写用户的 Id,用于标识调用者及校验分类创建权限。 */ Operator?: string } /** * DescribeMaterials返回参数结构体 */ export interface DescribeMaterialsResponse { /** * 媒体列表信息。 */ MaterialInfoSet?: Array<MaterialInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * HandleStreamConnectProject返回参数结构体 */ export interface HandleStreamConnectProjectResponse { /** * 输入源推流地址,当 Operation 取值 AddInput 且 InputType 为 RtmpPush 类型时有效。 */ StreamInputRtmpPushUrl: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * GrantResourceAuthorization返回参数结构体 */ export interface GrantResourceAuthorizationResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 导播台主监输出配置信息 */ export interface SwitcherPgmOutputConfig { /** * 导播台输出模板 ID,可取值: <li>10001:分辨率为1080 P;</li> <li>10002:分辨率为720 P;</li> <li>10003:分辨率为480 P。</li> */ TemplateId?: number /** * 导播台输出宽,单位:像素。 */ Width?: number /** * 导播台输出高,单位:像素。 */ Height?: number /** * 导播台输出帧率,单位:帧/秒 */ Fps?: number /** * 导播台输出码率, 单位:bit/s。 */ BitRate?: number } /** * 云剪导出信息。 */ export interface CMEExportInfo { /** * 导出媒体归属,个人或团队。 */ Owner: Entity /** * 导出的媒体名称,不得超过30个字符。 */ Name?: string /** * 导出的媒体信息,不得超过50个字符。 */ Description?: string /** * 导出的媒体分类路径,长度不能超过15字符。不存在默认创建。 */ ClassPath?: string /** * 导出的媒体标签,单个标签不得超过10个字符。 */ TagSet?: Array<string> /** * 第三方平台发布信息列表。暂未正式对外,请勿使用。 */ ThirdPartyPublishInfos?: Array<ThirdPartyPublishInfo> } /** * MoveResource请求参数结构体 */ export interface MoveResourceRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 待移动的原始资源信息,包含原始媒体或分类资源,以及资源归属。 */ SourceResource: ResourceInfo /** * 目标信息,包含分类及归属,仅支持移动资源到分类。 */ DestinationResource: ResourceInfo /** * 操作者。填写用户的 Id,用于标识调用者及校验资源访问以及写权限。 */ Operator?: string } /** * 直播拉流信息 */ export interface LivePullInputInfo { /** * 直播拉流地址。 */ InputUrl: string } /** * ImportMediaToProject请求参数结构体 */ export interface ImportMediaToProjectRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 项目 Id。 */ ProjectId: string /** * 导入媒资类型,取值: <li>VOD:云点播文件;</li> <li>EXTERNAL:媒资绑定。</li> 注意:如果不填默认为云点播文件,如果媒体存储在非腾讯云点播中,都需要使用媒资绑定。 */ SourceType?: string /** * 云点播媒资文件 Id,当 SourceType 取值 VOD 或者缺省的时候必填。 */ VodFileId?: string /** * 原始媒资文件信息,当 SourceType 取值 EXTERNAL 的时候必填。 */ ExternalMediaInfo?: ExternalMediaInfo /** * 媒体名称,不能超过30个字符。 */ Name?: string /** * 媒体预处理任务模板 ID,取值: <li>10:进行编辑预处理。</li> 注意:如果填0则不进行处理。 */ PreProcessDefinition?: number /** * 操作者。填写用户的 Id,用于标识调用者及校验项目和媒体文件访问权限。 */ Operator?: string } /** * 云点播导出信息。 */ export interface VODExportInfo { /** * 导出的媒资名称。 */ Name?: string /** * 导出的媒资分类 Id。 */ ClassId?: number /** * 第三方平台发布信息列表。暂未正式对外,请勿使用。 */ ThirdPartyPublishInfos?: Array<ThirdPartyPublishInfo> } /** * 排序 */ export interface SortBy { /** * 排序字段。 */ Field: string /** * 排序方式,可选值:Asc(升序)、Desc(降序),默认降序。 */ Order?: string } /** * 企鹅号发布信息。 */ export interface PenguinMediaPlatformPublishInfo { /** * 视频发布标题。 */ Title?: string /** * 视频发布描述信息。 */ Description?: string /** * 视频标签。 */ Tags?: Array<string> /** * 视频分类,详见[企鹅号官网](https://open.om.qq.com/resources/resourcesCenter)视频分类。 */ Category?: number } /** * 图片素材信息 */ export interface ImageMaterial { /** * 图片高度,单位:px。 */ Height: number /** * 图片宽度,单位:px。 */ Width: number /** * 素材媒体文件的展示 URL 地址。 */ MaterialUrl: string /** * 图片大小,单位:字节。 */ Size: number /** * 素材媒体文件的原始 URL 地址。 */ OriginalUrl: string /** * 云点播媒资 FileId。 */ VodFileId: string } /** * DescribeClass请求参数结构体 */ export interface DescribeClassRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 归属者。 */ Owner: Entity /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * DescribeSharedSpace返回参数结构体 */ export interface DescribeSharedSpaceResponse { /** * 查询到的共享空间总数。 */ TotalCount?: number /** * 各个共享空间对应的授权者信息。 注意:此字段可能返回 null,表示取不到有效值。 */ AuthorizerSet?: Array<Authorizer> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeAccounts返回参数结构体 */ export interface DescribeAccountsResponse { /** * 符合搜索条件的记录总数。 */ TotalCount: number /** * 账号信息列表。 */ AccountInfoSet: Array<AccountInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * MoveResource返回参数结构体 */ export interface MoveResourceResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * MoveClass请求参数结构体 */ export interface MoveClassRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 归属者。 */ Owner: Entity /** * 源分类路径。 */ SourceClassPath: string /** * 目标分类路径。 */ DestinationClassPath: string /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * 时间范围 */ export interface TimeRange { /** * 开始时间,使用 ISO 日期格式。 */ StartTime: string /** * 结束时间,使用 ISO 日期格式。 */ EndTime: string } /** * DeleteTeamMembers返回参数结构体 */ export interface DeleteTeamMembersResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * MoveClass返回参数结构体 */ export interface MoveClassResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ImportMediaToProject返回参数结构体 */ export interface ImportMediaToProjectResponse { /** * 媒体 Id。 */ MaterialId: string /** * 媒体预处理任务 ID,如果未指定发起预处理任务则为空。 */ TaskId: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyTeamMember返回参数结构体 */ export interface ModifyTeamMemberResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeTeamMembers返回参数结构体 */ export interface DescribeTeamMembersResponse { /** * 符合条件的记录总数。 */ TotalCount?: number /** * 团队成员列表。 */ MemberSet?: Array<TeamMemberInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * AddTeamMember返回参数结构体 */ export interface AddTeamMemberResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * CreateTeam返回参数结构体 */ export interface CreateTeamResponse { /** * 创建的团队 ID。 */ TeamId?: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyTeam请求参数结构体 */ export interface ModifyTeamRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 团队 ID。 */ TeamId: string /** * 团队名称,不能超过 30 个字符。 */ Name?: string /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * ModifyTeamMember请求参数结构体 */ export interface ModifyTeamMemberRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 团队 ID。 */ TeamId: string /** * 团队成员 ID。 */ MemberId: string /** * 成员备注,允许设置备注为空,不为空时长度不能超过15个字符。 */ Remark?: string /** * 成员角色,取值: <li>Admin:团队管理员;</li> <li>Member:普通成员。</li> */ Role?: string /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * CreateTeam请求参数结构体 */ export interface CreateTeamRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 团队名称,限30个字符。 */ Name: string /** * 团队所有者,指定用户 ID。 */ OwnerId: string /** * 团队所有者的备注,限30个字符。 */ OwnerRemark?: string /** * 自定义团队 ID。创建后不可修改,限20个英文字符及"-"。同时不能以 cmetid_开头。不填会生成默认团队 ID。 */ TeamId?: string } /** * 媒体基本信息。 */ export interface MaterialBasicInfo { /** * 媒体 Id。 */ MaterialId: string /** * 媒体类型,取值为: <li> AUDIO :音频;</li> <li> VIDEO :视频;</li> <li> IMAGE :图片;</li> <li> LINK :链接.</li> <li> OTHER : 其他.</li> */ MaterialType: string /** * 媒体归属实体。 */ Owner: Entity /** * 媒体名称。 */ Name: string /** * 媒体文件的创建时间,使用 ISO 日期格式。 */ CreateTime: string /** * 媒体文件的最近更新时间(如修改视频属性、发起视频处理等会触发更新媒体文件信息的操作),使用 ISO 日期格式。 */ UpdateTime: string /** * 媒体的分类路径。 */ ClassPath: string /** * 预置标签列表。 */ PresetTagSet: Array<PresetTagInfo> /** * 人工标签列表。 */ TagSet: Array<string> /** * 媒体文件的预览图。 */ PreviewUrl: string /** * 媒体绑定的标签信息列表 。 该字段已废弃。 注意:此字段可能返回 null,表示取不到有效值。 */ TagInfoSet: Array<MaterialTagInfo> } /** * 资源信息,包含资源以及归属信息 */ export interface ResourceInfo { /** * 媒资和分类资源。 注意:此字段可能返回 null,表示取不到有效值。 */ Resource: Resource /** * 资源归属,个人或团队。 */ Owner: Entity } /** * 媒体处理视频合成任务的预处理操作。 */ export interface MediaPreprocessOperation { /** * 预处理操作的类型,取值范围: <li>ImageTextMask:图片文字遮罩。</li> */ Type: string /** * 预处理操作参数。 当 Type 取值 ImageTextMask 时,参数为要保留的文字。 */ Args?: Array<string> } /** * 加入的团队信息 */ export interface JoinTeamInfo { /** * 团队 ID。 */ TeamId: string /** * 团队名称。 */ Name: string /** * 团队成员个数。 */ MemberCount: number /** * 成员在团队中的角色,取值有: <li>Owner:团队所有者,添加团队成员及修改团队成员解决时不能填此角色;</li> <li>Admin:团队管理员;</li> <li>Member:普通成员。</li> */ Role: string } /** * DescribeResourceAuthorization请求参数结构体 */ export interface DescribeResourceAuthorizationRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 归属者。 */ Owner: Entity /** * 资源。 */ Resource: Resource /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * CreateClass返回参数结构体 */ export interface CreateClassResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 卡槽信息。 */ export interface SlotInfo { /** * 卡槽 Id。 */ Id: number /** * 素材类型,同素材素材,可取值有: <li> AUDIO :音频;</li> <li> VIDEO :视频;</li> <li> IMAGE :图片。</li> */ Type: string /** * 默认素材 Id。 */ DefaultMaterialId: string /** * 素材时长,单位秒。 */ Duration: number } /** * 媒体替换信息。 */ export interface MediaReplacementInfo { /** * 替换的媒体类型,取值有: <li>CMEMaterialId:替换的媒体类型为媒体 ID;</li> <li>ImageUrl:替换的媒体类型为图片 URL;</li> 注:默认为 CMEMaterialId 。 */ MediaType?: string /** * 媒体 ID。 当媒体类型取值为 CMEMaterialId 时有效。 */ MaterialId?: string /** * 媒体 URL。 当媒体类型取值为 ImageUrl 时有效, 图片仅支持 jpg、png 格式,且大小不超过 2M 。 */ MediaUrl?: string /** * 替换媒体选取的开始时间,单位为秒,默认为 0。 */ StartTimeOffset?: number /** * 预处理操作。 注:目前该功能暂不支持,请勿使用。 */ PreprocessOperation?: MediaPreprocessOperation } /** * 任务基础信息。 */ export interface TaskBaseInfo { /** * 任务 Id。 */ TaskId: string /** * 任务类型,取值有: <li>VIDEO_EDIT_PROJECT_EXPORT:项目导出。</li> */ TaskType: string /** * 任务状态,取值有: <li>PROCESSING:处理中:</li> <li>SUCCESS:成功;</li> <li>FAIL:失败。</li> */ Status: string /** * 任务进度,取值为:0~100。 */ Progress: number /** * 错误码。 <li>0:成功;</li> <li>其他值:失败。</li> */ ErrCode: number /** * 错误信息。 */ ErrMsg: string /** * 创建时间,格式按照 ISO 8601 标准表示。 */ CreateTime: string } /** * 录制回放项目输入信息。 */ export interface RecordReplayProjectInput { /** * 录制拉流地址。 */ PullStreamUrl: string /** * 录制文件归属者。 */ MaterialOwner: Entity /** * 录制文件存储分类路径。 */ MaterialClassPath: string /** * 回放推流地址。 */ PushStreamUrl: string } /** * 视频流信息。 */ export interface VideoStreamInfo { /** * 码率,单位:bps。 */ Bitrate: number /** * 高度,单位:px。 */ Height: number /** * 宽度,单位:px。 */ Width: number /** * 编码格式。 */ Codec: string /** * 帧率,单位:hz。 */ Fps: number } /** * AddTeamMember请求参数结构体 */ export interface AddTeamMemberRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 团队 ID。 */ TeamId: string /** * 要添加的成员列表,一次最多添加30个成员。 */ TeamMembers: Array<AddMemberInfo> /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * ExportVideoEditProject返回参数结构体 */ export interface ExportVideoEditProjectResponse { /** * 任务 Id。 */ TaskId: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 第三方平台视频发布信息。 */ export interface ThirdPartyPublishInfo { /** * 发布通道 ID。 */ ChannelMaterialId: string /** * 企鹅号发布信息,如果使用的发布通道为企鹅号时必填。 */ PenguinMediaPlatformPublishInfo?: PenguinMediaPlatformPublishInfo /** * 新浪微博发布信息,如果使用的发布通道为新浪微博时必填。 */ WeiboPublishInfo?: WeiboPublishInfo /** * 快手发布信息,如果使用的发布通道为快手时必填。 */ KuaishouPublishInfo?: KuaishouPublishInfo /** * 腾讯云对象存储发布信息, 如果使用的发布通道为腾讯云对象存储时必填。 */ CosPublishInfo?: CosPublishInputInfo } /** * ListMedia请求参数结构体 */ export interface ListMediaRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 媒体分类路径,例如填写"/a/b",则代表浏览该分类路径下的媒体和子分类信息。 */ ClassPath: string /** * 媒体和分类的归属者。 */ Owner: Entity /** * 分页偏移量,默认值:0。 */ Offset?: number /** * 返回记录条数,默认值:10,最大值:50。 */ Limit?: number /** * 操作者。填写用户的 Id,用于标识调用者及校验对媒体的访问权限。 */ Operator?: string } /** * 点播拉流信息,包括输入拉流地址和播放次数。 */ export interface VodPullInputInfo { /** * 点播输入拉流 URL 。 */ InputUrls: Array<string> /** * 播放次数,取值有: <li>-1 : 循环播放,直到转推结束;</li> <li>0 : 不循环;</li> <li>大于0 : 具体循环次数,次数和时间以先结束的为准。</li> 默认不循环。 */ LoopTimes?: number } /** * ModifyTeam返回参数结构体 */ export interface ModifyTeamResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteLoginStatus请求参数结构体 */ export interface DeleteLoginStatusRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 用户 Id 列表,N 从 0 开始取值,最大 19。 */ UserIds: Array<string> } /** * GenerateVideoSegmentationSchemeByAi请求参数结构体 */ export interface GenerateVideoSegmentationSchemeByAiRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 视频拆条项目 Id 。 */ ProjectId: string /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * 直播剪辑项目输入参数。 */ export interface LiveStreamClipProjectInput { /** * 直播流播放地址,目前仅支持 HLS 和 FLV 格式。 */ Url: string /** * 直播流录制时长,单位为秒,最大值为 7200。 */ StreamRecordDuration: number } /** * DeleteTeamMembers请求参数结构体 */ export interface DeleteTeamMembersRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 团队 ID。 */ TeamId: string /** * 要删除的成员列表。 */ MemberIds: Array<string> /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * ExportVideoByTemplate请求参数结构体 */ export interface ExportVideoByTemplateRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 视频编辑模板 Id。 */ TemplateId: string /** * 导出模板 Id,目前不支持自定义创建,只支持下面的预置模板 Id。 <li>10:分辨率为 480P,输出视频格式为 MP4;</li> <li>11:分辨率为 720P,输出视频格式为 MP4;</li> <li>12:分辨率为 1080P,输出视频格式为 MP4。</li> */ Definition: number /** * 导出目标,可取值为: <li>CME:云剪,即导出为云剪媒体;</li> <li>VOD:云点播,即导出为云点播媒资。</li> */ ExportDestination: string /** * 需要替换的素材信息。 */ SlotReplacements?: Array<SlotReplacementInfo> /** * 导出的云剪媒体信息。当导出目标为 CME 时必填。 */ CMEExportInfo?: CMEExportInfo /** * 导出的云点播媒资信息。当导出目标为 VOD 时必填。 */ VODExportInfo?: VODExportInfo /** * 操作者。填写用户的 Id,用于标识调用者及校验项目导出权限。 */ Operator?: string } /** * DescribePlatforms请求参数结构体 */ export interface DescribePlatformsRequest { /** * 平台集合。 */ Platforms?: Array<string> /** * 平台绑定的 license Id 集合。 */ LicenseIds?: Array<string> /** * 分页返回的起始偏移量,默认值:0。 */ Offset?: number /** * 分页返回的记录条数,默认值:10。 */ Limit?: number } /** * 其他类型素材 */ export interface OtherMaterial { /** * 素材媒体文件的播放 URL 地址。 */ MaterialUrl: string /** * 云点播媒资 FileId。 */ VodFileId: string } /** * 回调事件内容。 */ export interface EventContent { /** * 事件类型,可取值为: <li>Storage.NewFileCreated:新文件产生;</li> <li>Project.StreamConnect.StatusChanged:云转推项目状态变更。</li> */ EventType: string /** * 新文件产生事件信息。仅当 EventType 为 Storage.NewFileCreated 时有效。 */ StorageNewFileCreatedEvent: StorageNewFileCreatedEvent /** * 云转推项目状态变更事件信息。仅当 EventType 为 Project.StreamConnect.StatusChanged 时有效。 */ ProjectStreamConnectStatusChangedEvent: ProjectStreamConnectStatusChangedEvent } /** * 视频素材信息 */ export interface VideoMaterial { /** * 素材元信息。 */ MetaData: MediaMetaData /** * 雪碧图信息。 */ ImageSpriteInfo: MediaImageSpriteInfo /** * 素材媒体文件的播放 URL 地址。 */ MaterialUrl: string /** * 素材媒体文件的封面图片地址。 */ CoverUrl: string /** * 媒体文件分辨率。取值为:LD/SD/HD/FHD/2K/4K。 */ Resolution: string /** * 素材状态。 注意:此字段可能返回 null,表示取不到有效值。 */ MaterialStatus: MaterialStatus /** * 素材媒体文件的原始 URL 地址。 */ OriginalUrl: string /** * 云点播媒资 FileId。 */ VodFileId: string } /** * DescribeResourceAuthorization返回参数结构体 */ export interface DescribeResourceAuthorizationResponse { /** * 符合条件的资源授权记录总数。 注意:此字段可能返回 null,表示取不到有效值。 */ TotalCount?: number /** * 授权信息列表。 */ AuthorizationInfoSet?: Array<AuthorizationInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * FlattenListMedia返回参数结构体 */ export interface FlattenListMediaResponse { /** * 符合条件的记录总数。 */ TotalCount: number /** * 该分类路径下及其子分类下的所有媒体基础信息列表。 */ MaterialInfoSet: Array<MaterialInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 制作云用户账号信息。 */ export interface AccountInfo { /** * 用户 Id。 */ UserId: string /** * 用户手机号码。 */ Phone: string /** * 用户昵称。 */ Nick: string /** * 账号状态,取值: <li>Normal:有效;</li> <li>Stopped:无效。</li> */ Status: string } /** * DescribeProjects请求参数结构体 */ export interface DescribeProjectsRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 项目 Id 列表,N 从 0 开始取值,最大 19。 */ ProjectIds?: Array<string> /** * 画布宽高比集合。 */ AspectRatioSet?: Array<string> /** * 项目类别,取值有: <li>VIDEO_EDIT:视频编辑。</li> <li>SWITCHER:导播台。</li> <li>VIDEO_SEGMENTATION:视频拆条。</li> <li>STREAM_CONNECT:云转推。</li> <li>RECORD_REPLAY:录制回放。</li> */ CategorySet?: Array<string> /** * 项目模式,一个项目可以有多种模式并相互切换。 当 Category 为 VIDEO_EDIT 时,可选模式有: <li>Default:默认模式。</li> <li>VideoEditTemplate:视频编辑模板制作模式。</li> */ Modes?: Array<string> /** * 列表排序,支持下列排序字段: <li>CreateTime:创建时间;</li> <li>UpdateTime:更新时间。</li> */ Sort?: SortBy /** * 项目归属者。 */ Owner?: Entity /** * 分页返回的起始偏移量,默认值:0。 */ Offset?: number /** * 分页返回的记录条数,默认值:10。 */ Limit?: number /** * 操作者。填写用户的 Id,用于标识调用者及校验项目访问权限。 */ Operator?: string } /** * DescribeLoginStatus返回参数结构体 */ export interface DescribeLoginStatusResponse { /** * 用户登录状态列表。 */ LoginStatusInfoSet?: Array<LoginStatusInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 云转推项目状态变更事件。 */ export interface ProjectStreamConnectStatusChangedEvent { /** * 项目 Id。 */ ProjectId: string /** * 项目状态,取值有: <li>Working:云转推推流开始;</li> <li>Stopped:云转推推流结束。</li> */ Status: string } /** * DescribeJoinTeams返回参数结构体 */ export interface DescribeJoinTeamsResponse { /** * 符合条件的记录总数。 */ TotalCount?: number /** * 团队列表 */ TeamSet?: Array<JoinTeamInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DescribeTeamMembers请求参数结构体 */ export interface DescribeTeamMembersRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 团队 ID。 */ TeamId: string /** * 成员 ID 列表,限指定30个指定成员。如不填,则返回指定团队下的所有成员。 */ MemberIds?: Array<string> /** * 分页偏移量,默认值:0 */ Offset?: number /** * 返回记录条数,默认值:30,最大值:30。 */ Limit?: number /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * 素材的状态,目前仅包含素材编辑可用状态。 */ export interface MaterialStatus { /** * 素材编辑可用状态,取值有: <li>NORMAL:正常,可直接用于编辑;</li> <li>ABNORMAL : 异常,不可用于编辑;</li> <li>PROCESSING:处理中,暂不可用于编辑。</li> */ EditorUsableStatus: string } /** * DescribeProjects返回参数结构体 */ export interface DescribeProjectsResponse { /** * 符合条件的记录总数。 */ TotalCount: number /** * 项目信息列表。 */ ProjectInfoSet: Array<ProjectInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 资源权限信息 */ export interface AuthorizationInfo { /** * 被授权者实体。 */ Authorizee: Entity /** * 详细授权值。 取值有: <li>R:可读,可以浏览素材,但不能使用该素材(将其添加到 Project),或复制到自己的媒资库中</li> <li>X:可用,可以使用该素材(将其添加到 Project),但不能将其复制到自己的媒资库中,意味着被授权者无法将该资源进一步扩散给其他个人或团队。</li> <li>C:可复制,既可以使用该素材(将其添加到 Project),也可以将其复制到自己的媒资库中。</li> <li>W:可修改、删除媒资。</li> */ PermissionSet: Array<string> } /** * 视频编辑模板素材信息。 */ export interface VideoEditTemplateMaterial { /** * 视频编辑模板宽高比。 */ AspectRatio: string /** * 卡槽信息。 */ SlotSet: Array<SlotInfo> /** * 模板预览视频 URL 地址 。 */ PreviewVideoUrl: string } /** * 卡槽替换信息。 */ export interface SlotReplacementInfo { /** * 卡槽 Id。 */ Id: number /** * 替换类型,可取值有: <li> AUDIO :音频;</li> <li> VIDEO :视频;</li> <li> IMAGE :图片;</li> <li> TEXT :文本。</li> 注意:这里必须保证替换的素材类型与模板轨道数据的素材类型一致。如果替换的类型为Text,,则必须保证模板轨道数据中相应卡槽的位置标记的是文本。 */ ReplacementType: string /** * 媒体替换信息,仅当要替换的媒体类型为音频、视频、图片时有效。 */ MediaReplacementInfo?: MediaReplacementInfo /** * 文本替换信息,仅当要替换的卡槽类型为文本时有效。 */ TextReplacementInfo?: TextReplacementInfo } /** * ParseEvent返回参数结构体 */ export interface ParseEventResponse { /** * 事件内容。 */ EventContent: EventContent /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteMaterial返回参数结构体 */ export interface DeleteMaterialResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * RevokeResourceAuthorization请求参数结构体 */ export interface RevokeResourceAuthorizationRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 资源所属实体。 */ Owner: Entity /** * 被授权资源。 */ Resources: Array<Resource> /** * 被授权目标实体。 */ Authorizees: Array<Entity> /** * 详细授权值。 取值有: <li>R:可读,可以浏览素材,但不能使用该素材(将其添加到 Project),或复制到自己的媒资库中</li> <li>X:可用,可以使用该素材(将其添加到 Project),但不能将其复制到自己的媒资库中,意味着被授权者无法将该资源进一步扩散给其他个人或团队。</li> <li>C:可复制,既可以使用该素材(将其添加到 Project),也可以将其复制到自己的媒资库中。</li> <li>W:可修改、删除媒资。</li> */ Permissions: Array<string> /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * DescribeTaskDetail请求参数结构体 */ export interface DescribeTaskDetailRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 任务 Id。 */ TaskId: string /** * 操作者。填写用户的 Id,用于标识调用者及校验对任务的访问权限。 */ Operator?: string } /** * 团队成员信息 */ export interface TeamMemberInfo { /** * 团队成员 ID。 */ MemberId: string /** * 团队成员备注。 */ Remark?: string /** * 团队成员角色,取值: <li>Owner:团队所有者,添加团队成员及修改团队成员解决时不能填此角色;</li> <li>Admin:团队管理员;</li> <li>Member:普通成员。</li> */ Role?: string } /** * COS 发布信息。 */ export interface CosPublishInputInfo { /** * 发布生成的对象存储文件所在的 COS Bucket 名,如 TopRankVideo-125xxx88。 */ Bucket: string /** * 发布生成的对象存储文件所在的 COS Bucket 所属园区,如 ap-chongqing。 */ Region: string /** * 发布生成的视频在 COS 存储的对象键。对象键(ObjectKey)是对象(Object)在存储桶(Bucket)中的唯一标识。 */ VideoKey: string /** * 发布生成的封面在 COS 存储的对象键。 */ CoverKey: string } /** * DescribeTasks返回参数结构体 */ export interface DescribeTasksResponse { /** * 符合搜索条件的记录总数。 */ TotalCount: number /** * 任务基础信息列表。 */ TaskBaseInfoSet: Array<TaskBaseInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ModifyProject请求参数结构体 */ export interface ModifyProjectRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 项目 Id。 */ ProjectId: string /** * 项目名称,不可超过30个字符。 */ Name?: string /** * 画布宽高比,取值有: <li>16:9;</li> <li>9:16。</li> */ AspectRatio?: string /** * 项目归属者。 */ Owner?: Entity /** * 项目模式,一个项目可以有多种模式并相互切换。 当 Category 为 VIDEO_EDIT 时,可选模式有: <li>Defualt:默认模式。</li> <li>VideoEditTemplate:视频编辑模板制作模式。</li> */ Mode?: string } /** * 媒体详情信息 */ export interface MaterialInfo { /** * 媒体基本信息。 */ BasicInfo: MaterialBasicInfo /** * 视频媒体信息。 注意:此字段可能返回 null,表示取不到有效值。 */ VideoMaterial: VideoMaterial /** * 音频媒体信息。 注意:此字段可能返回 null,表示取不到有效值。 */ AudioMaterial: AudioMaterial /** * 图片媒体信息。 注意:此字段可能返回 null,表示取不到有效值。 */ ImageMaterial: ImageMaterial /** * 链接媒体信息。 注意:此字段可能返回 null,表示取不到有效值。 */ LinkMaterial: LinkMaterial /** * 模板媒体信息。 注意:此字段可能返回 null,表示取不到有效值。 */ VideoEditTemplateMaterial: VideoEditTemplateMaterial /** * 其他类型媒体信息。 注意:此字段可能返回 null,表示取不到有效值。 */ OtherMaterial: OtherMaterial } /** * 登录态信息 */ export interface LoginStatusInfo { /** * 用户 Id。 */ UserId: string /** * 用户登录状态。 <li>Online:在线;</li> <li>Offline:离线。</li> */ Status: string } /** * DescribeClass返回参数结构体 */ export interface DescribeClassResponse { /** * 分类信息列表。 */ ClassInfoSet?: Array<ClassInfo> /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * GenerateVideoSegmentationSchemeByAi返回参数结构体 */ export interface GenerateVideoSegmentationSchemeByAiResponse { /** * 视频智能拆条任务 Id 。 */ TaskId: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 预置标签信息 */ export interface PresetTagInfo { /** * 标签 Id 。 */ Id: string /** * 标签名称。 */ Name: string /** * 父级预设 Id。 */ ParentTagId?: string } /** * DescribeSharedSpace请求参数结构体 */ export interface DescribeSharedSpaceRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 被授权目标,,个人或团队。 */ Authorizee: Entity /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * 快手视频发布信息。 */ export interface KuaishouPublishInfo { /** * 视频发布标题,限30个字符。 */ Title?: string } /** * CopyProject返回参数结构体 */ export interface CopyProjectResponse { /** * 复制后的项目 ID。 */ ProjectId: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * DeleteClass返回参数结构体 */ export interface DeleteClassResponse { /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * GrantResourceAuthorization请求参数结构体 */ export interface GrantResourceAuthorizationRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 资源归属者,个人或者团队。 */ Owner: Entity /** * 被授权资源。 */ Resources: Array<Resource> /** * 被授权目标,个人或者团队。 */ Authorizees: Array<Entity> /** * 详细授权值。 取值有: <li>R:可读,可以浏览媒体,但不能使用该媒体文件(将其添加到 Project),或复制到自己的媒资库中</li> <li>X:可用,可以使用该素材(将其添加到 Project),但不能将其复制到自己的媒资库中,意味着被授权者无法将该资源进一步扩散给其他个人或团队。</li> <li>C:可复制,既可以使用该素材(将其添加到 Project),也可以将其复制到自己的媒资库中。</li> <li>W:可修改、删除媒资。</li> */ Permissions: Array<string> /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * 文件元信息。 */ export interface MediaMetaData { /** * 大小。 */ Size: number /** * 容器类型。 */ Container: string /** * 视频流码率平均值与音频流码率平均值之和,单位:bps。 */ Bitrate: number /** * 视频流高度的最大值,单位:px。 */ Height: number /** * 视频流宽度的最大值,单位:px。 */ Width: number /** * 时长,单位:秒。 */ Duration: number /** * 视频拍摄时的选择角度,单位:度 */ Rotate: number /** * 视频流信息。 */ VideoStreamInfoSet: Array<VideoStreamInfo> /** * 音频流信息。 */ AudioStreamInfoSet: Array<AudioStreamInfo> } /** * 媒资绑定资源信息,包含媒资绑定模板 ID 和文件信息。 */ export interface ExternalMediaInfo { /** * 媒资绑定模板 ID,可取值为: <li>1000000:媒体文件为 URL,且 URL Scheme 为 https;</li> <li>1000001:媒体文件为 URL,且 URL Scheme 为 http。</li> 注:如果要支持其它存储平台或者类型的媒体绑定,请联系 [客服](https://cloud.tencent.com/online-service?from=doc_1156)。 */ Definition: number /** * 媒资绑定媒体路径或文件 ID。如果要绑定 URL 类型的媒体,请将 URL 的 <code>'https://'</code> 或者 <code>'http://'</code> 去掉,例如: 原始媒体 URL 为 `https://www.example.com/a.mp4`,则 MediaKey 为 `www.example.com/a.mp4`。 */ MediaKey: string } /** * 链接素材信息 */ export interface LinkMaterialInfo { /** * 素材基本信息。 */ BasicInfo: MaterialBasicInfo /** * 视频素材信息。 注意:此字段可能返回 null,表示取不到有效值。 */ VideoMaterial: VideoMaterial /** * 音频素材信息。 注意:此字段可能返回 null,表示取不到有效值。 */ AudioMaterial: AudioMaterial /** * 图片素材信息。 注意:此字段可能返回 null,表示取不到有效值。 */ ImageMaterial: ImageMaterial } /** * ExportVideoByEditorTrackData返回参数结构体 */ export interface ExportVideoByEditorTrackDataResponse { /** * 任务 Id。 */ TaskId: string /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 雪碧图 */ export interface MediaImageSpriteInfo { /** * 雪碧图小图的高度。 */ Height: number /** * 雪碧图小图的宽度。 */ Width: number /** * 雪碧图小图的总数量。 */ TotalCount: number /** * 截取雪碧图输出的地址。 */ ImageUrlSet: Array<string> /** * 雪碧图子图位置与时间关系的 WebVtt 文件地址。WebVtt 文件表明了各个雪碧图小图对应的时间点,以及在雪碧大图里的坐标位置,一般被播放器用于实现预览。 */ WebVttUrl: string } /** * ImportMaterial请求参数结构体 */ export interface ImportMaterialRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 媒体归属者,团队或个人。 */ Owner: Entity /** * 媒体名称,不能超过30个字符。 */ Name: string /** * 导入媒资类型,取值: <li>VOD:云点播文件;</li> <li>EXTERNAL:媒资绑定。</li> 注意:如果不填默认为云点播文件,如果媒体存储在非腾讯云点播中,都需要使用媒资绑定。 */ SourceType?: string /** * 云点播媒资 FileId,仅当 SourceType 为 VOD 时有效。 */ VodFileId?: string /** * 原始媒资文件信息,当 SourceType 取值 EXTERNAL 的时候必填。 */ ExternalMediaInfo?: ExternalMediaInfo /** * 媒体分类路径,形如:"/a/b",层级数不能超过10,每个层级长度不能超过15字符。若不填则默认为根路径。 */ ClassPath?: string /** * 媒体预处理任务模板 ID。取值: <li>10:进行编辑预处理。</li> */ PreProcessDefinition?: number /** * 操作者。填写用户的 Id,用于标识调用者及校验操作权限。 */ Operator?: string } /** * 模板插槽文本替换信息。 */ export interface TextReplacementInfo { /** * 替换的文本信息。 */ Text: string } /** * DescribeMaterials请求参数结构体 */ export interface DescribeMaterialsRequest { /** * 平台名称,指定访问的平台。 */ Platform: string /** * 媒体 ID 列表,N 从 0 开始取值,最大 19。 */ MaterialIds: Array<string> /** * 列表排序,支持下列排序字段: <li>CreateTime:创建时间;</li> <li>UpdateTime:更新时间。</li> */ Sort?: SortBy /** * 操作者。填写用户的 Id,用于标识调用者及校验媒体的访问权限。 */ Operator?: string }
the_stack
import type { InjectedOptionsParam, InjectedDependenciesParam, PineOptions, PineOptionsWithSelect, PineTypedResult, } from '..'; import type { Device, DeviceServiceEnvironmentVariable, DeviceVariable, DeviceTag, Application, } from '../types/models'; import { DeviceOverallStatus as OverallStatus } from '../types/device-overall-status'; import type * as DeviceState from '../types/device-state'; import type { DeviceTypeJson } from './config'; import { CurrentServiceWithCommit, DeviceWithServiceDetails, } from '../util/device-service-details'; import type { OsUpdateActionResult } from '../util/device-actions/os-update'; import * as url from 'url'; import once = require('lodash/once'); import chunk = require('lodash/chunk'); import flatten = require('lodash/flatten'); import groupBy = require('lodash/groupBy'); import * as bSemver from 'balena-semver'; import * as errors from 'balena-errors'; import * as memoizee from 'memoizee'; const CHUNK_SIZE = 50; import { isId, isNoDeviceForKeyResponse, isNotFoundResponse, mergePineOptions, treatAsMissingDevice, withSupervisorLockedError, } from '../util'; import { toWritable } from '../util/types'; import { getDeviceOsSemverWithVariant, ensureVersionCompatibility, normalizeDeviceOsVersion, } from '../util/device-os-version'; import { getCurrentServiceDetailsPineExpand, generateCurrentServiceDetails, } from '../util/device-service-details'; import { checkLocalModeSupported, getLocalModeSupport, LOCAL_MODE_ENV_VAR, LOCAL_MODE_SUPPORT_PROPERTIES, } from '../util/local-mode'; import { CONTAINER_ACTION_ENDPOINT_TIMEOUT, getSupervisorApiHelper, MIN_SUPERVISOR_MC_API, } from './device.supervisor-api.partial'; import type { SubmitBody, SelectableProps, } from '../../typings/pinejs-client-core'; import type { AtLeast } from '../../typings/utils'; import type { DeviceType } from '../types/device-type-json'; const MIN_OS_MC = '2.12.0'; const OVERRIDE_LOCK_ENV_VAR = 'RESIN_OVERRIDE_LOCK'; export * as DeviceState from '../types/device-state'; export type { DeviceOverallStatus as OverallStatus } from '../types/device-overall-status'; export type { SupervisorStatus } from './device.supervisor-api.partial'; export type DeviceMetrics = Pick< Device, | 'memory_usage' | 'memory_total' | 'storage_block_device' | 'storage_usage' | 'storage_total' | 'cpu_usage' | 'cpu_temp' | 'cpu_id' | 'is_undervolted' >; const getDeviceModel = function ( deps: InjectedDependenciesParam, opts: InjectedOptionsParam, ) { const { pine, request, // Do not destructure sub-modules, to allow lazy loading only when needed. sdkInstance, } = deps; const { apiUrl, deviceUrlsBase } = opts; const registerDevice = once(() => ( require('balena-register-device') as typeof import('balena-register-device') ).getRegisterDevice({ request }), ); const configModel = once(() => (require('./config') as typeof import('./config')).default(deps, opts), ); const applicationModel = once(() => (require('./application') as typeof import('./application')).default( deps, opts, ), ); const releaseModel = once(() => (require('./release') as typeof import('./release')).default(deps, opts), ); const hostappModel = once(() => (require('./hostapp') as typeof import('./hostapp')).default(deps), ); const { addCallbackSupportToModule } = require('../util/callbacks') as typeof import('../util/callbacks'); const { buildDependentResource } = require('../util/dependent-resource') as typeof import('../util/dependent-resource'); const hupActionHelper = once( () => ( require('../util/device-actions/os-update/utils') as typeof import('../util/device-actions/os-update/utils') ).hupActionHelper, ); const deviceTypesUtils = once( () => require('../util/device-types') as typeof import('../util/device-types'), ); const dateUtils = once( () => require('../util/date') as typeof import('../util/date'), ); const tagsModel = buildDependentResource<DeviceTag>( { pine }, { resourceName: 'device_tag', resourceKeyField: 'tag_key', parentResourceName: 'device', async getResourceId(uuidOrId: string | number): Promise<number> { const { id } = await exports.get(uuidOrId, { $select: 'id' }); return id; }, }, ); const configVarModel = buildDependentResource<DeviceVariable>( { pine }, { resourceName: 'device_config_variable', resourceKeyField: 'name', parentResourceName: 'device', async getResourceId(uuidOrId: string | number): Promise<number> { const { id } = await exports.get(uuidOrId, { $select: 'id' }); return id; }, }, ); const envVarModel = buildDependentResource<DeviceVariable>( { pine }, { resourceName: 'device_environment_variable', resourceKeyField: 'name', parentResourceName: 'device', async getResourceId(uuidOrId: string | number): Promise<number> { const { id } = await exports.get(uuidOrId, { $select: 'id' }); return id; }, }, ); async function batchDeviceOperation< TOpts extends PineOptionsWithSelect<Device>, >({ uuidOrIdOrIds, options, fn, }: { uuidOrIdOrIds: string | number | number[]; options?: TOpts; fn: (apps: { id: number; owns__device: Array< { id: number } & (TOpts extends PineOptionsWithSelect<Device> ? PineTypedResult<Device, TOpts> : {}) >; }) => Promise<void>; }): Promise<void> { if ( Array.isArray(uuidOrIdOrIds) && (!uuidOrIdOrIds.length || uuidOrIdOrIds.some((id) => typeof id !== 'number')) ) { throw new errors.BalenaInvalidParameterError( 'uuidOrIdOrIds', uuidOrIdOrIds, ); } // create a list of UUIDs or chunks of IDs const chunks: Array<string | number[]> = typeof uuidOrIdOrIds === 'string' ? [uuidOrIdOrIds] : chunk( !Array.isArray(uuidOrIdOrIds) ? [uuidOrIdOrIds] : uuidOrIdOrIds, CHUNK_SIZE, ); const apps: Array<Parameters<typeof fn>[0]> = []; for (const uuidOrIdOrIdsChunk of chunks) { const deviceFilter = Array.isArray(uuidOrIdOrIdsChunk) ? { id: { $in: uuidOrIdOrIdsChunk }, } : { uuid: { $startswith: uuidOrIdOrIdsChunk }, }; const applicationOptions = { $select: 'id', $expand: { owns__device: mergePineOptions( { $select: 'id', $filter: deviceFilter, }, options, ), }, $filter: { owns__device: { $any: { $alias: 'd', $expr: { d: deviceFilter, }, }, }, }, } as const; type defaultOptionsResult = Array< PineTypedResult<Application, typeof applicationOptions> >; apps.push( ...((await applicationModel().getAll( applicationOptions, )) as defaultOptionsResult as typeof apps), ); } const deviceIds = flatten( apps.map((app) => app.owns__device.map((d) => d.id)), ); if (!deviceIds.length) { throw new errors.BalenaDeviceNotFound(uuidOrIdOrIds.toString()); } if (typeof uuidOrIdOrIds === 'string' && deviceIds.length > 1) { throw new errors.BalenaAmbiguousDevice(uuidOrIdOrIds); } else if (Array.isArray(uuidOrIdOrIds)) { const deviceIdsSet = new Set(deviceIds); for (const id of uuidOrIdOrIds) { if (!deviceIdsSet.has(id)) { throw new errors.BalenaDeviceNotFound(id); } } } for (const app of apps) { await fn(app); } } // Infer dashboardUrl from apiUrl if former is undefined const dashboardUrl = opts.dashboardUrl ?? apiUrl!.replace(/api/, 'dashboard'); const getDeviceUrlsBase = once(async function () { if (deviceUrlsBase != null) { return deviceUrlsBase; } return (await configModel().getAll()).deviceUrlsBase; }); const getOsUpdateHelper = once(async () => { const $deviceUrlsBase = await getDeviceUrlsBase(); const { getOsUpdateHelper: _getOsUpdateHelper } = require('../util/device-actions/os-update') as typeof import('../util/device-actions/os-update'); return _getOsUpdateHelper($deviceUrlsBase, request); }); // Internal method for uuid/id disambiguation // Note that this throws an exception for missing uuids, but not missing ids const getId = async (uuidOrId: string | number) => { if (isId(uuidOrId)) { return uuidOrId; } else { const { id } = await exports.get(uuidOrId, { $select: 'id' }); return id; } }; const addExtraInfo = function < T extends Parameters<typeof normalizeDeviceOsVersion>[0], >(device: T) { normalizeDeviceOsVersion(device); return device; }; const getAppliedConfigVariableValue = async ( uuidOrId: string | number, name: string, ) => { const options = { $expand: { device_config_variable: { $select: 'value', $filter: { name, }, }, belongs_to__application: { $select: 'id', $expand: { application_config_variable: { $select: 'value', $filter: { name, }, }, }, }, }, } as const; const { device_config_variable: [deviceConfig], belongs_to__application: [ { application_config_variable: [appConfig], }, ], } = (await exports.get(uuidOrId, options)) as PineTypedResult< Device, typeof options >; return (deviceConfig ?? appConfig)?.value; }; const set = async ( uuidOrId: string | number, body: SubmitBody<Device>, ): Promise<void> => { const { id } = await exports.get(uuidOrId, { $select: 'id' }); await pine.patch({ resource: 'device', body, id, }); }; const exports = { _getId: getId, OverallStatus, /** * @summary Get Dashboard URL for a specific device * @function getDashboardUrl * @memberof balena.models.device * * @param {String} uuid - Device uuid * * @returns {String} - Dashboard URL for the specific device * @throws Exception if the uuid is empty * * @example * dashboardDeviceUrl = balena.models.device.getDashboardUrl('a44b544b8cc24d11b036c659dfeaccd8') */ getDashboardUrl(uuid: string): string { if (typeof uuid !== 'string' || uuid.length === 0) { throw new Error('The uuid option should be a non empty string'); } return url.resolve(dashboardUrl, `/devices/${uuid}/summary`); }, /** * @summary Get all devices * @name getAll * @public * @function * @memberof balena.models.device * * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - devices * @returns {Promise} * * @description * This method returns all devices that the current user can access. * In order to have the following computed properties in the result * you have to explicitly define them in a `$select` in the extra options: * * `overall_status` * * `overall_progress` * * @example * balena.models.device.getAll().then(function(devices) { * console.log(devices); * }); * * @example * balena.models.device.getAll({ $select: ['overall_status', 'overall_progress'] }).then(function(device) { * console.log(device); * }) * * @example * balena.models.device.getAll(function(error, devices) { * if (error) throw error; * console.log(devices); * }); */ async getAll(options?: PineOptions<Device>): Promise<Device[]> { if (options == null) { options = {}; } const devices = await pine.get({ resource: 'device', options: mergePineOptions({ $orderby: 'device_name asc' }, options), }); return devices.map(addExtraInfo) as Device[]; }, /** * @summary Get all devices by application * @name getAllByApplication * @public * @function * @memberof balena.models.device * * @description * This method returns all devices of a specific application. * In order to have the following computed properties in the result * you have to explicitly define them in a `$select` in the extra options: * * `overall_status` * * `overall_progress` * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - devices * @returns {Promise} * * @example * balena.models.device.getAllByApplication('MyApp').then(function(devices) { * console.log(devices); * }); * * @example * balena.models.device.getAllByApplication(123).then(function(devices) { * console.log(devices); * }); * * @example * balena.models.device.getAllByApplication('MyApp', { $select: ['overall_status', 'overall_progress'] }).then(function(device) { * console.log(device); * }) * * @example * balena.models.device.getAllByApplication('MyApp', function(error, devices) { * if (error) throw error; * console.log(devices); * }); */ async getAllByApplication( nameOrSlugOrId: string | number, options?: PineOptions<Device>, ): Promise<Device[]> { if (options == null) { options = {}; } const { id } = await applicationModel().get(nameOrSlugOrId, { $select: 'id', }); return await exports.getAll( mergePineOptions({ $filter: { belongs_to__application: id } }, options), ); }, /** * @summary Get all devices by parent device * @name getAllByParentDevice * @public * @function * @memberof balena.models.device * * @param {String|Number} parentUuidOrId - parent device uuid (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - devices * @returns {Promise} * * @example * balena.models.device.getAllByParentDevice('7cf02a6').then(function(devices) { * console.log(devices); * }); * * @example * balena.models.device.getAllByParentDevice(123).then(function(devices) { * console.log(devices); * }); * * @example * balena.models.device.getAllByParentDevice('7cf02a6', function(error, devices) { * if (error) throw error; * console.log(devices); * }); */ async getAllByParentDevice( parentUuidOrId: string | number, options?: PineOptions<Device>, ): Promise<Device[]> { if (options == null) { options = {}; } const { id } = await exports.get(parentUuidOrId, { $select: 'id' }); return await exports.getAll( mergePineOptions({ $filter: { is_managed_by__device: id } }, options), ); }, /** * @summary Get a single device * @name get * @public * @function * @memberof balena.models.device * * @description * This method returns a single device by id or uuid. * In order to have the following computed properties in the result * you have to explicitly define them in a `$select` in the extra options: * * `overall_status` * * `overall_progress` * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object} - device * @returns {Promise} * * @example * balena.models.device.get('7cf02a6').then(function(device) { * console.log(device); * }) * * @example * balena.models.device.get(123).then(function(device) { * console.log(device); * }) * * @example * balena.models.device.get('7cf02a6', { $select: ['overall_status', 'overall_progress'] }).then(function(device) { * console.log(device); * }) * * @example * balena.models.device.get('7cf02a6', function(error, device) { * if (error) throw error; * console.log(device); * }); */ async get( uuidOrId: string | number, options?: PineOptions<Device>, ): Promise<Device> { if (options == null) { options = {}; } if (uuidOrId == null) { throw new errors.BalenaDeviceNotFound(uuidOrId); } let device; if (isId(uuidOrId)) { device = await pine.get({ resource: 'device', id: uuidOrId, options, }); if (device == null) { throw new errors.BalenaDeviceNotFound(uuidOrId); } } else { const devices = await pine.get({ resource: 'device', options: mergePineOptions( { $filter: { uuid: { $startswith: uuidOrId }, }, }, options, ), }); if (devices.length === 0) { throw new errors.BalenaDeviceNotFound(uuidOrId); } if (devices.length > 1) { throw new errors.BalenaAmbiguousDevice(uuidOrId); } device = devices[0]; } return addExtraInfo(device) as Device; }, /** * @summary Get a single device along with its associated services' details, * including their associated commit * @name getWithServiceDetails * @public * @function * @memberof balena.models.device * * @description * This method does not map exactly to the underlying model: it runs a * larger prebuilt query, and reformats it into an easy to use and * understand format. If you want more control, or to see the raw model * directly, use `device.get(uuidOrId, options)` instead. * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object} - device with service details * @returns {Promise} * * @example * balena.models.device.getWithServiceDetails('7cf02a6').then(function(device) { * console.log(device); * }) * * @example * balena.models.device.getWithServiceDetails(123).then(function(device) { * console.log(device); * }) * * @example * balena.models.device.getWithServiceDetails('7cf02a6', function(error, device) { * if (error) throw error; * console.log(device); * }); */ async getWithServiceDetails( uuidOrId: string | number, options?: PineOptions<Device>, ): Promise<DeviceWithServiceDetails<CurrentServiceWithCommit>> { if (options == null) { options = {}; } const device = await exports.get( uuidOrId, mergePineOptions( { $expand: getCurrentServiceDetailsPineExpand(true) }, options, ), ); return generateCurrentServiceDetails(device); }, /** * @summary Get devices by name * @name getByName * @public * @function * @memberof balena.models.device * * @param {String} name - device name * @fulfil {Object[]} - devices * @returns {Promise} * * @example * balena.models.device.getByName('MyDevice').then(function(devices) { * console.log(devices); * }); * * @example * balena.models.device.getByName('MyDevice', function(error, devices) { * if (error) throw error; * console.log(devices); * }); */ async getByName( name: string, options?: PineOptions<Device>, ): Promise<Device[]> { if (options == null) { options = {}; } const devices = await exports.getAll( mergePineOptions({ $filter: { device_name: name } }, options), ); if (devices.length === 0) { throw new errors.BalenaDeviceNotFound(name); } return devices; }, /** * @summary Get the name of a device * @name getName * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {String} - device name * @returns {Promise} * * @example * balena.models.device.getName('7cf02a6').then(function(deviceName) { * console.log(deviceName); * }); * * @example * balena.models.device.getName(123).then(function(deviceName) { * console.log(deviceName); * }); * * @example * balena.models.device.getName('7cf02a6', function(error, deviceName) { * if (error) throw error; * console.log(deviceName); * }); */ getName: async (uuidOrId: string | number): Promise<string> => { const { device_name } = await exports.get(uuidOrId, { $select: 'device_name', }); return device_name; }, /** * @summary Get application name * @name getApplicationName * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {String} - application name * @returns {Promise} * * @example * balena.models.device.getApplicationName('7cf02a6').then(function(applicationName) { * console.log(applicationName); * }); * * @example * balena.models.device.getApplicationName(123).then(function(applicationName) { * console.log(applicationName); * }); * * @example * balena.models.device.getApplicationName('7cf02a6', function(error, applicationName) { * if (error) throw error; * console.log(applicationName); * }); */ getApplicationName: async (uuidOrId: string | number): Promise<string> => { const deviceOptions = { $select: 'id', $expand: { belongs_to__application: { $select: 'app_name' } }, } as const; const device = (await exports.get( uuidOrId, deviceOptions, )) as PineTypedResult<Device, typeof deviceOptions>; return device.belongs_to__application[0].app_name; }, /** * @summary Check if a device exists * @name has * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {Boolean} - has device * @returns {Promise} * * @example * balena.models.device.has('7cf02a6').then(function(hasDevice) { * console.log(hasDevice); * }); * * @example * balena.models.device.has(123).then(function(hasDevice) { * console.log(hasDevice); * }); * * @example * balena.models.device.has('7cf02a6', function(error, hasDevice) { * if (error) throw error; * console.log(hasDevice); * }); */ has: async (uuidOrId: string | number): Promise<boolean> => { try { await exports.get(uuidOrId, { $select: ['id'] }); return true; } catch (err) { if (err instanceof errors.BalenaDeviceNotFound) { return false; } throw err; } }, /** * @summary Check if a device is online * @name isOnline * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {Boolean} - is device online * @returns {Promise} * * @example * balena.models.device.isOnline('7cf02a6').then(function(isOnline) { * console.log('Is device online?', isOnline); * }); * * @example * balena.models.device.isOnline(123).then(function(isOnline) { * console.log('Is device online?', isOnline); * }); * * @example * balena.models.device.isOnline('7cf02a6', function(error, isOnline) { * if (error) throw error; * console.log('Is device online?', isOnline); * }); */ isOnline: async (uuidOrId: string | number): Promise<boolean> => { const { is_online } = await exports.get(uuidOrId, { $select: 'is_online', }); return is_online; }, /** * @summary Get the local IP addresses of a device * @name getLocalIPAddresses * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {String[]} - local ip addresses * @reject {Error} Will reject if the device is offline * @returns {Promise} * * @example * balena.models.device.getLocalIPAddresses('7cf02a6').then(function(localIPAddresses) { * localIPAddresses.forEach(function(localIP) { * console.log(localIP); * }); * }); * * @example * balena.models.device.getLocalIPAddresses(123).then(function(localIPAddresses) { * localIPAddresses.forEach(function(localIP) { * console.log(localIP); * }); * }); * * @example * balena.models.device.getLocalIPAddresses('7cf02a6', function(error, localIPAddresses) { * if (error) throw error; * * localIPAddresses.forEach(function(localIP) { * console.log(localIP); * }); * }); */ getLocalIPAddresses: async ( uuidOrId: string | number, ): Promise<string[]> => { const { is_online, ip_address, vpn_address } = await exports.get( uuidOrId, { $select: ['is_online', 'ip_address', 'vpn_address'] }, ); if (!is_online) { throw new Error(`The device is offline: ${uuidOrId}`); } const ips = (ip_address ?? '').split(' '); return ips.filter((ip) => ip !== vpn_address); }, /** * @summary Get the MAC addresses of a device * @name getMACAddresses * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {String[]} - mac addresses * @returns {Promise} * * @example * balena.models.device.getMACAddresses('7cf02a6').then(function(macAddresses) { * macAddresses.forEach(function(mac) { * console.log(mac); * }); * }); * * @example * balena.models.device.getMACAddresses(123).then(function(macAddresses) { * macAddresses.forEach(function(mac) { * console.log(mac); * }); * }); * * @example * balena.models.device.getMACAddresses('7cf02a6', function(error, macAddresses) { * if (error) throw error; * * macAddresses.forEach(function(mac) { * console.log(mac); * }); * }); */ getMACAddresses: async (uuidOrId: string | number): Promise<string[]> => { const { mac_address } = await exports.get(uuidOrId, { $select: ['mac_address'], }); if (mac_address == null) { return []; } return mac_address.split(' '); }, /** * @summary Get the metrics related information for a device * @name getMetrics * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {Object} - device metrics * @returns {Promise} * * @example * balena.models.device.getMetrics('7cf02a6').then(function(deviceMetrics) { * console.log(deviceMetrics); * }); * * @example * balena.models.device.getMetrics(123).then(function(deviceMetrics) { * console.log(deviceMetrics); * }); * * @example * balena.models.device.getMetrics('7cf02a6', function(error, deviceMetrics) { * if (error) throw error; * * console.log(deviceMetrics); * }); */ getMetrics: async (uuidOrId: string | number): Promise<DeviceMetrics> => { const device = await exports.get(uuidOrId, { $select: [ 'memory_usage', 'memory_total', 'storage_block_device', 'storage_usage', 'storage_total', 'cpu_usage', 'cpu_temp', 'cpu_id', 'is_undervolted', ], }); // @ts-expect-error delete device.__metadata; return device; }, /** * @summary Remove device * @name remove * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.remove('7cf02a6'); * * @example * balena.models.device.remove(123); * * @example * balena.models.device.remove('7cf02a6', function(error) { * if (error) throw error; * }); */ remove: async (uuidOrId: string | number): Promise<void> => { const { uuid } = await exports.get(uuidOrId, { $select: 'uuid' }); await pine.delete({ resource: 'device', id: { uuid, }, }); }, /** * @summary Deactivate device * @name deactivate * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.deactivate('7cf02a6'); * * @example * balena.models.device.deactivate(123); * * @example * balena.models.device.deactivate('7cf02a6', function(error) { * if (error) throw error; * }); */ deactivate: async (uuidOrId: string | number): Promise<void> => { const { id } = await exports.get(uuidOrId, { $select: 'id' }); await pine.patch({ resource: 'device', body: { is_active: false, }, id, }); }, /** * @summary Rename device * @name rename * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String} newName - the device new name * * @returns {Promise} * * @example * balena.models.device.rename('7cf02a6', 'NewName'); * * @example * balena.models.device.rename(123, 'NewName'); * * @example * balena.models.device.rename('7cf02a6', 'NewName', function(error) { * if (error) throw error; * }); */ rename: (uuidOrId: string | number, newName: string): Promise<void> => set(uuidOrId, { device_name: newName, }), /** * @summary Note a device * @name note * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String} note - the note * * @returns {Promise} * * @example * balena.models.device.note('7cf02a6', 'My useful note'); * * @example * balena.models.device.note(123, 'My useful note'); * * @example * balena.models.device.note('7cf02a6', 'My useful note', function(error) { * if (error) throw error; * }); */ note: (uuidOrId: string | number, note: string): Promise<void> => set(uuidOrId, { note }), /** * @summary Set a custom location for a device * @name setCustomLocation * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Object} location - the location ({ latitude: 123, longitude: 456 }) * * @returns {Promise} * * @example * balena.models.device.setCustomLocation('7cf02a6', { latitude: 123, longitude: 456 }); * * @example * balena.models.device.setCustomLocation(123, { latitude: 123, longitude: 456 }); * * @example * balena.models.device.setCustomLocation('7cf02a6', { latitude: 123, longitude: 456 }, function(error) { * if (error) throw error; * }); */ setCustomLocation: ( uuidOrId: string | number, location: { latitude: string | number; longitude: string | number }, ): Promise<void> => set(uuidOrId, { custom_latitude: String(location.latitude), custom_longitude: String(location.longitude), }), /** * @summary Clear the custom location of a device * @name unsetCustomLocation * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * * @returns {Promise} * * @example * balena.models.device.unsetCustomLocation('7cf02a6'); * * @example * balena.models.device.unsetCustomLocation(123); * * @example * balena.models.device.unsetLocation('7cf02a6', function(error) { * if (error) throw error; * }); */ unsetCustomLocation: (uuidOrId: string | number): Promise<void> => exports.setCustomLocation(uuidOrId, { latitude: '', longitude: '', }), /** * @summary Move a device to another application * @name move * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String|Number} applicationNameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * * @returns {Promise} * * @example * balena.models.device.move('7cf02a6', 'MyApp'); * * @example * balena.models.device.move(123, 'MyApp'); * * @example * balena.models.device.move(123, 456); * * @example * balena.models.device.move('7cf02a6', 'MyApp', function(error) { * if (error) throw error; * }); */ move: async ( uuidOrId: string | number, applicationNameOrSlugOrId: string | number, ): Promise<void> => { const deviceOptions = { $select: 'uuid', $expand: { is_of__device_type: { $select: 'slug' } }, } as const; const applicationOptions = { $select: 'id', $expand: { is_for__device_type: { $select: 'slug' } }, } as const; const [device, deviceTypes, application] = await Promise.all([ exports.get(uuidOrId, deviceOptions) as Promise< PineTypedResult<Device, typeof deviceOptions> >, configModel().getDeviceTypes(), applicationModel().get( applicationNameOrSlugOrId, applicationOptions, ) as Promise<PineTypedResult<Application, typeof applicationOptions>>, ]); const osDeviceType = deviceTypesUtils().getBySlug( deviceTypes, device.is_of__device_type[0].slug, ); const targetAppDeviceType = deviceTypesUtils().getBySlug( deviceTypes, application.is_for__device_type[0].slug, ); const isCompatibleMove = deviceTypesUtils().isDeviceTypeCompatibleWith( osDeviceType, targetAppDeviceType, ); if (!isCompatibleMove) { throw new errors.BalenaInvalidDeviceType( `Incompatible application: ${applicationNameOrSlugOrId}`, ); } await pine.patch<Device>({ resource: 'device', body: { belongs_to__application: application.id, }, id: { uuid: device.uuid, }, }); }, // TODO: Move this in the supervisor helper as well /** * @summary Restart application on device * @name restartApplication * @public * @function * @memberof balena.models.device * * @description * This function restarts the Docker container running * the application on the device, but doesn't reboot * the device itself. * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.restartApplication('7cf02a6'); * * @example * balena.models.device.restartApplication(123); * * @example * balena.models.device.restartApplication('7cf02a6', function(error) { * if (error) throw error; * }); */ restartApplication: (uuidOrId: string | number): Promise<void> => withSupervisorLockedError(async () => { try { const deviceId = await getId(uuidOrId); const { body } = await request.send({ method: 'POST', url: `/device/${deviceId}/restart`, baseUrl: apiUrl, timeout: CONTAINER_ACTION_ENDPOINT_TIMEOUT, }); return body; } catch (err) { if (isNotFoundResponse(err)) { treatAsMissingDevice(uuidOrId, err); } throw err; } }), ...getSupervisorApiHelper(deps, opts), /** * @summary Get the target supervisor state on a device * @name getSupervisorTargetState * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.getSupervisorTargetState('7cf02a6').then(function(state) { * console.log(state); * }); * * @example * balena.models.device.getSupervisorTargetState(123).then(function(state) { * console.log(state); * }); * * @example * balena.models.device.getSupervisorTargetState('7cf02a6', function(error, state) { * if (error) throw error; * console.log(state); * }); */ getSupervisorTargetState: async ( uuidOrId: string | number, ): Promise<DeviceState.DeviceState> => { const { uuid } = await exports.get(uuidOrId, { $select: 'uuid' }); const { body } = await request.send({ url: `/device/v2/${uuid}/state`, baseUrl: apiUrl, }); return body; }, /** * @summary Get display name for a device * @name getDisplayName * @public * @function * @memberof balena.models.device * * @deprecated use balena.models.deviceType.getName * @see {@link balena.models.device.getSupportedDeviceTypes} for a list of supported devices * * @param {String} deviceTypeSlug - device type slug * @fulfil {String} - device display name * @returns {Promise} * * @example * balena.models.device.getDisplayName('raspberry-pi').then(function(deviceTypeName) { * console.log(deviceTypeName); * // Raspberry Pi * }); * * @example * balena.models.device.getDisplayName('raspberry-pi', function(error, deviceTypeName) { * if (error) throw error; * console.log(deviceTypeName); * // Raspberry Pi * }); */ getDisplayName: async ( deviceTypeSlug: string, ): Promise<string | undefined> => { try { const { name } = await exports.getManifestBySlug(deviceTypeSlug); return name; } catch (error) { if (error instanceof errors.BalenaInvalidDeviceType) { return; } throw error; } }, /** * @summary Get device slug * @name getDeviceSlug * @public * @function * @memberof balena.models.device * * @deprecated use balena.models.deviceType.getSlugByName * @see {@link balena.models.device.getSupportedDeviceTypes} for a list of supported devices * * @param {String} deviceTypeName - device type name * @fulfil {String} - device slug name * @returns {Promise} * * @example * balena.models.device.getDeviceSlug('Raspberry Pi').then(function(deviceTypeSlug) { * console.log(deviceTypeSlug); * // raspberry-pi * }); * * @example * balena.models.device.getDeviceSlug('Raspberry Pi', function(error, deviceTypeSlug) { * if (error) throw error; * console.log(deviceTypeSlug); * // raspberry-pi * }); */ getDeviceSlug: async ( deviceTypeName: string, ): Promise<string | undefined> => { try { const { slug } = await exports.getManifestBySlug(deviceTypeName); return slug; } catch (error) { if (error instanceof errors.BalenaInvalidDeviceType) { return; } throw error; } }, /** * @summary Get supported device types * @name getSupportedDeviceTypes * @public * @function * @memberof balena.models.device * * @deprecated use balena.models.deviceType.getAll * @fulfil {String[]} - supported device types * @returns {Promise} * * @example * balena.models.device.getSupportedDeviceTypes().then(function(supportedDeviceTypes) { * supportedDeviceTypes.forEach(function(supportedDeviceType) { * console.log('Balena supports:', supportedDeviceType); * }); * }); * * @example * balena.models.device.getSupportedDeviceTypes(function(error, supportedDeviceTypes) { * if (error) throw error; * * supportedDeviceTypes.forEach(function(supportedDeviceType) { * console.log('Balena supports:', supportedDeviceType); * }); * }); */ getSupportedDeviceTypes: async (): Promise<string[]> => { const deviceTypes = await configModel().getDeviceTypes(); return deviceTypes.map((dt) => dt.name); }, /** * @summary Get a device manifest by slug * @name getManifestBySlug * @public * @function * @memberof balena.models.device * * @deprecated use balena.models.deviceType.getBySlugOrName * @param {String} slugOrName - device slug * @fulfil {Object} - device manifest * @returns {Promise} * * @example * balena.models.device.getManifestBySlug('raspberry-pi').then(function(manifest) { * console.log(manifest); * }); * * @example * balena.models.device.getManifestBySlug('raspberry-pi', function(error, manifest) { * if (error) throw error; * console.log(manifest); * }); */ getManifestBySlug: async ( slugOrName: string, ): Promise<DeviceTypeJson.DeviceType> => { const deviceTypes = await configModel().getDeviceTypes(); const deviceManifest = deviceTypes.find( (deviceType) => deviceType.name === slugOrName || deviceType.slug === slugOrName || deviceType.aliases?.includes(slugOrName), ); if (deviceManifest == null) { throw new errors.BalenaInvalidDeviceType(slugOrName); } return deviceManifest; }, /** * @summary Get a device manifest by application name * @name getManifestByApplication * @public * @function * @memberof balena.models.device * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @fulfil {Object} - device manifest * @returns {Promise} * * @example * balena.models.device.getManifestByApplication('MyApp').then(function(manifest) { * console.log(manifest); * }); * * @example * balena.models.device.getManifestByApplication(123).then(function(manifest) { * console.log(manifest); * }); * * @example * balena.models.device.getManifestByApplication('MyApp', function(error, manifest) { * if (error) throw error; * console.log(manifest); * }); */ getManifestByApplication: async ( nameOrSlugOrId: string | number, ): Promise<DeviceTypeJson.DeviceType> => { const applicationOptions = { $select: 'id', $expand: { is_for__device_type: { $select: 'slug' } }, } as const; const app = (await applicationModel().get( nameOrSlugOrId, applicationOptions, )) as PineTypedResult<Application, typeof applicationOptions>; return await exports.getManifestBySlug(app.is_for__device_type[0].slug); }, /** * @summary Generate a random key, useful for both uuid and api key. * @name generateUniqueKey * @function * @public * @memberof balena.models.device * * @returns {String} A generated key * * @example * randomKey = balena.models.device.generateUniqueKey(); * // randomKey is a randomly generated key that can be used as either a uuid or an api key * console.log(randomKey); */ generateUniqueKey(): string { // Wrap with a function so that we can lazy load registerDevice return registerDevice().generateUniqueKey(); }, /** * @summary Register a new device with a Balena application. * @name register * @public * @function * @memberof balena.models.device * * @param {String|Number} applicationNameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {String} uuid - device uuid * * @fulfil {Object} Device registration info ({ id: "...", uuid: "...", api_key: "..." }) * @returns {Promise} * * @example * var uuid = balena.models.device.generateUniqueKey(); * balena.models.device.register('MyApp', uuid).then(function(registrationInfo) { * console.log(registrationInfo); * }); * * @example * var uuid = balena.models.device.generateUniqueKey(); * balena.models.device.register(123, uuid).then(function(registrationInfo) { * console.log(registrationInfo); * }); * * @example * var uuid = balena.models.device.generateUniqueKey(); * balena.models.device.register('MyApp', uuid, function(error, registrationInfo) { * if (error) throw error; * console.log(registrationInfo); * }); */ async register( applicationNameOrSlugOrId: string | number, uuid: string, ): Promise<{ id: number; uuid: string; api_key: string; }> { const applicationOptions = { $select: 'id', $expand: { is_for__device_type: { $select: 'slug' } }, } as const; const [userId, apiKey, application] = await Promise.all([ sdkInstance.auth.getUserId(), applicationModel().generateProvisioningKey(applicationNameOrSlugOrId), applicationModel().get( applicationNameOrSlugOrId, applicationOptions, ) as Promise<PineTypedResult<Application, typeof applicationOptions>>, ]); return await registerDevice().register({ userId, applicationId: application.id, uuid, deviceType: application.is_for__device_type[0].slug, provisioningApiKey: apiKey, apiEndpoint: apiUrl!, }); }, /** * @summary Generate a device key * @name generateDeviceKey * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.generateDeviceKey('7cf02a6').then(function(deviceApiKey) { * console.log(deviceApiKey); * }); * * @example * balena.models.device.generateDeviceKey(123).then(function(deviceApiKey) { * console.log(deviceApiKey); * }); * * @example * balena.models.device.generateDeviceKey('7cf02a6', function(error, deviceApiKey) { * if (error) throw error; * console.log(deviceApiKey); * }); */ generateDeviceKey: async (uuidOrId: string | number): Promise<string> => { try { const deviceId = await getId(uuidOrId); const { body } = await request.send({ method: 'POST', url: `/api-key/device/${deviceId}/device-key`, baseUrl: apiUrl, }); return body; } catch (err) { if (isNoDeviceForKeyResponse(err)) { treatAsMissingDevice(uuidOrId, err); } throw err; } }, /** * @summary Check if a device is web accessible with device utls * @name hasDeviceUrl * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {Boolean} - has device url * @returns {Promise} * * @example * balena.models.device.hasDeviceUrl('7cf02a6').then(function(hasDeviceUrl) { * if (hasDeviceUrl) { * console.log('The device has device URL enabled'); * } * }); * * @example * balena.models.device.hasDeviceUrl(123).then(function(hasDeviceUrl) { * if (hasDeviceUrl) { * console.log('The device has device URL enabled'); * } * }); * * @example * balena.models.device.hasDeviceUrl('7cf02a6', function(error, hasDeviceUrl) { * if (error) throw error; * * if (hasDeviceUrl) { * console.log('The device has device URL enabled'); * } * }); */ hasDeviceUrl: async (uuidOrId: string | number): Promise<boolean> => { const { is_web_accessible } = await exports.get(uuidOrId, { $select: 'is_web_accessible', }); return is_web_accessible; }, /** * @summary Get a device url * @name getDeviceUrl * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {String} - device url * @returns {Promise} * * @example * balena.models.device.getDeviceUrl('7cf02a6').then(function(url) { * console.log(url); * }); * * @example * balena.models.device.getDeviceUrl(123).then(function(url) { * console.log(url); * }); * * @example * balena.models.device.getDeviceUrl('7cf02a6', function(error, url) { * if (error) throw error; * console.log(url); * }); */ getDeviceUrl: async (uuidOrId: string | number): Promise<string> => { const hasDeviceUrl = await exports.hasDeviceUrl(uuidOrId); if (!hasDeviceUrl) { throw new Error(`Device is not web accessible: ${uuidOrId}`); } const $deviceUrlsBase = await getDeviceUrlsBase(); const { uuid } = await exports.get(uuidOrId, { $select: 'uuid' }); return `https://${uuid}.${$deviceUrlsBase}`; }, /** * @summary Enable device url for a device * @name enableDeviceUrl * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.enableDeviceUrl('7cf02a6'); * * @example * balena.models.device.enableDeviceUrl(123); * * @example * balena.models.device.enableDeviceUrl('7cf02a6', function(error) { * if (error) throw error; * }); */ enableDeviceUrl: (uuidOrId: string | number): Promise<void> => set(uuidOrId, { is_web_accessible: true, }), /** * @summary Disable device url for a device * @name disableDeviceUrl * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.disableDeviceUrl('7cf02a6'); * * @example * balena.models.device.disableDeviceUrl(123); * * @example * balena.models.device.disableDeviceUrl('7cf02a6', function(error) { * if (error) throw error; * }); */ disableDeviceUrl: (uuidOrId: string | number): Promise<void> => set(uuidOrId, { is_web_accessible: false, }), /** * @summary Enable local mode * @name enableLocalMode * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.enableLocalMode('7cf02a6'); * * @example * balena.models.device.enableLocalMode(123); * * @example * balena.models.device.enableLocalMode('7cf02a6', function(error) { * if (error) throw error; * }); */ async enableLocalMode(uuidOrId: string | number): Promise<void> { const selectedProps: Array<SelectableProps<Device>> = [ 'id', ...LOCAL_MODE_SUPPORT_PROPERTIES, ]; const device = await exports.get(uuidOrId, { $select: selectedProps }); checkLocalModeSupported(device); return await exports.configVar.set(device.id, LOCAL_MODE_ENV_VAR, '1'); }, /** * @summary Disable local mode * @name disableLocalMode * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.disableLocalMode('7cf02a6'); * * @example * balena.models.device.disableLocalMode(123); * * @example * balena.models.device.disableLocalMode('7cf02a6', function(error) { * if (error) throw error; * }); */ disableLocalMode: (uuidOrId: string | number): Promise<void> => exports.configVar.set(uuidOrId, LOCAL_MODE_ENV_VAR, '0'), /** * @summary Check if local mode is enabled on the device * @name isInLocalMode * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {Boolean} - has device url * @returns {Promise} * * @example * balena.models.device.isInLocalMode('7cf02a6').then(function(isInLocalMode) { * if (isInLocalMode) { * console.log('The device has local mode enabled'); * } * }); * * @example * balena.models.device.isInLocalMode(123).then(function(isInLocalMode) { * if (isInLocalMode) { * console.log('The device has local mode enabled'); * } * }); * * @example * balena.models.device.isInLocalMode('7cf02a6', function(error, isInLocalMode) { * if (error) throw error; * * if (isInLocalMode) { * console.log('The device has local mode enabled'); * } * }); */ isInLocalMode: async (uuidOrId: string | number): Promise<boolean> => { const value = await exports.configVar.get(uuidOrId, LOCAL_MODE_ENV_VAR); return value === '1'; }, /** * @summary Returns whether local mode is supported along with a message describing the reason why local mode is not supported. * @name getLocalModeSupport * @public * @function * @memberof balena.models.device * * @param {Object} device - A device object * @returns {Object} Local mode support info ({ supported: true/false, message: "..." }) * * @example * balena.models.device.get('7cf02a6').then(function(device) { * balena.models.device.getLocalModeSupport(device); * }) */ getLocalModeSupport, /** * @summary Enable lock override * @name enableLockOverride * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.enableLockOverride('7cf02a6'); * * @example * balena.models.device.enableLockOverride(123); * * @example * balena.models.device.enableLockOverride('7cf02a6', function(error) { * if (error) throw error; * }); */ enableLockOverride: (uuidOrId: string | number): Promise<void> => configVarModel.set(uuidOrId, OVERRIDE_LOCK_ENV_VAR, '1'), /** * @summary Disable lock override * @name disableLockOverride * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.disableLockOverride('7cf02a6'); * * @example * balena.models.device.disableLockOverride(123); * * @example * balena.models.device.disableLockOverride('7cf02a6', function(error) { * if (error) throw error; * }); */ disableLockOverride: (uuidOrId: string | number): Promise<void> => configVarModel.set(uuidOrId, OVERRIDE_LOCK_ENV_VAR, '0'), /** * @summary Check if a device has the lock override enabled * @name hasLockOverride * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.hasLockOverride('7cf02a6'); * * @example * balena.models.device.hasLockOverride(123); * * @example * balena.models.device.hasLockOverride('7cf02a6', function(error) { * if (error) throw error; * }); */ hasLockOverride: async (uuidOrId: string | number): Promise<boolean> => { return ( (await getAppliedConfigVariableValue( uuidOrId, OVERRIDE_LOCK_ENV_VAR, )) === '1' ); }, /** * @summary Get the status of a device * @name getStatus * @public * @function * @memberof balena.models.device * * @description * Convenience method for getting the overall status of a device. * It's recommended to use `balena.models.device.get()` instead, * in case that you need to retrieve more device fields than just the status. * * @see {@link balena.models.device.get} for an example on selecting the `overall_status` field. * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {String} - device status * @returns {Promise} * * @example * balena.models.device.getStatus('7cf02a6').then(function(status) { * console.log(status); * }); * * @example * balena.models.device.getStatus(123).then(function(status) { * console.log(status); * }); * * @example * balena.models.device.getStatus('7cf02a6', function(error, status) { * if (error) throw error; * console.log(status); * }); */ async getStatus(uuidOrId: string | number): Promise<string> { if (typeof uuidOrId !== 'string' && typeof uuidOrId !== 'number') { throw new errors.BalenaInvalidParameterError('uuidOrId', uuidOrId); } const { overall_status } = await exports.get(uuidOrId, { $select: 'overall_status', }); return overall_status; }, /** * @summary Get the progress of a device * @name getProgress * @public * @function * @memberof balena.models.device * * @description * Convenience method for getting the overall progress of a device. * It's recommended to use `balena.models.device.get()` instead, * in case that you need to retrieve more device fields than just the progress. * * @see {@link balena.models.device.get} for an example on selecting the `overall_progress` field. * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {Number|Null} - device progress * @returns {Promise} * * @example * balena.models.device.getProgress('7cf02a6').then(function(progress) { * console.log(progress); * }); * * @example * balena.models.device.getProgress(123).then(function(progress) { * console.log(progress); * }); * * @example * balena.models.device.getProgress('7cf02a6', function(error, progress) { * if (error) throw error; * console.log(progress); * }); */ async getProgress(uuidOrId: string | number): Promise<number | null> { if (typeof uuidOrId !== 'string' && typeof uuidOrId !== 'number') { throw new errors.BalenaInvalidParameterError('uuidOrId', uuidOrId); } const { overall_progress } = await exports.get(uuidOrId, { $select: 'overall_progress', }); return overall_progress; }, /** * @summary Grant support access to a device until a specified time * @name grantSupportAccess * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Number} expiryTimestamp - a timestamp in ms for when the support access will expire * @returns {Promise} * * @example * balena.models.device.grantSupportAccess('7cf02a6', Date.now() + 3600 * 1000); * * @example * balena.models.device.grantSupportAccess(123, Date.now() + 3600 * 1000); * * @example * balena.models.device.grantSupportAccess('7cf02a6', Date.now() + 3600 * 1000, function(error) { * if (error) throw error; * }); */ async grantSupportAccess( uuidOrId: string | number, expiryTimestamp: number, ): Promise<void> { if (expiryTimestamp == null || expiryTimestamp <= Date.now()) { throw new errors.BalenaInvalidParameterError( 'expiryTimestamp', expiryTimestamp, ); } return await set(uuidOrId, { // @ts-expect-error a number is valid to set but it will always be returned as an ISO string so the typings specify string rather than string | number is_accessible_by_support_until__date: expiryTimestamp, }); }, /** * @summary Revoke support access to a device * @name revokeSupportAccess * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @returns {Promise} * * @example * balena.models.device.revokeSupportAccess('7cf02a6'); * * @example * balena.models.device.revokeSupportAccess(123); * * @example * balena.models.device.revokeSupportAccess('7cf02a6', function(error) { * if (error) throw error; * }); */ revokeSupportAccess: (uuidOrId: string | number): Promise<void> => set(uuidOrId, { is_accessible_by_support_until__date: null, }), /** * @summary Get a string showing when a device was last set as online * @name lastOnline * @public * @function * @memberof balena.models.device * * @description * If the device has never been online this method returns the string `Connecting...`. * * @param {Object} device - A device object * @returns {String} * * @example * balena.models.device.get('7cf02a6').then(function(device) { * balena.models.device.lastOnline(device); * }) */ lastOnline( device: AtLeast<Device, 'last_connectivity_event' | 'is_online'>, ): string { const lce = device.last_connectivity_event; if (!lce) { return 'Connecting...'; } const { timeSince } = dateUtils(); if (device.is_online) { return `Online (for ${timeSince(lce, false)})`; } return timeSince(lce); }, /** * @summary Get the OS version (version number and variant combined) running on a device * @name getOsVersion * @public * @function * @memberof balena.models.device * * @param {Object} device - A device object * @returns {?String} * * @example * balena.models.device.get('7cf02a6').then(function(device) { * console.log(device.os_version); // => 'balenaOS 2.26.0+rev1' * console.log(device.os_variant); // => 'prod' * balena.models.device.getOsVersion(device); // => '2.26.0+rev1.prod' * }) */ getOsVersion: ( device: AtLeast<Device, 'os_variant' | 'os_version'>, ): string => getDeviceOsSemverWithVariant(device)!, /** * @summary Get whether the device is configured to track the current application release * @name isTrackingApplicationRelease * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {Boolean} - is tracking the current application release * @returns {Promise} * * @example * balena.models.device.isTrackingApplicationRelease('7cf02a6').then(function(isEnabled) { * console.log(isEnabled); * }); * * @example * balena.models.device.isTrackingApplicationRelease('7cf02a6', function(error, isEnabled) { * console.log(isEnabled); * }); */ isTrackingApplicationRelease: async ( uuidOrId: string | number, ): Promise<boolean> => { const { should_be_running__release } = await exports.get(uuidOrId, { $select: 'should_be_running__release', }); return !should_be_running__release; }, /** * @summary Get the hash of the currently tracked release for a specific device * @name getTargetReleaseHash * @public * @function * @memberof balena.models.device * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @fulfil {String} - The release hash of the currently tracked release * @returns {Promise} * * @example * balena.models.device.getTargetReleaseHash('7cf02a6').then(function(release) { * console.log(release); * }); * * @example * balena.models.device.getTargetReleaseHash('7cf02a6', function(release) { * console.log(release); * }); */ getTargetReleaseHash: async ( uuidOrId: string | number, ): Promise<string | undefined> => { const deviceOptions = { $select: 'id', $expand: { should_be_running__release: { $select: 'commit', }, belongs_to__application: { $select: 'id', $expand: { should_be_running__release: { $select: 'commit' } }, }, }, } as const; const { should_be_running__release, belongs_to__application } = (await exports.get(uuidOrId, deviceOptions)) as PineTypedResult< Device, typeof deviceOptions >; if (should_be_running__release.length > 0) { return should_be_running__release[0]!.commit; } const targetRelease = belongs_to__application[0].should_be_running__release[0]; if (targetRelease) { return targetRelease.commit; } }, /** * @summary Set a specific device to run a particular release * @name pinToRelease * @public * @function * @memberof balena.models.device * * @description Configures the device to run a particular release * and not get updated when the current application release changes. * * @param {String|Number|Number[]} uuidOrIdOrIds - device uuid (string) or id (number) or array of ids * @param {String|Number} fullReleaseHashOrId - the hash of a successful release (string) or id (number) * @returns {Promise} * * @example * balena.models.device.pinToRelease('7cf02a6', 'f7caf4ff80114deeaefb7ab4447ad9c661c50847').then(function() { * ... * }); * * @example * balena.models.device.pinToRelease(123, 'f7caf4ff80114deeaefb7ab4447ad9c661c50847').then(function() { * ... * }); * * @example * balena.models.device.pinToRelease('7cf02a6', 'f7caf4ff80114deeaefb7ab4447ad9c661c50847', function(error) { * if (error) throw error; * ... * }); */ pinToRelease: async ( uuidOrIdOrIds: string | number | number[], fullReleaseHashOrId: string | number, ): Promise<void> => { const getRelease = memoizee( async (appId: number) => { const releaseFilterProperty = isId(fullReleaseHashOrId) ? 'id' : 'commit'; return await releaseModel().get(fullReleaseHashOrId, { $top: 1, $select: 'id', $filter: { [releaseFilterProperty]: fullReleaseHashOrId, status: 'success', belongs_to__application: appId, }, $orderby: 'created_at desc', }); }, { primitive: true, promise: true }, ); await batchDeviceOperation({ uuidOrIdOrIds, fn: async (app) => { const release = await getRelease(app.id); await pine.patch<Device>({ resource: 'device', options: { $filter: { id: { $in: app.owns__device.map((d) => d.id) }, }, }, body: { should_be_running__release: release.id, }, }); }, }); }, /** * @summary Set a specific device to run a particular supervisor release * @name setSupervisorRelease * @public * @function * @memberof balena.models.device * * @description Configures the device to run a particular supervisor release. * * @param {String|Number|Number[]} uuidOrIdOrIds - device uuid (string) or id (number) or array of ids * @param {String|Number} supervisorVersionOrId - the version of a released supervisor (string) or id (number) * @returns {Promise} * * @example * balena.models.device.setSupervisorRelease('7cf02a6', 'v10.8.0').then(function() { * ... * }); * * @example * balena.models.device.setSupervisorRelease(123, 'v11.4.14').then(function() { * ... * }); * * @example * balena.models.device.setSupervisorRelease('7cf02a6', 123, function(error) { * if (error) throw error; * ... * }); */ setSupervisorRelease: async ( uuidOrIdOrIds: string | number | number[], supervisorVersionOrId: string | number, ): Promise<void> => { const releaseFilterProperty = isId(supervisorVersionOrId) ? 'id' : 'supervisor_version'; const getRelease = memoizee( async (deviceTypeSlug: string) => { const [supervisorRelease] = await pine.get({ resource: 'supervisor_release', options: { $top: 1, $select: 'id', $filter: { [releaseFilterProperty]: supervisorVersionOrId, is_for__device_type: { $any: { $alias: 'dt', $expr: { dt: { slug: deviceTypeSlug, }, }, }, }, }, }, }); if (supervisorRelease == null) { throw new errors.BalenaReleaseNotFound(supervisorVersionOrId); } return supervisorRelease; }, { primitive: true, promise: true }, ); await batchDeviceOperation({ uuidOrIdOrIds, options: { $select: ['id', 'supervisor_version', 'os_version'], $expand: { is_of__device_type: { $select: 'slug' } }, }, fn: async (app) => { app.owns__device.forEach((device) => { ensureVersionCompatibility( device.supervisor_version, MIN_SUPERVISOR_MC_API, 'supervisor', ); ensureVersionCompatibility(device.os_version, MIN_OS_MC, 'host OS'); }); const devicesByDeviceType = groupBy( app.owns__device, (device) => device.is_of__device_type[0].slug, ); await Promise.all( Object.entries(devicesByDeviceType).map(async ([dt, devices]) => { const release = await getRelease(dt); await pine.patch<Device>({ resource: 'device', options: { $filter: { id: { $in: devices.map((d) => d.id) }, }, }, body: { should_be_managed_by__supervisor_release: release.id, }, }); }), ); }, }); }, /** * @summary Configure a specific device to track the current application release * @name trackApplicationRelease * @public * @function * @memberof balena.models.device * * @description The device's current release will be updated with each new successfully built release. * * @param {String|Number|Number[]} uuidOrIdOrIds - device uuid (string) or id (number) or ids * @returns {Promise} * * @example * balena.models.device.trackApplicationRelease('7cf02a6').then(function() { * ... * }); * * @example * balena.models.device.trackApplicationRelease('7cf02a6', function(error) { * if (error) throw error; * ... * }); */ trackApplicationRelease: async ( uuidOrIdOrIds: string | number | number[], ): Promise<void> => { await batchDeviceOperation({ uuidOrIdOrIds, fn: async (app) => { await pine.patch<Device>({ resource: 'device', options: { $filter: { id: { $in: app.owns__device.map((d) => d.id) }, }, }, body: { should_be_running__release: null, }, }); }, }); }, /** * @summary Check whether the provided device can update to the target os version * @name _checkOsUpdateTarget * @private * @function * @memberof balena.models.device * * @description * Utility method exported for testability * * @param {Object} device - A device object * @param {String} targetOsVersion - semver-compatible version for the target device * @throws Exception if update isn't supported * @returns {void} */ _checkOsUpdateTarget( { uuid, is_of__device_type, is_online, os_version, os_variant, }: Pick<Device, 'uuid' | 'is_online' | 'os_version' | 'os_variant'> & { is_of__device_type: [Pick<DeviceType, 'slug'>]; }, targetOsVersion: string, ) { if (!uuid) { throw new Error('The uuid of the device is not available'); } if (!is_online) { throw new Error(`The device is offline: ${uuid}`); } if (!os_version) { throw new Error( `The current os version of the device is not available: ${uuid}`, ); } const deviceType = is_of__device_type?.[0]?.slug; if (!deviceType) { throw new Error( `The device type of the device is not available: ${uuid}`, ); } // error the property is missing if (os_variant === undefined) { throw new Error( `The os variant of the device is not available: ${uuid}`, ); } const currentOsVersion = getDeviceOsSemverWithVariant({ os_version, os_variant, }) || os_version; // if the os_version couldn't be parsed // rely on getHUPActionType to throw an error // this will throw an error if the action isn't available hupActionHelper().getHUPActionType( deviceType, currentOsVersion, targetOsVersion, ); }, /** * @summary Start an OS update on a device * @name startOsUpdate * @public * @function * @memberof balena.models.device * * @param {String} uuid - full device uuid * @param {String} targetOsVersion - semver-compatible version for the target device * Unsupported (unpublished) version will result in rejection. * The version **must** be the exact version number, a "prod" variant and greater than the one running on the device. * To resolve the semver-compatible range use `balena.model.os.getMaxSatisfyingVersion`. * @fulfil {Object} - action response * @returns {Promise} * * @example * balena.models.device.startOsUpdate('7cf02a687b74206f92cb455969cf8e98', '2.29.2+rev1.prod').then(function(status) { * console.log(result.status); * }); * * @example * balena.models.device.startOsUpdate('7cf02a687b74206f92cb455969cf8e98', '2.29.2+rev1.prod', function(error, status) { * if (error) throw error; * console.log(result.status); * }); */ startOsUpdate: async ( uuid: string, targetOsVersion: string, ): Promise<OsUpdateActionResult> => { if (!targetOsVersion) { throw new errors.BalenaInvalidParameterError( 'targetOsVersion', targetOsVersion, ); } const deviceOpts = { $select: toWritable(['is_online', 'os_version', 'os_variant'] as const), $expand: { is_of__device_type: { $select: 'slug' as const } }, }; const device = (await exports.get(uuid, deviceOpts)) as PineTypedResult< Device, typeof deviceOpts > & Pick<Device, 'uuid'>; device.uuid = uuid; // this will throw an error if the action isn't available exports._checkOsUpdateTarget(device, targetOsVersion); const osVersions = ( await hostappModel().getAllOsVersions([ device.is_of__device_type[0].slug, ]) )[device.is_of__device_type[0].slug]; if ( !osVersions.some( (v) => bSemver.compare(v.rawVersion, targetOsVersion) === 0, ) ) { throw new errors.BalenaInvalidParameterError( 'targetOsVersion', targetOsVersion, ); } const osUpdateHelper = await getOsUpdateHelper(); return await osUpdateHelper.startOsUpdate(uuid, targetOsVersion); }, /** * @summary Get the OS update status of a device * @name getOsUpdateStatus * @public * @function * @memberof balena.models.device * * @param {String} uuid - full device uuid * @fulfil {Object} - action response * @returns {Promise} * * @example * balena.models.device.getOsUpdateStatus('7cf02a687b74206f92cb455969cf8e98').then(function(status) { * console.log(result.status); * }); * * @example * balena.models.device.getOsUpdateStatus('7cf02a687b74206f92cb455969cf8e98', function(error, status) { * if (error) throw error; * console.log(result.status); * }); */ getOsUpdateStatus: async (uuid: string): Promise<OsUpdateActionResult> => { try { const osUpdateHelper = await getOsUpdateHelper(); return await osUpdateHelper.getOsUpdateStatus(uuid); } catch (err) { if (err.statusCode !== 400) { throw err; } // as an attempt to reduce the requests for this method // check whether the device exists only when the request rejects // so that it's rejected with the appropriate BalenaDeviceNotFound error await exports.get(uuid, { $select: 'id' }); // if the device exists, then re-throw the original error throw err; } }, /** * @namespace balena.models.device.tags * @memberof balena.models.device */ tags: addCallbackSupportToModule({ /** * @summary Get all device tags for an application * @name getAllByApplication * @public * @function * @memberof balena.models.device.tags * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - device tags * @returns {Promise} * * @example * balena.models.device.tags.getAllByApplication('MyApp').then(function(tags) { * console.log(tags); * }); * * @example * balena.models.device.tags.getAllByApplication(999999).then(function(tags) { * console.log(tags); * }); * * @example * balena.models.device.tags.getAllByApplication('MyApp', function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ async getAllByApplication( nameOrSlugOrId: string | number, options?: PineOptions<DeviceTag>, ): Promise<DeviceTag[]> { if (options == null) { options = {}; } const { id } = await applicationModel().get(nameOrSlugOrId, { $select: 'id', }); return await tagsModel.getAll( mergePineOptions( { $filter: { device: { $any: { $alias: 'd', $expr: { d: { belongs_to__application: id } }, }, }, }, }, options, ), ); }, /** * @summary Get all device tags for a device * @name getAllByDevice * @public * @function * @memberof balena.models.device.tags * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - device tags * @returns {Promise} * * @example * balena.models.device.tags.getAllByDevice('7cf02a6').then(function(tags) { * console.log(tags); * }); * * @example * balena.models.device.tags.getAllByDevice(123).then(function(tags) { * console.log(tags); * }); * * @example * balena.models.device.tags.getAllByDevice('7cf02a6', function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ getAllByDevice: tagsModel.getAllByParent, /** * @summary Get all device tags * @name getAll * @public * @function * @memberof balena.models.device.tags * * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - device tags * @returns {Promise} * * @example * balena.models.device.tags.getAll().then(function(tags) { * console.log(tags); * }); * * @example * balena.models.device.tags.getAll(function(error, tags) { * if (error) throw error; * console.log(tags) * }); */ getAll: tagsModel.getAll, /** * @summary Set a device tag * @name set * @public * @function * @memberof balena.models.device.tags * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String} tagKey - tag key * @param {String|undefined} value - tag value * * @returns {Promise} * * @example * balena.models.device.tags.set('7cf02a6', 'EDITOR', 'vim'); * * @example * balena.models.device.tags.set(123, 'EDITOR', 'vim'); * * @example * balena.models.device.tags.set('7cf02a6', 'EDITOR', 'vim', function(error) { * if (error) throw error; * }); */ set: tagsModel.set, /** * @summary Remove a device tag * @name remove * @public * @function * @memberof balena.models.device.tags * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String} tagKey - tag key * @returns {Promise} * * @example * balena.models.device.tags.remove('7cf02a6', 'EDITOR'); * * @example * balena.models.device.tags.remove('7cf02a6', 'EDITOR', function(error) { * if (error) throw error; * }); */ remove: tagsModel.remove, }), /** * @namespace balena.models.device.configVar * @memberof balena.models.device */ configVar: addCallbackSupportToModule({ /** * @summary Get all config variables for a device * @name getAllByDevice * @public * @function * @memberof balena.models.device.configVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - device config variables * @returns {Promise} * * @example * balena.models.device.configVar.getAllByDevice('7cf02a6').then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.configVar.getAllByDevice(999999).then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.configVar.getAllByDevice('7cf02a6', function(error, vars) { * if (error) throw error; * console.log(vars) * }); */ getAllByDevice: configVarModel.getAllByParent, /** * @summary Get all device config variables by application * @name getAllByApplication * @public * @function * @memberof balena.models.device.configVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - device config variables * @returns {Promise} * * @example * balena.models.device.configVar.getAllByApplication('MyApp').then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.configVar.getAllByApplication(999999).then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.configVar.getAllByApplication('MyApp', function(error, vars) { * if (error) throw error; * console.log(vars) * }); */ async getAllByApplication( nameOrSlugOrId: string | number, options?: PineOptions<DeviceVariable>, ): Promise<DeviceVariable[]> { if (options == null) { options = {}; } const { id } = await applicationModel().get(nameOrSlugOrId, { $select: 'id', }); return await configVarModel.getAll( mergePineOptions( { $filter: { device: { $any: { $alias: 'd', $expr: { d: { belongs_to__application: id, }, }, }, }, }, $orderby: 'name asc', }, options, ), ); }, /** * @summary Get the value of a specific config variable * @name get * @public * @function * @memberof balena.models.device.configVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String} key - config variable name * @fulfil {String|undefined} - the config variable value (or undefined) * @returns {Promise} * * @example * balena.models.device.configVar.get('7cf02a6', 'BALENA_VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.device.configVar.get(999999, 'BALENA_VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.device.configVar.get('7cf02a6', 'BALENA_VAR', function(error, value) { * if (error) throw error; * console.log(value) * }); */ get: configVarModel.get, /** * @summary Set the value of a specific config variable * @name set * @public * @function * @memberof balena.models.device.configVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String} key - config variable name * @param {String} value - config variable value * @returns {Promise} * * @example * balena.models.device.configVar.set('7cf02a6', 'BALENA_VAR', 'newvalue').then(function() { * ... * }); * * @example * balena.models.device.configVar.set(999999, 'BALENA_VAR', 'newvalue').then(function() { * ... * }); * * @example * balena.models.device.configVar.set('7cf02a6', 'BALENA_VAR', 'newvalue', function(error) { * if (error) throw error; * ... * }); */ set: configVarModel.set, /** * @summary Clear the value of a specific config variable * @name remove * @public * @function * @memberof balena.models.device.configVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String} key - config variable name * @returns {Promise} * * @example * balena.models.device.configVar.remove('7cf02a6', 'BALENA_VAR').then(function() { * ... * }); * * @example * balena.models.device.configVar.remove(999999, 'BALENA_VAR').then(function() { * ... * }); * * @example * balena.models.device.configVar.remove('7cf02a6', 'BALENA_VAR', function(error) { * if (error) throw error; * ... * }); */ remove: configVarModel.remove, }), /** * @namespace balena.models.device.envVar * @memberof balena.models.device */ envVar: addCallbackSupportToModule({ /** * @summary Get all environment variables for a device * @name getAllByDevice * @public * @function * @memberof balena.models.device.envVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - device environment variables * @returns {Promise} * * @example * balena.models.device.envVar.getAllByDevice('7cf02a6').then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.envVar.getAllByDevice(999999).then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.envVar.getAllByDevice('7cf02a6', function(error, vars) { * if (error) throw error; * console.log(vars) * }); */ getAllByDevice: envVarModel.getAllByParent, /** * @summary Get all device environment variables by application * @name getAllByApplication * @public * @function * @memberof balena.models.device.envVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - device environment variables * @returns {Promise} * * @example * balena.models.device.envVar.getAllByApplication('MyApp').then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.envVar.getAllByApplication(999999).then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.envVar.getAllByApplication('MyApp', function(error, vars) { * if (error) throw error; * console.log(vars) * }); */ async getAllByApplication( nameOrSlugOrId: string | number, options?: PineOptions<DeviceVariable>, ): Promise<DeviceVariable[]> { if (options == null) { options = {}; } const { id } = await applicationModel().get(nameOrSlugOrId, { $select: 'id', }); return await envVarModel.getAll( mergePineOptions( { $filter: { device: { $any: { $alias: 'd', $expr: { d: { belongs_to__application: id, }, }, }, }, }, $orderby: 'name asc', }, options, ), ); }, /** * @summary Get the value of a specific environment variable * @name get * @public * @function * @memberof balena.models.device.envVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String} key - environment variable name * @fulfil {String|undefined} - the environment variable value (or undefined) * @returns {Promise} * * @example * balena.models.device.envVar.get('7cf02a6', 'VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.device.envVar.get(999999, 'VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.device.envVar.get('7cf02a6', 'VAR', function(error, value) { * if (error) throw error; * console.log(value) * }); */ get: envVarModel.get, /** * @summary Set the value of a specific environment variable * @name set * @public * @function * @memberof balena.models.device.envVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String} key - environment variable name * @param {String} value - environment variable value * @returns {Promise} * * @example * balena.models.device.envVar.set('7cf02a6', 'VAR', 'newvalue').then(function() { * ... * }); * * @example * balena.models.device.envVar.set(999999, 'VAR', 'newvalue').then(function() { * ... * }); * * @example * balena.models.device.envVar.set('7cf02a6', 'VAR', 'newvalue', function(error) { * if (error) throw error; * ... * }); */ set: envVarModel.set, /** * @summary Clear the value of a specific environment variable * @name remove * @public * @function * @memberof balena.models.device.envVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {String} key - environment variable name * @returns {Promise} * * @example * balena.models.device.envVar.remove('7cf02a6', 'VAR').then(function() { * ... * }); * * @example * balena.models.device.envVar.remove(999999, 'VAR').then(function() { * ... * }); * * @example * balena.models.device.envVar.remove('7cf02a6', 'VAR', function(error) { * if (error) throw error; * ... * }); */ remove: envVarModel.remove, }), /** * @namespace balena.models.device.serviceVar * @memberof balena.models.device */ serviceVar: addCallbackSupportToModule({ /** * @summary Get all service variable overrides for a device * @name getAllByDevice * @public * @function * @memberof balena.models.device.serviceVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - service variables * @returns {Promise} * * @example * balena.models.device.serviceVar.getAllByDevice('7cf02a6').then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.serviceVar.getAllByDevice(999999).then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.serviceVar.getAllByDevice('7cf02a6', function(error, vars) { * if (error) throw error; * console.log(vars) * }); */ async getAllByDevice( uuidOrId: string | number, options?: PineOptions<DeviceServiceEnvironmentVariable>, ): Promise<DeviceServiceEnvironmentVariable[]> { if (options == null) { options = {}; } const { id: deviceId } = await exports.get(uuidOrId, { $select: 'id' }); return await pine.get({ resource: 'device_service_environment_variable', options: mergePineOptions( { $filter: { service_install: { $any: { $alias: 'si', $expr: { si: { device: deviceId } }, }, }, }, }, options, ), }); }, /** * @summary Get all device service variable overrides by application * @name getAllByApplication * @public * @function * @memberof balena.models.device.serviceVar * * @param {String|Number} nameOrSlugOrId - application name (string) (deprecated), slug (string) or id (number) * @param {Object} [options={}] - extra pine options to use * @fulfil {Object[]} - service variables * @returns {Promise} * * @example * balena.models.device.serviceVar.getAllByApplication('MyApp').then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.serviceVar.getAllByApplication(999999).then(function(vars) { * console.log(vars); * }); * * @example * balena.models.device.serviceVar.getAllByApplication('MyApp', function(error, vars) { * if (error) throw error; * console.log(vars) * }); */ async getAllByApplication( nameOrSlugOrId: string | number, options?: PineOptions<DeviceServiceEnvironmentVariable>, ): Promise<DeviceServiceEnvironmentVariable[]> { if (options == null) { options = {}; } const { id } = await applicationModel().get(nameOrSlugOrId, { $select: 'id', }); return await pine.get({ resource: 'device_service_environment_variable', options: mergePineOptions( { $filter: { service_install: { $any: { $alias: 'si', $expr: { si: { device: { $any: { $alias: 'd', $expr: { d: { belongs_to__application: id, }, }, }, }, }, }, }, }, }, $orderby: 'name asc', }, options, ), }); }, /** * @summary Get the overriden value of a service variable on a device * @name get * @public * @function * @memberof balena.models.device.serviceVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Number} id - service id * @param {String} key - variable name * @fulfil {String|undefined} - the variable value (or undefined) * @returns {Promise} * * @example * balena.models.device.serviceVar.get('7cf02a6', 123, 'VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.device.serviceVar.get(999999, 123, 'VAR').then(function(value) { * console.log(value); * }); * * @example * balena.models.device.serviceVar.get('7cf02a6', 123, 'VAR', function(error, value) { * if (error) throw error; * console.log(value) * }); */ async get( uuidOrId: string | number, serviceId: number, key: string, ): Promise<string | undefined> { const { id: deviceId } = await exports.get(uuidOrId, { $select: 'id' }); const [variable] = await pine.get({ resource: 'device_service_environment_variable', options: { $select: 'value', $filter: { service_install: { $any: { $alias: 'si', $expr: { si: { device: deviceId, installs__service: serviceId, }, }, }, }, name: key, }, }, }); return variable?.value; }, /** * @summary Set the overriden value of a service variable on a device * @name set * @public * @function * @memberof balena.models.device.serviceVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Number} id - service id * @param {String} key - variable name * @param {String} value - variable value * @returns {Promise} * * @example * balena.models.device.serviceVar.set('7cf02a6', 123, 'VAR', 'override').then(function() { * ... * }); * * @example * balena.models.device.serviceVar.set(999999, 123, 'VAR', 'override').then(function() { * ... * }); * * @example * balena.models.device.serviceVar.set('7cf02a6', 123, 'VAR', 'override', function(error) { * if (error) throw error; * ... * }); */ async set( uuidOrId: string | number, serviceId: number, key: string, value: string, ): Promise<void> { value = String(value); const deviceFilter = isId(uuidOrId) ? uuidOrId : { $any: { $alias: 'd', $expr: { d: { uuid: uuidOrId, }, }, }, }; const serviceInstalls = await pine.get({ resource: 'service_install', options: { $select: 'id', $filter: { device: deviceFilter, installs__service: serviceId, }, }, }); const [serviceInstall] = serviceInstalls; if (serviceInstall == null) { throw new errors.BalenaServiceNotFound(serviceId); } if (serviceInstalls.length > 1) { throw new errors.BalenaAmbiguousDevice(uuidOrId); } await pine.upsert<DeviceServiceEnvironmentVariable>({ resource: 'device_service_environment_variable', id: { service_install: serviceInstall.id, name: key, }, body: { value, }, }); }, /** * @summary Clear the overridden value of a service variable on a device * @name remove * @public * @function * @memberof balena.models.device.serviceVar * * @param {String|Number} uuidOrId - device uuid (string) or id (number) * @param {Number} id - service id * @param {String} key - variable name * @returns {Promise} * * @example * balena.models.device.serviceVar.remove('7cf02a6', 123, 'VAR').then(function() { * ... * }); * * @example * balena.models.device.serviceVar.remove(999999, 123, 'VAR').then(function() { * ... * }); * * @example * balena.models.device.serviceVar.remove('7cf02a6', 123, 'VAR', function(error) { * if (error) throw error; * ... * }); */ async remove( uuidOrId: string | number, serviceId: number, key: string, ): Promise<void> { const { id: deviceId } = await exports.get(uuidOrId, { $select: 'id' }); await pine.delete({ resource: 'device_service_environment_variable', options: { $filter: { service_install: { $any: { $alias: 'si', $expr: { si: { device: deviceId, service: serviceId, }, }, }, }, name: key, }, }, }); }, }), }; return exports; }; export { getDeviceModel as default };
the_stack
import {KeyValue, merge, removeTrailingChar} from "./lib/Utils" import * as FS from 'fs' import * as path from "path" import * as mkdirp from "mkdirp" import {DatabaseError, DataError} from "./lib/Errors" import {DBParentData} from "./lib/DBParentData" import {ArrayInfo} from "./lib/ArrayInfo" import {Config, JsonDBConfig} from "./lib/JsonDBConfig" type DataPath = Array<string> export type FindCallback = (entry: any, index: number | string) => boolean export class JsonDB { private loaded: boolean = false private data: KeyValue = {} private readonly config : JsonDBConfig /** * JSONDB Constructor * @param filename where to save the "DB". Can also be used to give the whole configuration * @param saveOnPush save the database at each push command into the json file * @param humanReadable the JSON file will be readable easily by a human * @param separator what to use as separator */ constructor(filename: string | Config, saveOnPush: boolean = true, humanReadable: boolean = false, separator: string = '/') { if(filename instanceof Config) { this.config = filename } else { this.config = new Config(filename, saveOnPush, humanReadable, separator) } if (!FS.existsSync(this.config.filename)) { const dirname = path.dirname(this.config.filename) mkdirp.sync(dirname) this.save(true) this.loaded = true } } /** * Process datapath into different parts * @param dataPath */ private processDataPath(dataPath: string): DataPath { if (dataPath === undefined || !dataPath.trim()) { throw new DataError("The Data Path can't be empty", 6) } if (dataPath == this.config.separator) { return [] } dataPath = removeTrailingChar(dataPath, this.config.separator) const path = dataPath.split(this.config.separator) path.shift() return path } private retrieveData(dataPath: DataPath, create: boolean = false) { this.load() const thisDb = this const recursiveProcessDataPath = (data: any, index: number): any => { let property = dataPath[index] /** * Find the wanted Data or create it. */ function findData(isArray: boolean = false) { if (data.hasOwnProperty(property)) { data = data[property] } else if (create) { if (isArray) { data[property] = [] } else { data[property] = {} } data = data[property] } else { throw new DataError(`Can't find dataPath: ${thisDb.config.separator}${dataPath.join(thisDb.config.separator)}. Stopped at ${property}`, 5) } } const arrayInfo = ArrayInfo.processArray(property) if (arrayInfo) { property = arrayInfo.property findData(true) if (!Array.isArray(data)) { throw new DataError(`DataPath: ${thisDb.config.separator}${dataPath.join(thisDb.config.separator)}. ${property} is not an array.`, 11) } const arrayIndex = arrayInfo.getIndex(data, true) if (!arrayInfo.append && data.hasOwnProperty(arrayIndex)) { data = data[arrayIndex] } else if (create) { if (arrayInfo.append) { data.push({}) data = data[data.length - 1] } else { data[arrayIndex] = {} data = data[arrayIndex] } } else { throw new DataError(`DataPath: ${thisDb.config.separator}${dataPath.join(thisDb.config.separator)}. . Can't find index ${arrayInfo.index} in array ${property}`, 10) } } else { findData() } if (dataPath.length == ++index) { return data } return recursiveProcessDataPath(data, index) } if (dataPath.length === 0) { return this.data } return recursiveProcessDataPath(this.data, 0) } private getParentData(dataPath: string, create: boolean): DBParentData { const path = this.processDataPath(dataPath) const last = path.pop() return new DBParentData(this.retrieveData(path, create), this, dataPath, last) } /** * Get the wanted data * @param dataPath path of the data to retrieve */ public getData(dataPath: string): any { const path = this.processDataPath(dataPath) return this.retrieveData(path, false) } /** * Same as getData only here it's directly typed to your object * @param dataPath path of the data to retrieve */ public getObject<T>(dataPath: string): T { return this.getData(dataPath); } /** * Check for existing datapath * @param dataPath */ public exists(dataPath: string): boolean { try { this.getData(dataPath) return true } catch (e) { if (e instanceof DataError) { return false } throw e } } /** * Returns the number of element which constitutes the array * @param dataPath */ public count(dataPath: string): number { const result = this.getData(dataPath); if (!Array.isArray(result)) { throw new DataError(`DataPath: ${dataPath} is not an array.`, 11) } const path = this.processDataPath(dataPath); const data = this.retrieveData(path, false); return data.length; } /** * Returns the index of the object that meets the criteria submitted. Returns -1, if no match is found. * @param dataPath base dataPath from where to start searching * @param searchValue value to look for in the dataPath * @param propertyName name of the property to look for searchValue */ public getIndex(dataPath: string, searchValue: (string | number), propertyName:string = 'id'): number { const data = this.getArrayData(dataPath); return data.map(function (element:any) {return element[propertyName];}).indexOf(searchValue); } /** * Return the index of the value inside the array. Returns -1, if no match is found. * @param dataPath base dataPath from where to start searching * @param searchValue value to look for in the dataPath */ public getIndexValue(dataPath: string, searchValue: (string | number)) : number { return this.getArrayData(dataPath).indexOf(searchValue); } private getArrayData(dataPath: string) { const result = this.getData(dataPath); if (!Array.isArray(result)) { throw new DataError(`DataPath: ${dataPath} is not an array.`, 11) } const path = this.processDataPath(dataPath); return this.retrieveData(path, false); } /** * Find all specific entry in an array/object * @param rootPath base dataPath from where to start searching * @param callback method to filter the result and find the wanted entry. Receive the entry and it's index. */ public filter<T>(rootPath: string, callback: FindCallback): T[] | undefined { const result = this.getData(rootPath) if (Array.isArray(result)) { return result.filter(callback) as T[] } if (result instanceof Object) { const entries = Object.entries(result) const found = entries.filter((entry: [string, any]) => { return callback(entry[1], entry[0]) }) as [string, T][] if (!found || found.length < 1) { return undefined } return found.map((entry: [string, T]) => { return entry[1] }) } throw new DataError("The entry at the path (" + rootPath + ") needs to be either an Object or an Array", 12) } /** * Find a specific entry in an array/object * @param rootPath base dataPath from where to start searching * @param callback method to filter the result and find the wanted entry. Receive the entry and it's index. */ public find<T>(rootPath: string, callback: FindCallback): T | undefined { const result = this.getData(rootPath) if (Array.isArray(result)) { return result.find(callback) as T } if (result instanceof Object) { const entries = Object.entries(result) const found = entries.find((entry: Array<any>) => { return callback(entry[1], entry[0]) }) if (!found || found.length < 2) { return undefined } return found[1] as T } throw new DataError("The entry at the path (" + rootPath + ") needs to be either an Object or an Array", 12) } /** * Pushing data into the database * @param dataPath path leading to the data * @param data data to push * @param override overriding or not the data, if not, it will merge them */ public push(dataPath: string, data: any, override: boolean = true): void { const dbData = this.getParentData(dataPath, true) if (!dbData) { throw new Error("Data not found") } let toSet = data if (!override) { if (Array.isArray(data)) { let storedData = dbData.getData() if (storedData === undefined) { storedData = [] } else if (!Array.isArray(storedData)) { throw new DataError("Can't merge another type of data with an Array", 3) } toSet = storedData.concat(data) } else if (data === Object(data)) { if (Array.isArray(dbData.getData())) { throw new DataError("Can't merge an Array with an Object", 4) } toSet = merge(dbData.getData(), data) } } dbData.setData(toSet) if (this.config.saveOnPush) { this.save() } } /** * Delete the data * @param dataPath path leading to the data */ public delete(dataPath: string): void { const dbData = this.getParentData(dataPath, true) if (!dbData) { return } dbData.delete() if (this.config.saveOnPush) { this.save() } } /** * Only use this if you know what you're doing. * It reset the full data of the database. * @param data */ public resetData(data: any): void { this.data = data } /** * Reload the database from the file */ public reload(): void { this.loaded = false this.load() }; /** * Manually load the database * It is automatically called when the first getData is done */ public load(): void { if (this.loaded) { return } try { const data = FS.readFileSync(this.config.filename, 'utf8') this.data = JSON.parse(data) this.loaded = true } catch (err) { const error = new DatabaseError("Can't Load Database", 1, err) throw error } } /** * Manually save the database * By default you can't save the database if it's not loaded * @param force force the save of the database */ public save(force?: boolean): void { force = force || false if (!force && !this.loaded) { throw new DatabaseError("DataBase not loaded. Can't write", 7) } let data = "" try { if (this.config.humanReadable) { data = JSON.stringify(this.data, null, 4) } else { data = JSON.stringify(this.data) } FS.writeFileSync(this.config.filename, data, 'utf8') } catch (err) { const error = new DatabaseError("Can't save the database", 2, err) throw error } } }
the_stack
import { expect } from 'chai'; import { DetachedSequenceId, NodeId } from '../Identifiers'; import { ChangeNode } from '../generic'; import { StablePlace, StableRange, ConstraintEffect } from '../default-edits'; import { AnchoredChange, PlaceAnchor, PlaceAnchorSemanticsChoice, RangeAnchor, RelativePlaceAnchor, resolveChangeAnchors, findLastOffendingChange, resolveNodeAnchor, resolvePlaceAnchor, resolveRangeAnchor, updateRelativePlaceAnchorForChange, updateRelativePlaceAnchorForPath, EvaluatedChange, } from '../anchored-edits'; import { assert, fail } from '../Common'; import { Side, Snapshot } from '../Snapshot'; import { EditValidationResult } from '../Checkout'; import { ReconciliationChange, ReconciliationEdit, ReconciliationPath } from '../ReconciliationPath'; import { makeEmptyNode, leftTraitLabel, rightTraitLabel } from './utilities/TestUtilities'; const left: ChangeNode = makeEmptyNode('left' as NodeId); const priorSibling: ChangeNode = makeEmptyNode('prior' as NodeId); const nextSibling: ChangeNode = makeEmptyNode('next' as NodeId); const right: ChangeNode = makeEmptyNode('right' as NodeId); const parent: ChangeNode = { ...makeEmptyNode('parent' as NodeId), traits: { [leftTraitLabel]: [left], [rightTraitLabel]: [right] }, }; const initialTree: ChangeNode = { ...makeEmptyNode('root' as NodeId), traits: { parentTraitLabel: [parent], }, }; const leftTraitLocation = { parent: parent.identifier, label: leftTraitLabel, }; const startPlace = StablePlace.atStartOf(leftTraitLocation); const endPlace = StablePlace.atEndOf(leftTraitLocation); const beforePlace = StablePlace.before(left); const afterPlace = StablePlace.after(left); const startAnchor = PlaceAnchor.atStartOf( leftTraitLocation, PlaceAnchorSemanticsChoice.RelativeToNode ) as RelativePlaceAnchor; const endAnchor = PlaceAnchor.atEndOf( leftTraitLocation, PlaceAnchorSemanticsChoice.RelativeToNode ) as RelativePlaceAnchor; const beforeAnchor = PlaceAnchor.before(left, PlaceAnchorSemanticsChoice.RelativeToNode) as RelativePlaceAnchor; const afterAnchor = PlaceAnchor.after(left, PlaceAnchorSemanticsChoice.RelativeToNode) as RelativePlaceAnchor; const mockDetachedSequenceId = 42 as DetachedSequenceId; const mockNodeId = 'mock-node-id' as NodeId; const mockPlace = 'mock-place' as unknown as StablePlace; const mockRange = 'mock-range' as unknown as StableRange; const mockPlaceAnchor = 'mock-place-anchor' as unknown as RelativePlaceAnchor; const mockSnapshot = 'mock-snapshot' as unknown as Snapshot; const mockPath = 'mock-path' as unknown as ReconciliationPath<AnchoredChange>; const mockEvaluatedChange = 'mock-evaluated-change' as unknown as EvaluatedChange<AnchoredChange>; describe('Anchor Glass Box Tests', () => { describe(resolveChangeAnchors.name, () => { const testCases = [ { name: 'Insert', input: AnchoredChange.insert(mockDetachedSequenceId, beforeAnchor), expected: AnchoredChange.insert(mockDetachedSequenceId, mockPlace), }, { name: 'Detach', input: AnchoredChange.detach(RangeAnchor.only(right), mockDetachedSequenceId), expected: AnchoredChange.detach(mockRange, mockDetachedSequenceId), }, { name: 'SetValue (set payload)', input: AnchoredChange.setPayload(left.identifier, 42), expected: AnchoredChange.setPayload(mockNodeId, 42), }, { name: 'SetValue (clear payload)', input: AnchoredChange.clearPayload(left.identifier), expected: AnchoredChange.clearPayload(mockNodeId), }, { name: 'Constraint', input: AnchoredChange.constraint(RangeAnchor.only(right), ConstraintEffect.ValidRetry), expected: AnchoredChange.constraint(mockRange, ConstraintEffect.ValidRetry), }, ]; for (const testCase of testCases) { it(`attempts to resolve anchors in ${testCase.name} changes`, () => { const change = testCase.input; const actualHappy = resolveChangeAnchors(change, mockSnapshot, [], { nodeResolver: () => mockNodeId, placeResolver: () => mockPlace, rangeResolver: () => mockRange, }); expect(actualHappy).deep.equal(testCase.expected); const actualSad = resolveChangeAnchors(change, mockSnapshot, [], { nodeResolver: () => undefined, placeResolver: () => undefined, rangeResolver: () => undefined, }); expect(actualSad).equal(undefined); }); } it('throws when given an unsupported change type', () => { const fakeChange = { type: -42 }; expect(() => resolveChangeAnchors(fakeChange as AnchoredChange, mockSnapshot, [])).throws(); }); }); describe(resolveNodeAnchor.name, () => { it('returns the given NodeAnchor as a NodeId if the node exists in the snapshot', () => { const snapshot = Snapshot.fromTree(left); expect(resolveNodeAnchor(left.identifier, snapshot, [])).equals(left.identifier); }); it('returns undefined if the node does not exists in the snapshot', () => { const snapshot = Snapshot.fromTree(left); expect(resolveNodeAnchor(mockNodeId, snapshot, [])).equals(undefined); }); }); describe(resolveRangeAnchor.name, () => { it('returns a range with resolved places when possible', () => { expect( resolveRangeAnchor(RangeAnchor.only(left), mockSnapshot, [], { placeResolver: () => mockPlace, rangeValidator: () => EditValidationResult.Valid, }) ).deep.equals(RangeAnchor.from(mockPlace).to(mockPlace)); }); it('returns undefined if either place cannot be resolved', () => { expect( resolveRangeAnchor(RangeAnchor.only(left), mockSnapshot, [], { placeResolver: (place: PlaceAnchor) => (place.side === Side.After ? mockPlace : undefined), rangeValidator: () => EditValidationResult.Valid, }) ).equals(undefined); expect( resolveRangeAnchor(RangeAnchor.only(left), mockSnapshot, [], { placeResolver: (place: PlaceAnchor) => (place.side === Side.Before ? undefined : mockPlace), rangeValidator: () => EditValidationResult.Valid, }) ).equals(undefined); }); it('returns undefined the resolved places do not make a valid range', () => { expect( resolveRangeAnchor(RangeAnchor.only(left), mockSnapshot, [], { placeResolver: () => mockPlace, rangeValidator: () => EditValidationResult.Malformed, }) ).equals(undefined); expect( resolveRangeAnchor(RangeAnchor.only(left), mockSnapshot, [], { placeResolver: () => mockPlace, rangeValidator: () => EditValidationResult.Invalid, }) ).equals(undefined); }); }); describe(resolvePlaceAnchor.name, () => { it('returns the given anchor when that anchor is valid in the current snapshot', () => { const snapshot = Snapshot.fromTree(initialTree); const testWithPlace = (place) => resolvePlaceAnchor(place, snapshot, []); expect(testWithPlace(startPlace)).contains(startPlace); expect(testWithPlace(endPlace)).contains(endPlace); expect(testWithPlace(beforePlace)).contains(beforePlace); expect(testWithPlace(afterPlace)).contains(afterPlace); expect(testWithPlace(PlaceAnchor.atStartOf(leftTraitLocation))).contains(startPlace); expect(testWithPlace(PlaceAnchor.atEndOf(leftTraitLocation))).contains(endPlace); expect(testWithPlace(PlaceAnchor.before(left))).contains(beforePlace); expect(testWithPlace(PlaceAnchor.after(left))).contains(afterPlace); }); it('returns undefined when the anchor is invalid and not updatable', () => { expect( resolvePlaceAnchor(mockPlace, mockSnapshot, [], { placeUpdatorForPath: () => undefined, placeValidator: () => EditValidationResult.Invalid, }) ).equals(undefined); }); it('returns undefined when the anchor is invalid and bound to the node', () => { const resolvePlaceAnchorForInvalidPlace = (place) => resolvePlaceAnchor(place, mockSnapshot, [], { placeUpdatorForPath: () => fail(), placeValidator: () => EditValidationResult.Invalid, }); expect(resolvePlaceAnchorForInvalidPlace(startPlace)).equals(undefined); expect(resolvePlaceAnchorForInvalidPlace(endPlace)).equals(undefined); expect(resolvePlaceAnchorForInvalidPlace(beforePlace)).equals(undefined); expect(resolvePlaceAnchorForInvalidPlace(afterPlace)).equals(undefined); }); it('returns an updated anchor when the anchor is invalid but updatable to be valid', () => { let updateCountdown = 5; const inputSnapshot = Snapshot.fromTree(initialTree); const inputPlace = PlaceAnchor.after(mockNodeId); const placeUpdatorForPath = ( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange> ): PlaceAnchor | undefined => { expect(place).equals(inputPlace); expect(path).equals(mockPath); return --updateCountdown ? inputPlace : afterAnchor; }; const placeValidator = (snapshot, place) => { expect(snapshot).equals(inputSnapshot); return place === inputPlace ? EditValidationResult.Invalid : EditValidationResult.Valid; }; expect( resolvePlaceAnchor(inputPlace, inputSnapshot, mockPath, { placeUpdatorForPath, placeValidator, }) ).contains(PlaceAnchor.after(left)); // Check that it took the expected number of updates expect(updateCountdown).equals(0); }); it('returns undefined when the anchor is invalid and updatable to be invalid', () => { let updateCountdown = 5; const inputSnapshot = Snapshot.fromTree(initialTree); const inputPlace = PlaceAnchor.after(mockNodeId); const placeUpdatorForPath = ( place: RelativePlaceAnchor, path: ReconciliationPath<AnchoredChange> ): PlaceAnchor | undefined => { expect(place).equals(inputPlace); expect(path).equals(mockPath); return --updateCountdown ? inputPlace : undefined; }; const placeValidator = (snapshot, place) => { expect(snapshot).equals(inputSnapshot); expect(place).equals(inputPlace); return EditValidationResult.Invalid; }; expect( resolvePlaceAnchor(inputPlace, inputSnapshot, mockPath, { placeUpdatorForPath, placeValidator, }) ).equals(undefined); // Check that it took the expected number of updates expect(updateCountdown).equals(0); }); it('throws when given an unsupported choice of anchor semantics', () => { const fakeAnchor = { semantics: -42 }; expect(() => resolvePlaceAnchor(fakeAnchor as PlaceAnchor, mockSnapshot, [])).throws(); }); }); describe(updateRelativePlaceAnchorForPath.name, () => { it('does not update anchors for start and end of traits', () => { expect(updateRelativePlaceAnchorForPath(startAnchor, [])).equals(undefined); expect(updateRelativePlaceAnchorForPath(endAnchor, [])).equals(undefined); }); it('does not update anchors when the last offending change is not found', () => { expect( updateRelativePlaceAnchorForPath(startAnchor, [], { lastOffendingChangeFinder: () => undefined, placeUpdatorForChange: () => fail(), }) ).equals(undefined); }); it('tries to update anchors when the last offending change is found', () => { expect( updateRelativePlaceAnchorForPath(beforeAnchor, [], { lastOffendingChangeFinder: () => mockEvaluatedChange, placeUpdatorForChange: (place, change) => { expect(place).equals(beforeAnchor); expect(change).equals(mockEvaluatedChange); return mockPlace; }, }) ).equals(mockPlace); expect( updateRelativePlaceAnchorForPath(beforeAnchor, [], { lastOffendingChangeFinder: () => mockEvaluatedChange, placeUpdatorForChange: (place, change) => { expect(place).equals(beforeAnchor); expect(change).equals(mockEvaluatedChange); return undefined; }, }) ).equals(undefined); }); }); describe(findLastOffendingChange.name, () => { function makeEdit(changes: readonly AnchoredChange[]): ReconciliationEdit<AnchoredChange> { assert(changes.length > 0); const steps: ReconciliationChange<AnchoredChange>[] = changes.map(makeChange); return Object.assign(steps, { before: snapshotBeforeChange(changes[0]), after: steps[steps.length - 1].after, }); } function makeChange(change: AnchoredChange): ReconciliationChange<AnchoredChange> { return { resolvedChange: change, after: snapshotAfterChange(change), }; } function snapshotBeforeChange(change: AnchoredChange): Snapshot { return change === stayInvalidChange || change === mendingChange ? invalidSnapshot : validSnapshot; } function snapshotAfterChange(change: AnchoredChange): Snapshot { return change === stayValidChange || change === mendingChange ? validSnapshot : invalidSnapshot; } const validSnapshot = 'valid-snapshot' as unknown as Snapshot; const invalidSnapshot = 'invalid-snapshot' as unknown as Snapshot; const priorOffendingChange = 'prior-offending-change' as unknown as AnchoredChange; const lastOffendingChange = 'last-offending-change' as unknown as AnchoredChange; const stayValidChange = 'stay-valid-change' as unknown as AnchoredChange; const stayInvalidChange = 'stay-invalid-change' as unknown as AnchoredChange; const mendingChange = 'mending-change' as unknown as AnchoredChange; const priorOffendingEdit = makeEdit([priorOffendingChange]); const lastOffendingEdit = makeEdit([lastOffendingChange]); const mendingEdit = makeEdit([mendingChange]); const stayValidEdit = makeEdit([stayValidChange]); const stayInvalidEdit = makeEdit([stayInvalidChange]); const testWithPath = (path: ReconciliationPath<AnchoredChange>) => findLastOffendingChange(mockPlaceAnchor, path, { placeValidator: (snapshot) => snapshot === invalidSnapshot ? EditValidationResult.Invalid : snapshot === validSnapshot ? EditValidationResult.Valid : fail(), }); describe('returns undefined when the place is invalid throughout the path', () => { const testCases: ReconciliationPath<AnchoredChange>[] = [ [], [stayInvalidEdit], [stayInvalidEdit, stayInvalidEdit, stayInvalidEdit], [makeEdit([stayInvalidChange, stayInvalidChange, stayInvalidChange])], ]; for (let i = 0; i < testCases.length; ++i) { it(`Test Case ${i}`, () => { expect(testWithPath(testCases[i])).equals(undefined); }); } }); describe('returns the last offending change when there is one', () => { const testCases: ReconciliationPath<AnchoredChange>[] = [ [lastOffendingEdit], [lastOffendingEdit, stayInvalidEdit], [stayValidEdit, lastOffendingEdit], [stayValidEdit, lastOffendingEdit, stayInvalidEdit], [stayValidEdit, priorOffendingEdit, stayInvalidEdit, mendingEdit, lastOffendingEdit], [stayValidEdit, priorOffendingEdit, stayInvalidEdit, mendingEdit, lastOffendingEdit, stayInvalidEdit], [priorOffendingEdit, mendingEdit, priorOffendingEdit, mendingEdit, lastOffendingEdit], [makeEdit([stayValidChange, lastOffendingChange])], [makeEdit([lastOffendingChange, stayInvalidChange])], [makeEdit([stayValidChange, lastOffendingChange, stayInvalidChange])], [makeEdit([stayValidChange, priorOffendingChange, mendingChange, lastOffendingChange])], [ makeEdit([ priorOffendingChange, mendingChange, priorOffendingChange, mendingChange, lastOffendingChange, ]), ], [stayInvalidEdit, makeEdit([mendingChange, lastOffendingChange])], ]; for (let i = 0; i < testCases.length; ++i) { it(`Test Case ${i}`, () => { const actual = testWithPath(testCases[i]); expect(actual).deep.equals({ before: validSnapshot, after: invalidSnapshot, change: lastOffendingChange, }); }); } }); }); describe(updateRelativePlaceAnchorForChange.name, () => { const afterPrior = PlaceAnchor.after(priorSibling); const beforeNext = PlaceAnchor.before(nextSibling); const rangesInSitu = [ { range: RangeAnchor.from(startAnchor).to(beforeNext), trait: [left, nextSibling], }, { range: RangeAnchor.from(startAnchor).to(afterAnchor), trait: [left], }, { range: RangeAnchor.from(startAnchor).to(endAnchor), trait: [left], }, { range: RangeAnchor.from(beforeAnchor).to(beforeNext), trait: [left, nextSibling], }, { range: RangeAnchor.from(beforeAnchor).to(afterAnchor), trait: [left], }, { range: RangeAnchor.from(beforeAnchor).to(endAnchor), trait: [left], }, { range: RangeAnchor.from(afterPrior).to(beforeNext), trait: [priorSibling, left, nextSibling], }, { range: RangeAnchor.from(afterPrior).to(afterAnchor), trait: [priorSibling, left], }, { range: RangeAnchor.from(afterPrior).to(endAnchor), trait: [priorSibling, left], }, ]; function evaluateCase(caseIndex: number, anchor: RelativePlaceAnchor): PlaceAnchor | undefined { const before = Snapshot.fromTree({ ...parent, traits: { [leftTraitLabel]: rangesInSitu[caseIndex].trait }, }); const filteredTrait = rangesInSitu[caseIndex].trait.filter((sibling) => sibling !== left); const after = Snapshot.fromTree({ ...parent, traits: filteredTrait.length ? { [leftTraitLabel]: filteredTrait } : {}, }); const evaluatedChange: EvaluatedChange<AnchoredChange> = { change: AnchoredChange.detach(rangesInSitu[caseIndex].range), before, after, }; return updateRelativePlaceAnchorForChange(anchor, evaluatedChange); } describe('can update before(X) and after(X) when X is detached', () => { for (let i = 0; i < rangesInSitu.length; ++i) { it(`Test Case ${i}`, () => { const expectedAfter = rangesInSitu[i].trait[0] === priorSibling ? afterPrior : startAnchor; const expectedBefore = rangesInSitu[i].trait[rangesInSitu[i].trait.length - 1] === nextSibling ? beforeNext : endAnchor; expect(evaluateCase(i, afterAnchor)).deep.equals(expectedAfter); expect(evaluateCase(i, beforeAnchor)).deep.equals(expectedBefore); }); } }); describe('does not update anchors for start and end of traits', () => { for (let i = 0; i < rangesInSitu.length; ++i) { it(`Test Case ${i}`, () => { expect(evaluateCase(i, startAnchor)).equals(undefined); expect(evaluateCase(i, endAnchor)).equals(undefined); }); } }); it('does not update anchors when the containing parent is deleted', () => { const before = Snapshot.fromTree(initialTree); const after = Snapshot.fromTree({ ...initialTree, traits: {}, }); const evaluatedChange: EvaluatedChange<AnchoredChange> = { change: AnchoredChange.detach(RangeAnchor.only(parent)), before, after, }; expect(updateRelativePlaceAnchorForChange(startAnchor, evaluatedChange)).equals(undefined); expect(updateRelativePlaceAnchorForChange(endAnchor, evaluatedChange)).equals(undefined); expect(updateRelativePlaceAnchorForChange(afterAnchor, evaluatedChange)).equals(undefined); expect(updateRelativePlaceAnchorForChange(beforeAnchor, evaluatedChange)).equals(undefined); }); }); });
the_stack
import { useMemo } from 'react'; import { Fetcher, util } from "graphql-ts-client-api"; import { loadQuery, useQueryLoader, usePreloadedQuery, useLazyLoadQuery, useMutation, useFragment, useRefetchableFragment, EnvironmentProviderOptions, PreloadedQuery, LoadQueryOptions, UseMutationConfig, usePaginationFragment } from "react-relay"; import { IEnvironment, RenderPolicy, FetchPolicy, CacheConfig, fetchQuery, MutationConfig, Disposable, Environment, FetchQueryFetchPolicy, FragmentRefs, ReadOnlyRecordProxy, Variables, RecordProxy, DataID, ConnectionHandler, getRelayHandleKey, generateClientID } from "relay-runtime"; import type { TypedOperation, TypedQuery, TypedMutation, TypedFragment } from 'graphql-ts-client-relay'; import { TypedEnvironment } from 'graphql-ts-client-relay'; import { useRefetchableFragmentHookType } from "react-relay/relay-hooks/useRefetchableFragment"; import { usePaginationFragmentHookType } from 'react-relay/relay-hooks/usePaginationFragment'; import { RelayObservable } from "relay-runtime/lib/network/RelayObservable"; import { getStableStorageKey } from 'relay-runtime/lib/store/RelayStoreUtils'; export type { ImplementationType } from './CommonTypes'; export { upcastTypes, downcastTypes } from './CommonTypes'; /* * - - - - - - - - - - - - - - - - - - - - * * PreloadedQueryOf * OperationOf * OperationResponseOf * OperationVariablesOf * FragmentDataOf * FragmentKeyOf * * OperationType * FragmentKeyType * - - - - - - - - - - - - - - - - - - - - */ export type PreloadedQueryOf<TTypedQuery> = TTypedQuery extends TypedQuery<infer TResponse, infer TVariables> ? PreloadedQuery<OperationType<TResponse, TVariables>> : never ; export type OperationOf<TTypedOperation> = TTypedOperation extends TypedOperation<"Query" | "Mutation", infer TResponse, infer TVariables> ? OperationType<TResponse, TVariables> : never ; export type OperationResponseOf<TTypedOperation> = TTypedOperation extends TypedOperation<"Query" | "Mutation", infer TResponse, any> ? TResponse : never ; export type OperationVariablesOf<TTypedOperation> = TTypedOperation extends TypedOperation<"Query" | "Mutation", any, infer TVariables> ? TVariables : never ; export type FragmentDataOf<TTypedFragment> = TTypedFragment extends TypedFragment<string, string, infer TData, object> ? TData : never; export type FragmentKeyOf<TTypedFragment> = TTypedFragment extends TypedFragment<infer TFragmentName, string, infer TData, object> ? FragmentKeyType<TFragmentName, TData> : never ; export type OperationType<TResponse, TVariables> = { readonly response: TResponse, readonly variables: TVariables }; export type FragmentKeyType<TFragmentName extends string, TData extends object> = { readonly " $data": TData, readonly " $fragmentRefs": FragmentRefs<TFragmentName> } /* * - - - - - - - - - - - - - - - - - - - - * createTypedQuery * createTypedMutation * createTypedFragment * - - - - - - - - - - - - - - - - - - - - */ export function createTypedQuery<TResponse extends object, TVariables extends object>( name: string, fetcher: Fetcher<"Query", TResponse, TVariables> ): TypedQuery<TResponse, TVariables> { return typedEnvironment.query(name, fetcher); } export function createTypedMutation<TResponse extends object, TVariables extends object>( name: string, fetcher: Fetcher<"Mutation", TResponse, TVariables> ): TypedMutation<TResponse, TVariables> { return typedEnvironment.mutation(name, fetcher); } export function createTypedFragment< TFragmentName extends string, TFetchable extends string, TData extends object, TUnresolvedVariables extends object >( name: TFragmentName, fetcher: Fetcher<TFetchable, TData, TUnresolvedVariables> ): TypedFragment< TFragmentName, TFetchable, TData, TUnresolvedVariables > { return typedEnvironment.fragment(name, fetcher); } /* * - - - - - - - - - - - - - - - - - - - - * loadTypedQuery * fetchTypedQuery * useTypedQueryLoader * useTypedPreloadedQuery * useTypedLazyLoadQuery * useTypedMutation * useTypedFragment * useTypedRefetchableFragment * - - - - - - - - - - - - - - - - - - - - */ export function loadTypedQuery< TResponse extends object, TVariables extends object, TEnvironmentProviderOptions extends EnvironmentProviderOptions = {} >( environment: IEnvironment, query: TypedQuery<TResponse, TVariables>, variables: TVariables, options?: LoadQueryOptions, environmentProviderOptions?: TEnvironmentProviderOptions, ): PreloadedQuery<OperationType<TResponse, TVariables>> { return loadQuery<OperationType<TResponse, TVariables>>( environment, query.taggedNode, variables, options, environmentProviderOptions ); } export function fetchTypedQuery<TResponse extends object, TVariables extends object>( environment: Environment, query: TypedQuery<TResponse, TVariables>, variables: TVariables, cacheConfig?: { networkCacheConfig?: CacheConfig | null | undefined, fetchPolicy?: FetchQueryFetchPolicy | null | undefined } | null, ): RelayObservable<TResponse> { return fetchQuery<OperationType<TResponse, TVariables>>( environment, query.taggedNode, variables, cacheConfig ); } export function useTypedQueryLoader<TResponse extends object, TVariables extends object>( query: TypedQuery<TResponse, TVariables>, initialQueryReference?: PreloadedQuery<OperationType<TResponse, TVariables>> | null ) { return useQueryLoader<OperationType<TResponse, TVariables>>( query.taggedNode, initialQueryReference ); } export function useTypedPreloadedQuery<TResponse extends object, TVariables extends object>( query: TypedQuery<TResponse, TVariables>, preloadedQuery: PreloadedQuery<OperationType<TResponse, TVariables>>, options?: { UNSTABLE_renderPolicy?: RenderPolicy | undefined; }, ): TResponse { const response = usePreloadedQuery<OperationType<TResponse, TVariables>>( query.taggedNode, preloadedQuery, options ); return useMemo(() => { return util.exceptNullValues(response); }, [response]); } export function useTypedLazyLoadQuery<TResponse extends object, TVariables extends object>( query: TypedQuery<TResponse, TVariables>, variables: TVariables, options?: { fetchKey?: string | number | undefined; fetchPolicy?: FetchPolicy | undefined; networkCacheConfig?: CacheConfig | undefined; UNSTABLE_renderPolicy?: RenderPolicy | undefined; }, ): TResponse { const response = useLazyLoadQuery<OperationType<TResponse, TVariables>>( query.taggedNode, variables, options ) return useMemo(() => { return util.exceptNullValues(response); }, [response]); } export function useTypedMutation<TResponse extends object, TVariables extends object>( mutation: TypedMutation<TResponse, TVariables>, commitMutationFn?: ( environment: IEnvironment, config: MutationConfig<OperationType<TResponse, TVariables>> ) => Disposable, ): [(config: UseMutationConfig<OperationType<TResponse, TVariables>>) => Disposable, boolean] { return useMutation(mutation.taggedNode, commitMutationFn); } export function useTypedFragment<TFragmentName extends string, TFetchable extends string, TData extends object>( fragment: TypedFragment<TFragmentName, TFetchable, TData, object>, fragmentRef: FragmentKeyType<TFragmentName, TData>, ): TData; export function useTypedFragment<TFragmentName extends string, TFetchable extends string, TData extends object>( fragment: TypedFragment<TFragmentName, TFetchable, TData, object>, fragmentRef: FragmentKeyType<TFragmentName, TData> | undefined, ): TData | undefined{ const data = useFragment( fragment.taggedNode, fragmentRef ?? null ); return useMemo(() => { return util.exceptNullValues(data) as TData | undefined; }, [data]); } export function useTypedRefetchableFragment<TFragmentName extends string, TFetchable extends string, TData extends object, TVariables extends object>( fragment: TypedFragment<TFragmentName, TFetchable, TData, TVariables>, fragmentRef: FragmentKeyType<TFragmentName, TData>, ): useRefetchableFragmentHookType<OperationType<TData, TVariables>, FragmentKeyType<TFragmentName, TVariables>, TData>; export function useTypedRefetchableFragment<TFragmentName extends string, TFetchable extends string, TData extends object, TVariables extends object>( fragment: TypedFragment<TFragmentName, TFetchable, TData, TVariables>, fragmentRef: FragmentKeyType<TFragmentName, TData> | undefined, ): useRefetchableFragmentHookType<OperationType<TData, TVariables>, FragmentKeyType<TFragmentName, TVariables>, TData | undefined> { const tuple = useRefetchableFragment( fragment.taggedNode, fragmentRef ?? null ); return useMemo(() => { return [ util.exceptNullValues(tuple[0]) as TData | undefined, tuple[1] ]; }, [tuple]); } export function useTypedPaginationFragment<TFragmentName extends string, TFetchable extends string, TData extends object, TVariables extends object>( fragment: TypedFragment<TFragmentName, TFetchable, TData, TVariables>, parentFragmentRef: FragmentKeyType<TFragmentName, TData>, ): usePaginationFragmentHookType<OperationType<TData, TVariables>, FragmentKeyType<TFragmentName, TVariables>, TData>; export function useTypedPaginationFragment<TFragmentName extends string, TFetchable extends string, TData extends object, TVariables extends object>( fragment: TypedFragment<TFragmentName, TFetchable, TData, TVariables>, fragmentRef: FragmentKeyType<TFragmentName, TData> | undefined, ): usePaginationFragmentHookType<OperationType<TData, TVariables>, FragmentKeyType<TFragmentName, TVariables>, TData | undefined> { const obj = usePaginationFragment( fragment.taggedNode, fragmentRef ?? null ); return useMemo(() => { return { ...obj, data: util.exceptNullValues(obj.data) as TData | undefined }; }, [obj]); } /* * - - - - - - - - - - - - - - - - - - - - * getConnection * getConnectionID * - - - - - - - - - - - - - - - - - - - - */ export function getConnection( record: ReadOnlyRecordProxy, key: string | { readonly key: string, readonly handler?: string }, filters?: Variables | null, ): RecordProxy | undefined { const connKey = typeof key === "string" ? key : key.key; const connHandler = typeof key === "string" ? undefined : key.handler; let connection: RecordProxy | null | undefined; if (connHandler === undefined) { connection = ConnectionHandler.getConnection(record, connKey, filters); } else { connection = record.getLinkedRecord(getRelayHandleKey(connHandler, connKey), filters !== null ? filters : undefined); } return connection !== null ? connection : undefined; } export function getConnectionID( recordID: DataID, key: string | { readonly key: string, readonly handler?: string }, filters?: Variables | null, ): DataID { const connKey = typeof key === "string" ? key : key.key; const connHandler = typeof key === "string" ? undefined : key.handler; if (connHandler === undefined) { return ConnectionHandler.getConnectionID(recordID, connKey, filters); } const storageKey = getStableStorageKey(getRelayHandleKey(connHandler, connKey), filters ?? {}); return generateClientID(recordID, storageKey); } const typedEnvironment = new TypedEnvironment(`type Query { findDepartmentsLikeName(before: String, last: Int, after: String, first: Int, name: String): DepartmentConnection! findEmployees(before: String, last: Int, after: String, first: Int, mockedErrorProbability: Int, supervisorId: String, departmentId: String, name: String): EmployeeConnection! node(id: ID!): Node } type DepartmentConnection { totalCount: Int! edges: [DepartmentEdge!]! pageInfo: PageInfo! } type DepartmentEdge { node: Department! cursor: String! } type Department implements Node { id: ID! name: String! employees: [Employee!]! avgSalary: Float! } interface Node { id: ID! } type Employee implements Node { id: ID! firstName: String! lastName: String! gender: Gender! salary: Float! department: Department! supervisor: Employee subordinates: [Employee!]! } enum Gender { MALE FEMALE } type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: String! endCursor: String! } type EmployeeConnection { totalCount: Int! edges: [EmployeeEdge!]! pageInfo: PageInfo! } type EmployeeEdge { node: Employee! cursor: String! } type Mutation { mergeDepartment(input: DepartmentInput!): Department! deleteDepartment(id: ID): ID! mergeEmployee(input: EmployeeInput!): Employee! deleteEmployee(id: ID): ID! } input DepartmentInput { id: String! name: String! } input EmployeeInput { id: String! firstName: String! lastName: String! gender: Gender! salary: Float! departmentId: String! supervisorId: String } `);
the_stack
import AnchoredOperationModel from '../../lib/core/models/AnchoredOperationModel'; import Config from '../../lib/core/models/Config'; import DownloadManager from '../../lib/core/DownloadManager'; import ErrorCode from '../../lib/core/ErrorCode'; import IBlockchain from '../../lib/core/interfaces/IBlockchain'; import ICas from '../../lib/core/interfaces/ICas'; import IOperationStore from '../../lib/core/interfaces/IOperationStore'; import ITransactionStore from '../../lib/core/interfaces/ITransactionStore'; import MockBlockchain from '../mocks/MockBlockchain'; import MockCas from '../mocks/MockCas'; import MockOperationStore from '../mocks/MockOperationStore'; import MockTransactionStore from '../mocks/MockTransactionStore'; import OperationGenerator from '../generators/OperationGenerator'; import OperationType from '../../lib/core/enums/OperationType'; import Resolver from '../../lib/core/Resolver'; import TransactionModel from '../../lib/common/models/TransactionModel'; import VersionManager from '../../lib/core/VersionManager'; import VersionModel from '../../lib/core/models/VersionModel'; describe('VersionManager', async () => { let config: Config; let blockChain: IBlockchain; let cas: ICas; let operationStore: IOperationStore; let downloadMgr: DownloadManager; let mockTransactionStore: ITransactionStore; beforeEach(() => { config = require('../json/config-test.json'); blockChain = new MockBlockchain(); cas = new MockCas(); operationStore = new MockOperationStore(); downloadMgr = new DownloadManager(1, cas); mockTransactionStore = new MockTransactionStore(); }); describe('initialize()', async () => { it('should initialize all the objects correctly.', async () => { const versionModels: VersionModel[] = [ { startingBlockchainTime: 1000, version: 'test-version-1' } ]; const versionMgr = new VersionManager(config, versionModels); spyOn(versionMgr as any, 'loadDefaultExportsForVersion').and.callFake(async (version: string, className: string) => { return (await import(`./versions/${version}/${className}`)).default; }); const resolver = new Resolver(versionMgr, operationStore); await versionMgr.initialize(blockChain, cas, downloadMgr, operationStore, resolver, mockTransactionStore); expect(versionMgr['batchWriters'].get('test-version-1') as any ['versionMetadataFetcher']).toBeDefined(); expect(versionMgr['transactionProcessors'].get('test-version-1') as any ['versionMetadataFetcher']).toBeDefined(); // No exception thrown == initialize was successful }); it('should throw if version metadata is the wrong type.', async () => { const versionModels: VersionModel[] = [ { startingBlockchainTime: 1000, version: 'test-version-1' } ]; const versionMgr = new VersionManager(config, versionModels); spyOn(versionMgr as any, 'loadDefaultExportsForVersion').and.callFake(async (version: string, className: string) => { if (className === 'VersionMetadata') { const fakeClass = class {}; // a fake class that does nothing return fakeClass; } else { return (await import(`./versions/${version}/${className}`)).default; } }); const resolver = new Resolver(versionMgr, operationStore); try { await versionMgr.initialize(blockChain, cas, downloadMgr, operationStore, resolver, mockTransactionStore); fail('expect to throw but did not'); } catch (e) { expect(e.code).toEqual(ErrorCode.VersionManagerVersionMetadataIncorrectType); } }); it('should throw if the versions folder is missing.', async () => { const versionModels: VersionModel[] = [ { startingBlockchainTime: 1000, version: 'invalid_version' } ]; const versionMgr = new VersionManager(config, versionModels); const resolver = new Resolver(versionMgr, operationStore); await expectAsync(versionMgr.initialize(blockChain, cas, downloadMgr, operationStore, resolver, mockTransactionStore)).toBeRejected(); }); }); describe('loadDefaultExportsForVersion()', async () => { it('should be able to load a default export of a versioned component successfully.', async () => { const versionModels: VersionModel[] = [ { startingBlockchainTime: 1, version: 'unused' } ]; const versionManager = new VersionManager(config, versionModels); const OperationProcessor = await (versionManager as any).loadDefaultExportsForVersion('latest', 'OperationProcessor'); const operationProcessor = new OperationProcessor(); expect(operationProcessor).toBeDefined(); }); }); describe('getTransactionSelector()', async () => { it('should return the correct version of `ITransactionSelector`.', async () => { const versionModels: VersionModel[] = [ { startingBlockchainTime: 1000, version: '1000' }, { startingBlockchainTime: 2000, version: '2000' } ]; const versionManager = new VersionManager(config, versionModels); // Setting up loading of mock ITransactionSelector implementations. const mockTransactionSelector1 = class { selectQualifiedTransactions () { return []; } }; const anyTransactionModel = OperationGenerator.generateTransactionModel(); const mockTransactionSelector2 = class { selectQualifiedTransactions () { return [anyTransactionModel]; } }; spyOn(versionManager as any, 'loadDefaultExportsForVersion').and.callFake(async (version: string, className: string) => { if (className === 'TransactionSelector') { if (version === '1000') { return mockTransactionSelector1; } else { // '2000' return mockTransactionSelector2; } } // Else we are loading components unrelated to this test, default to loading from `latest` version folder. const classObject = (await import(`../../lib/core/versions/latest/${className}`)).default; // Override the `intialize()` call so no network call occurs, else the test the will fail in GitHub CICD. if (className === 'MongoDbOperationQueue') { classObject.prototype.initialize = async () => {}; } return classObject; }); const resolver = new Resolver(versionManager, operationStore); await versionManager.initialize(blockChain, cas, downloadMgr, operationStore, resolver, mockTransactionStore); const transactions = await versionManager.getTransactionSelector(2001).selectQualifiedTransactions([]); expect(transactions[0].anchorString).toEqual(anyTransactionModel.anchorString); }); }); describe('getVersionMetadata', () => { it('should return the expected versionMetadata', async () => { const versionModels: VersionModel[] = [ { startingBlockchainTime: 1000, version: 'test-version-1' } ]; const versionMgr = new VersionManager(config, versionModels); spyOn(versionMgr as any, 'loadDefaultExportsForVersion').and.callFake(async (version: string, className: string) => { return (await import(`./versions/${version}/${className}`)).default; }); const resolver = new Resolver(versionMgr, operationStore); await versionMgr.initialize(blockChain, cas, downloadMgr, operationStore, resolver, mockTransactionStore); const result = versionMgr.getVersionMetadata(1001); expect(result.normalizedFeeToPerOperationFeeMultiplier).toEqual(0.01); }); }); describe('get* functions.', async () => { it('should return the correct version-ed objects for valid version.', async () => { const versionModels: VersionModel[] = [ { startingBlockchainTime: 1000, version: 'test-version-1' } ]; const versionMgr = new VersionManager(config, versionModels); spyOn(versionMgr as any, 'loadDefaultExportsForVersion').and.callFake(async (version: string, className: string) => { return (await import(`./versions/${version}/${className}`)).default; }); const resolver = new Resolver(versionMgr, operationStore); await versionMgr.initialize(blockChain, cas, downloadMgr, operationStore, resolver, mockTransactionStore); // Get the objects for the valid version (see versions/testingversion1 folder) and call // functions on the objects to make sure that the correct objects are being returned. // For testing, the functions in the above testingversion folder are throwing errors so // that is way that we can tell that the correct object is actually being returned. const batchWriter = versionMgr.getBatchWriter(1000); await expectAsync(batchWriter.write()).toBeRejected(); const operationProcessor = versionMgr.getOperationProcessor(1001); const namedAnchoredOpModel: AnchoredOperationModel = { type: OperationType.Create, didUniqueSuffix: 'unusedDidUniqueSuffix', transactionTime: 0, transactionNumber: 0, operationIndex: 0, operationBuffer: Buffer.from('') }; await expectAsync(operationProcessor.apply(namedAnchoredOpModel, undefined)).toBeRejected(); const requestHandler = versionMgr.getRequestHandler(2000); await expectAsync(requestHandler.handleResolveRequest('')).toBeRejected(); const txProcessor = versionMgr.getTransactionProcessor(10000); const txModel: TransactionModel = { anchorString: '', transactionNumber: 0, transactionTime: 0, transactionTimeHash: '', transactionFeePaid: 1, normalizedTransactionFee: 1, writer: 'writer' }; await expectAsync(txProcessor.processTransaction(txModel)).toBeRejected(); }); it('should throw for an invalid version.', async () => { const versionModels: VersionModel[] = [ { startingBlockchainTime: 1000, version: 'test-version-1' } ]; const versionMgr = new VersionManager(config, versionModels); spyOn(versionMgr as any, 'loadDefaultExportsForVersion').and.callFake(async (version: string, className: string) => { return (await import(`./versions/${version}/${className}`)).default; }); const resolver = new Resolver(versionMgr, operationStore); await versionMgr.initialize(blockChain, cas, downloadMgr, operationStore, resolver, mockTransactionStore); // Expect an invalid blockchain time input to throw expect(() => { versionMgr.getBatchWriter(0); }).toThrowError(); expect(() => { versionMgr.getOperationProcessor(999); }).toThrowError(); expect(() => { versionMgr.getRequestHandler(100); }).toThrowError(); expect(() => { versionMgr.getTransactionProcessor(500); }).toThrowError(); }); }); });
the_stack
import type {Mutable, Class} from "@swim/util"; import {Affinity, Animator} from "@swim/component"; import {AnyLength, Length, AnyR2Point, R2Point, R2Box, Transform} from "@swim/math"; import {AnyGeoPoint, GeoPoint, GeoBox} from "@swim/geo"; import {ThemeAnimator} from "@swim/theme"; import {ViewContextType, ViewFlags, View} from "@swim/view"; import { AnyGraphicsRenderer, GraphicsRendererType, GraphicsRenderer, GraphicsView, CanvasCompositeOperation, CanvasRenderer, WebGLRenderer, } from "@swim/graphics"; import type {GeoViewContext} from "../geo/GeoViewContext"; import {GeoViewInit, GeoView} from "../geo/GeoView"; import {GeoRippleOptions, GeoRippleView} from "../effect/GeoRippleView"; import type {GeoRasterViewContext} from "./GeoRasterViewContext"; import type {GeoRasterViewObserver} from "./GeoRasterViewObserver"; /** @public */ export interface GeoRasterViewInit extends GeoViewInit { geoAnchor?: AnyGeoPoint; viewAnchor?: AnyR2Point; xAlign?: number; yAlign?: number; width?: AnyLength; height?: AnyLength; opacity?: number; compositeOperation?: CanvasCompositeOperation; } /** @public */ export class GeoRasterView extends GeoView { constructor() { super(); this.canvas = this.createCanvas(); Object.defineProperty(this, "renderer", { value: this.createRenderer(), writable: true, enumerable: true, configurable: true, }); this.ownRasterFrame = null; } override readonly observerType?: Class<GeoRasterViewObserver>; override readonly contextType?: Class<GeoRasterViewContext>; @Animator<GeoRasterView, GeoPoint | null, AnyGeoPoint | null>({ type: GeoPoint, value: null, didSetState(newGeoCenter: GeoPoint | null, oldGeoCenter: GeoPoint | null): void { this.owner.projectGeoAnchor(newGeoCenter); }, willSetValue(newGeoAnchor: GeoPoint | null, oldGeoAnchor: GeoPoint | null): void { this.owner.callObservers("viewWillSetGeoAnchor", newGeoAnchor, oldGeoAnchor, this.owner); }, didSetValue(newGeoAnchor: GeoPoint | null, oldGeoAnchor: GeoPoint | null): void { this.owner.setGeoBounds(newGeoAnchor !== null ? newGeoAnchor.bounds : GeoBox.undefined()); if (this.mounted) { this.owner.projectRaster(this.owner.viewContext); } this.owner.callObservers("viewDidSetGeoAnchor", newGeoAnchor, oldGeoAnchor, this.owner); }, }) readonly geoAnchor!: Animator<this, GeoPoint | null, AnyGeoPoint | null>; @Animator({type: R2Point, value: R2Point.undefined()}) readonly viewAnchor!: Animator<this, R2Point | null, AnyR2Point | null>; @Animator({type: Number, value: 0.5, updateFlags: View.NeedsComposite}) readonly xAlign!: Animator<this, number>; @Animator({type: Number, value: 0.5, updateFlags: View.NeedsComposite}) readonly yAlign!: Animator<this, number>; @ThemeAnimator({type: Length, value: null, updateFlags: View.NeedsResize | View.NeedsLayout | View.NeedsRender | View.NeedsComposite}) readonly width!: ThemeAnimator<this, Length | null, AnyLength | null>; @ThemeAnimator({type: Length, value: null, updateFlags: View.NeedsResize | View.NeedsLayout | View.NeedsRender | View.NeedsComposite}) readonly height!: ThemeAnimator<this, Length | null, AnyLength | null>; @ThemeAnimator({type: Number, value: 1, updateFlags: View.NeedsComposite}) readonly opacity!: ThemeAnimator<this, number>; @Animator({type: String, value: "source-over", updateFlags: View.NeedsComposite}) readonly compositeOperation!: Animator<this, CanvasCompositeOperation>; get pixelRatio(): number { return window.devicePixelRatio || 1; } /** @internal */ readonly canvas: HTMLCanvasElement; get compositor(): GraphicsRenderer | null { const parent = this.parent; if (parent instanceof GraphicsView) { return parent.renderer; } else { return null; } } override readonly renderer!: GraphicsRenderer | null; setRenderer(renderer: AnyGraphicsRenderer | null): void { if (typeof renderer === "string") { renderer = this.createRenderer(renderer as GraphicsRendererType); } (this as Mutable<this>).renderer = renderer; this.requireUpdate(View.NeedsRender | View.NeedsComposite); } protected createRenderer(rendererType: GraphicsRendererType = "canvas"): GraphicsRenderer | null { if (rendererType === "canvas") { const context = this.canvas.getContext("2d"); if (context !== null) { return new CanvasRenderer(context, Transform.identity(), this.pixelRatio); } else { throw new Error("Failed to create canvas rendering context"); } } else if (rendererType === "webgl") { const context = this.canvas.getContext("webgl"); if (context !== null) { return new WebGLRenderer(context, this.pixelRatio); } else { throw new Error("Failed to create webgl rendering context"); } } else { throw new Error("Failed to create " + rendererType + " renderer"); } } protected override needsUpdate(updateFlags: ViewFlags, immediate: boolean): ViewFlags { updateFlags = super.needsUpdate(updateFlags, immediate); const rasterFlags = updateFlags & (View.NeedsRender | View.NeedsComposite); if (rasterFlags !== 0) { updateFlags |= View.NeedsComposite; this.setFlags(this.flags | View.NeedsDisplay | View.NeedsComposite | rasterFlags); } return updateFlags; } protected override needsProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): ViewFlags { if ((this.flags & View.ProcessMask) === 0 && (processFlags & (View.NeedsResize | View.NeedsProject)) === 0) { processFlags = 0; } return processFlags; } protected override onResize(viewContext: ViewContextType<this>): void { super.onResize(viewContext); this.requireUpdate(View.NeedsRender | View.NeedsComposite); } protected override onProject(viewContext: ViewContextType<this>): void { super.onProject(viewContext); this.projectRaster(viewContext); } protected projectGeoAnchor(geoAnchor: GeoPoint | null): void { if (this.mounted) { const viewContext = this.viewContext as ViewContextType<this>; const viewAnchor = geoAnchor !== null && geoAnchor.isDefined() ? viewContext.geoViewport.project(geoAnchor) : null; this.viewAnchor.setInterpolatedValue(this.viewAnchor.value, viewAnchor); this.projectRaster(viewContext); } } protected projectRaster(viewContext: ViewContextType<this>): void { let viewAnchor: R2Point | null; if (this.viewAnchor.hasAffinity(Affinity.Intrinsic)) { const geoAnchor = this.geoAnchor.value; viewAnchor = geoAnchor !== null && geoAnchor.isDefined() ? viewContext.geoViewport.project(geoAnchor) : null; this.viewAnchor.setValue(viewAnchor, Affinity.Intrinsic); } else { viewAnchor = this.viewAnchor.value; } if (viewAnchor !== null) { const viewFrame = viewContext.viewFrame; const viewWidth = viewFrame.width; const viewHeight = viewFrame.height; const viewSize = Math.min(viewWidth, viewHeight); let width: Length | number | null = this.width.value; width = width instanceof Length ? width.pxValue(viewSize) : viewWidth; let height: Length | number | null = this.height.value; height = height instanceof Length ? height.pxValue(viewSize) : viewHeight; const x = viewAnchor.x - width * this.xAlign.getValue(); const y = viewAnchor.y - height * this.yAlign.getValue(); const rasterFrame = new R2Box(x, y, x + width, y + height); this.setRasterFrame(rasterFrame); this.setViewFrame(rasterFrame); this.setCulled(!viewFrame.intersects(rasterFrame)); } else { this.setCulled(!this.viewFrame.intersects(this.rasterFrame)); } } protected override needsDisplay(displayFlags: ViewFlags, viewContext: ViewContextType<this>): ViewFlags { if ((this.flags & View.DisplayMask) !== 0) { displayFlags |= View.NeedsComposite; } else if ((displayFlags & View.NeedsComposite) !== 0) { displayFlags = View.NeedsDisplay | View.NeedsComposite; } else { displayFlags = 0; } return displayFlags; } protected override onRender(viewContext: ViewContextType<this>): void { const rasterFrame = this.rasterFrame; this.resizeCanvas(this.canvas, rasterFrame); this.resetRenderer(rasterFrame); this.clearCanvas(rasterFrame); super.onRender(viewContext); } protected override didComposite(viewContext: ViewContextType<this>): void { this.compositeImage(viewContext); super.didComposite(viewContext); } override extendViewContext(viewContext: GeoViewContext): ViewContextType<this> { const rasterViewContext = Object.create(viewContext); rasterViewContext.compositor = viewContext.renderer; rasterViewContext.renderer = this.renderer; return rasterViewContext; } /** @internal */ readonly ownRasterFrame: R2Box | null; get rasterFrame(): R2Box { let rasterFrame = this.ownRasterFrame; if (rasterFrame === null) { rasterFrame = this.deriveRasterFrame(); } return rasterFrame; } /** @internal */ setRasterFrame(rasterFrame: R2Box | null): void { (this as Mutable<this>).ownRasterFrame = rasterFrame; } protected deriveRasterFrame(): R2Box { return this.deriveViewBounds(); } protected createCanvas(): HTMLCanvasElement { return document.createElement("canvas"); } protected resizeCanvas(canvas: HTMLCanvasElement, rasterFrame: R2Box): void { const pixelRatio = this.pixelRatio; const newWidth = rasterFrame.width; const newHeight = rasterFrame.height; const newCanvasWidth = newWidth * pixelRatio; const newCanvasHeight = newHeight * pixelRatio; const oldCanvasWidth = canvas.width; const oldCanvasHeight = canvas.height; if (newCanvasWidth !== oldCanvasWidth || newCanvasHeight !== oldCanvasHeight) { canvas.width = newCanvasWidth; canvas.height = newCanvasHeight; canvas.style.width = newWidth + "px"; canvas.style.height = newHeight + "px"; } } protected clearCanvas(rasterFrame: R2Box): void { const renderer = this.renderer; if (renderer instanceof CanvasRenderer) { renderer.context.clearRect(0, 0, rasterFrame.xMax, rasterFrame.yMax); } else if (renderer instanceof WebGLRenderer) { const context = renderer.context; context.clear(context.COLOR_BUFFER_BIT | context.DEPTH_BUFFER_BIT); } } protected resetRenderer(rasterFrame: R2Box): void { const renderer = this.renderer; if (renderer instanceof CanvasRenderer) { const pixelRatio = this.pixelRatio; const dx = rasterFrame.xMin * pixelRatio; const dy = rasterFrame.yMin * pixelRatio; renderer.context.setTransform(pixelRatio, 0, 0, pixelRatio, -dx, -dy); renderer.setTransform(Transform.affine(pixelRatio, 0, 0, pixelRatio, -dx, -dy)); } else if (renderer instanceof WebGLRenderer) { renderer.context.viewport(rasterFrame.x, rasterFrame.y, rasterFrame.xMax, rasterFrame.yMax); } } protected compositeImage(viewContext: ViewContextType<this>): void { const compositor = viewContext.compositor; if (compositor instanceof CanvasRenderer) { const context = compositor.context; const rasterFrame = this.rasterFrame; const canvas = this.canvas; if (rasterFrame.isDefined() && rasterFrame.width !== 0 && rasterFrame.height !== 0 && canvas.width !== 0 && canvas.height !== 0) { const globalAlpha = context.globalAlpha; const globalCompositeOperation = context.globalCompositeOperation; context.globalAlpha = this.opacity.getValue(); context.globalCompositeOperation = this.compositeOperation.getValue(); context.drawImage(canvas, rasterFrame.x, rasterFrame.y, rasterFrame.width, rasterFrame.height); context.globalAlpha = globalAlpha; context.globalCompositeOperation = globalCompositeOperation; } } } ripple(options?: GeoRippleOptions): GeoRippleView | null { return GeoRippleView.ripple(this, options); } override init(init: GeoRasterViewInit): void { super.init(init); if (init.geoAnchor !== void 0) { this.geoAnchor(init.geoAnchor); } if (init.viewAnchor !== void 0) { this.viewAnchor(init.viewAnchor); } if (init.xAlign !== void 0) { this.xAlign(init.xAlign); } if (init.yAlign !== void 0) { this.yAlign(init.yAlign); } if (init.width !== void 0) { this.width(init.width); } if (init.height !== void 0) { this.height(init.height); } if (init.opacity !== void 0) { this.opacity(init.opacity); } if (init.compositeOperation !== void 0) { this.compositeOperation(init.compositeOperation); } } static override readonly MountFlags: ViewFlags = GeoView.MountFlags | View.NeedsComposite; static override readonly UncullFlags: ViewFlags = GeoView.UncullFlags | View.NeedsComposite; static override readonly UnhideFlags: ViewFlags = GeoView.UnhideFlags | View.NeedsComposite; }
the_stack
import { kea } from 'kea' import React from 'react' import api from 'lib/api' import { dayjs } from 'lib/dayjs' import { errorToast } from 'lib/utils' import { generateRandomAnimal } from 'lib/utils/randomAnimal' import { toast } from 'react-toastify' import { funnelLogic } from 'scenes/funnels/funnelLogic' import { cleanFilters } from 'scenes/insights/utils/cleanFilters' import { teamLogic } from 'scenes/teamLogic' import { urls } from 'scenes/urls' import { Breadcrumb, Experiment, ExperimentResults, FilterType, FunnelVizType, InsightModel, InsightType, InsightShortId, } from '~/types' import { experimentLogicType } from './experimentLogicType' import { router } from 'kea-router' import { experimentsLogic } from './experimentsLogic' import { FunnelLayout } from 'lib/constants' const DEFAULT_DURATION = 14 // days export const experimentLogic = kea<experimentLogicType>({ path: ['scenes', 'experiment', 'experimentLogic'], connect: { values: [teamLogic, ['currentTeamId']], actions: [experimentsLogic, ['loadExperiments']] }, actions: { setExperimentResults: (experimentResults: ExperimentResults | null) => ({ experimentResults }), setExperiment: (experiment: Experiment) => ({ experiment }), createExperiment: (draft?: boolean, runningTime?: number, sampleSize?: number) => ({ draft, runningTime, sampleSize, }), setExperimentFunnelId: (shortId: InsightShortId) => ({ shortId }), createNewExperimentFunnel: (filters?: Partial<FilterType>) => ({ filters }), setFilters: (filters: Partial<FilterType>) => ({ filters }), setExperimentId: (experimentId: number | 'new') => ({ experimentId }), setNewExperimentData: (experimentData: Partial<Experiment>) => ({ experimentData }), emptyData: true, launchExperiment: true, endExperiment: true, editExperiment: true, }, reducers: { experimentId: [ null as number | 'new' | null, { setExperimentId: (_, { experimentId }) => experimentId, }, ], newExperimentData: [ null as Partial<Experiment> | null, { setNewExperimentData: (vals, { experimentData }) => { if (experimentData.filters) { const newFilters = { ...vals?.filters, ...experimentData.filters } return { ...vals, ...experimentData, filters: newFilters } } return { ...vals, ...experimentData } }, emptyData: () => null, }, ], experimentResults: [ null as ExperimentResults | null, { setExperimentResults: (_, { experimentResults }) => experimentResults, }, ], experimentFunnelId: [ null as InsightShortId | null, { setExperimentFunnelId: (_, { shortId }) => shortId, }, ], editingExistingExperiment: [ false, { editExperiment: () => true, createExperiment: () => false, }, ], }, listeners: ({ values, actions }) => ({ createExperiment: async ({ draft, runningTime, sampleSize }) => { let response: Experiment | null = null const isUpdate = !!values.newExperimentData?.id try { if (values.newExperimentData?.id) { response = await api.update( `api/projects/${values.currentTeamId}/experiments/${values.experimentId}`, { ...values.newExperimentData, parameters: { ...values.newExperimentData.parameters, recommended_running_time: runningTime, recommended_sample_size: sampleSize, }, ...(!draft && { start_date: dayjs() }), } ) } else { response = await api.create(`api/projects/${values.currentTeamId}/experiments`, { ...values.newExperimentData, parameters: { ...values.newExperimentData?.parameters, recommended_running_time: runningTime, recommended_sample_size: sampleSize, }, ...(!draft && { start_date: dayjs() }), }) } } catch (error) { errorToast( 'Error creating your experiment', 'Attempting to create this experiment returned an error:', error.status !== 0 ? error.detail : "Check your internet connection and make sure you don't have an extension blocking our requests.", error.code ) return } if (response?.id) { const experimentId = response.id toast.success( <div data-attr="success-toast"> <h1>Experiment {isUpdate ? 'updated' : 'created'} successfully!</h1> {!isUpdate && <p>Click here to launch this experiment.</p>} </div>, { onClick: () => { router.actions.push(urls.experiment(experimentId)) }, closeOnClick: true, onClose: () => { router.actions.push(urls.experiment(experimentId)) }, } ) } }, createNewExperimentFunnel: async ({ filters }) => { const newInsight = { name: generateRandomAnimal(), description: '', tags: [], filters: cleanFilters({ insight: InsightType.FUNNELS, funnel_viz_type: FunnelVizType.Steps, date_from: dayjs().subtract(DEFAULT_DURATION, 'day').format('YYYY-MM-DDTHH:mm'), date_to: dayjs().endOf('d').format('YYYY-MM-DDTHH:mm'), layout: FunnelLayout.horizontal, ...filters, }), result: null, } const createdInsight: InsightModel = await api.create( `api/projects/${teamLogic.values.currentTeamId}/insights`, newInsight ) actions.setExperimentFunnelId(createdInsight.short_id) }, setFilters: ({ filters }) => { funnelLogic.findMounted({ dashboardItemId: values.experimentFunnelId })?.actions.setFilters(filters) }, loadExperimentSuccess: async ({ experimentData }) => { if (!experimentData?.start_date) { // loading a draft mode experiment actions.createNewExperimentFunnel(experimentData?.filters) actions.setNewExperimentData({ ...experimentData }) } else { try { const response = await api.get( `api/projects/${values.currentTeamId}/experiments/${values.experimentId}/results` ) actions.setExperimentResults({ ...response, itemID: Math.random().toString(36).substring(2, 15) }) } catch (error) { if (error.code === 'no_data') { actions.setExperimentResults({ funnel: [], filters: {}, probability: 0, itemID: Math.random().toString(36).substring(2, 15), }) return } errorToast( 'Error loading experiment results', 'Attempting to load results returned an error:', error.status !== 0 ? error.detail : "Check your internet connection and make sure you don't have an extension blocking our requests.", error.code ) actions.setExperimentResults(null) } } }, launchExperiment: async () => { const response: Experiment = await api.update( `api/projects/${values.currentTeamId}/experiments/${values.experimentId}`, { start_date: dayjs(), } ) actions.setExperimentId(response.id || 'new') actions.loadExperiment() }, endExperiment: async () => { const response: Experiment = await api.update( `api/projects/${values.currentTeamId}/experiments/${values.experimentId}`, { end_date: dayjs(), } ) actions.setExperimentId(response.id || 'new') actions.loadExperiment() }, }), loaders: ({ values }) => ({ experimentData: [ null as Experiment | null, { loadExperiment: async () => { if (values.experimentId && values.experimentId !== 'new') { const response = await api.get( `api/projects/${values.currentTeamId}/experiments/${values.experimentId}` ) return response as Experiment } return null }, }, ], }), selectors: { breadcrumbs: [ (s) => [s.experimentData, s.experimentId], (experimentData, experimentId): Breadcrumb[] => [ { name: 'Experiments', path: urls.experiments(), }, { name: experimentData?.name || 'New Experiment', path: urls.experiment(experimentId || 'new'), }, ], ], minimumDetectableChange: [ (s) => [s.newExperimentData], (newExperimentData): number => { return newExperimentData?.parameters?.minimum_detectable_effect || 5 }, ], recommendedSampleSize: [ (s) => [s.minimumDetectableChange], (mde) => (conversionRate: number) => { // Using the rule of thumb: 16 * sigma^2 / (mde^2) // refer https://en.wikipedia.org/wiki/Sample_size_determination with default beta and alpha // The results are same as: https://www.evanmiller.org/ab-testing/sample-size.html // and also: https://marketing.dynamicyield.com/ab-test-duration-calculator/ // this is per variant, so we need to multiply by 2 return 2 * Math.ceil((1600 * conversionRate * (1 - conversionRate / 100)) / (mde * mde)) }, ], expectedRunningTime: [ () => [], () => (entrants: number, sampleSize: number): number => { // recommended people / (actual people / day) = expected days return parseFloat((sampleSize / (entrants / DEFAULT_DURATION)).toFixed(1)) }, ], conversionRateForVariant: [ (s) => [s.experimentResults], (experimentResults) => (variant: string): string => { const errorResult = "Can't find variant" if (!experimentResults) { return errorResult } const variantResults = experimentResults.funnel.find( (variantFunnel) => variantFunnel[0].breakdown_value?.[0] === variant ) if (!variantResults) { return errorResult } return `${( (variantResults[variantResults.length - 1].count / variantResults[0].count) * 100 ).toFixed(1)}%` }, ], }, urlToAction: ({ actions, values }) => ({ '/experiments/:id': ({ id }) => { if (id) { const parsedId = id === 'new' ? 'new' : parseInt(id) // TODO: optimise loading if already loaded Experiment // like in featureFlagLogic.tsx if (parsedId === 'new') { actions.createNewExperimentFunnel() actions.emptyData() } if (parsedId !== values.experimentId) { actions.setExperimentId(parsedId) } if (parsedId !== 'new') { actions.loadExperiment() } } }, }), })
the_stack
import { observableArray, observable } from '../dist' import { trackArrayChanges } from '../dist/observableArray.changeTracking' function captureCompareArraysCalls (callback) { var origCompareArrays = trackArrayChanges.compareArrays, interceptedCompareArrays = function () { callLog.push(Array.prototype.slice.call(arguments, 0)) return origCompareArrays.apply(this, arguments) }, // aliases = [], callLog = [] trackArrayChanges.compareArrays = interceptedCompareArrays // Find and intercept all the aliases // for (var key in ko.utils) { // if (ko.utils[key] === origCompareArrays) { // aliases.push(key); // ko.utils[key] = interceptedCompareArrays; // } // } try { callback(callLog) } finally { // Undo the interceptor trackArrayChanges.compareArrays = origCompareArrays // for (var i = 0; i < aliases.length; i++) { // ko.utils[aliases[i]] = origCompareArrays; // } } } describe('Observable Array change tracking', function () { it('Supplies changelists to subscribers', function () { var myArray = observableArray(['Alpha', 'Beta', 'Gamma']), changelist myArray.subscribe(function (changes) { changelist = changes }, null, 'arrayChange') // Not going to test all possible types of mutation, because we know the diffing // logic is all in ko.utils.compareArrays, which is tested separately. Just // checking that a simple 'push' comes through OK. myArray.push('Delta') expect(changelist).toEqual([ { status: 'added', value: 'Delta', index: 3 } ]) }) it('Only computes diffs when there\'s at least one active arrayChange subscription', function () { captureCompareArraysCalls(function (callLog) { var myArray = observableArray(['Alpha', 'Beta', 'Gamma']), changelist // Nobody has yet subscribed for arrayChange notifications, so // array mutations don't involve computing diffs myArray(['Another']) expect(callLog.length).toBe(0) // When there's a subscriber, it does compute diffs var subscription = myArray.subscribe(function (changes) { changelist = changes }, null, 'arrayChange') myArray(['Changed']) expect(callLog.length).toBe(1) expect(changelist.sort(compareChangeListItems)).toEqual([ { status: 'added', value: 'Changed', index: 0 }, { status: 'deleted', value: 'Another', index: 0 } ]) // If all the subscriptions are disposed, it stops computing diffs subscription.dispose() myArray(['Changed again']) expect(callLog.length).toBe(1) // Did not increment // ... but that doesn't stop someone else subscribing in the future, // then diffs are computed again myArray.subscribe(function (changes) { changelist = changes }, null, 'arrayChange') myArray(['Changed once more']) expect(callLog.length).toBe(2) // Verify that changes are from the previous array value (at subscription time) and not from the last notified value expect(changelist.sort(compareChangeListItems)).toEqual([ { status: 'added', value: 'Changed once more', index: 0 }, { status: 'deleted', value: 'Changed again', index: 0 } ]) }) }) it('Reuses cached diff results', function () { captureCompareArraysCalls(function (callLog) { var myArray = observableArray(['Alpha', 'Beta', 'Gamma']), changelist1, changelist2 myArray.subscribe(function (changes) { changelist1 = changes }, null, 'arrayChange') myArray.subscribe(function (changes) { changelist2 = changes }, null, 'arrayChange') myArray(['Gamma']) // See that, not only did it invoke compareArrays only once, but the // return values from getChanges are the same array instances expect(callLog.length).toBe(1) expect(changelist1).toEqual([ { status: 'deleted', value: 'Alpha', index: 0 }, { status: 'deleted', value: 'Beta', index: 1 } ]) expect(changelist2).toBe(changelist1) // Then when there's a further change, there's a further diff myArray(['Delta']) expect(callLog.length).toBe(2) expect(changelist1.sort(compareChangeListItems)).toEqual([ { status: 'added', value: 'Delta', index: 0 }, { status: 'deleted', value: 'Gamma', index: 0 } ]) expect(changelist2).toBe(changelist1) }) }) it('Converts a non array to an array', function () { captureCompareArraysCalls(function (callLog) { const myArray = observable('hello').extend({ trackArrayChanges: true }) let changelist1 myArray.subscribe(function (changes) { changelist1 = changes }, null, 'arrayChange') myArray(1) // See that, not only did it invoke compareArrays only once, but the // return values from getChanges are the same array instances expect(callLog.length).toBe(1) expect(changelist1).toEqual([ { status: 'added', value: 1, index: 0 }, { status: 'deleted', value: 'hello', index: 0 } ]) // Objects get converted to Array myArray({a: 1}) expect(callLog.length).toBe(2) expect(changelist1).toEqual([ { status: 'added', value: {a: 1}, index: 0 }, { status: 'deleted', value: 1, index: 0 } ]) }) }) it('Skips the diff algorithm when the array mutation is a known operation', function () { captureCompareArraysCalls(function (callLog) { var myArray = observableArray(['Alpha', 'Beta', 'Gamma']), browserSupportsSpliceWithoutDeletionCount = [1, 2].splice(1).length === 1 // Make sure there is one subscription, or we short-circuit cacheDiffForKnownOperation. myArray.subscribe(function () {}, null, 'arrayChange') // Push testKnownOperation(myArray, 'push', { args: ['Delta', 'Epsilon'], result: ['Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon'], changes: [ { status: 'added', value: 'Delta', index: 3 }, { status: 'added', value: 'Epsilon', index: 4 } ] }) // Pop testKnownOperation(myArray, 'pop', { args: [], result: ['Alpha', 'Beta', 'Gamma', 'Delta'], changes: [ { status: 'deleted', value: 'Epsilon', index: 4 } ] }) // Pop empty array testKnownOperation(observableArray([]), 'pop', { args: [], result: [], changes: undefined }) // Shift testKnownOperation(myArray, 'shift', { args: [], result: ['Beta', 'Gamma', 'Delta'], changes: [ { status: 'deleted', value: 'Alpha', index: 0 } ] }) // Shift empty array testKnownOperation(observableArray([]), 'shift', { args: [], result: [], changes: undefined }) // Unshift testKnownOperation(myArray, 'unshift', { args: ['First', 'Second'], result: ['First', 'Second', 'Beta', 'Gamma', 'Delta'], changes: [ { status: 'added', value: 'First', index: 0 }, { status: 'added', value: 'Second', index: 1 } ] }) // Splice testKnownOperation(myArray, 'splice', { args: [2, 3, 'Another', 'YetAnother'], result: ['First', 'Second', 'Another', 'YetAnother'], changes: [ { status: 'added', value: 'Another', index: 2 }, { status: 'deleted', value: 'Beta', index: 2 }, { status: 'added', value: 'YetAnother', index: 3 }, { status: 'deleted', value: 'Gamma', index: 3 }, { status: 'deleted', value: 'Delta', index: 4 } ] }) // Splice - no 'deletion count' supplied (deletes everything after start index) if (browserSupportsSpliceWithoutDeletionCount) { testKnownOperation(myArray, 'splice', { args: [2], result: ['First', 'Second'], changes: [ { status: 'deleted', value: 'Another', index: 2 }, { status: 'deleted', value: 'YetAnother', index: 3 } ] }) } else { // Browser doesn't support that underlying operation, so just set the state // to what it needs to be to run the remaining tests var prevCallLogLength = callLog.length myArray(['First', 'Second']) // Also restore previous call log length callLog.splice(prevCallLogLength, callLog.length) } // Splice - deletion end index out of bounds testKnownOperation(myArray, 'splice', { args: [1, 50, 'X', 'Y'], result: ['First', 'X', 'Y'], changes: [ { status: 'added', value: 'X', index: 1 }, { status: 'deleted', value: 'Second', index: 1 }, { status: 'added', value: 'Y', index: 2 } ] }) // Splice - deletion start index out of bounds testKnownOperation(myArray, 'splice', { args: [25, 3, 'New1', 'New2'], result: ['First', 'X', 'Y', 'New1', 'New2'], changes: [ { status: 'added', value: 'New1', index: 3 }, { status: 'added', value: 'New2', index: 4 } ] }) // Splice - deletion start index negative (means 'from end of array') testKnownOperation(myArray, 'splice', { args: [-3, 2, 'Blah', 'Another'], result: ['First', 'X', 'Blah', 'Another', 'New2'], changes: [ { status: 'added', value: 'Blah', index: 2 }, { status: 'deleted', value: 'Y', index: 2 }, { status: 'added', value: 'Another', index: 3 }, { status: 'deleted', value: 'New1', index: 3 } ] }) // Slice - swapping items should find moves // NOTE: ko.utils.compareArrays will report the change list as // { status: 'deleted', value: 'First', index: 0, moved: 1 }, // { status: 'added', value: 'First', index: 1, moved: 0 } // which is also valid. testKnownOperation(myArray, 'splice', { args: [0, 2, 'X', 'First'], result: ['X', 'First', 'Blah', 'Another', 'New2'], changes: [ { status: 'added', value: 'X', index: 0, moved: 1 }, { status: 'deleted', value: 'First', index: 0, moved: 1 }, { status: 'added', value: 'First', index: 1, moved: 0 }, { status: 'deleted', value: 'X', index: 1, moved: 0 } ] }) expect(callLog.length).toBe(0) // Never needed to run the diff algorithm }) }) it('should restore previous subscription notifications', function () { var source = observableArray() var notifySubscribers = source.notifySubscribers var arrayChange = source.subscribe(function () { }, null, 'arrayChange') arrayChange.dispose() expect(source.notifySubscribers).toBe(notifySubscribers) }) it('Should support tracking of any observable using extender', function () { var myArray = observable(['Alpha', 'Beta', 'Gamma']).extend({trackArrayChanges: true}), changelist myArray.subscribe(function (changes) { changelist = changes }, null, 'arrayChange') myArray(['Alpha', 'Beta', 'Gamma', 'Delta']) expect(changelist).toEqual([ { status: 'added', value: 'Delta', index: 3 } ]) // Should treat null value as an empty array myArray(null) expect(changelist).toEqual([ { status: 'deleted', value: 'Alpha', index: 0 }, { status: 'deleted', value: 'Beta', index: 1 }, { status: 'deleted', value: 'Gamma', index: 2 }, { status: 'deleted', value: 'Delta', index: 3 } ]) // Check that extending the observable again doesn't break anything an only one diff is generated var changelist2, callCount = 0 myArray = myArray.extend({trackArrayChanges: true}) myArray.subscribe(function (changes) { callCount++ changelist2 = changes }, null, 'arrayChange') myArray(['Gamma']) expect(callCount).toEqual(1) expect(changelist2).toEqual([ { status: 'added', value: 'Gamma', index: 0 } ]) expect(changelist2).toBe(changelist) }) // Per: https://github.com/knockout/knockout/issues/1503 it('Should clean up a single arrayChange dependency', function () { var source = observableArray() var arrayChange = source.subscribe(function () {}, null, 'arrayChange') expect(source.getSubscriptionsCount('arrayChange')).toBe(1) arrayChange.dispose() expect(source.getSubscriptionsCount()).toBe(0) }) it('Should support recursive updates (modify array within arrayChange callback)', function () { // See https://github.com/knockout/knockout/issues/1552 var toAdd = { name: '1', nodes: [ { name: '1.1', nodes: [ { name: '1.1.1', nodes: [] } ] }, { name: '1.2', nodes: [] }, { name: '1.3', nodes: [] } ] } var list = observableArray([]) // This adds all descendent nodes to the list when a node is added list.subscribe(function (events) { events = events.slice(0) for (var i = 0; i < events.length; i++) { var event = events[i] switch (event.status) { case 'added': list.push.apply(list, event.value.nodes) break } } }, null, 'arrayChange') // Add the top-level node list.push(toAdd) // See that descendent nodes are also added expect(list()).toEqual([ toAdd, toAdd.nodes[0], toAdd.nodes[1], toAdd.nodes[2], toAdd.nodes[0].nodes[0] ]) }) it('Should honor "dontLimitMoves" option', function () { // In order to test this, we must have a scenario in which a move is not recognized as such without the option. // This scenario doesn't represent the definition of the spec itself and may need to be modified if the move // detection algorithm in Knockout is changed. (See also the similar test in arrayEditDetectionBehaviors.js) var array1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T'] var array2 = [1, 2, 3, 4, 'T', 6, 7, 8, 9, 10] var myArray = observableArray(array1), changelist myArray.subscribe(function (changes) { changelist = changes }, null, 'arrayChange') // The default behavior is to limit moves myArray(array2) expect(changelist[changelist.length - 1]).toEqual({ status: 'deleted', value: 'T', index: 19 }) // Change the behavior by extending again with the dontLimitMoves option myArray.extend({ trackArrayChanges: { dontLimitMoves: true } }) myArray(array1) expect(changelist[changelist.length - 1]).toEqual({ status: 'added', value: 'T', index: 19, moved: 4 }) }) function testKnownOperation (array, operationName, options) { var changeList, subscription = array.subscribe(function (changes) { expect(array()).toEqual(options.result) changeList = changes }, null, 'arrayChange') array[operationName].apply(array, options.args) subscription.dispose() // The ordering of added/deleted items for replaced entries isn't defined, so // we'll sort by index and then status just so the tests can get consistent results if (changeList && changeList.sort) { changeList.sort(compareChangeListItems) } expect(changeList).toEqual(options.changes) } function compareChangeListItems (a, b) { return (a.index - b.index) || a.status.localeCompare(b.status) } })
the_stack
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { BidiModule } from '@angular/cdk/bidi'; import { CommonModule } from '@angular/common'; import { PortalModule } from '@angular/cdk/portal'; import { PlatformModule } from '@angular/cdk/platform'; import { SmoothScrollModule } from '../../smooth-scroll/src/smooth-scroll.module'; import { NgScrollbar } from './ng-scrollbar'; import { ScrollViewport } from './scroll-viewport'; import { NgAttr } from './utils/ng-attr.directive'; import { ResizeSensor } from './resize-sensor/resize-sensor.directive'; import { HideNativeScrollbar } from './hide-native-scrollbar/hide-native-scrollbar'; import { ScrollbarX, ScrollbarY } from './scrollbar/scrollbar.component'; describe('NgScrollbar Component', () => { let component: NgScrollbar; let fixture: ComponentFixture<NgScrollbar>; let componentElement: HTMLElement; beforeEach(() => { TestBed.configureTestingModule({ imports: [ CommonModule, BidiModule, PortalModule, PlatformModule, SmoothScrollModule ], declarations: [ NgScrollbar, NgAttr, HideNativeScrollbar, ResizeSensor, ScrollbarY, ScrollbarX, ScrollViewport ] }).compileComponents(); }); beforeEach(waitForAsync(() => { fixture = TestBed.createComponent(NgScrollbar); component = fixture.componentInstance; componentElement = fixture.debugElement.nativeElement; fixture.detectChanges(); })); afterEach(() => { fixture.destroy(); }); it('should create <ng-scrollbar> component', () => { expect(component).toBeTruthy(); }); it('should initialize component', () => { component.ngOnInit(); expect(component.viewport).toBeDefined(); expect(component.scrolled).toBeDefined(); expect(component.verticalScrolled).toBeDefined(); expect(component.horizontalScrolled).toBeDefined(); expect(component.state).toBeDefined(); }); it('should update state on ngAfterViewInit', () => { const updateSpy = spyOn<any>(component, 'updateState'); component.ngAfterViewInit(); expect(updateSpy).toHaveBeenCalled(); }); it('should update state on ngOnChanges', () => { const updateSpy = spyOn<any>(component, 'updateState'); component.ngOnChanges({}); // if (component.viewport) { // // } expect(updateSpy).toHaveBeenCalled(); }); it('should clean up all observables on ngOnDestroy', () => { component.ngOnDestroy(); expect(component['destroyed'].isStopped).toBeTrue(); }); /** * NgScrollbar State Test */ it('should show vertical scrollbar when viewport is scrollable"', () => { component.track = 'vertical'; component.visibility = 'native'; component.viewport.nativeElement.style.height = '300px'; component.viewport.nativeElement.innerHTML = '<div style="height: 1000px"></div>'; fixture.detectChanges(); component.ngAfterViewInit(); expect(component.state.verticalUsed).toBeTrue(); expect(component.state.isVerticallyScrollable).toBeTrue(); expect(component.state.horizontalUsed).toBeFalse(); expect(component.state.isHorizontallyScrollable).toBeFalse(); expect(component['scrollbarY']).toBeTruthy(); expect(component['scrollbarX']).toBeFalsy(); }); it('should show vertical scrollbar if visiblity="always" even if viewport is not scrollable', () => { component.track = 'vertical'; component.visibility = 'always'; component.viewport.nativeElement.style.height = '1000px'; component.viewport.nativeElement.innerHTML = '<div style="height: 300px"></div>'; fixture.detectChanges(); component.ngAfterViewInit(); expect(component.state.verticalUsed).toBeTrue(); expect(component.state.isVerticallyScrollable).toBeFalse(); expect(component.state.horizontalUsed).toBeFalse(); expect(component.state.isHorizontallyScrollable).toBeFalse(); expect(component['scrollbarY']).toBeTruthy(); expect(component['scrollbarX']).toBeFalsy(); }); it('should not show vertical scrollbar if viewport is not scrollable', () => { component.track = 'vertical'; component.visibility = 'native'; component.viewport.nativeElement.style.height = '1000px'; component.viewport.nativeElement.innerHTML = '<div style="height: 300px"></div>'; fixture.detectChanges(); component.ngAfterViewInit(); expect(component.state.verticalUsed).toBeFalse(); expect(component.state.isVerticallyScrollable).toBeFalse(); expect(component.state.horizontalUsed).toBeFalse(); expect(component.state.isHorizontallyScrollable).toBeFalse(); expect(component['scrollbarY']).toBeFalsy(); expect(component['scrollbarX']).toBeFalsy(); }); it('should show horizontal scrollbar', () => { component.track = 'horizontal'; component.visibility = 'always'; component.viewport.nativeElement.style.width = '300px'; component.viewport.nativeElement.innerHTML = '<div style="width: 1000px; height: 300px"></div>'; fixture.detectChanges(); component.ngAfterViewInit(); expect(component.state.horizontalUsed).toBeTrue(); expect(component.state.isHorizontallyScrollable).toBeTrue(); expect(component.state.verticalUsed).toBeFalse(); expect(component.state.isVerticallyScrollable).toBeFalse(); expect(component['scrollbarY']).toBeFalsy(); expect(component['scrollbarX']).toBeTruthy(); }); it('should show horizontal scrollbar if visiblity="always" even if viewport is not scrollable', () => { component.track = 'horizontal'; component.visibility = 'always'; component.viewport.nativeElement.style.width = '1000px'; component.viewport.nativeElement.innerHTML = '<div style="width: 300px; height: 300px"></div>'; fixture.detectChanges(); component.ngAfterViewInit(); expect(component.state.horizontalUsed).toBeTrue(); expect(component.state.isHorizontallyScrollable).toBeFalse(); expect(component.state.verticalUsed).toBeFalse(); expect(component.state.isVerticallyScrollable).toBeFalse(); expect(component['scrollbarY']).toBeFalsy(); expect(component['scrollbarX']).toBeTruthy(); }); it('should not show horizontal scrollbar if viewport is not scrollable', () => { component.track = 'horizontal'; component.visibility = 'native'; component.viewport.nativeElement.style.width = '1000px'; component.viewport.nativeElement.innerHTML = '<div style="width: 300px; height: 300px"></div>'; fixture.detectChanges(); component.ngAfterViewInit(); expect(component.state.horizontalUsed).toBeFalse(); expect(component.state.isHorizontallyScrollable).toBeFalse(); expect(component.state.verticalUsed).toBeFalse(); expect(component.state.isVerticallyScrollable).toBeFalse(); expect(component['scrollbarY']).toBeFalsy(); expect(component['scrollbarX']).toBeFalsy(); }); it('should show all scrollbars if visiblity="always"', () => { component.track = 'all'; component.visibility = 'always'; component.viewport.nativeElement.style.width = '1000px'; component.viewport.nativeElement.style.height = '1000px'; component.viewport.nativeElement.innerHTML = '<div style="width: 300px; height: 300px"></div>'; fixture.detectChanges(); component.ngAfterViewInit(); expect(component.state.horizontalUsed).toBeTrue(); expect(component.state.isHorizontallyScrollable).toBeFalse(); expect(component.state.verticalUsed).toBeTrue(); expect(component.state.isVerticallyScrollable).toBeFalse(); expect(component['scrollbarY']).toBeTruthy(); expect(component['scrollbarX']).toBeTruthy(); }); it('should show all scrollbars if viewport is vertically and horizontally scrollable', () => { component.track = 'all'; component.visibility = 'native'; component.viewport.nativeElement.style.width = '200px'; component.viewport.nativeElement.style.height = '200px'; component.viewport.nativeElement.innerHTML = '<div style="width: 300px; height: 300px"></div>'; fixture.detectChanges(); component.ngAfterViewInit(); expect(component.state.horizontalUsed).toBeTrue(); expect(component.state.isHorizontallyScrollable).toBeTrue(); expect(component.state.verticalUsed).toBeTrue(); expect(component.state.isVerticallyScrollable).toBeTrue(); expect(component['scrollbarY']).toBeTruthy(); expect(component['scrollbarX']).toBeTruthy(); }); it('[Auto-height]: component height should match content height', () => { component.autoHeightDisabled = false; component.track = 'all'; component.appearance = 'standard'; component.viewport.nativeElement.innerHTML = '<div style="width: 300px; height: 300px"></div>'; component.ngOnInit(); component.ngAfterViewInit(); fixture.detectChanges(); expect(component['scrollbarY']).toBeFalsy(); expect(component['scrollbarX']).toBeFalsy(); expect(window.getComputedStyle(component.nativeElement).height).toBe('300px'); }); // it('[Auto-height]: component height should match content height when horizontally scrollable', () => { // component.autoHeightDisabled = false; // component.track = 'all'; // component.appearance = 'standard'; // component.viewport.nativeElement.innerHTML = '<div style="width: 300px; height: 300px"></div>'; // component.viewport.nativeElement.style.width = '200px'; // component.viewport.nativeElement.style.height = `${300 + component['scrollbarX']?.nativeElement.clientHeight}px`; // component.ngOnInit(); // component.ngAfterViewInit(); // fixture.detectChanges(); // // // expect(component['scrollbarY']).toBeFalsy(); // expect(component.state.verticalUsed).toBeFalsy(); // expect(component['scrollbarX']).toBeTruthy(); // expect(window.getComputedStyle(component.nativeElement).height).toBe(`${300 + component['scrollbarX']?.nativeElement.clientHeight}px`); // }); // it('[Auto-width]: component width should match content width', () => { // component.autoWidthDisabled = false; // component.autoHeightDisabled = true; // component.appearance = 'standard'; // component.track = 'all'; // component.viewport.nativeElement.innerHTML = '<div style="width: 300px; height: 300px"></div>'; // component.viewport.nativeElement.style.position = 'fixed'; // component.viewport.nativeElement.style.width = '300px'; // // component.ngAfterViewInit(); // fixture.detectChanges(); // // expect(component['scrollbarY']).toBeFalsy(); // expect(component['scrollbarX']).toBeFalsy(); // console.log(window.getComputedStyle(component.nativeElement).width, window.getComputedStyle(component.viewport.nativeElement.firstElementChild).width); // expect(window.getComputedStyle(component.nativeElement).width).toBe('300px'); // }); });
the_stack
import * as H from 'history'; import * as queryString from 'query-string'; import * as React from 'react'; import {analyticsEvent} from './util/analytics'; import {Chart, ChartComponent, ChartType} from './chart'; import {DataSourceEnum, SourceSelection} from './datasource/data_source'; import {Details} from './details'; import {EmbeddedDataSource, EmbeddedSourceSpec} from './datasource/embedded'; import {FormattedMessage, WrappedComponentProps, injectIntl} from 'react-intl'; import {getI18nMessage} from './util/error_i18n'; import {IndiInfo} from 'topola'; import {Intro} from './intro'; import {Loader, Message, Portal} from 'semantic-ui-react'; import {Media} from './util/media'; import {Redirect, Route, RouteComponentProps, Switch} from 'react-router-dom'; import {TopBar} from './menu/top_bar'; import {TopolaData} from './util/gedcom_util'; import { getSelection, UploadSourceSpec, UrlSourceSpec, GedcomUrlDataSource, UploadedDataSource, } from './datasource/load_data'; import { loadWikiTree, PRIVATE_ID_PREFIX, WikiTreeDataSource, WikiTreeSourceSpec, } from './datasource/wikitree'; /** Shows an error message in the middle of the screen. */ function ErrorMessage(props: {message?: string}) { return ( <Message negative className="error"> <Message.Header> <FormattedMessage id="error.failed_to_load_file" defaultMessage={'Failed to load file'} /> </Message.Header> <p>{props.message}</p> </Message> ); } interface ErrorPopupProps { message?: string; open: boolean; onDismiss: () => void; } /** * Shows a dismissable error message in the bottom left corner of the screen. */ function ErrorPopup(props: ErrorPopupProps) { return ( <Portal open={props.open} onClose={props.onDismiss}> <Message negative className="errorPopup" onDismiss={props.onDismiss}> <Message.Header> <FormattedMessage id="error.error" defaultMessage={'Error'} /> </Message.Header> <p>{props.message}</p> </Message> </Portal> ); } enum AppState { INITIAL, LOADING, ERROR, SHOWING_CHART, LOADING_MORE, } type DataSourceSpec = | UrlSourceSpec | UploadSourceSpec | WikiTreeSourceSpec | EmbeddedSourceSpec; /** Arguments passed to the application, primarily through URL parameters. */ interface Arguments { sourceSpec?: DataSourceSpec; selection?: IndiInfo; chartType: ChartType; standalone: boolean; freezeAnimation?: boolean; showSidePanel: boolean; } /** * Retrieve arguments passed into the application through the URL and uploaded * data. */ function getArguments(location: H.Location<any>): Arguments { const search = queryString.parse(location.search); const getParam = (name: string) => { const value = search[name]; return typeof value === 'string' ? value : undefined; }; const view = getParam('view'); const chartTypes = new Map<string | undefined, ChartType>([ ['relatives', ChartType.Relatives], ['fancy', ChartType.Fancy], ]); const hash = getParam('file'); const url = getParam('url'); const embedded = getParam('embedded') === 'true'; // False by default. var sourceSpec: DataSourceSpec | undefined = undefined; if (getParam('source') === 'wikitree') { sourceSpec = { source: DataSourceEnum.WIKITREE, authcode: getParam('?authcode'), }; } else if (hash) { sourceSpec = { source: DataSourceEnum.UPLOADED, hash, gedcom: location.state && location.state.data, images: location.state && location.state.images, }; } else if (url) { sourceSpec = { source: DataSourceEnum.GEDCOM_URL, url, handleCors: getParam('handleCors') !== 'false', // True by default. }; } else if (embedded) { sourceSpec = {source: DataSourceEnum.EMBEDDED}; } const indi = getParam('indi'); const parsedGen = Number(getParam('gen')); const selection = indi ? {id: indi, generation: !isNaN(parsedGen) ? parsedGen : 0} : undefined; return { sourceSpec, selection, // Hourglass is the default view. chartType: chartTypes.get(view) || ChartType.Hourglass, showSidePanel: getParam('sidePanel') !== 'false', // True by default. standalone: getParam('standalone') !== 'false' && !embedded, freezeAnimation: getParam('freeze') === 'true', // False by default }; } /** * Returs true if the changes object has values that are different than those * in state. */ function hasUpdatedValues<T>(state: T, changes: Partial<T> | undefined) { if (!changes) { return false; } return Object.entries(changes).some( ([key, value]) => value !== undefined && state[key] !== value, ); } interface State { /** State of the application. */ state: AppState; /** Loaded data. */ data?: TopolaData; /** Selected individual. */ selection?: IndiInfo; /** Error to display. */ error?: string; /** Whether the side panel is shown. */ showSidePanel?: boolean; /** Whether the app is in standalone mode, i.e. showing 'open file' menus. */ standalone: boolean; /** Type of displayed chart. */ chartType: ChartType; /** Whether to show the error popup. */ showErrorPopup: boolean; /** Specification of the source of the data. */ sourceSpec?: DataSourceSpec; /** Freeze animations after initial chart render. */ freezeAnimation?: boolean; } class AppComponent extends React.Component< RouteComponentProps & WrappedComponentProps, {} > { state: State = { state: AppState.INITIAL, standalone: true, chartType: ChartType.Hourglass, showErrorPopup: false, }; chartRef: ChartComponent | null = null; /** Sets the state with a new individual selection and chart type. */ private updateDisplay( selection: IndiInfo, otherStateChanges?: Partial<State>, ) { if ( !this.state.selection || this.state.selection.id !== selection.id || this.state.selection!.generation !== selection.generation || hasUpdatedValues(this.state, otherStateChanges) ) { this.setState( Object.assign({}, this.state, {selection}, otherStateChanges), ); } } /** Sets error message after data load failure. */ private setError(error: string) { this.setState( Object.assign({}, this.state, { state: AppState.ERROR, error, }), ); } componentDidMount() { this.componentDidUpdate(); } private readonly uploadedDataSource = new UploadedDataSource(); private readonly gedcomUrlDataSource = new GedcomUrlDataSource(); private readonly wikiTreeDataSource = new WikiTreeDataSource(this.props.intl); private readonly embeddedDataSource = new EmbeddedDataSource(); private isNewData(sourceSpec: DataSourceSpec, selection?: IndiInfo) { if ( !this.state.sourceSpec || this.state.sourceSpec.source !== sourceSpec.source ) { // New data source means new data. return true; } const newSource = {spec: sourceSpec, selection}; const oldSouce = { spec: this.state.sourceSpec, selection: this.state.selection, }; switch (newSource.spec.source) { case DataSourceEnum.UPLOADED: return this.uploadedDataSource.isNewData( newSource as SourceSelection<UploadSourceSpec>, oldSouce as SourceSelection<UploadSourceSpec>, this.state.data, ); case DataSourceEnum.GEDCOM_URL: return this.gedcomUrlDataSource.isNewData( newSource as SourceSelection<UrlSourceSpec>, oldSouce as SourceSelection<UrlSourceSpec>, this.state.data, ); case DataSourceEnum.WIKITREE: return this.wikiTreeDataSource.isNewData( newSource as SourceSelection<WikiTreeSourceSpec>, oldSouce as SourceSelection<WikiTreeSourceSpec>, this.state.data, ); case DataSourceEnum.EMBEDDED: return this.embeddedDataSource.isNewData( newSource as SourceSelection<EmbeddedSourceSpec>, oldSouce as SourceSelection<EmbeddedSourceSpec>, this.state.data, ); } } private loadData(sourceSpec: DataSourceSpec, selection?: IndiInfo) { switch (sourceSpec.source) { case DataSourceEnum.UPLOADED: return this.uploadedDataSource.loadData({spec: sourceSpec, selection}); case DataSourceEnum.GEDCOM_URL: return this.gedcomUrlDataSource.loadData({spec: sourceSpec, selection}); case DataSourceEnum.WIKITREE: return this.wikiTreeDataSource.loadData({spec: sourceSpec, selection}); case DataSourceEnum.EMBEDDED: return this.embeddedDataSource.loadData({spec: sourceSpec, selection}); } } async componentDidUpdate() { if (this.props.location.pathname !== '/view') { if (this.state.state !== AppState.INITIAL) { this.setState(Object.assign({}, this.state, {state: AppState.INITIAL})); } return; } const args = getArguments(this.props.location); if (!args.sourceSpec) { this.props.history.replace({pathname: '/'}); } else if ( this.state.state === AppState.INITIAL || this.isNewData(args.sourceSpec, args.selection) ) { // Set loading state. this.setState( Object.assign({}, this.state, { state: AppState.LOADING, sourceSpec: args.sourceSpec, selection: args.selection, standalone: args.standalone, chartType: args.chartType, }), ); try { const data = await this.loadData(args.sourceSpec, args.selection); // Set state with data. this.setState( Object.assign({}, this.state, { state: AppState.SHOWING_CHART, data, selection: getSelection(data.chartData, args.selection), showSidePanel: args.showSidePanel, }), ); } catch (error) { this.setError(getI18nMessage(error, this.props.intl)); } } else if ( this.state.state === AppState.SHOWING_CHART || this.state.state === AppState.LOADING_MORE ) { // Update selection if it has changed in the URL. const selection = getSelection( this.state.data!.chartData, args.selection, ); const loadMoreFromWikitree = args.sourceSpec.source === DataSourceEnum.WIKITREE && (!this.state.selection || this.state.selection.id !== selection.id); this.updateDisplay(selection, { chartType: args.chartType, state: loadMoreFromWikitree ? AppState.LOADING_MORE : AppState.SHOWING_CHART, }); if (loadMoreFromWikitree) { try { const data = await loadWikiTree(args.selection!.id, this.props.intl); const selection = getSelection(data.chartData, args.selection); this.setState( Object.assign({}, this.state, { state: AppState.SHOWING_CHART, data, selection, }), ); } catch (error) { this.showErrorPopup( this.props.intl.formatMessage( { id: 'error.failed_wikitree_load_more', defaultMessage: 'Failed to load data from WikiTree. {error}', }, {error}, ), {state: AppState.SHOWING_CHART}, ); } } } } /** * Called when the user clicks an individual box in the chart. * Updates the browser URL. */ private onSelection = (selection: IndiInfo) => { // Don't allow selecting WikiTree private profiles. if (selection.id.startsWith(PRIVATE_ID_PREFIX)) { return; } analyticsEvent('selection_changed'); const location = this.props.location; const search = queryString.parse(location.search); search.indi = selection.id; search.gen = String(selection.generation); location.search = queryString.stringify(search); this.props.history.push(location); }; private onPrint = () => { analyticsEvent('print'); this.chartRef && this.chartRef.print(); }; private showErrorPopup(message: string, otherStateChanges?: Partial<State>) { this.setState( Object.assign( {}, this.state, { showErrorPopup: true, error: message, }, otherStateChanges, ), ); } private onDownloadPdf = async () => { analyticsEvent('download_pdf'); try { this.chartRef && (await this.chartRef.downloadPdf()); } catch (e) { this.showErrorPopup( this.props.intl.formatMessage({ id: 'error.failed_pdf', defaultMessage: 'Failed to generate PDF file.' + ' Please try with a smaller diagram or download an SVG file.', }), ); } }; private onDownloadPng = async () => { analyticsEvent('download_png'); try { this.chartRef && (await this.chartRef.downloadPng()); } catch (e) { this.showErrorPopup( this.props.intl.formatMessage({ id: 'error.failed_png', defaultMessage: 'Failed to generate PNG file.' + ' Please try with a smaller diagram or download an SVG file.', }), ); } }; private onDownloadSvg = () => { analyticsEvent('download_svg'); this.chartRef && this.chartRef.downloadSvg(); }; private onDismissErrorPopup = () => { this.setState( Object.assign({}, this.state, { showErrorPopup: false, }), ); }; private renderMainArea = () => { switch (this.state.state) { case AppState.SHOWING_CHART: case AppState.LOADING_MORE: return ( <div id="content"> <ErrorPopup open={this.state.showErrorPopup} message={this.state.error} onDismiss={this.onDismissErrorPopup} /> {this.state.state === AppState.LOADING_MORE ? ( <Loader active size="small" className="loading-more" /> ) : null} <Chart data={this.state.data!.chartData} selection={this.state.selection!} chartType={this.state.chartType} onSelection={this.onSelection} freezeAnimation={this.state.freezeAnimation} ref={(ref) => (this.chartRef = ref)} /> {this.state.showSidePanel ? ( <Media at="large" className="sidePanel"> <Details gedcom={this.state.data!.gedcom} indi={this.state.selection!.id} /> </Media> ) : null} </div> ); case AppState.ERROR: return <ErrorMessage message={this.state.error!} />; case AppState.INITIAL: case AppState.LOADING: return <Loader active size="large" />; } }; render() { return ( <> <Route render={(props: RouteComponentProps) => ( <TopBar {...props} data={this.state.data && this.state.data.chartData} allowAllRelativesChart={ this.state.sourceSpec?.source !== DataSourceEnum.WIKITREE } showingChart={ this.props.history.location.pathname === '/view' && (this.state.state === AppState.SHOWING_CHART || this.state.state === AppState.LOADING_MORE) } standalone={this.state.standalone} eventHandlers={{ onSelection: this.onSelection, onPrint: this.onPrint, onDownloadPdf: this.onDownloadPdf, onDownloadPng: this.onDownloadPng, onDownloadSvg: this.onDownloadSvg, }} showWikiTreeMenus={ this.state.sourceSpec?.source === DataSourceEnum.WIKITREE } /> )} /> <Switch> <Route exact path="/" component={Intro} /> <Route exact path="/view" render={this.renderMainArea} /> <Redirect to={'/'} /> </Switch> </> ); } } export const App = injectIntl(AppComponent);
the_stack
import { defaultSelectId } from '../utils/utilities'; import { EntityAdapter, createEntityAdapter } from '@ngrx/entity'; import { EntityCollection, ChangeState, ChangeStateMap, ChangeType } from './entity-collection'; import { createEmptyEntityCollection } from './entity-collection-creator'; import { IdSelector, Update } from '../utils/ngrx-entity-models'; import { MergeStrategy } from '../actions/merge-strategy'; import { EntityChangeTracker } from './entity-change-tracker'; import { EntityChangeTrackerBase } from './entity-change-tracker-base'; interface Hero { id: number; name: string; power?: string; } function sortByName(a: { name: string }, b: { name: string }): number { return a.name.localeCompare(b.name); } /** Test version of toUpdate that assumes entity has key named 'id' */ function toUpdate(entity: any) { return { id: entity.id, changes: entity }; } const adapter: EntityAdapter<Hero> = createEntityAdapter<Hero>({ sortComparer: sortByName }); describe('EntityChangeTrackerBase', () => { let origCollection: EntityCollection<Hero>; let tracker: EntityChangeTracker<Hero>; beforeEach(() => { origCollection = createEmptyEntityCollection<Hero>('Hero'); origCollection.entities = { 1: { id: 1, name: 'Alice', power: 'Strong' }, 2: { id: 2, name: 'Gail', power: 'Loud' }, 7: { id: 7, name: 'Bob', power: 'Swift' } }; origCollection.ids = [1, 7, 2]; tracker = new EntityChangeTrackerBase(adapter, defaultSelectId); }); describe('#commitAll', () => { it('should clear all tracked changes', () => { let { collection } = createTestTrackedEntities(); expect(Object.keys(collection.changeState).length).toBe(3, 'tracking 3 entities'); collection = tracker.commitAll(collection); expect(Object.keys(collection.changeState).length).toBe(0, 'tracking zero entities'); }); }); describe('#commitOne', () => { it('should clear current tracking of the given entity', () => { // tslint:disable-next-line:prefer-const let { collection, deletedEntity, addedEntity, updatedEntity } = createTestTrackedEntities(); collection = tracker.commitMany([updatedEntity], collection); expect(collection.changeState[updatedEntity.id]).toBeUndefined('no changes tracked for updated entity'); expect(collection.changeState[deletedEntity.id]).toBeDefined('still tracking deleted entity'); expect(collection.changeState[addedEntity.id]).toBeDefined('still tracking added entity'); }); }); describe('#commitMany', () => { it('should clear current tracking of the given entities', () => { // tslint:disable-next-line:prefer-const let { collection, deletedEntity, addedEntity, updatedEntity } = createTestTrackedEntities(); collection = tracker.commitMany([addedEntity, updatedEntity], collection); expect(collection.changeState[addedEntity.id]).toBeUndefined('no changes tracked for added entity'); expect(collection.changeState[updatedEntity.id]).toBeUndefined('no changes tracked for updated entity'); expect(collection.changeState[deletedEntity.id]).toBeDefined('still tracking deleted entity'); }); }); describe('#trackAddOne', () => { it('should return a new collection with tracked new entity', () => { const addedEntity = { id: 42, name: 'Ted', power: 'Chatty' }; const collection = tracker.trackAddOne(addedEntity, origCollection); expect(collection).not.toBe(origCollection); const change = collection.changeState[addedEntity.id]; expect(change).toBeDefined('tracking the entity'); expectChangeType(change, ChangeType.Added); expect(change.originalValue).toBeUndefined('no original value for a new entity'); }); it('should leave added entity tracked as added when entity is updated', () => { const addedEntity = { id: 42, name: 'Ted', power: 'Chatty' }; let collection = tracker.trackAddOne(addedEntity, origCollection); const updatedEntity = { ...addedEntity, name: 'Double Test' }; collection = tracker.trackUpdateOne(toUpdate(updatedEntity), collection); // simulate the collection update collection.entities[addedEntity.id] = updatedEntity; const change = collection.changeState[updatedEntity.id]; expect(change).toBeDefined('is still tracked as an added entity'); expectChangeType(change, ChangeType.Added); expect(change.originalValue).toBeUndefined('still no original value for added entity'); }); it('should return same collection if called with null entity', () => { const collection = tracker.trackAddOne(null, origCollection); expect(collection).toBe(origCollection); }); it('should return the same collection if MergeStrategy.IgnoreChanges', () => { const addedEntity = { id: 42, name: 'Ted', power: 'Chatty' }; const collection = tracker.trackAddOne(addedEntity, origCollection, MergeStrategy.IgnoreChanges); expect(collection).toBe(origCollection); const change = collection.changeState[addedEntity.id]; expect(change).toBeUndefined('not tracking the entity'); }); }); describe('#trackAddMany', () => { const newEntities = [{ id: 42, name: 'Ted', power: 'Chatty' }, { id: 84, name: 'Sally', power: 'Laughter' }]; it('should return a new collection with tracked new entities', () => { const collection = tracker.trackAddMany(newEntities, origCollection); expect(collection).not.toBe(origCollection); const trackKeys = Object.keys(collection.changeState); expect(trackKeys).toEqual(['42', '84'], 'tracking new entities'); trackKeys.forEach((key, ix) => { const change = collection.changeState[key]; expect(change).toBeDefined(`tracking the entity ${key}`); expectChangeType(change, ChangeType.Added, `tracking ${key} as a new entity`); expect(change.originalValue).toBeUndefined(`no original value for new entity ${key}`); }); }); it('should return same collection if called with empty array', () => { const collection = tracker.trackAddMany([] as any, origCollection); expect(collection).toBe(origCollection); }); }); describe('#trackDeleteOne', () => { it('should return a new collection with tracked "deleted" entity', () => { const existingEntity = getFirstExistingEntity(); const collection = tracker.trackDeleteOne(existingEntity.id, origCollection); expect(collection).not.toBe(origCollection); const change = collection.changeState[existingEntity.id]; expect(change).toBeDefined('tracking the entity'); expectChangeType(change, ChangeType.Deleted); expect(change.originalValue).toBe(existingEntity, 'originalValue is the existing entity'); }); it('should return a new collection with tracked "deleted" entity, deleted by key', () => { const existingEntity = getFirstExistingEntity(); const collection = tracker.trackDeleteOne(existingEntity.id, origCollection); expect(collection).not.toBe(origCollection); const change = collection.changeState[existingEntity.id]; expect(change).toBeDefined('tracking the entity'); expectChangeType(change, ChangeType.Deleted); expect(change.originalValue).toBe(existingEntity, 'originalValue is the existing entity'); }); it('should untrack (commit) an added entity when it is removed', () => { const addedEntity = { id: 42, name: 'Ted', power: 'Chatty' }; let collection = tracker.trackAddOne(addedEntity, origCollection); // Add it to the collection as the reducer would collection = { ...collection, entities: { ...collection.entities, 42: addedEntity }, ids: (collection.ids as number[]).concat(42) }; let change = collection.changeState[addedEntity.id]; expect(change).toBeDefined('tracking the new entity'); collection = tracker.trackDeleteOne(addedEntity.id, collection); change = collection.changeState[addedEntity.id]; expect(change).not.toBeDefined('is no longer tracking the new entity'); }); it('should switch an updated entity to a deleted entity when it is removed', () => { const existingEntity = getFirstExistingEntity(); const updatedEntity = toUpdate({ ...existingEntity, name: 'test update' }); let collection = tracker.trackUpdateOne(toUpdate(updatedEntity), origCollection); let change = collection.changeState[updatedEntity.id]; expect(change).toBeDefined('tracking the updated existing entity'); expectChangeType(change, ChangeType.Updated, 'updated at first'); collection = tracker.trackDeleteOne(updatedEntity.id, collection); change = collection.changeState[updatedEntity.id]; expect(change).toBeDefined('tracking the deleted, updated entity'); expectChangeType(change, ChangeType.Deleted, 'after delete'); expect(change.originalValue).toEqual(existingEntity, 'tracking original value'); }); it('should leave deleted entity tracked as deleted when try to update', () => { const existingEntity = getFirstExistingEntity(); let collection = tracker.trackDeleteOne(existingEntity.id, origCollection); let change = collection.changeState[existingEntity.id]; expect(change).toBeDefined('tracking the deleted entity'); expectChangeType(change, ChangeType.Deleted); // This shouldn't be possible but let's try it. const updatedEntity = { ...existingEntity, name: 'Double Test' }; collection.entities[existingEntity.id] = updatedEntity; collection = tracker.trackUpdateOne(toUpdate(updatedEntity), collection); change = collection.changeState[updatedEntity.id]; expect(change).toBeDefined('is still tracked as a deleted entity'); expectChangeType(change, ChangeType.Deleted); expect(change.originalValue).toEqual(existingEntity, 'still tracking original value'); }); it('should return same collection if called with null entity', () => { const collection = tracker.trackDeleteOne(null, origCollection); expect(collection).toBe(origCollection); }); it('should return same collection if called with a key not found', () => { const collection = tracker.trackDeleteOne('1234', origCollection); expect(collection).toBe(origCollection); }); it('should return same collection if MergeStrategy.IgnoreChanges', () => { const existingEntity = getFirstExistingEntity(); const collection = tracker.trackDeleteOne(existingEntity.id, origCollection, MergeStrategy.IgnoreChanges); expect(collection).toBe(origCollection); const change = collection.changeState[existingEntity.id]; expect(change).toBeUndefined('not tracking the entity'); }); }); describe('#trackDeleteMany', () => { it('should return a new collection with tracked "deleted" entities', () => { const existingEntities = getSomeExistingEntities(2); const collection = tracker.trackDeleteMany(existingEntities.map(e => e.id), origCollection); expect(collection).not.toBe(origCollection); existingEntities.forEach((entity, ix) => { const change = collection.changeState[existingEntities[ix].id]; expect(change).toBeDefined(`tracking entity #${ix}`); expectChangeType(change, ChangeType.Deleted, `entity #${ix}`); expect(change.originalValue).toBe(existingEntities[ix], `entity #${ix} originalValue`); }); }); it('should return same collection if called with empty array', () => { const collection = tracker.trackDeleteMany([], origCollection); expect(collection).toBe(origCollection); }); it('should return same collection if called with a key not found', () => { const collection = tracker.trackDeleteMany(['1234', 456], origCollection); expect(collection).toBe(origCollection); }); }); describe('#trackUpdateOne', () => { it('should return a new collection with tracked updated entity', () => { const existingEntity = getFirstExistingEntity(); const updatedEntity = toUpdate({ ...existingEntity, name: 'test update' }); const collection = tracker.trackUpdateOne(updatedEntity, origCollection); expect(collection).not.toBe(origCollection); const change = collection.changeState[existingEntity.id]; expect(change).toBeDefined('tracking the entity'); expectChangeType(change, ChangeType.Updated); expect(change.originalValue).toBe(existingEntity, 'originalValue is the existing entity'); }); it('should return a new collection with tracked updated entity, updated by key', () => { const existingEntity = getFirstExistingEntity(); const updatedEntity = toUpdate({ ...existingEntity, name: 'test update' }); const collection = tracker.trackUpdateOne(updatedEntity, origCollection); expect(collection).not.toBe(origCollection); const change = collection.changeState[existingEntity.id]; expect(change).toBeDefined('tracking the entity'); expectChangeType(change, ChangeType.Updated); expect(change.originalValue).toBe(existingEntity, 'originalValue is the existing entity'); }); it('should leave updated entity tracked as updated if try to add', () => { const existingEntity = getFirstExistingEntity(); const updatedEntity = toUpdate({ ...existingEntity, name: 'test update' }); let collection = tracker.trackUpdateOne(updatedEntity, origCollection); let change = collection.changeState[existingEntity.id]; expect(change).toBeDefined('tracking the updated entity'); expectChangeType(change, ChangeType.Updated); // This shouldn't be possible but let's try it. const addedEntity = { ...existingEntity, name: 'Double Test' }; collection.entities[existingEntity.id] = addedEntity; collection = tracker.trackAddOne(addedEntity, collection); change = collection.changeState[addedEntity.id]; expect(change).toBeDefined('is still tracked as an updated entity'); expectChangeType(change, ChangeType.Updated); expect(change.originalValue).toEqual(existingEntity, 'still tracking original value'); }); it('should return same collection if called with null entity', () => { const collection = tracker.trackUpdateOne(null, origCollection); expect(collection).toBe(origCollection); }); it('should return same collection if called with a key not found', () => { const updateEntity = toUpdate({ id: '1234', name: 'Mr. 404' }); const collection = tracker.trackUpdateOne(updateEntity, origCollection); expect(collection).toBe(origCollection); }); it('should return same collection if MergeStrategy.IgnoreChanges', () => { const existingEntity = getFirstExistingEntity(); const updatedEntity = toUpdate({ ...existingEntity, name: 'test update' }); const collection = tracker.trackUpdateOne(updatedEntity, origCollection, MergeStrategy.IgnoreChanges); expect(collection).toBe(origCollection); const change = collection.changeState[existingEntity.id]; expect(change).toBeUndefined('not tracking the entity'); }); }); describe('#trackUpdateMany', () => { it('should return a new collection with tracked updated entities', () => { const existingEntities = getSomeExistingEntities(2); const updateEntities = existingEntities.map(e => toUpdate({ ...e, name: e.name + ' updated' })); const collection = tracker.trackUpdateMany(updateEntities, origCollection); expect(collection).not.toBe(origCollection); existingEntities.forEach((entity, ix) => { const change = collection.changeState[existingEntities[ix].id]; expect(change).toBeDefined(`tracking entity #${ix}`); expectChangeType(change, ChangeType.Updated, `entity #${ix}`); expect(change.originalValue).toBe(existingEntities[ix], `entity #${ix} originalValue`); }); }); it('should return same collection if called with empty array', () => { const collection = tracker.trackUpdateMany([], origCollection); expect(collection).toBe(origCollection); }); it('should return same collection if called with entities whose keys are not found', () => { const updateEntities = [toUpdate({ id: '1234', name: 'Mr. 404' }), toUpdate({ id: 456, name: 'Ms. 404' })]; const collection = tracker.trackUpdateMany(updateEntities, origCollection); expect(collection).toBe(origCollection); }); }); describe('#trackUpsertOne', () => { it('should return a new collection with tracked added entity', () => { const addedEntity = { id: 42, name: 'Ted', power: 'Chatty' }; const collection = tracker.trackUpsertOne(addedEntity, origCollection); expect(collection).not.toBe(origCollection); const change = collection.changeState[addedEntity.id]; expect(change).toBeDefined('tracking the entity'); expectChangeType(change, ChangeType.Added); expect(change.originalValue).toBeUndefined('no originalValue for added entity'); }); it('should return a new collection with tracked updated entity', () => { const existingEntity = getFirstExistingEntity(); const collection = tracker.trackUpsertOne(existingEntity, origCollection); expect(collection).not.toBe(origCollection); const change = collection.changeState[existingEntity.id]; expect(change).toBeDefined('tracking the entity'); expectChangeType(change, ChangeType.Updated); expect(change.originalValue).toBe(existingEntity, 'originalValue is the existing entity'); }); it('should not change orig value of updated entity that is updated again', () => { const existingEntity = getFirstExistingEntity(); let collection = tracker.trackUpsertOne(existingEntity, origCollection); let change = collection.changeState[existingEntity.id]; expect(change).toBeDefined('tracking the updated entity'); expectChangeType(change, ChangeType.Updated, 'first updated'); const updatedAgainEntity = { ...existingEntity, name: 'Double Test' }; collection = tracker.trackUpsertOne(updatedAgainEntity, collection); change = collection.changeState[updatedAgainEntity.id]; expect(change).toBeDefined('is still tracked as an updated entity'); expectChangeType(change, ChangeType.Updated, 'still updated after attempted add'); expect(change.originalValue).toEqual(existingEntity, 'still tracking original value'); }); it('should return same collection if called with null entity', () => { const collection = tracker.trackUpsertOne(null, origCollection); expect(collection).toBe(origCollection); }); it('should return same collection if MergeStrategy.IgnoreChanges', () => { const existingEntity = getFirstExistingEntity(); const updatedEntity = { ...existingEntity, name: 'test update' }; const collection = tracker.trackUpsertOne(updatedEntity, origCollection, MergeStrategy.IgnoreChanges); expect(collection).toBe(origCollection); const change = collection.changeState[existingEntity.id]; expect(change).toBeUndefined('not tracking the entity'); }); }); describe('#trackUpsertMany', () => { it('should return a new collection with tracked upserted entities', () => { const addedEntity = { id: 42, name: 'Ted', power: 'Chatty' }; const exitingEntities = getSomeExistingEntities(2); const updatedEntities = exitingEntities.map(e => ({ ...e, name: e.name + 'test' })); const upsertEntities = updatedEntities.concat(addedEntity); const collection = tracker.trackUpsertMany(upsertEntities, origCollection); expect(collection).not.toBe(origCollection); updatedEntities.forEach((entity, ix) => { const change = collection.changeState[updatedEntities[ix].id]; expect(change).toBeDefined(`tracking entity #${ix}`); // first two should be updated, the 3rd is added expectChangeType(change, ix === 2 ? ChangeType.Added : ChangeType.Updated, `entity #${ix}`); if (change.changeType === ChangeType.Updated) { expect(change.originalValue).toBe(exitingEntities[ix], `entity #${ix} originalValue`); } else { expect(change.originalValue).toBeUndefined(`no originalValue for added entity #${ix}`); } }); }); it('should return same collection if called with empty array', () => { const collection = tracker.trackUpsertMany([], origCollection); expect(collection).toBe(origCollection); }); }); describe('#undoAll', () => { it('should clear all tracked changes', () => { let { collection } = createTestTrackedEntities(); expect(Object.keys(collection.changeState).length).toBe(3, 'tracking 3 entities'); collection = tracker.undoAll(collection); expect(Object.keys(collection.changeState).length).toBe(0, 'tracking zero entities'); }); it('should restore the collection to the pre-change state', () => { // tslint:disable-next-line:prefer-const let { collection, addedEntity, deletedEntity, preUpdatedEntity, updatedEntity } = createTestTrackedEntities(); // Before undo expect(collection.entities[addedEntity.id]).toBeDefined('added entity should be present'); expect(collection.entities[deletedEntity.id]).toBeUndefined('deleted entity should be missing'); expect(updatedEntity.name).not.toEqual(preUpdatedEntity.name, 'updated entity should be changed'); collection = tracker.undoAll(collection); // After undo expect(collection.entities[addedEntity.id]).toBeUndefined('added entity should be removed'); expect(collection.entities[deletedEntity.id]).toBeDefined('deleted entity should be restored'); const revertedUpdate = collection.entities[updatedEntity.id]; expect(revertedUpdate.name).toEqual(preUpdatedEntity.name, 'updated entity should be restored'); }); }); describe('#undoOne', () => { it('should restore the collection to the pre-change state for the given entity', () => { // tslint:disable-next-line:prefer-const let { collection, addedEntity, deletedEntity, preUpdatedEntity, updatedEntity } = createTestTrackedEntities(); collection = tracker.undoOne(deletedEntity, collection); expect(collection.entities[deletedEntity.id]).toBeDefined('deleted entity should be restored'); expect(collection.entities[addedEntity.id]).toBeDefined('added entity should still be present'); expect(updatedEntity.name).not.toEqual(preUpdatedEntity.name, 'updated entity should be changed'); }); it('should do nothing when the given entity is null', () => { // tslint:disable-next-line:prefer-const let { collection, addedEntity, deletedEntity, preUpdatedEntity, updatedEntity } = createTestTrackedEntities(); collection = tracker.undoOne(null, collection); expect(collection.entities[addedEntity.id]).toBeDefined('added entity should be present'); expect(collection.entities[deletedEntity.id]).toBeUndefined('deleted entity should be missing'); expect(updatedEntity.name).not.toEqual(preUpdatedEntity.name, 'updated entity should be changed'); }); }); describe('#undoMany', () => { it('should restore the collection to the pre-change state for the given entities', () => { // tslint:disable-next-line:prefer-const let { collection, addedEntity, deletedEntity, preUpdatedEntity, updatedEntity } = createTestTrackedEntities(); collection = tracker.undoMany([addedEntity, deletedEntity, updatedEntity], collection); expect(collection.entities[addedEntity.id]).toBeUndefined('added entity should be removed'); expect(collection.entities[deletedEntity.id]).toBeDefined('deleted entity should be restored'); const revertedUpdate = collection.entities[updatedEntity.id]; expect(revertedUpdate.name).toEqual(preUpdatedEntity.name, 'updated entity should be restored'); }); it('should do nothing when there are no entities to undo', () => { // tslint:disable-next-line:prefer-const let { collection, addedEntity, deletedEntity, preUpdatedEntity, updatedEntity } = createTestTrackedEntities(); collection = tracker.undoMany([], collection); expect(collection.entities[addedEntity.id]).toBeDefined('added entity should be present'); expect(collection.entities[deletedEntity.id]).toBeUndefined('deleted entity should be missing'); expect(updatedEntity.name).not.toEqual(preUpdatedEntity.name, 'updated entity should be changed'); }); }); /// helpers /// /** Simulate the state of the collection after some test changes */ function createTestTrackedEntities() { const addedEntity = { id: 42, name: 'Ted', power: 'Chatty' }; const [deletedEntity, preUpdatedEntity] = getSomeExistingEntities(2); const updatedEntity = { ...preUpdatedEntity, name: 'Test Me' }; let collection = tracker.trackAddOne(addedEntity, origCollection); collection = tracker.trackDeleteOne(deletedEntity.id, collection); collection = tracker.trackUpdateOne(toUpdate(updatedEntity), collection); // Make the collection match these changes collection.ids = (collection.ids.slice(1, collection.ids.length) as number[]).concat(42); const entities: { [id: number]: Hero } = { ...collection.entities, 42: addedEntity, [updatedEntity.id]: updatedEntity }; delete entities[deletedEntity.id]; collection.entities = entities; return { collection, addedEntity, deletedEntity, preUpdatedEntity, updatedEntity }; } /** Test for ChangeState with expected ChangeType */ function expectChangeType(change: ChangeState<any>, expectedChangeType: ChangeType, msg?: string) { expect(ChangeType[change.changeType]).toEqual(ChangeType[expectedChangeType], msg); } /** Get the first entity in `originalCollection` */ function getFirstExistingEntity() { return getExistingEntityById(origCollection.ids[0]); } /** * Get the first 'n' existing entities from `originalCollection` * @param n Number of them to get */ function getSomeExistingEntities(n: number) { const ids = (origCollection.ids as string[]).slice(0, n); return getExistingEntitiesById(ids); } function getExistingEntityById(id: number | string) { return getExistingEntitiesById([id as string])[0]; } function getExistingEntitiesById(ids: string[]) { return ids.map(id => origCollection.entities[id]); } });
the_stack
import * as tf from '../index'; import {ALL_ENVS, describeWithFlags} from '../jasmine_util'; import {expectArraysClose} from '../test_util'; describeWithFlags('maxPool3d', ALL_ENVS, () => { it('4D x=[2,2,2,1] f=[2,2,2] s=1 p=valid', async () => { const x = tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2, 1]); const result = tf.maxPool3d(x, 2, 1, 'valid'); expect(result.shape).toEqual([1, 1, 1, 1]); expectArraysClose(await result.data(), [8]); }); it('x=[1,1,1,1,1] f=[1,1,1] s=1 [0] => [0]', async () => { const x = tf.tensor5d([0], [1, 1, 1, 1, 1]); const result = tf.maxPool3d(x, 1, 1, 0); expect(result.shape).toEqual([1, 1, 1, 1, 1]); expectArraysClose(await result.data(), [0]); }); it('x=[1,2,2,2,1] f=[2,2,2] s=1 p=valid', async () => { const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]); const result = tf.maxPool3d(x, 2, 1, 'valid'); expect(result.shape).toEqual([1, 1, 1, 1, 1]); expectArraysClose(await result.data(), [8]); }); it('x=[1,2,2,2,1] f=[2,2,2] s=1 p=same', async () => { const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]); const expected = [8, 8, 8, 8, 8, 8, 8, 8]; const result = tf.maxPool3d(x, 2, 1, 'same'); expect(result.shape).toEqual([1, 2, 2, 2, 1]); expectArraysClose(await result.data(), expected); }); it('x=[1,3,3,3,1] f=[2,2,2] s=1 p=valid', async () => { const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ], [1, 3, 3, 3, 1]); const expected = [14, 15, 17, 18, 23, 24, 26, 27]; const result = tf.maxPool3d(x, 2, 1, 'valid'); expect(result.shape).toEqual([1, 2, 2, 2, 1]); expectArraysClose(await result.data(), expected); }); it('x=[1,3,3,3,1] f=[2,2,2] s=1 p=same', async () => { const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ], [1, 3, 3, 3, 1]); const expected = [ 14, 15, 15, 17, 18, 18, 17, 18, 18, 23, 24, 24, 26, 27, 27, 26, 27, 27, 23, 24, 24, 26, 27, 27, 26, 27, 27 ]; const result = tf.maxPool3d(x, 2, 1, 'same'); expect(result.shape).toEqual([1, 3, 3, 3, 1]); expectArraysClose(await result.data(), expected); }); it('x=[1,3,3,3,1] f=[2,2,2] s=1 p=valid, ignores NaNs', async () => { const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, NaN, 8, NaN, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, NaN, 23, 24, 25, 26, 27 ], [1, 3, 3, 3, 1]); const expected = [14, 15, 17, 18, 23, 24, 26, 27]; const result = tf.maxPool3d(x, 2, 1, 'valid'); expect(result.shape).toEqual([1, 2, 2, 2, 1]); expectArraysClose(await result.data(), expected); }); it('x=[2,3,3,3,1] f=[2,2,2] s=1 p=valid', async () => { const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 ], [2, 3, 3, 3, 1]); const expected = [14, 15, 17, 18, 23, 24, 26, 27, 41, 42, 44, 45, 50, 51, 53, 54]; const result = tf.maxPool3d(x, 2, 1, 'valid'); expect(result.shape).toEqual([2, 2, 2, 2, 1]); expectArraysClose(await result.data(), expected); }); it('x=[1,3,3,3,2] f=[2,2,2] s=1 p=valid', async () => { const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 ], [1, 3, 3, 3, 2]); const expected = [27, 28, 29, 30, 33, 34, 35, 36, 45, 46, 47, 48, 51, 52, 53, 54]; const result = tf.maxPool3d(x, 2, 1, 'valid'); expect(result.shape).toEqual([1, 2, 2, 2, 2]); expectArraysClose(await result.data(), expected); }); it('x=[1,2,2,2,1] f=[2,2,2] s=1 p=1 roundingMode=floor', async () => { const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]); const expected = [ 1, 2, 2, 3, 4, 4, 3, 4, 4, 5, 6, 6, 7, 8, 8, 7, 8, 8, 5, 6, 6, 7, 8, 8, 7, 8, 8 ]; const result = tf.maxPool3d(x, 2, 1, 1, 'floor'); expect(result.shape).toEqual([1, 3, 3, 3, 1]); expectArraysClose(await result.data(), expected); }); it('throws when x is not rank 5', async () => { // tslint:disable-next-line:no-any const x: any = tf.tensor1d([1]); expect(() => tf.maxPool3d(x as tf.Tensor5D, 2, 1, 'valid')).toThrowError(); }); it('throws when dimRoundingMode is set and pad is not a number', async () => { const x = tf.tensor5d([1], [1, 1, 1, 1, 1]); const pad = 'valid'; const dimRoundingMode = 'round'; expect(() => tf.maxPool3d(x, 2, 1, pad, dimRoundingMode)).toThrowError(); }); it('throws when passed a non-tensor', () => { expect(() => tf.maxPool3d({} as tf.Tensor5D, 2, 1, 'valid')).toThrowError(); }); it('accepts a tensor-like object', async () => { const x = [[[[[0]]]]]; // 1x1x1x1x1 const result = tf.maxPool3d(x, 1, 1, 0); expect(result.shape).toEqual([1, 1, 1, 1, 1]); expectArraysClose(await result.data(), [0]); }); }); describeWithFlags('maxPool3dBackprop', ALL_ENVS, () => { it('gradient x=[2,2,2,1] f=[1,1,1] s=1', async () => { const dy = tf.tensor4d([1, 2, 1, 2, 1, 2, 1, 2], [2, 2, 2, 1]); const x = tf.tensor4d([1, 2, 3, 4, 5, 6, 7, 8], [2, 2, 2, 1]); const expected = [1, 2, 1, 2, 1, 2, 1, 2]; const dx = tf.grad((x: tf.Tensor4D) => tf.maxPool3d(x, 1, 1, 0))(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); it('gradient x=[1,2,2,2,1] f=[1,1,1] s=1', async () => { const dy = tf.tensor5d([1, 2, 1, 2, 1, 2, 1, 2], [1, 2, 2, 2, 1]); const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]); const expected = [1, 2, 1, 2, 1, 2, 1, 2]; const dx = tf.grad((x: tf.Tensor5D) => tf.maxPool3d(x, 1, 1, 0))(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); it('gradient x=[1,2,2,2,1] f=[2,2,2] s=2', async () => { const dy = tf.tensor5d([1], [1, 1, 1, 1, 1]); const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]); const expected = [0, 0, 0, 0, 0, 0, 0, 1]; const dx = tf.grad((x: tf.Tensor5D) => tf.maxPool3d(x, 2, 1, 0))(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); it('gradient with clone x=[1,2,2,2,1] f=[2,2,2] s=1', async () => { const dy = tf.tensor5d([1], [1, 1, 1, 1, 1]); const x = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]); const expected = [0, 0, 0, 0, 0, 0, 0, 1]; const dx = tf.grad( (x: tf.Tensor5D) => tf.maxPool3d(x.clone(), 2, 1, 0).clone())(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); it('gradient x=[1,3,3,3,1] f=[2,2,2] s=1 no dup max value', async () => { const dy = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]); const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ], [1, 3, 3, 3, 1]); const expected = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 3, 4, 0, 0, 0, 0, 5, 6, 0, 7, 8 ]; const dx = tf.grad((x: tf.Tensor5D) => tf.maxPool3d(x, 2, 1, 0))(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); it('gradient x=[1,3,3,3,1] f=[2,2,2] s=1 dup max value', async () => { const dy = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]); const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 27, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 14 ], [1, 3, 3, 3, 1]); const expected = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const dx = tf.grad((x: tf.Tensor5D) => tf.maxPool3d(x, 2, 1, 0))(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); it('gradient x=[1,4,4,4,1] f=[2,2,2] s=2', async () => { const dy = tf.tensor5d([1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 2, 2, 1]); const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64 ], [1, 4, 4, 4, 1]); const expected = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 6, 0, 0, 0, 0, 0, 7, 0, 8 ]; const dx = tf.grad((x: tf.Tensor5D) => tf.maxPool3d(x, 2, 2, 0))(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); it('gradient x=[1,3,3,3,2] f=[2,2,2] s=1 no dup max value', async () => { const dy = tf.tensor5d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [1, 2, 2, 2, 2]); const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 ], [1, 3, 3, 3, 2]); const expected = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 5, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 11, 12, 0, 0, 13, 14, 15, 16 ]; const dx = tf.grad((x: tf.Tensor5D) => tf.maxPool3d(x, 2, 1, 0))(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); it('gradient x=[1,3,3,3,2] f=[2,2,2] s=1 dup max value', async () => { const dy = tf.tensor5d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [1, 2, 2, 2, 2]); const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 53, 54, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 27, 28 ], [1, 3, 3, 3, 2]); const expected = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 64, 72, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const dx = tf.grad((x: tf.Tensor5D) => tf.maxPool3d(x, 2, 1, 0))(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); it('gradient x=[2,3,3,3,1] f=[2,2,2] s=1 no dup max value', async () => { const dy = tf.tensor5d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [2, 2, 2, 2, 1]); const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 ], [2, 3, 3, 3, 1]); const expected = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 3, 4, 0, 0, 0, 0, 5, 6, 0, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 10, 0, 11, 12, 0, 0, 0, 0, 13, 14, 0, 15, 16 ]; const dx = tf.grad((x: tf.Tensor5D) => tf.maxPool3d(x, 2, 1, 0))(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); it('gradient x=[2,3,3,3,1] f=[2,2,2] s=1 dup max value', async () => { const dy = tf.tensor5d( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [2, 2, 2, 2, 1]); const x = tf.tensor5d( [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 27, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 14, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 54, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 41 ], [2, 3, 3, 3, 1]); const expected = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 36, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; const dx = tf.grad((x: tf.Tensor5D) => tf.maxPool3d(x, 2, 1, 0))(x, dy); expect(dx.shape).toEqual(x.shape); expectArraysClose(await dx.data(), expected); }); });
the_stack
import { PacketType } from "socket.io-parser"; import msgpack = require("notepack.io"); import debugModule from "debug"; import type { DefaultEventsMap, EventNames, EventParams, EventsMap, TypedEventBroadcaster, } from "./typed-events"; const debug = debugModule("socket.io-emitter"); const UID = "emitter"; /** * Request types, for messages between nodes */ enum RequestType { SOCKETS = 0, ALL_ROOMS = 1, REMOTE_JOIN = 2, REMOTE_LEAVE = 3, REMOTE_DISCONNECT = 4, REMOTE_FETCH = 5, SERVER_SIDE_EMIT = 6, } export interface EmitterOptions { /** * @default "socket.io" */ key?: string; } interface BroadcastOptions { nsp: string; broadcastChannel: string; requestChannel: string; } interface BroadcastFlags { volatile?: boolean; compress?: boolean; } export class Emitter<EmitEvents extends EventsMap = DefaultEventsMap> { private readonly opts: EmitterOptions; private readonly broadcastOptions: BroadcastOptions; constructor( readonly redisClient: any, opts?: EmitterOptions, readonly nsp: string = "/" ) { this.opts = Object.assign( { key: "socket.io", }, opts ); this.broadcastOptions = { nsp, broadcastChannel: this.opts.key + "#" + nsp + "#", requestChannel: this.opts.key + "-request#" + nsp + "#", }; } /** * Return a new emitter for the given namespace. * * @param nsp - namespace * @public */ public of(nsp: string): Emitter<EmitEvents> { return new Emitter( this.redisClient, this.opts, (nsp[0] !== "/" ? "/" : "") + nsp ); } /** * Emits to all clients. * * @return Always true * @public */ public emit<Ev extends EventNames<EmitEvents>>( ev: Ev, ...args: EventParams<EmitEvents, Ev> ): true { return new BroadcastOperator<EmitEvents>( this.redisClient, this.broadcastOptions ).emit(ev, ...args); } /** * Targets a room when emitting. * * @param room * @return BroadcastOperator * @public */ public to(room: string | string[]): BroadcastOperator<EmitEvents> { return new BroadcastOperator(this.redisClient, this.broadcastOptions).to( room ); } /** * Targets a room when emitting. * * @param room * @return BroadcastOperator * @public */ public in(room: string | string[]): BroadcastOperator<EmitEvents> { return new BroadcastOperator(this.redisClient, this.broadcastOptions).in( room ); } /** * Excludes a room when emitting. * * @param room * @return BroadcastOperator * @public */ public except(room: string | string[]): BroadcastOperator<EmitEvents> { return new BroadcastOperator( this.redisClient, this.broadcastOptions ).except(room); } /** * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to * receive messages (because of network slowness or other issues, or because they’re connected through long polling * and is in the middle of a request-response cycle). * * @return BroadcastOperator * @public */ public get volatile(): BroadcastOperator<EmitEvents> { return new BroadcastOperator(this.redisClient, this.broadcastOptions) .volatile; } /** * Sets the compress flag. * * @param compress - if `true`, compresses the sending data * @return BroadcastOperator * @public */ public compress(compress: boolean): BroadcastOperator<EmitEvents> { return new BroadcastOperator( this.redisClient, this.broadcastOptions ).compress(compress); } /** * Makes the matching socket instances join the specified rooms * * @param rooms * @public */ public socketsJoin(rooms: string | string[]): void { return new BroadcastOperator( this.redisClient, this.broadcastOptions ).socketsJoin(rooms); } /** * Makes the matching socket instances leave the specified rooms * * @param rooms * @public */ public socketsLeave(rooms: string | string[]): void { return new BroadcastOperator( this.redisClient, this.broadcastOptions ).socketsLeave(rooms); } /** * Makes the matching socket instances disconnect * * @param close - whether to close the underlying connection * @public */ public disconnectSockets(close: boolean = false): void { return new BroadcastOperator( this.redisClient, this.broadcastOptions ).disconnectSockets(close); } /** * Send a packet to the Socket.IO servers in the cluster * * @param args - any number of serializable arguments */ public serverSideEmit(...args: any[]): void { const withAck = typeof args[args.length - 1] === "function"; if (withAck) { throw new Error("Acknowledgements are not supported"); } const request = JSON.stringify({ uid: UID, type: RequestType.SERVER_SIDE_EMIT, data: args, }); this.redisClient.publish(this.broadcastOptions.requestChannel, request); } } export const RESERVED_EVENTS: ReadonlySet<string | Symbol> = new Set(<const>[ "connect", "connect_error", "disconnect", "disconnecting", "newListener", "removeListener", ]); export class BroadcastOperator<EmitEvents extends EventsMap> implements TypedEventBroadcaster<EmitEvents> { constructor( private readonly redisClient: any, private readonly broadcastOptions: BroadcastOptions, private readonly rooms: Set<string> = new Set<string>(), private readonly exceptRooms: Set<string> = new Set<string>(), private readonly flags: BroadcastFlags = {} ) {} /** * Targets a room when emitting. * * @param room * @return a new BroadcastOperator instance * @public */ public to(room: string | string[]): BroadcastOperator<EmitEvents> { const rooms = new Set(this.rooms); if (Array.isArray(room)) { room.forEach((r) => rooms.add(r)); } else { rooms.add(room); } return new BroadcastOperator( this.redisClient, this.broadcastOptions, rooms, this.exceptRooms, this.flags ); } /** * Targets a room when emitting. * * @param room * @return a new BroadcastOperator instance * @public */ public in(room: string | string[]): BroadcastOperator<EmitEvents> { return this.to(room); } /** * Excludes a room when emitting. * * @param room * @return a new BroadcastOperator instance * @public */ public except(room: string | string[]): BroadcastOperator<EmitEvents> { const exceptRooms = new Set(this.exceptRooms); if (Array.isArray(room)) { room.forEach((r) => exceptRooms.add(r)); } else { exceptRooms.add(room); } return new BroadcastOperator( this.redisClient, this.broadcastOptions, this.rooms, exceptRooms, this.flags ); } /** * Sets the compress flag. * * @param compress - if `true`, compresses the sending data * @return a new BroadcastOperator instance * @public */ public compress(compress: boolean): BroadcastOperator<EmitEvents> { const flags = Object.assign({}, this.flags, { compress }); return new BroadcastOperator( this.redisClient, this.broadcastOptions, this.rooms, this.exceptRooms, flags ); } /** * Sets a modifier for a subsequent event emission that the event data may be lost if the client is not ready to * receive messages (because of network slowness or other issues, or because they’re connected through long polling * and is in the middle of a request-response cycle). * * @return a new BroadcastOperator instance * @public */ public get volatile(): BroadcastOperator<EmitEvents> { const flags = Object.assign({}, this.flags, { volatile: true }); return new BroadcastOperator( this.redisClient, this.broadcastOptions, this.rooms, this.exceptRooms, flags ); } /** * Emits to all clients. * * @return Always true * @public */ public emit<Ev extends EventNames<EmitEvents>>( ev: Ev, ...args: EventParams<EmitEvents, Ev> ): true { if (RESERVED_EVENTS.has(ev)) { throw new Error(`"${ev}" is a reserved event name`); } // set up packet object const data = [ev, ...args]; const packet = { type: PacketType.EVENT, data: data, nsp: this.broadcastOptions.nsp, }; const opts = { rooms: [...this.rooms], flags: this.flags, except: [...this.exceptRooms], }; const msg = msgpack.encode([UID, packet, opts]); let channel = this.broadcastOptions.broadcastChannel; if (this.rooms && this.rooms.size === 1) { channel += this.rooms.keys().next().value + "#"; } debug("publishing message to channel %s", channel); this.redisClient.publish(channel, msg); return true; } /** * Makes the matching socket instances join the specified rooms * * @param rooms * @public */ public socketsJoin(rooms: string | string[]): void { const request = JSON.stringify({ type: RequestType.REMOTE_JOIN, opts: { rooms: [...this.rooms], except: [...this.exceptRooms], }, rooms: Array.isArray(rooms) ? rooms : [rooms], }); this.redisClient.publish(this.broadcastOptions.requestChannel, request); } /** * Makes the matching socket instances leave the specified rooms * * @param rooms * @public */ public socketsLeave(rooms: string | string[]): void { const request = JSON.stringify({ type: RequestType.REMOTE_LEAVE, opts: { rooms: [...this.rooms], except: [...this.exceptRooms], }, rooms: Array.isArray(rooms) ? rooms : [rooms], }); this.redisClient.publish(this.broadcastOptions.requestChannel, request); } /** * Makes the matching socket instances disconnect * * @param close - whether to close the underlying connection * @public */ public disconnectSockets(close: boolean = false): void { const request = JSON.stringify({ type: RequestType.REMOTE_DISCONNECT, opts: { rooms: [...this.rooms], except: [...this.exceptRooms], }, close, }); this.redisClient.publish(this.broadcastOptions.requestChannel, request); } }
the_stack
import * as fs from 'fs'; import * as path from 'path'; import * as tsickle from 'tsickle'; import * as ts from 'typescript'; import {FileLoader} from './cache'; import * as perfTrace from './perf_trace'; import {BazelOptions} from './tsconfig'; import {DEBUG, debug} from './worker'; export type ModuleResolver = (moduleName: string, containingFile: string, compilerOptions: ts.CompilerOptions, host: ts.ModuleResolutionHost) => ts.ResolvedModuleWithFailedLookupLocations; /** * Narrows down the type of some properties from non-optional to required, so * that we do not need to check presence before each access. */ export interface BazelTsOptions extends ts.CompilerOptions { rootDirs: string[]; rootDir: string; outDir: string; typeRoots: string[]; } declare interface packageJson { typings?: string; } export function narrowTsOptions(options: ts.CompilerOptions): BazelTsOptions { if (!options.rootDirs) { throw new Error(`compilerOptions.rootDirs should be set by tsconfig.bzl`); } if (!options.rootDir) { throw new Error(`compilerOptions.rootDir should be set by tsconfig.bzl`); } if (!options.outDir) { throw new Error(`compilerOptions.outDir should be set by tsconfig.bzl`); } return options as BazelTsOptions; } function validateBazelOptions(bazelOpts: BazelOptions) { if (!bazelOpts.isJsTranspilation) return; if (bazelOpts.compilationTargetSrc && bazelOpts.compilationTargetSrc.length > 1) { throw new Error( 'In JS transpilation mode, only one file can appear in ' + 'bazelOptions.compilationTargetSrc.'); } if (!bazelOpts.transpiledJsOutputFileName && !bazelOpts.transpiledJsOutputDirectory) { throw new Error( 'In JS transpilation mode, either transpiledJsOutputFileName or ' + 'transpiledJsOutputDirectory must be specified in tsconfig.'); } if (bazelOpts.transpiledJsOutputFileName && bazelOpts.transpiledJsOutputDirectory) { throw new Error( 'In JS transpilation mode, cannot set both ' + 'transpiledJsOutputFileName and transpiledJsOutputDirectory.'); } } const SOURCE_EXT = /((\.d)?\.tsx?|\.js)$/; /** * CompilerHost that knows how to cache parsed files to improve compile times. */ export class CompilerHost implements ts.CompilerHost, tsickle.TsickleHost { /** * Lookup table to answer file stat's without looking on disk. */ private knownFiles = new Set<string>(); /** * rootDirs relative to the rootDir, eg "bazel-out/local-fastbuild/bin" */ private relativeRoots: string[]; getCancelationToken?: () => ts.CancellationToken; directoryExists?: (dir: string) => boolean; googmodule: boolean; es5Mode: boolean; prelude: string; untyped: boolean; typeBlackListPaths: Set<string>; transformDecorators: boolean; transformTypesToClosure: boolean; addDtsClutzAliases: boolean; isJsTranspilation: boolean; provideExternalModuleDtsNamespace: boolean; options: BazelTsOptions; moduleResolutionHost: ts.ModuleResolutionHost = this; // TODO(evanm): delete this once tsickle is updated. host: ts.ModuleResolutionHost = this; private allowActionInputReads = true; constructor( public inputFiles: string[], options: ts.CompilerOptions, readonly bazelOpts: BazelOptions, private delegate: ts.CompilerHost, private fileLoader: FileLoader, private moduleResolver: ModuleResolver = ts.resolveModuleName) { this.options = narrowTsOptions(options); this.relativeRoots = this.options.rootDirs.map(r => path.relative(this.options.rootDir, r)); inputFiles.forEach((f) => { this.knownFiles.add(f); }); // getCancelationToken is an optional method on the delegate. If we // unconditionally implement the method, we will be forced to return null, // in the absense of the delegate method. That won't match the return type. // Instead, we optionally set a function to a field with the same name. if (delegate && delegate.getCancellationToken) { this.getCancelationToken = delegate.getCancellationToken.bind(delegate); } // Override directoryExists so that TypeScript can automatically // include global typings from node_modules/@types // see getAutomaticTypeDirectiveNames in // TypeScript:src/compiler/moduleNameResolver if (this.allowActionInputReads && delegate && delegate.directoryExists) { this.directoryExists = delegate.directoryExists.bind(delegate); } validateBazelOptions(bazelOpts); this.googmodule = bazelOpts.googmodule; this.es5Mode = bazelOpts.es5Mode; this.prelude = bazelOpts.prelude; this.untyped = bazelOpts.untyped; this.typeBlackListPaths = new Set(bazelOpts.typeBlackListPaths); this.transformDecorators = bazelOpts.tsickle; this.transformTypesToClosure = bazelOpts.tsickle; this.addDtsClutzAliases = bazelOpts.addDtsClutzAliases; this.isJsTranspilation = Boolean(bazelOpts.isJsTranspilation); this.provideExternalModuleDtsNamespace = !bazelOpts.hasImplementation; } /** * For the given potentially absolute input file path (typically .ts), returns * the relative output path. For example, for * /path/to/root/blaze-out/k8-fastbuild/genfiles/my/file.ts, will return * my/file.js or my/file.mjs (depending on ES5 mode). */ relativeOutputPath(fileName: string) { let result = this.rootDirsRelative(fileName); result = result.replace(/(\.d)?\.[jt]sx?$/, ''); if (!this.bazelOpts.es5Mode) result += '.closure'; return result + '.js'; } /** * Workaround https://github.com/Microsoft/TypeScript/issues/8245 * We use the `rootDirs` property both for module resolution, * and *also* to flatten the structure of the output directory * (as `rootDir` would do for a single root). * To do this, look for the pattern outDir/relativeRoots[i]/path/to/file * or relativeRoots[i]/path/to/file * and replace that with path/to/file */ flattenOutDir(fileName: string): string { let result = fileName; // outDir/relativeRoots[i]/path/to/file -> relativeRoots[i]/path/to/file if (fileName.startsWith(this.options.rootDir)) { result = path.relative(this.options.outDir, fileName); } for (const dir of this.relativeRoots) { // relativeRoots[i]/path/to/file -> path/to/file const rel = path.relative(dir, result); if (!rel.startsWith('..')) { result = rel; // relativeRoots is sorted longest first so we can short-circuit // after the first match break; } } return result; } /** Avoid using tsickle on files that aren't in srcs[] */ shouldSkipTsickleProcessing(fileName: string): boolean { return this.bazelOpts.isJsTranspilation || this.bazelOpts.compilationTargetSrc.indexOf(fileName) === -1; } /** Whether the file is expected to be imported using a named module */ shouldNameModule(fileName: string): boolean { return this.bazelOpts.compilationTargetSrc.indexOf(fileName) !== -1; } /** Allows suppressing warnings for specific known libraries */ shouldIgnoreWarningsForPath(filePath: string): boolean { return this.bazelOpts.ignoreWarningPaths.some( p => !!filePath.match(new RegExp(p))); } /** * fileNameToModuleId gives the module ID for an input source file name. * @param fileName an input source file name, e.g. * /root/dir/bazel-out/host/bin/my/file.ts. * @return the canonical path of a file within blaze, without /genfiles/ or * /bin/ path parts, excluding a file extension. For example, "my/file". */ fileNameToModuleId(fileName: string): string { return this.relativeOutputPath( fileName.substring(0, fileName.lastIndexOf('.'))); } /** * TypeScript SourceFile's have a path with the rootDirs[i] still present, eg. * /build/work/bazel-out/local-fastbuild/bin/path/to/file * @return the path without any rootDirs, eg. path/to/file */ private rootDirsRelative(fileName: string): string { for (const root of this.options.rootDirs) { if (fileName.startsWith(root)) { // rootDirs are sorted longest-first, so short-circuit the iteration // see tsconfig.ts. return path.posix.relative(root, fileName); } } return fileName; } /** * Massages file names into valid goog.module names: * - resolves relative paths to the given context * - resolves non-relative paths which takes module_root into account * - replaces '/' with '.' in the '<workspace>' namespace * - replace first char if non-alpha * - replace subsequent non-alpha numeric chars */ pathToModuleName(context: string, importPath: string): string { // tsickle hands us an output path, we need to map it back to a source // path in order to do module resolution with it. // outDir/relativeRoots[i]/path/to/file -> // rootDir/relativeRoots[i]/path/to/file if (context.startsWith(this.options.outDir)) { context = path.join( this.options.rootDir, path.relative(this.options.outDir, context)); } // Try to get the resolved path name from TS compiler host which can // handle resolution for libraries with module_root like rxjs and @angular. let resolvedPath: string|null = null; const resolved = this.moduleResolver(importPath, context, this.options, this); if (resolved && resolved.resolvedModule && resolved.resolvedModule.resolvedFileName) { resolvedPath = resolved.resolvedModule.resolvedFileName; // /build/work/bazel-out/local-fastbuild/bin/path/to/file -> // path/to/file resolvedPath = this.rootDirsRelative(resolvedPath); } else { // importPath can be an absolute file path in google3. // Try to trim it as a path relative to bin and genfiles, and if so, // handle its file extension in the block below and prepend the workspace // name. const trimmed = this.rootDirsRelative(importPath); if (trimmed !== importPath) { resolvedPath = trimmed; } } if (resolvedPath) { // Strip file extensions. importPath = resolvedPath.replace(SOURCE_EXT, ''); // Make sure all module names include the workspace name. if (importPath.indexOf(this.bazelOpts.workspaceName) !== 0) { importPath = path.posix.join(this.bazelOpts.workspaceName, importPath); } } // Remove the __{LOCALE} from the module name. if (this.bazelOpts.locale) { const suffix = '__' + this.bazelOpts.locale.toLowerCase(); if (importPath.toLowerCase().endsWith(suffix)) { importPath = importPath.substring(0, importPath.length - suffix.length); } } // Replace characters not supported by goog.module and '.' with // '$<Hex char code>' so that the original module name can be re-obtained // without any loss. // See goog.VALID_MODULE_RE_ in Closure's base.js for characters supported // by google.module. const escape = (c: string) => { return '$' + c.charCodeAt(0).toString(16); }; const moduleName = importPath.replace(/^[0-9]|[^a-zA-Z_0-9_/]/g, escape) .replace(/\//g, '.'); return moduleName; } /** * Converts file path into a valid AMD module name. * * An AMD module can have an arbitrary name, so that it is require'd by name * rather than by path. See http://requirejs.org/docs/whyamd.html#namedmodules * * "However, tools that combine multiple modules together for performance need * a way to give names to each module in the optimized file. For that, AMD * allows a string as the first argument to define()" */ amdModuleName(sf: ts.SourceFile): string|undefined { if (!this.shouldNameModule(sf.fileName)) return undefined; // /build/work/bazel-out/local-fastbuild/bin/path/to/file.ts // -> path/to/file let fileName = this.rootDirsRelative(sf.fileName).replace(SOURCE_EXT, ''); let workspace = this.bazelOpts.workspaceName; // Workaround https://github.com/bazelbuild/bazel/issues/1262 // // When the file comes from an external bazel repository, // and TypeScript resolves runfiles symlinks, then the path will look like // output_base/execroot/local_repo/external/another_repo/foo/bar // We want to name such a module "another_repo/foo/bar" just as it would be // named by code in that repository. // As a workaround, check for the /external/ path segment, and fix up the // workspace name to be the name of the external repository. if (fileName.startsWith('external/')) { const parts = fileName.split('/'); workspace = parts[1]; fileName = parts.slice(2).join('/'); } if (this.bazelOpts.moduleName) { const relativeFileName = path.posix.relative(this.bazelOpts.package, fileName); // check that the fileName was actually underneath the package directory if (!relativeFileName.startsWith('..')) { if (this.bazelOpts.moduleRoot) { const root = this.bazelOpts.moduleRoot.replace(SOURCE_EXT, ''); if (root === relativeFileName || path.posix.join(root, 'index') === relativeFileName) { return this.bazelOpts.moduleName; } } // Support the common case of commonjs convention that index is the // default module in a directory. // This makes our module naming scheme more conventional and lets users // refer to modules with the natural name they're used to. if (relativeFileName === 'index') { return this.bazelOpts.moduleName; } return path.posix.join(this.bazelOpts.moduleName, relativeFileName); } } if (fileName.startsWith('node_modules/')) { return fileName.substring('node_modules/'.length); } // path/to/file -> // myWorkspace/path/to/file return path.posix.join(workspace, fileName); } /** * Resolves the typings file from a package at the specified path. Helper * function to `resolveTypeReferenceDirectives`. */ private resolveTypingFromDirectory(typePath: string, primary: boolean): ts.ResolvedTypeReferenceDirective | undefined { // Looks for the `typings` attribute in a package.json file // if it exists const pkgFile = path.posix.join(typePath, 'package.json'); if (this.fileExists(pkgFile)) { const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf-8')) as packageJson; let typings = pkg['typings']; if (typings) { if (typings === '.' || typings === './') { typings = 'index.d.ts'; } const maybe = path.posix.join(typePath, typings); if (this.fileExists(maybe)) { return { primary, resolvedFileName: maybe }; } } } // Look for an index.d.ts file in the path const maybe = path.posix.join(typePath, 'index.d.ts'); if (this.fileExists(maybe)) { return { primary, resolvedFileName: maybe }; } return undefined; } /** * Override the default typescript resolveTypeReferenceDirectives function. * Resolves /// <reference types="x" /> directives under bazel. The default * typescript secondary search behavior needs to be overridden to support * looking under `bazelOpts.nodeModulesPrefix` */ resolveTypeReferenceDirectives(names: string[], containingFile: string): ts.ResolvedTypeReferenceDirective[] { if (!this.allowActionInputReads) return []; const result: ts.ResolvedTypeReferenceDirective[] = []; names.forEach(name => { let resolved: ts.ResolvedTypeReferenceDirective | undefined; // primary search if (this.options.typeRoots) { this.options.typeRoots.forEach(typeRoot => { if (!resolved) { resolved = this.resolveTypingFromDirectory(path.posix.join(typeRoot, name), true); } }); } // secondary search if (!resolved) { resolved = this.resolveTypingFromDirectory(path.posix.join(this.bazelOpts.nodeModulesPrefix, name), false); } // Types not resolved should be silently ignored. Leave it to Typescript // to either error out with "TS2688: Cannot find type definition file for // 'foo'" or for the build to fail due to a missing type that is used. if (!resolved) { if (DEBUG) { debug(`Failed to resolve type reference directive '${name}'`); } return; } // In typescript 2.x the return type for this function // is `(ts.ResolvedTypeReferenceDirective | undefined)[]` thus we actually // do allow returning `undefined` in the array but the function is typed // `(ts.ResolvedTypeReferenceDirective)[]` to compile with both typescript // 2.x and 3.0/3.1 without error. Typescript 3.0/3.1 do handle the `undefined` // values in the array correctly despite the return signature. // It looks like the return type change was a mistake because // it was changed back to include `| undefined` recently: // https://github.com/Microsoft/TypeScript/pull/28059. result.push(resolved as ts.ResolvedTypeReferenceDirective); }); return result; } /** Loads a source file from disk (or the cache). */ getSourceFile( fileName: string, languageVersion: ts.ScriptTarget, onError?: (message: string) => void) { return perfTrace.wrap(`getSourceFile ${fileName}`, () => { const sf = this.fileLoader.loadFile(fileName, fileName, languageVersion) as ts.SourceFile&{_hasGeneratedAmdModuleName?: boolean}; if (!/\.d\.tsx?$/.test(fileName) && (this.options.module === ts.ModuleKind.AMD || this.options.module === ts.ModuleKind.UMD)) { const moduleName = this.amdModuleName(sf); if (sf.moduleName === moduleName || !moduleName) return sf; if (sf.moduleName) { throw new Error( `ERROR: ${sf.fileName} ` + `contains a module name declaration ${sf.moduleName} ` + `which would be overwritten with ${moduleName} ` + `by Bazel's TypeScript compiler.`); } // Setting the moduleName is equivalent to the original source having the triple // slash `///<amd-module name="some/name"/>` directive. Also note that we tag // source files for which we assigned a generated module name. This is necessary // so that we can reset the module name when the same source file is loaded from // a cache, but with a different module format where the auto-generated module // names are not desirable. The module name should not leak from previous // compilations through a potential source file cache. sf._hasGeneratedAmdModuleName = true; sf.moduleName = moduleName; return sf; } // If the loaded source file has a generated amd module name applied from // previous compilations (in worker mode), reset the file module name // as neither the UMD or AMD module format is used (for which we generate // the AMD module names automatically). if (sf._hasGeneratedAmdModuleName) { sf.moduleName = undefined; } return sf; }); } writeFile( fileName: string, content: string, writeByteOrderMark: boolean, onError: ((message: string) => void)|undefined, sourceFiles: ReadonlyArray<ts.SourceFile>|undefined): void { perfTrace.wrap( `writeFile ${fileName}`, () => this.writeFileImpl( fileName, content, writeByteOrderMark, onError, sourceFiles)); } writeFileImpl( fileName: string, content: string, writeByteOrderMark: boolean, onError: ((message: string) => void)|undefined, sourceFiles: ReadonlyArray<ts.SourceFile>|undefined): void { // Workaround https://github.com/Microsoft/TypeScript/issues/18648 // This bug is fixed in TS 2.9 const version = ts.versionMajorMinor; const [major, minor] = version.split('.').map(s => Number(s)); const workaroundNeeded = major <= 2 && minor <= 8; if (workaroundNeeded && (this.options.module === ts.ModuleKind.AMD || this.options.module === ts.ModuleKind.UMD) && fileName.endsWith('.d.ts') && sourceFiles && sourceFiles.length > 0 && sourceFiles[0].moduleName) { content = `/// <amd-module name="${sourceFiles[0].moduleName}" />\n${content}`; } fileName = this.flattenOutDir(fileName); if (this.bazelOpts.isJsTranspilation) { if (this.bazelOpts.transpiledJsOutputFileName) { fileName = this.bazelOpts.transpiledJsOutputFileName!; } else { // Strip the input directory path off of fileName to get the logical // path within the input directory. fileName = path.relative(this.bazelOpts.transpiledJsInputDirectory!, fileName); // Then prepend the output directory name. fileName = path.join(this.bazelOpts.transpiledJsOutputDirectory!, fileName); } } else if (!this.bazelOpts.es5Mode) { // Write ES6 transpiled files to *.mjs. if (this.bazelOpts.locale) { // i18n paths are required to end with __locale.js so we put // the .closure segment before the __locale fileName = fileName.replace(/(__[^\.]+)?\.js$/, '.closure$1.js'); } else { fileName = fileName.replace(/\.js$/, '.mjs'); } } // Prepend the output directory. fileName = path.join(this.options.outDir, fileName); // Our file cache is based on mtime - so avoid writing files if they // did not change. if (!fs.existsSync(fileName) || fs.readFileSync(fileName, 'utf-8') !== content) { this.delegate.writeFile( fileName, content, writeByteOrderMark, onError, sourceFiles); } } /** * Performance optimization: don't try to stat files we weren't explicitly * given as inputs. * This also allows us to disable Bazel sandboxing, without accidentally * reading .ts inputs when .d.ts inputs are intended. * Note that in worker mode, the file cache will also guard against arbitrary * file reads. */ fileExists(filePath: string): boolean { // Under Bazel, users do not declare deps[] on their node_modules. // This means that we do not list all the needed .d.ts files in the files[] // section of tsconfig.json, and that is what populates the knownFiles set. // In addition, the node module resolver may need to read package.json files // and these are not permitted in the files[] section. // So we permit reading node_modules/* from action inputs, even though this // can include data[] dependencies and is broader than we would like. // This should only be enabled under Bazel, not Blaze. if (this.allowActionInputReads && filePath.indexOf('/node_modules/') >= 0) { const result = this.fileLoader.fileExists(filePath); if (DEBUG && !result && this.delegate.fileExists(filePath)) { debug("Path exists, but is not registered in the cache", filePath); Object.keys((this.fileLoader as any).cache.lastDigests).forEach(k => { if (k.endsWith(path.basename(filePath))) { debug(" Maybe you meant to load from", k); } }); } return result; } return this.knownFiles.has(filePath); } getDefaultLibLocation(): string { // Since we override getDefaultLibFileName below, we must also provide the // directory containing the file. // Otherwise TypeScript looks in C:\lib.xxx.d.ts for the default lib. return path.dirname( this.getDefaultLibFileName({target: ts.ScriptTarget.ES5})); } getDefaultLibFileName(options: ts.CompilerOptions): string { if (this.bazelOpts.nodeModulesPrefix) { return path.join( this.bazelOpts.nodeModulesPrefix, 'typescript/lib', ts.getDefaultLibFileName({target: ts.ScriptTarget.ES5})); } return this.delegate.getDefaultLibFileName(options); } realpath(s: string): string { // tsc-wrapped relies on string matching of file paths for things like the // file cache and for strict deps checking. // TypeScript will try to resolve symlinks during module resolution which // makes our checks fail: the path we resolved as an input isn't the same // one the module resolver will look for. // See https://github.com/Microsoft/TypeScript/pull/12020 // So we simply turn off symlink resolution. return s; } // Delegate everything else to the original compiler host. getCanonicalFileName(path: string) { return this.delegate.getCanonicalFileName(path); } getCurrentDirectory(): string { return this.delegate.getCurrentDirectory(); } useCaseSensitiveFileNames(): boolean { return this.delegate.useCaseSensitiveFileNames(); } getNewLine(): string { return this.delegate.getNewLine(); } getDirectories(path: string) { return this.delegate.getDirectories ? this.delegate.getDirectories(path) : []; } readFile(fileName: string): string|undefined { return this.delegate.readFile(fileName); } trace(s: string): void { console.error(s); } }
the_stack
import type { RawSourceMap, SFCBlock, SFCDescriptor } from '@vuedx/compiler-sfc' import { FindPosition, Position as SourceMapPosition, SourceMapConsumer, } from 'source-map' import { Position, Range, TextDocument, } from 'vscode-languageserver-textdocument' import { annotations, BlockTransformer, TransformerError, } from './BlockTransformer' import type { VueSFCDocument } from './VueSFCDocument' import * as Path from 'path' import { MappingKind, MappingMetadata } from '@vuedx/compiler-tsx' import { cache } from '@vuedx/shared' const METADATA_PREFIX = ';;;VueDX:' export class VueBlockDocument { public readonly source: TextDocument public readonly generated: TextDocument | null = null public readonly sourceMap: SourceMapConsumer | null = null public readonly rawSourceMap: RawSourceMap | null = null public readonly errors: TransformerError[] = [] public ast?: any public readonly sourceRange: Range public readonly ignoredZones: Array<{ start: number end: number range: Range }> = [] public readonly tsxCompletionsOffset: number | null = null public readonly tsCompletionsOffset: number | null = null private readonly templateGlobals: { start: number; end: number } | null = null public get block(): SFCBlock { return this.blockGetter() } public get descriptor(): SFCDescriptor { return this.descriptorGetter() } public get fileName(): string { return this.id } public readonly tsFileName: string | null = null constructor( private readonly id: string, public readonly parent: VueSFCDocument, private readonly blockGetter: () => SFCBlock, private readonly descriptorGetter: () => SFCDescriptor, private readonly transformer?: BlockTransformer, ) { const block = blockGetter() const descriptor = descriptorGetter() this.source = TextDocument.create( id, Path.posix.extname(id).substr(1), 0, block.content, ) this.sourceMap = null this.sourceRange = { start: { line: block.loc.start.line, character: block.loc.start.column, }, end: { line: block.loc.start.line, character: block.loc.start.column, }, } if (this.transformer != null) { const tsLang = this.transformer.output(block) this.tsFileName = id.replace(/lang\..*$/, `lang.${tsLang}`) try { const { ast, code, map, errors } = this.transformer.transform( block.content, id, { block, document: parent, descriptor, annotations, }, ) this.ast = ast this.errors = errors ?? [] if (map != null) { this.sourceMap = new SourceMapConsumer(map) this.rawSourceMap = map } this.generated = TextDocument.create( this.tsFileName, tsLang, // TODO: Convert to vscode lang 0, code, ) let lastIndex = 0 this.ignoredZones = [] while (lastIndex < code.length) { const start = code.indexOf( annotations.diagnosticsIgnore.start, lastIndex, ) if (start < 0) break let end = code.indexOf(annotations.diagnosticsIgnore.end, start) if (end < 0) { end = code.length } this.ignoredZones.push({ start, end, range: { start: this.generated.positionAt(start), end: this.generated.positionAt(end), }, }) lastIndex = end } this.tsxCompletionsOffset = null if (tsLang === 'tsx') { const tsxOffset = code.indexOf(annotations.tsxCompletions) if (tsxOffset >= 0) { const prefixLength = tsxOffset + annotations.tsxCompletions.length this.tsxCompletionsOffset = prefixLength + 1 // TODO: Maybe use next index of "<"" } } const tsOffset = code.indexOf(annotations.tsCompletions) if (tsOffset >= 0) { this.tsCompletionsOffset = tsOffset } else { this.tsCompletionsOffset = null } const globalsOffset = code.indexOf(annotations.templateGlobals.start) if (globalsOffset >= 0) { const start = globalsOffset + annotations.templateGlobals.end.length const end = code.indexOf( annotations.templateGlobals.end, globalsOffset, ) this.templateGlobals = { start, end } } } catch (error) { this.errors = [ { code: 1, message: error.message, severity: 'error', start: block.loc.start.offset, length: 1, source: 'SFC/VirtualDocument', }, ] } } } @cache() public generatedOffetAt(offset: number): number { return this.generatedOffetAndLengthAt(offset, 1).offset } @cache((args: [number, number]) => `${args[0]}:${args[1]}`) public generatedOffetAndLengthAt( offset: number, length: number, ): { offset: number; length: number } { if (this.sourceMap == null || this.generated == null) { return { offset: offset - this.block.loc.start.offset, length } } const args = { ...this.toSourceMapPosition( this.source.positionAt(offset - this.block.loc.start.offset), ), source: this.fileName, } const gen = this.generated const opPos: SourceMapPosition = this.sourceMap.generatedPositionFor(args) const opOffset = this.generated.offsetAt(this.toPosition(opPos)) const opOrginal = this.originalOffsetMappingAt(opOffset, 1) let position = opPos let result = opOffset let original = opOrginal if (opOrginal?.mapping != null) { const positions = this.sourceMap .allGeneratedPositionsFor({ ...this.toSourceMapPosition( this.source.positionAt(opOrginal.mapping.s.s), ), source: this.fileName, }) .filter((position) => { const og = this.originalOffsetMappingAt( gen.offsetAt(this.toPosition(position)), -1, ) return og?.mapping != null && og.mapping.k !== MappingKind.reverseOnly }) const newPosition = positions.pop() if (newPosition != null) { position = newPosition result = this.generated.offsetAt(this.toPosition(position)) original = this.originalOffsetMappingAt(result, -1) } } // If generated text is copied from original text then we can get exact position. if (original?.mapping?.k === MappingKind.copy) { const diff = offset - original.mapping.s.s - this.block.loc.start.offset return { offset: result + diff, length } } // Transformed text sohuld always match the whole text. return { offset: result, length: original?.mapping != null ? original.mapping.g.l : length, } } /** * Find original position in .vue file for position in genreated text * @param offset position in generated text * @returns position in .vue file */ @cache() public originalOffsetAt(offset: number): number { return ( this.originalOffsetAndLengthAt(offset, 1)?.offset ?? this.block.loc.start.offset ) } /** * Find original range in .vue file for position in genreated text * @param offset position in generated text * @param length range at offset * @returns range in .vue file */ @cache((args: [number, number]) => `${args[0]}:${args[1]}`) public originalOffsetAndLengthAt( offset: number, length: number, ): { offset: number; length: number } | null { const result = this.originalOffsetMappingAt(offset, 0) if (result == null) return null if (result.mapping != null && this.generated != null) { switch (result.mapping.k) { case MappingKind.transformed: case MappingKind.reverseOnly: return { offset: result.offset, length: result.mapping.s.e - result.mapping.s.e, } case MappingKind.copy: { const len = this.generated.getText().length const min = Math.max(0, offset - result.mapping.g.l) const max = Math.min(len, offset + result.mapping.g.l) const content = this.generated.getText().substring(min, max) const query = this.source .getText() .substring(result.mapping.s.s, result.mapping.s.e) const pos = content.indexOf(query) const diff = offset - (min + pos) return { offset: result.offset + diff, length } } } } return { offset: result.offset, length } } private originalOffsetMappingAt( offset: number, bias: -1 | 0 | 1 = 0, ): { offset: number; mapping?: MappingMetadata } | null { if (this.sourceMap == null || this.generated == null) { return { offset: this.block.loc.start.offset + offset } // no source map == no transformation } const position = this.toSourceMapPosition( this.generated.positionAt(offset), ) as FindPosition if (bias > 0) { position.bias = SourceMapConsumer.LEAST_UPPER_BOUND } else if (bias < 0) { position.bias = SourceMapConsumer.GREATEST_LOWER_BOUND } const original = this.sourceMap.originalPositionFor(position) if (original.line == null) return null return { offset: this.block.loc.start.offset + this.source.offsetAt(this.toPosition(original)), mapping: this.getMappingMetadata(original.name), } } @cache() public getMappingMetadata(context?: string): MappingMetadata | undefined { if (context?.startsWith(METADATA_PREFIX) === true) { return JSON.parse(context.substr(METADATA_PREFIX.length)) } return undefined } public isOffsetInIgonredZone(offset: number): boolean { return this.ignoredZones.some( (zone) => zone.start <= offset && offset <= zone.end, ) } public isOffsetInTemplateGlobals(offset: number): boolean { return this.templateGlobals == null ? false : this.templateGlobals.start <= offset && offset <= this.templateGlobals.end } public toSourceMapPosition(position: Position): SourceMapPosition { return { line: position.line + 1, column: position.character } } public toPosition(position: SourceMapPosition): Position { return { line: position.line - 1, character: position.column } } }
the_stack
import { PdfGridRow } from './pdf-grid-row'; import { PdfGrid } from './pdf-grid'; import { PdfGridCellStyle } from './styles/style'; import { PdfStringLayouter, PdfStringLayoutResult } from './../../graphics/fonts/string-layouter'; import { PdfDocument } from './../../document/pdf-document'; import { PdfFont } from './../../graphics/fonts/pdf-font'; import { PdfBrush } from './../../graphics/brushes/pdf-brush'; import { PdfPen } from './../../graphics/pdf-pen'; import { PdfStringFormat } from './../../graphics/fonts/pdf-string-format'; import { RectangleF, PointF, SizeF } from './../../drawing/pdf-drawing'; import { PdfGraphics } from './../../graphics/pdf-graphics'; import { PdfDashStyle, PdfLineCap } from './../../graphics/enum'; import { PdfBorderOverlapStyle } from './../tables/light-tables/enum'; import { PdfSolidBrush } from './../../graphics/brushes/pdf-solid-brush'; import { PdfColor } from './../../graphics/pdf-color'; import { PdfImage } from './../../graphics/images/pdf-image'; import { PdfBitmap } from './../../graphics/images/pdf-bitmap'; import { PdfTextWebLink } from './../../annotations/pdf-text-web-link'; import { PdfPage } from './../../pages/pdf-page'; import { PdfLayoutType } from './../../graphics/figures/enum'; import { PdfGridLayouter , PdfGridLayoutFormat } from './../../structured-elements/grid/layout/grid-layouter'; import { PdfLayoutParams, PdfLayoutResult, PdfLayoutFormat } from '../../../implementation/graphics/figures/base/element-layouter'; /** * `PdfGridCell` class represents the schema of a cell in a 'PdfGrid'. */ export class PdfGridCell { //Fields /** * The `row span`. * @private */ private gridRowSpan : number; /** * The `column span`. * @private */ private colSpan : number; /** * Specifies the current `row`. * @private */ private gridRow : PdfGridRow; /** * The actual `value` of the cell. * @private */ private objectValue : Object; /** * Current cell `style`. * @private */ private cellStyle : PdfGridCellStyle; /** * `Width` of the cell. * @default 0 * @private */ private cellWidth : number = 0; /** * `Height` of the cell. * @default 0 * @private */ private cellHeight : number = 0; /** * `tempval`to stores current width . * @default 0 * @private */ private tempval : number = 0; private fontSpilt : boolean = false; /** * The `remaining string`. * @private */ private remaining : string; /** * Specifies weather the `cell is drawn`. * @default true * @private */ private finsh : boolean = true; /** * 'parent ' of the grid cell. * @private */ private parent : PdfGridCell ; /** * `StringFormat` of the cell. * @private */ private format : PdfStringFormat; /** * The `remaining height` of row span. * @default 0 * @private */ public rowSpanRemainingHeight : number = 0; private internalIsCellMergeContinue : boolean; private internalIsRowMergeContinue : boolean; private internalIsCellMergeStart : boolean; private internalIsRowMergeStart : boolean; public hasRowSpan : boolean = false; public hasColSpan : boolean = false; /** * the 'isFinish' is set to page finish */ private isFinish : boolean = true; /** * The `present' to store the current cell. * @default false * @private */ public present : boolean = false; /** * The `Count` of the page. * @private */ public pageCount : number ; //constructor /** * Initializes a new instance of the `PdfGridCell` class. * @private */ public constructor() /** * Initializes a new instance of the `PdfGridCell` class. * @private */ public constructor(row : PdfGridRow) public constructor(row ?: PdfGridRow) { this.gridRowSpan = 1; this.colSpan = 1; if (typeof row !== 'undefined') { this.gridRow = row; } } //Properties public get isCellMergeContinue() : boolean { return this.internalIsCellMergeContinue; } public set isCellMergeContinue(value : boolean) { this.internalIsCellMergeContinue = value; } public get isRowMergeContinue() : boolean { return this.internalIsRowMergeContinue; } public set isRowMergeContinue(value : boolean) { this.internalIsRowMergeContinue = value; } public get isCellMergeStart() : boolean { return this.internalIsCellMergeStart; } public set isCellMergeStart(value : boolean) { this.internalIsCellMergeStart = value; } public get isRowMergeStart() : boolean { return this.internalIsRowMergeStart; } public set isRowMergeStart(value : boolean) { this.internalIsRowMergeStart = value; } /** * Gets or sets the `remaining string` after the row split between pages. * @private */ public get remainingString() : string { return this.remaining; } public set remainingString(value : string) { this.remaining = value; } /** * Gets or sets the `FinishedDrawingCell` . * @private */ public get FinishedDrawingCell() : boolean { return this.isFinish; } public set FinishedDrawingCell(value : boolean) { this.isFinish = value; } /** * Gets or sets the `string format`. * @private */ public get stringFormat() : PdfStringFormat { if (this.format == null) { this.format = new PdfStringFormat(); } return this.format; } public set stringFormat(value : PdfStringFormat) { this.format = value; } /** * Gets or sets the parent `row`. * @private */ public get row() : PdfGridRow { return this.gridRow; } public set row(value : PdfGridRow) { this.gridRow = value; } /** * Gets or sets the `value` of the cell. * @private */ public get value() : Object { return this.objectValue; } public set value(value : Object) { this.objectValue = value; if (this.objectValue instanceof PdfGrid) { this.row.grid.isSingleGrid = false; let grid : PdfGrid = this.objectValue as PdfGrid; grid.ParentCell = this; (this.objectValue as PdfGrid).isChildGrid = true; let rowCount : number = this.row.grid.rows.count; for (let i : number = 0; i < rowCount; i++) { let row : PdfGridRow = this.row.grid.rows.getRow(i); let colCount : number = row.cells.count; for (let j : number = 0; j < colCount; j++) { let cell : PdfGridCell = row.cells.getCell(j); cell.parent = this; } } } } /** * Gets or sets a value that indicates the total number of rows that cell `spans` within a PdfGrid. * @private */ public get rowSpan() : number { return this.gridRowSpan; } public set rowSpan(value : number) { if (value < 1) { throw new Error('ArgumentException : Invalid span specified, must be greater than or equal to 1'); } else { this.gridRowSpan = value; this.row.rowSpanExists = true; this.row.grid.hasRowSpanSpan = true; } } /** * Gets or sets the cell `style`. * @private */ public get style() : PdfGridCellStyle { if (this.cellStyle == null) { this.cellStyle = new PdfGridCellStyle(); } return this.cellStyle; } public set style(value : PdfGridCellStyle) { this.cellStyle = value; } /** * Gets the `height` of the PdfGrid cell.[Read-Only]. * @private */ public get height() : number { if (this.cellHeight === 0) { this.cellHeight = this.measureHeight(); } return this.cellHeight; } public set height(value : number) { this.cellHeight = value; } /** * Gets or sets a value that indicates the total number of columns that cell `spans` within a PdfGrid. * @private */ public get columnSpan() : number { return this.colSpan; } public set columnSpan(value : number) { if (value < 1) { throw Error('Invalid span specified, must be greater than or equal to 1'); } else { this.colSpan = value; this.row.columnSpanExists = true; } } /** * Gets the `width` of the PdfGrid cell.[Read-Only]. * @private */ public get width() : number { if (this.cellWidth === 0 || this.row.grid.isComplete) { this.cellWidth = this.measureWidth(); } return Math.round(this.cellWidth); } public set width(value : number) { this.cellWidth = value; } //Implementation /** * `Calculates the width`. * @private */ private measureWidth() : number { // .. Calculate the cell text width. // .....Add border widths, cell spacings and paddings to the width. let width : number = 0; let layouter : PdfStringLayouter = new PdfStringLayouter(); if (typeof this.objectValue === 'string') { /* tslint:disable */ let slr : PdfStringLayoutResult = layouter.layout((this.objectValue as string), this.getTextFont(), this.stringFormat, new SizeF(Number.MAX_VALUE, Number.MAX_VALUE), false, new SizeF(0, 0)); width += slr.actualSize.width; width += (this.style.borders.left.width + this.style.borders.right.width) * 2; } else if (this.objectValue instanceof PdfGrid) { width = (this.objectValue as PdfGrid).size.width; //width += this.objectValue.style.cellSpacing; } else if (this.objectValue instanceof PdfImage || this.objectValue instanceof PdfBitmap) { width += (this.objectValue as PdfImage).width; } else if (this.objectValue instanceof PdfTextWebLink) { let webLink : PdfTextWebLink = this.objectValue as PdfTextWebLink; let result : PdfStringLayoutResult = layouter.layout(webLink.text, webLink.font, webLink.stringFormat, new SizeF(0, 0), false, new SizeF(0, 0)); /* tslint:enable */ width += result.actualSize.width; width += (this.style.borders.left.width + this.style.borders.right.width) * 2; } if (!(this.objectValue instanceof PdfGrid)) { if (this.style.cellPadding != null) { width += (this.style.cellPadding.left + this.style.cellPadding.right); } else { width += (this.row.grid.style.cellPadding.left + this.row.grid.style.cellPadding.right); } } else { if (this.style.cellPadding != null || typeof this.style.cellPadding !== 'undefined') { if (typeof this.style.cellPadding.left !== 'undefined' && this.style.cellPadding.hasLeftPad) { width += this.style.cellPadding.left; } if (typeof this.style.cellPadding.right !== 'undefined' && this.style.cellPadding.hasRightPad) { width += this.style.cellPadding.right; } } else { if (typeof this.row.grid.style.cellPadding.left !== 'undefined' && this.row.grid.style.cellPadding.hasLeftPad) { width += this.row.grid.style.cellPadding.left; } if (typeof this.row.grid.style.cellPadding.right !== 'undefined' && this.row.grid.style.cellPadding.hasRightPad) { width += this.row.grid.style.cellPadding.right; } } } width += this.row.grid.style.cellSpacing; return width; } /** * Draw the `cell background`. * @private */ public drawCellBackground(graphics : PdfGraphics, bounds : RectangleF) : void { let backgroundBrush : PdfBrush = this.getBackgroundBrush(); //graphics.isTemplateGraphics = true; if (backgroundBrush != null) { graphics.save(); graphics.drawRectangle(backgroundBrush, bounds.x, bounds.y, bounds.width, bounds.height); graphics.restore(); } if (this.style.backgroundImage != null) { let image : PdfImage = this.getBackgroundImage(); graphics.drawImage(this.style.backgroundImage, bounds.x, bounds.y, bounds.width, bounds.height); } } /** * `Adjusts the text layout area`. * @private */ /* tslint:disable */ private adjustContentLayoutArea(bounds : RectangleF) : RectangleF { //Add Padding value to its Cell Bounds let returnBounds : RectangleF = new RectangleF(bounds.x, bounds.y, bounds.width, bounds.height); if (!(this.objectValue instanceof PdfGrid)) { if (typeof this.style.cellPadding === 'undefined' || this.style.cellPadding == null) { returnBounds.x += this.gridRow.grid.style.cellPadding.left + this.cellStyle.borders.left.width; returnBounds.y += this.gridRow.grid.style.cellPadding.top + this.cellStyle.borders.top.width; returnBounds.width -= (this.gridRow.grid.style.cellPadding.right + this.gridRow.grid.style.cellPadding.left); returnBounds.height -= (this.gridRow.grid.style.cellPadding.bottom + this.gridRow.grid.style.cellPadding.top); returnBounds.height -= (this.cellStyle.borders.top.width + this.cellStyle.borders.bottom.width); } else { returnBounds.x += this.style.cellPadding.left + this.cellStyle.borders.left.width; returnBounds.y += this.style.cellPadding.top + this.cellStyle.borders.top.width; returnBounds.width -= (this.style.cellPadding.right + this.style.cellPadding.left); returnBounds.width -= (this.cellStyle.borders.left.width + this.cellStyle.borders.right.width); returnBounds.height -= (this.style.cellPadding.bottom + this.style.cellPadding.top); returnBounds.height -= (this.cellStyle.borders.top.width + this.cellStyle.borders.bottom.width); if (this.rowSpan === 1) { returnBounds.width -= (this.style.borders.left.width); } } } else{ if (this.style.cellPadding == null || typeof this.style.cellPadding === 'undefined') { if(typeof this.gridRow.grid.style.cellPadding.left !== 'undefined' && this.gridRow.grid.style.cellPadding.hasLeftPad){ returnBounds.x += this.gridRow.grid.style.cellPadding.left + this.cellStyle.borders.left.width; returnBounds.width -= this.gridRow.grid.style.cellPadding.left; } if(typeof this.gridRow.grid.style.cellPadding.top !== 'undefined' && this.gridRow.grid.style.cellPadding.hasTopPad){ returnBounds.y += this.gridRow.grid.style.cellPadding.top + this.cellStyle.borders.top.width; returnBounds.height -= this.gridRow.grid.style.cellPadding.top; } if(typeof this.gridRow.grid.style.cellPadding.right !== 'undefined' && this.gridRow.grid.style.cellPadding.hasRightPad){ returnBounds.width -= this.gridRow.grid.style.cellPadding.right; } if(typeof this.gridRow.grid.style.cellPadding.bottom !== 'undefined' && this.gridRow.grid.style.cellPadding.hasBottomPad){ returnBounds.height -= this.gridRow.grid.style.cellPadding.bottom; } } else { if(typeof this.style.cellPadding.left !== 'undefined' && this.style.cellPadding.hasLeftPad) { returnBounds.x += this.style.cellPadding.left + this.cellStyle.borders.left.width; returnBounds.width -= this.style.cellPadding.left; } if(typeof this.style.cellPadding.top !== 'undefined' && this.style.cellPadding.hasTopPad) { returnBounds.y += this.style.cellPadding.top + this.cellStyle.borders.top.width; returnBounds.height -= this.style.cellPadding.top; } if(typeof this.style.cellPadding.right !== 'undefined' && this.style.cellPadding.hasRightPad){ returnBounds.width -= this.style.cellPadding.right; } if(typeof this.style.cellPadding.bottom !== 'undefined' && this.style.cellPadding.hasBottomPad){ returnBounds.height -= this.style.cellPadding.bottom; } } returnBounds.width -= (this.cellStyle.borders.left.width + this.cellStyle.borders.right.width); returnBounds.height -= (this.cellStyle.borders.top.width + this.cellStyle.borders.bottom.width); } return returnBounds; } /** * `Draws` the specified graphics. * @private */ public draw(graphics : PdfGraphics, bounds : RectangleF, cancelSubsequentSpans : boolean) : PdfStringLayoutResult { let isrowbreak : boolean = false; /*if (!this.row.grid.isSingleGrid) { //Check whether the Grid Span to Nextpage if ((this.remainingString != null) || (PdfGridLayouter.repeatRowIndex != -1)) { this.DrawParentCells(graphics, bounds, true); } else if (this.row.grid.rows.count > 1) { for (let i : number = 0; i < this.row.grid.rows.count; i++) { if (this.row == this.row.grid.rows.getRow(i)) { if (this.row.grid.rows.getRow(i).rowBreakHeight > 0) isrowbreak = true; if ((i > 0) && (isrowbreak)) this.DrawParentCells(graphics, bounds, false); } } } } */ let result : PdfStringLayoutResult = null; /*if (cancelSubsequentSpans) { //..Cancel all subsequent cell spans, if no space exists. let currentCellIndex : number = this.row.cells.indexOf(this); for (let i : number = currentCellIndex + 1; i <= currentCellIndex + this.colSpan; i++) { this.row.cells.getCell(i).isCellMergeContinue = false; this.row.cells.getCell(i).isRowMergeContinue = false; } this.colSpan = 1; }*/ //..Skip cells which were already covered by spanmap. if (this.internalIsCellMergeContinue || this.internalIsRowMergeContinue) { if (this.internalIsCellMergeContinue && this.row.grid.style.allowHorizontalOverflow) { if ((this.row.rowOverflowIndex > 0 && (this.row.cells.indexOf(this) != this.row.rowOverflowIndex + 1)) || (this.row.rowOverflowIndex == 0 && this.internalIsCellMergeContinue)) { return result; } } else { return result; } } //Adjust bounds with Row and Column Spacing bounds = this.adjustOuterLayoutArea(bounds, graphics); this.drawCellBackground(graphics, bounds); let textPen : PdfPen = this.getTextPen(); let textBrush : PdfBrush = this.getTextBrush(); if (typeof textPen === 'undefined' && typeof textBrush === 'undefined') { textBrush = new PdfSolidBrush(new PdfColor(0, 0, 0)); } let font : PdfFont = this.getTextFont(); let strFormat : PdfStringFormat = this.getStringFormat(); let innerLayoutArea : RectangleF = bounds; if (innerLayoutArea.height >= graphics.clientSize.height) { // If to break row to next page. if (this.row.grid.allowRowBreakAcrossPages) { innerLayoutArea.height -= innerLayoutArea.y; //bounds.height -= bounds.y; // if(this.row.grid.isChildGrid) // { // innerLayoutArea.height -= this.row.grid.ParentCell.row.grid.style.cellPadding.bottom; // } } // if user choose to cut the row whose height is more than page height. // else // { // innerLayoutArea.height = graphics.clientSize.height; // bounds.height = graphics.clientSize.height; // } } innerLayoutArea = this.adjustContentLayoutArea(innerLayoutArea); if (typeof this.objectValue === 'string' || typeof this.remaining === 'string') { let temp : string; let layoutRectangle : RectangleF; if (innerLayoutArea.height < font.height) layoutRectangle = new RectangleF(innerLayoutArea.x, innerLayoutArea.y, innerLayoutArea.width, font.height); else layoutRectangle = innerLayoutArea; if (innerLayoutArea.height < font.height && this.row.grid.isChildGrid && this.row.grid.ParentCell != null) { let height : number = layoutRectangle.height - this.row.grid.ParentCell.row.grid.style.cellPadding.bottom - this.row.grid.style.cellPadding.bottom; if(this.row.grid.splitChildRowIndex != -1){ this.fontSpilt = true; this.row.rowFontSplit = true; } if (height > 0 && height < font.height) layoutRectangle.height = height; // else if (height + this.row.grid.style.cellPadding.bottom > 0 && height + this.row.grid.style.cellPadding.bottom < font.height) // layoutRectangle.height = height + this.row.grid.style.cellPadding.bottom; // else if (bounds.height < font.height) // layoutRectangle.height = bounds.height; // else if (bounds.height - this.row.grid.ParentCell.row.grid.style.cellPadding.bottom < font.height) // layoutRectangle.height = bounds.height - this.row.grid.ParentCell.row.grid.style.cellPadding.bottom; } if(this.gridRow.grid.style.cellSpacing != 0) { layoutRectangle.width -= this.gridRow.grid.style.cellSpacing; bounds.width -= this.gridRow.grid.style.cellSpacing; } if (this.isFinish) { // if (this.row.grid.splitChildRowIndex != -1 && !this.row.grid.isChildGrid && typeof this.remaining === 'undefined'){ // this.remaining = ''; // graphics.drawString(this.remaining, font, textPen, textBrush, layoutRectangle.x, layoutRectangle.y, layoutRectangle.width, layoutRectangle.height, strFormat); // } else { temp = this.remaining === '' ? this.remaining : (this.objectValue as string); graphics.drawString(temp, font, textPen, textBrush, layoutRectangle.x, layoutRectangle.y, layoutRectangle.width, layoutRectangle.height, strFormat); if (this.row.grid.splitChildRowIndex != -1 && !this.row.grid.isChildGrid && typeof this.remaining === 'undefined'){ this.remaining = ''; //graphics.drawString(this.remaining, font, textPen, textBrush, layoutRectangle.x, layoutRectangle.y, layoutRectangle.width, layoutRectangle.height, strFormat); } } else { if(typeof this.remaining == 'undefined' ||this.remaining === null){ this.remaining = ''; } if (this.row.repeatFlag) { graphics.drawString((this.remaining as string), font, textPen, textBrush, layoutRectangle.x, layoutRectangle.y, layoutRectangle.width, layoutRectangle.height, strFormat); } // else { // if(this.row.grid.ParentCell.row.repeatFlag) { // graphics.drawString((this.remaining as string), font, textPen, textBrush, layoutRectangle.x, layoutRectangle.y, layoutRectangle.width, layoutRectangle.height, strFormat); // } else { // layoutRectangle.height = this.row.height; // graphics.drawString((this.objectValue as string), font, textPen, textBrush, layoutRectangle.x, layoutRectangle.y, layoutRectangle.width, layoutRectangle.height, strFormat); // bounds.height = this.row.height; // } // } this.isFinish = true; //graphics.drawString((this.remaining as string), font, textPen, textBrush, layoutRectangle.x, layoutRectangle.y, layoutRectangle.width, layoutRectangle.height, strFormat); } result = graphics.stringLayoutResult; // if(this.row.grid.isChildGrid && this.row.rowBreakHeight > 0 && result !=null) { // bounds.height -= this.row.grid.ParentCell.row.grid.style.cellPadding.bottom; // } } else if (this.objectValue instanceof PdfGrid ) { let childGrid : PdfGrid = this.objectValue as PdfGrid; childGrid.isChildGrid = true; childGrid.ParentCell = this; let layoutRect : RectangleF; layoutRect = innerLayoutArea; if(this.gridRow.grid.style.cellSpacing != 0){ bounds.width -= this.gridRow.grid.style.cellSpacing; } // layoutRect = bounds; // if (this.style.cellPadding != null){ // layoutRect = bounds; // } else if((this.row.grid.style.cellPadding != null) && (childGrid.style.cellPadding.bottom === 0.5) && (childGrid.style.cellPadding.top === 0.5) // && (childGrid.style.cellPadding.left === 5.76) && (childGrid.style.cellPadding.right === 5.76) // && (this.gridRow.grid.style.cellSpacing === 0) && (childGrid.style.cellSpacing === 0)) { // layoutRect = innerLayoutArea; // } // if(this.objectValue.style.cellPadding != null && typeof this.objectValue.style.cellPadding !== 'undefined'){ // layoutRect = bounds; // } let layouter : PdfGridLayouter= new PdfGridLayouter(childGrid); let format : PdfLayoutFormat = new PdfGridLayoutFormat(); if (this.row.grid.LayoutFormat != null) format = this.row.grid.LayoutFormat; else format.layout = PdfLayoutType.Paginate; let param : PdfLayoutParams = new PdfLayoutParams(); if (graphics.layer != null) { // Define layout parameters. param.page = graphics.page as PdfPage; param.bounds = layoutRect; param.format = format; //Set the span childGrid.setSpan(); childGrid.checkSpan(); // Draw the child grid. let childGridResult : PdfLayoutResult = layouter.Layouter(param); //let childGridResult : PdfLayoutResult = layouter.innerLayout(param); this.value = childGrid; if(this.row.grid.splitChildRowIndex !== -1){ this.height = this.row.rowBreakHeightValue; } if (param.page != childGridResult.page) //&& (isWidthGreaterthanParent != true)) { childGridResult.bounds.height = this.row.rowBreakHeightValue; if(this.row.rowBreakHeight == 0) this.row.NestedGridLayoutResult = childGridResult; else this.row.rowBreakHeight = this.row.rowBreakHeightValue; //bounds.height = this.row.rowBreakHeight; //After drawing paginated nested grid, the bounds of the parent grid in start page should be corrected for borders. //bounds.height = graphics.clientSize.height - bounds.y; } } } else if (this.objectValue instanceof PdfImage || this.objectValue instanceof PdfBitmap) { let imageBounds : RectangleF; if ((this.objectValue as PdfImage).width <= innerLayoutArea.width) { imageBounds = new RectangleF(innerLayoutArea.x, innerLayoutArea.y, (this.objectValue as PdfImage).width, innerLayoutArea.height); } else { imageBounds = innerLayoutArea; } graphics.drawImage(this.objectValue as PdfImage, imageBounds.x, imageBounds.y, imageBounds.width, imageBounds.height); } else if (this.objectValue instanceof PdfTextWebLink) { (this.objectValue as PdfTextWebLink).draw(graphics.currentPage, innerLayoutArea); } else if (typeof this.objectValue === 'undefined') { this.objectValue = ""; graphics.drawString(this.objectValue as string, font, textPen, textBrush, innerLayoutArea.x, innerLayoutArea.y,innerLayoutArea.width, innerLayoutArea.height,strFormat); if (this.style.cellPadding != null && this.style.cellPadding.bottom == 0 && this.style.cellPadding.left == 0 && this.style.cellPadding.right == 0 && this.style.cellPadding.top == 0) { bounds.width -= (this.style.borders.left.width + this.style.borders.right.width); } if (this.gridRow.grid.style.cellSpacing != 0) { bounds.width -= this.gridRow.grid.style.cellSpacing; } } if (this.style.borders != null) { if(!this.fontSpilt) this.drawCellBorders(graphics, bounds); else { if(this.row.grid.ParentCell.row.grid.splitChildRowIndex != -1){ this.row.rowFontSplit = false; this.drawCellBorders(graphics, bounds); } } } return result; } /* tslint:enable */ /** * Draws the `cell border` constructed by drawing lines. * @private */ public drawCellBorders(graphics : PdfGraphics, bounds : RectangleF) : void { if (this.row.grid.style.borderOverlapStyle === PdfBorderOverlapStyle.Inside) { bounds.x += this.style.borders.left.width; bounds.y += this.style.borders.top.width; bounds.width -= this.style.borders.right.width; bounds.height -= this.style.borders.bottom.width; } let p1 : PointF = new PointF(bounds.x, bounds.y + bounds.height); let p2 : PointF = new PointF(bounds.x, bounds.y); let pen : PdfPen = this.cellStyle.borders.left; if (this.cellStyle.borders.left.dashStyle === PdfDashStyle.Solid) { pen.lineCap = PdfLineCap.Square; } // SetTransparency(ref graphics, pen); if (pen.width !== 0) { graphics.drawLine(pen, p1, p2); } p1 = new PointF(bounds.x + bounds.width, bounds.y); p2 = new PointF(bounds.x + bounds.width, bounds.y + bounds.height); pen = this.cellStyle.borders.right; if ((bounds.x + bounds.width) > (graphics.clientSize.width - (pen.width / 2))) { p1 = new PointF(graphics.clientSize.width - (pen.width / 2), bounds.y); p2 = new PointF(graphics.clientSize.width - (pen.width / 2), bounds.y + bounds.height); } if (this.cellStyle.borders.right.dashStyle === PdfDashStyle.Solid) { pen.lineCap = PdfLineCap.Square; } if (pen.width !== 0) { graphics.drawLine(pen, p1, p2); } p1 = new PointF(bounds.x, bounds.y); p2 = new PointF(bounds.x + bounds.width, bounds.y); pen = this.cellStyle.borders.top; if (this.cellStyle.borders.top.dashStyle === PdfDashStyle.Solid) { pen.lineCap = PdfLineCap.Square; } if (pen.width !== 0) { graphics.drawLine(pen, p1, p2); } p1 = new PointF(bounds.x + bounds.width, bounds.y + bounds.height); p2 = new PointF(bounds.x, bounds.y + bounds.height); pen = this.cellStyle.borders.bottom; if ((bounds.y + bounds.height) > (graphics.clientSize.height - (pen.width / 2))) { p1 = new PointF((bounds.x + bounds.width), (graphics.clientSize.height - (pen.width / 2))); p2 = new PointF(bounds.x, (graphics.clientSize.height - (pen.width / 2))); } if (this.cellStyle.borders.bottom.dashStyle === PdfDashStyle.Solid) { pen.lineCap = PdfLineCap.Square; } if (pen.width !== 0) { graphics.drawLine(pen, p1, p2); } } // private setTransparency(graphics : PdfGraphics, pen : PdfPen) : void { // let alpha : number = (pen.color.a / 255) as number; // graphics.save(); // graphics.setTransparency(alpha); // } /** * `Adjusts the outer layout area`. * @private */ /* tslint:disable */ private adjustOuterLayoutArea(bounds : RectangleF, g : PdfGraphics) : RectangleF { let isHeader : boolean = false; let cellSpacing : number = this.row.grid.style.cellSpacing; if (cellSpacing > 0) { bounds = new RectangleF(bounds.x + cellSpacing, bounds.y + cellSpacing, bounds.width - cellSpacing, bounds.height - cellSpacing); } let currentColIndex : number = this.row.cells.indexOf(this); if (this.columnSpan > 1|| (this.row.rowOverflowIndex > 0 && (currentColIndex == this.row.rowOverflowIndex + 1) && this.isCellMergeContinue)) { let span : number = this.columnSpan; if (span == 1 && this.isCellMergeContinue) { for (let j : number = currentColIndex + 1; j < this.row.grid.columns.count; j++) { if (this.row.cells.getCell(j).isCellMergeContinue) span++; else break; } } let totalWidth : number = 0; for (let i : number = currentColIndex; i < currentColIndex + span; i++) { if (this.row.grid.style.allowHorizontalOverflow) { let width : number; let compWidth : number = this.row.grid.size.width < g.clientSize.width ? this.row.grid.size.width : g.clientSize.width; if(this.row.grid.size.width > g.clientSize.width) { width = bounds.x + totalWidth + this.row.grid.columns.getColumn(i).width; } else { width = totalWidth + this.row.grid.columns.getColumn(i).width; } if (width > compWidth) { break; } } totalWidth += this.row.grid.columns.getColumn(i).width; } totalWidth -= this.row.grid.style.cellSpacing; bounds.width = totalWidth; } if (this.rowSpan > 1 || this.row.rowSpanExists) { let span : number = this.rowSpan; let currentRowIndex : number = this.row.grid.rows.rowCollection.indexOf(this.row); if (currentRowIndex == -1) { currentRowIndex = this.row.grid.headers.indexOf(this.row); if (currentRowIndex != -1) { isHeader = true; } } // if (span == 1 && this.isCellMergeContinue) { // for (let j : number = currentRowIndex + 1; j < this.row.grid.rows.count; j++) // { // let flag : boolean = (isHeader ? this.row.grid.headers.getHeader(j).cells.getCell(currentColIndex).isCellMergeContinue : this.row.grid.rows.getRow(j).cells.getCell(currentColIndex).isCellMergeContinue); // if (flag) // span++; // else // break; // } // } let totalHeight : number = 0; let max : number = 0; for (let i : number = currentRowIndex; i < currentRowIndex + span; i++) { totalHeight += (isHeader ? this.row.grid.headers.getHeader(i).height : this.row.grid.rows.getRow(i).height); let row : PdfGridRow = this.row.grid.rows.getRow(i); let rowIndex : number = this.row.grid.rows.rowCollection.indexOf(row); /*if (this.rowSpan > 1) { for (let k : number = 0; k < this.row.cells.count; k++) { let cell : PdfGridCell = this.row.cells.getCell(k); if(cell.rowSpan>1) { let tempHeight : number =0; for (let j :number = i; j < i +cell.rowSpan; j++) { if (!this.row.grid.rows.getRow(j).isRowSpanRowHeightSet) this.row.grid.rows.getRow(j).isRowHeightSet = false; tempHeight += this.row.grid.rows.getRow(j).height; if (!this.row.grid.rows.getRow(j).isRowSpanRowHeightSet) this.row.grid.rows.getRow(j).isRowHeightSet = true; } //To check the Row spanned cell height is greater than the total spanned row height. if(cell.height>tempHeight) { if (max < (cell.height - tempHeight)) { max = cell.height - tempHeight; if (this.rowSpanRemainingHeight != 0 && max > this.rowSpanRemainingHeight) { max += this.rowSpanRemainingHeight; } let index :number = row.cells.indexOf(cell); //set the m_rowspanRemainingHeight to last rowspanned row. this.row.grid.rows.getRow((rowIndex +cell.rowSpan) - 1).cells.getCell(index).rowSpanRemainingHeight = max; this.rowSpanRemainingHeight = this.row.grid.rows.getRow((rowIndex + cell.rowSpan) - 1).cells.getCell(index).rowSpanRemainingHeight; } } } } } if (!this.row.grid.rows.getRow(i).isRowSpanRowHeightSet) this.row.grid.rows.getRow(i).isRowHeightSet = true;*/ } let cellIndex = this.row.cells.indexOf(this); totalHeight -= this.row.grid.style.cellSpacing; // if (this.row.cells.getCell(cellIndex).height > totalHeight && (!this.row.grid.rows.getRow((currentRowIndex + span) - 1).isRowHeightSet)) { // this.row.grid.rows.getRow((currentRowIndex + span) - 1).cells.getCell(cellIndex).rowSpanRemainingHeight = this.row.cells.getCell(cellIndex).height - totalHeight; // totalHeight = this.row.cells.getCell(cellIndex).height; // bounds.height = totalHeight; // } else { bounds.height = totalHeight; // } if (!this.row.rowMergeComplete) { bounds.height = totalHeight; } } return bounds; } /* tslint:enable */ /** * Gets the `text font`. * @private */ private getTextFont() : PdfFont { if (typeof this.style.font !== 'undefined' && this.style.font != null) { return this.style.font; } else if (typeof this.row.style.font !== 'undefined' && this.row.style.font != null) { return this.row.style.font; } else if (typeof this.row.grid.style.font !== 'undefined' && this.row.grid.style.font != null) { return this.row.grid.style.font; } else { return PdfDocument.defaultFont; } } /** * Gets the `text brush`. * @private */ private getTextBrush() : PdfBrush { if (typeof this.style.textBrush !== 'undefined' && this.style.textBrush != null) { return this.style.textBrush; } else if (typeof this.row.style.textBrush !== 'undefined' && this.row.style.textBrush != null) { return this.row.style.textBrush; } else { return this.row.grid.style.textBrush; } } /** * Gets the `text pen`. * @private */ private getTextPen() : PdfPen { if (typeof this.style.textPen !== 'undefined' && this.style.textPen != null) { return this.style.textPen; } else if (typeof this.row.style.textPen !== 'undefined' && this.row.style.textPen != null) { return this.row.style.textPen; } else { return this.row.grid.style.textPen; } } /** * Gets the `background brush`. * @private */ private getBackgroundBrush() : PdfBrush { if (typeof this.style.backgroundBrush !== 'undefined' && this.style.backgroundBrush != null) { return this.style.backgroundBrush; } else if (typeof this.row.style.backgroundBrush !== 'undefined' && this.row.style.backgroundBrush != null) { return this.row.style.backgroundBrush; } else { return this.row.grid.style.backgroundBrush; } } /** * Gets the `background image`. * @private */ private getBackgroundImage() : PdfImage { if (typeof this.style.backgroundImage !== 'undefined' && this.style.backgroundImage != null) { return this.style.backgroundImage; } else if (typeof this.row.style.backgroundImage !== 'undefined' && this.row.style.backgroundImage != null) { return this.row.style.backgroundImage; } else { return this.row.grid.style.backgroundImage; } } /** * Gets the current `StringFormat`. * @private */ private getStringFormat() : PdfStringFormat { if (typeof this.style.stringFormat !== 'undefined' && this.style.stringFormat != null) { return this.style.stringFormat; } else { return this.stringFormat; } } /** * Calculates the `height`. * @private */ public measureHeight() : number { // .. Calculate the cell text height. // .....Add border widths, cell spacings and paddings to the height. let width : number = this.calculateWidth(); // //check whether the Current PdfGridCell has padding if (this.style.cellPadding == null || typeof this.style.cellPadding === 'undefined') { width -= (this.gridRow.grid.style.cellPadding.right + this.gridRow.grid.style.cellPadding.left); //width -= (this.style.borders.left.width + this.style.borders.right.width); } else { width -= (this.style.cellPadding.right + this.style.cellPadding.left); width -= (this.style.borders.left.width + this.style.borders.right.width); } let height : number = 0; let layouter : PdfStringLayouter = new PdfStringLayouter(); if (typeof this.objectValue === 'string' || typeof this.remaining === 'string') { let currentValue : string = this.objectValue as string; /* tslint:disable */ if (!this.isFinish) currentValue = !(this.remaining === null || this.remaining === '' || typeof this.remaining === 'undefined') ? this.remaining : (this.objectValue as string); let slr : PdfStringLayoutResult = null; let cellIndex : number = this.row.cells.indexOf(this); if (this.gridRow.grid.style.cellSpacing != 0){ width -= this.gridRow.grid.style.cellSpacing * 2; } if(!this.row.cells.getCell(cellIndex).hasColSpan && !this.row.cells.getCell(cellIndex).hasRowSpan) { if(this.gridRow.grid.isChildGrid) { if (width < 0) { this.tempval = width; if (this.style.cellPadding == null || typeof this.style.cellPadding === 'undefined') { this.tempval += (this.gridRow.grid.style.cellPadding.right + this.gridRow.grid.style.cellPadding.left); } else { this.tempval += (this.style.cellPadding.right + this.style.cellPadding.left); this.tempval += (this.style.borders.left.width + this.style.borders.right.width); } } else { this.tempval = width; } slr = layouter.layout(currentValue, this.getTextFont(), this.stringFormat, new SizeF(this.tempval, 0), false, new SizeF(0, 0)); height += slr.actualSize.height; } else { slr = layouter.layout(currentValue, this.getTextFont(), this.stringFormat, new SizeF(width, 0), false, new SizeF(0, 0)); height += slr.actualSize.height; } } /* tslint:enable */ height += (this.style.borders.top.width + this.style.borders.bottom.width) * 2; } else if (this.objectValue instanceof PdfGrid) { let cellIndex : number = this.row.cells.indexOf(this); let internalWidth : number = 0; if ((this.style.cellPadding != null || typeof this.style.cellPadding !== 'undefined' )) { internalWidth = this.calculateWidth(); if (typeof this.style.cellPadding.left !== 'undefined' && this.style.cellPadding.hasLeftPad) { internalWidth -= this.style.cellPadding.left; } if (typeof this.style.cellPadding.right !== 'undefined' && this.style.cellPadding.hasRightPad) { internalWidth -= this.style.cellPadding.right; } } else if ((this.row.grid.style.cellPadding != null || typeof this.row.grid.style.cellPadding !== 'undefined')) { internalWidth = this.calculateWidth(); if (typeof this.row.grid.style.cellPadding.left !== 'undefined' && this.row.grid.style.cellPadding.hasLeftPad) { internalWidth -= this.row.grid.style.cellPadding.left; } if (typeof this.row.grid.style.cellPadding.right !== 'undefined' && this.row.grid.style.cellPadding.hasRightPad) { internalWidth -= this.row.grid.style.cellPadding.right; } } else { internalWidth = this.calculateWidth(); } (this.objectValue as PdfGrid).tempWidth = internalWidth; if (!this.row.cells.getCell(cellIndex).hasColSpan && !this.row.cells.getCell(cellIndex).hasRowSpan) { height = (this.objectValue as PdfGrid).size.height; } else { height += (this.style.borders.top.width + this.style.borders.bottom.width) * 2; } if (this.gridRow.grid.style.cellSpacing !== 0 ) { width -= this.gridRow.grid.style.cellSpacing * 2; //height += (this.row.grid.style.cellPadding.top + this.row.grid.style.cellPadding.bottom); } if (this.style.cellPadding != null || typeof this.style.cellPadding !== 'undefined') { if (typeof this.row.grid.style.cellPadding.top !== 'undefined' && this.row.grid.style.cellPadding.hasTopPad) { height += this.row.grid.style.cellPadding.top; } if (this.row.grid.style.cellPadding.hasBottomPad && typeof this.row.grid.style.cellPadding.bottom !== 'undefined') { height += this.row.grid.style.cellPadding.bottom; } } height += this.objectValue.style.cellSpacing; } else if (this.objectValue instanceof PdfImage || this.objectValue instanceof PdfBitmap) { height += (this.objectValue as PdfImage).height; } else if (this.objectValue instanceof PdfTextWebLink) { let webLink : PdfTextWebLink = this.objectValue as PdfTextWebLink; /* tslint:disable */ let slr : PdfStringLayoutResult = layouter.layout(webLink.text, webLink.font, webLink.stringFormat, new SizeF(width, 0), false, new SizeF(0, 0)); /* tslint:enable */ height += slr.actualSize.height; height += (this.style.borders.top.width + this.style.borders.bottom.width) * 2; } else if (typeof this.objectValue === 'undefined') { if (this.style.cellPadding == null || typeof this.style.cellPadding === 'undefined') { width -= (this.gridRow.grid.style.cellPadding.right + this.gridRow.grid.style.cellPadding.left); } else { width -= (this.style.cellPadding.right + this.style.cellPadding.left); width -= (this.style.borders.left.width + this.style.borders.right.width); } height += (this.style.borders.top.width + this.style.borders.bottom.width) * 2; } //Add padding top and bottom value to height if (!(this.objectValue instanceof PdfGrid)) { if (this.style.cellPadding == null || typeof this.style.cellPadding === 'undefined') { height += (this.row.grid.style.cellPadding.top + this.row.grid.style.cellPadding.bottom); } else { height += (this.style.cellPadding.top + this.style.cellPadding.bottom); } } else { if (this.style.cellPadding == null || typeof this.style.cellPadding === 'undefined') { if (typeof this.row.grid.style.cellPadding.top !== 'undefined' && this.row.grid.style.cellPadding.hasTopPad) { height += this.row.grid.style.cellPadding.top; } if (typeof this.row.grid.style.cellPadding.bottom !== 'undefined' && this.row.grid.style.cellPadding.hasBottomPad) { height += this.row.grid.style.cellPadding.bottom; } } else { if (typeof this.style.cellPadding.top !== 'undefined' && this.style.cellPadding.hasTopPad) { height += this.style.cellPadding.top; } if (typeof this.style.cellPadding.bottom !== 'undefined' && this.style.cellPadding.hasBottomPad) { height += this.style.cellPadding.bottom; } } } height += this.row.grid.style.cellSpacing; return height; } /** * return the calculated `width` of the cell. * @private */ private calculateWidth() : number { let cellIndex : number = this.row.cells.indexOf(this); let rowindex : number = this.row.grid.rows.rowCollection.indexOf(this.row); let columnSpan : number = this.columnSpan; let width : number = 0; if (columnSpan === 1) { for (let i : number = 0; i < columnSpan; i++) { width += this.row.grid.columns.getColumn(cellIndex + i).width; } } else if (columnSpan > 1) { for (let i : number = 0; i < columnSpan; i++) { width += this.row.grid.columns.getColumn(cellIndex + i).width; if ( (i + 1) < columnSpan) { this.row.cells.getCell(cellIndex + i + 1).hasColSpan = true; } } } if (this.parent != null && this.parent.row.width > 0) { if ((this.row.grid.isChildGrid) && this.parent != null && (this.row.width > this.parent.row.width)) { width = 0; for (let j : number = 0; j < this.parent.columnSpan; j++) { width += this.parent.row.grid.columns.getColumn(j).width; } width = width / this.row.cells.count; } } return width; } } /** * `PdfGridCellCollection` class provides access to an ordered, * strongly typed collection of 'PdfGridCell' objects. * @private */ export class PdfGridCellCollection { //Fields /** * @hidden * @private */ private gridRow : PdfGridRow; /** * @hidden * @private */ private cells : PdfGridCell[] = []; //Constructor /** * Initializes a new instance of the `PdfGridCellCollection` class with the row. * @private */ public constructor(row : PdfGridRow) { this.gridRow = row; } //Properties /** * Gets the current `cell`. * @private */ public getCell(index : number) : PdfGridCell { if (index < 0 || index >= this.count) { throw new Error('IndexOutOfRangeException'); } return this.cells[index]; } /** * Gets the cells `count`.[Read-Only]. * @private */ public get count() : number { return this.cells.length; } //Implementation /** * `Adds` this instance. * @private */ public add() : PdfGridCell /** * `Adds` this instance. * @private */ public add(cell : PdfGridCell) : void public add(cell ?: PdfGridCell) : PdfGridCell|void { if (typeof cell === 'undefined') { let tempcell : PdfGridCell = new PdfGridCell(); this.add(tempcell); return cell; } else { cell.row = this.gridRow; this.cells.push(cell); } } /** * Returns the `index of` a particular cell in the collection. * @private */ public indexOf(cell : PdfGridCell) : number { return this.cells.indexOf(cell); } }
the_stack
import {Mutable, FromAny} from "@swim/util"; import {Affinity, FastenerOwner} from "@swim/component"; import {AnyLength, Length, AnyTransform, Transform} from "@swim/math"; import {FontFamily, AnyColor, Color, AnyBoxShadow, BoxShadow} from "@swim/style"; import {ThemeAnimatorInit, ThemeAnimatorClass, ThemeAnimator} from "@swim/theme"; import {StringStyleAnimator} from "./"; // forward import import {NumberStyleAnimator} from "./"; // forward import import {LengthStyleAnimator} from "./"; // forward import import {ColorStyleAnimator} from "./"; // forward import import {FontFamilyStyleAnimator} from "./"; // forward import import {TransformStyleAnimator} from "./"; // forward import import {BoxShadowStyleAnimator} from "./"; // forward import import {StyleContext} from "../"; // forward import /** @public */ export interface StyleAnimatorInit<T = unknown, U = never> extends ThemeAnimatorInit<T, U> { extends?: {prototype: StyleAnimator<any, any>} | string | boolean | null; propertyNames: string | ReadonlyArray<string>; parse?(value: string): T; fromCssValue?(value: CSSStyleValue): T; } /** @public */ export type StyleAnimatorDescriptor<O = unknown, T = unknown, U = never, I = {}> = ThisType<StyleAnimator<O, T, U> & I> & StyleAnimatorInit<T, U> & Partial<I>; /** @public */ export interface StyleAnimatorClass<A extends StyleAnimator<any, any> = StyleAnimator<any, any, any>> extends ThemeAnimatorClass<A> { } /** @public */ export interface StyleAnimatorFactory<A extends StyleAnimator<any, any> = StyleAnimator<any, any, any>> extends StyleAnimatorClass<A> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): StyleAnimatorFactory<A> & I; specialize(type: unknown): StyleAnimatorFactory | null; define<O, T, U = never>(className: string, descriptor: StyleAnimatorDescriptor<O, T, U>): StyleAnimatorFactory<StyleAnimator<any, T, U>>; define<O, T, U = never, I = {}>(className: string, descriptor: {implements: unknown} & StyleAnimatorDescriptor<O, T, U, I>): StyleAnimatorFactory<StyleAnimator<any, T, U> & I>; <O, T extends Length | null | undefined = Length | null | undefined, U extends AnyLength | null | undefined = AnyLength | null | undefined>(descriptor: {type: typeof Length} & StyleAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends Color | null | undefined = Color | null | undefined, U extends AnyColor | null | undefined = AnyColor | null | undefined>(descriptor: {type: typeof Color} & StyleAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends BoxShadow | null | undefined = BoxShadow | null | undefined, U extends AnyBoxShadow | null | undefined = AnyBoxShadow | null | undefined>(descriptor: {type: typeof BoxShadow} & StyleAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends Transform | null | undefined = Transform | null | undefined, U extends AnyTransform | null | undefined = AnyTransform | null | undefined>(descriptor: {type: typeof Transform} & StyleAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends FontFamily | ReadonlyArray<FontFamily> | null | undefined = FontFamily | ReadonlyArray<FontFamily> | null | undefined, U extends FontFamily | ReadonlyArray<FontFamily> | null | undefined = FontFamily | ReadonlyArray<FontFamily> | null | undefined>(descriptor: {type: typeof FontFamily} & StyleAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends string | null | undefined = string | null | undefined, U extends string | null | undefined = string | null | undefined>(descriptor: {type: typeof String} & StyleAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T extends number | null | undefined = number | null | undefined, U extends number | string | null | undefined = number | string | null | undefined>(descriptor: {type: typeof Number} & StyleAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T, U = never>(descriptor: ({type: FromAny<T, U>} | {fromAny(value: T | U): T}) & StyleAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T, U = never>(descriptor: StyleAnimatorDescriptor<O, T, U>): PropertyDecorator; <O, T, U = never, I = {}>(descriptor: {implements: unknown} & StyleAnimatorDescriptor<O, T, U, I>): PropertyDecorator; } /** @public */ export interface StyleAnimator<O = unknown, T = unknown, U = never> extends ThemeAnimator<O, T, U> { get propertyNames(): string | ReadonlyArray<string>; // prototype property get propertyValue(): T | undefined; get computedValue(): T | undefined; /** @internal */ readonly ownValue: T; get value(): T; set value(value: T); /** @override @protected */ onSetValue(newValue: T, oldValue: T): void; readonly priority: string | undefined; setPriority(priority: string | undefined): void; parse(value: string): T; fromCssValue(value: CSSStyleValue): T; } /** @public */ export const StyleAnimator = (function (_super: typeof ThemeAnimator) { const StyleAnimator: StyleAnimatorFactory = _super.extend("StyleAnimator"); Object.defineProperty(StyleAnimator.prototype, "propertyNames", { get(this: StyleAnimator): string | ReadonlyArray<string> { throw new Error("no property names"); }, configurable: true, }); Object.defineProperty(StyleAnimator.prototype, "propertyValue", { get: function <T>(this: StyleAnimator<unknown, T>): T | undefined { let propertyValue: T | undefined; const styleContext = this.owner; if (StyleContext.is(styleContext)) { let value = styleContext.getStyle(this.propertyNames); if (typeof CSSStyleValue !== "undefined" && value instanceof CSSStyleValue) { // CSS Typed OM support try { propertyValue = this.fromCssValue(value); } catch (e) { // swallow decode errors } if (propertyValue === void 0) { value = value.toString(); } } if (typeof value === "string" && value.length !== 0) { try { propertyValue = this.parse(value); } catch (e) { // swallow parse errors } } } return propertyValue; }, configurable: true, }); Object.defineProperty(StyleAnimator.prototype, "computedValue", { get: function <T>(this: StyleAnimator<unknown, T>): T | undefined { let computedValue: T | undefined; const styleContext = this.owner; let node: Node | undefined; if (StyleContext.is(styleContext) && (node = styleContext.node, node instanceof Element)) { const styles = getComputedStyle(node); const propertyNames = this.propertyNames; let propertyValue = ""; if (typeof propertyNames === "string") { propertyValue = styles.getPropertyValue(propertyNames); } else { for (let i = 0, n = propertyNames.length; i < n && propertyValue.length === 0; i += 1) { propertyValue = styles.getPropertyValue(propertyNames[i]!); } } if (propertyValue.length !== 0) { try { computedValue = this.parse(propertyValue); } catch (e) { // swallow parse errors } } } return computedValue; }, configurable: true, }); Object.defineProperty(StyleAnimator.prototype, "value", { get<T>(this: StyleAnimator<unknown, T>): T { let value = this.ownValue; if (!this.definedValue(value)) { const propertyValue = this.propertyValue; if (propertyValue !== void 0) { value = propertyValue; this.setAffinity(Affinity.Extrinsic); } } return value; }, set<T>(this: StyleAnimator<unknown, T>, value: T): void { (this as Mutable<typeof this>).ownValue = value; }, configurable: true, }); StyleAnimator.prototype.onSetValue = function <T>(this: StyleAnimator<unknown, T>, newValue: T, oldValue: T): void { const styleContext = this.owner; if (StyleContext.is(styleContext)) { const propertyNames = this.propertyNames; if (typeof propertyNames === "string") { styleContext.setStyle(propertyNames, newValue, this.priority); } else { for (let i = 0, n = propertyNames.length; i < n; i += 1) { styleContext.setStyle(propertyNames[i]!, newValue, this.priority); } } } _super.prototype.onSetValue.call(this, newValue, oldValue); }; StyleAnimator.prototype.setPriority = function (this: StyleAnimator<unknown, unknown>, priority: string | undefined): void { (this as Mutable<typeof this>).priority = priority; const styleContext = this.owner; const value = this.value; if (StyleContext.is(styleContext) && this.definedValue(value)) { const propertyNames = this.propertyNames; if (typeof propertyNames === "string") { styleContext.setStyle(propertyNames, value, priority); } else { for (let i = 0, n = propertyNames.length; i < n; i += 1) { styleContext.setStyle(propertyNames[i]!, value, priority); } } } }; StyleAnimator.prototype.parse = function <T>(this: StyleAnimator<unknown, T>): T { throw new Error(); }; StyleAnimator.prototype.fromCssValue = function <T>(this: StyleAnimator<unknown, T>, value: CSSStyleValue): T { throw new Error(); }; StyleAnimator.construct = function <A extends StyleAnimator<any, any, any>>(animatorClass: {prototype: A}, animator: A | null, owner: FastenerOwner<A>): A { animator = _super.construct(animatorClass, animator, owner) as A; (animator as Mutable<typeof animator>).priority = void 0; return animator; }; StyleAnimator.specialize = function (type: unknown): StyleAnimatorFactory | null { if (type === String) { return StringStyleAnimator; } else if (type === Number) { return NumberStyleAnimator; } else if (type === Length) { return LengthStyleAnimator; } else if (type === Color) { return ColorStyleAnimator; } else if (type === FontFamily) { return FontFamilyStyleAnimator; } else if (type === BoxShadow) { return BoxShadowStyleAnimator; } else if (type === Transform) { return TransformStyleAnimator; } return null; }; StyleAnimator.define = function <O, T, U>(className: string, descriptor: StyleAnimatorDescriptor<O, T, U>): StyleAnimatorFactory<StyleAnimator<any, T, U>> { let superClass = descriptor.extends as StyleAnimatorFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const look = descriptor.look; const value = descriptor.value; const initValue = descriptor.initValue; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.look; delete descriptor.value; delete descriptor.initValue; if (superClass === void 0 || superClass === null) { superClass = this.specialize(descriptor.type); } if (superClass === null) { superClass = this; if (descriptor.fromAny === void 0 && FromAny.is<T, U>(descriptor.type)) { descriptor.fromAny = descriptor.type.fromAny; } } const animatorClass = superClass.extend(className, descriptor); animatorClass.construct = function (animatorClass: {prototype: StyleAnimator<any, any, any>}, animator: StyleAnimator<O, T, U> | null, owner: O): StyleAnimator<O, T, U> { animator = superClass!.construct(animatorClass, animator, owner); if (affinity !== void 0) { animator.initAffinity(affinity); } if (inherits !== void 0) { animator.initInherits(inherits); } if (look !== void 0) { (animator as Mutable<typeof animator>).look = look; } if (initValue !== void 0) { (animator as Mutable<typeof animator>).value = animator.fromAny(initValue()); (animator as Mutable<typeof animator>).state = animator.value; } else if (value !== void 0) { (animator as Mutable<typeof animator>).value = animator.fromAny(value); (animator as Mutable<typeof animator>).state = animator.value; } return animator; }; return animatorClass; }; return StyleAnimator; })(ThemeAnimator);
the_stack
import { AccountContract, BufferString, common, crypto, decryptNEP2, encryptNEP2, NetworkType, PrivateKeyString, privateKeyToPublicKey, publicKeyToAddress, UpdateAccountNameOptions, UserAccount, UserAccountID, } from '@neo-one/client-common'; import { utils } from '@neo-one/utils'; import debug from 'debug'; import _ from 'lodash'; import { BehaviorSubject, Observable } from 'rxjs'; import { distinctUntilChanged, map } from 'rxjs/operators'; import * as args from '../../args'; import { LockedAccountError, UnknownAccountError } from '../../errors'; import { KeyStore } from '../LocalUserAccountProvider'; const logger = debug('NEOONE:LocalKeystore'); /** * Wallet in the "locked" state. */ export interface LockedWallet { /** * `type` differentiates a `LockedWallet` from other `LocalWallet`s, i.e. an `UnlockedWallet` */ readonly type: 'locked'; /** * `UserAccount` this `LockedWallet` refers to. */ readonly userAccount: UserAccount; /** * NEP-2 encrypted key of this `LockedWallet`. */ readonly nep2: string; } /** * Wallet in the "unlocked" state. */ export interface UnlockedWallet { /** * `type` differentiates an `UnlockedWallet` from other `LocalWallet`s, i.e. an `LockedWallet` */ readonly type: 'unlocked'; /** * `UserAccount` this `UnlockedWallet` refers to. */ readonly userAccount: UserAccount; /** * Private key for this `UnlockedWallet`. */ readonly privateKey: PrivateKeyString; /** * NEP-2 encrypted key of this `UnlockedWallet`. `undefined` if the `privateKey` has never been encrypted. */ readonly nep2?: string | undefined; } /** * Locally stored wallet that is either in a `'locked'` or `'unlocked'` state (`type`). */ export type LocalWallet = LockedWallet | UnlockedWallet; /** * Mapping from `NetworkType` -> `AddressString` -> `LocalWallet` */ export type Wallets = { readonly [Network in string]?: { readonly [Address in string]?: LocalWallet } }; /** * Base interface that must be implemented to use the `LocalKeyStore`. */ export interface LocalStore { /** * @returns `Promise` that resolves to all available `LocalWallet`s. */ readonly getWallets: () => Promise<readonly LocalWallet[]>; /** * Optional method that returns the available wallets synchronously. * * @returns All available `LocalWallet`s */ readonly getWalletsSync?: () => readonly LocalWallet[]; /** * Save a wallet to the store. */ readonly saveWallet: (wallet: LocalWallet) => Promise<void>; /** * Delete a wallet from the store. */ readonly deleteWallet: (account: LocalWallet) => Promise<void>; } const flattenWallets = (wallets: Wallets) => _.flatten( Object.values(wallets) .filter(utils.notNull) .map((networkWallets) => Object.values(networkWallets)), ).filter(utils.notNull); /** * `LocalKeyStore` implements the `KeyStore` interface expected by `LocalUserAccountProvider` via an underlying `Store` implementation. */ export class LocalKeyStore implements KeyStore { public readonly currentUserAccount$: Observable<UserAccount | undefined>; public readonly userAccounts$: Observable<readonly UserAccount[]>; public readonly wallets$: Observable<readonly LocalWallet[]>; private readonly currentAccountInternal$: BehaviorSubject<UserAccount | undefined>; private readonly accountsInternal$: BehaviorSubject<readonly UserAccount[]>; private readonly walletsInternal$: BehaviorSubject<Wallets>; private readonly store: LocalStore; private readonly initPromise: Promise<void>; public constructor(store: LocalStore) { this.walletsInternal$ = new BehaviorSubject<Wallets>({}); this.wallets$ = this.walletsInternal$.pipe( distinctUntilChanged((a, b) => _.isEqual(a, b)), map(flattenWallets), ); this.accountsInternal$ = new BehaviorSubject([] as readonly UserAccount[]); this.wallets$ .pipe(map((wallets) => wallets.map(({ userAccount }) => userAccount))) .subscribe(this.accountsInternal$); this.userAccounts$ = this.accountsInternal$; this.currentAccountInternal$ = new BehaviorSubject(undefined as UserAccount | undefined); this.currentUserAccount$ = this.currentAccountInternal$.pipe(distinctUntilChanged()); this.store = store; if (store.getWalletsSync !== undefined) { this.initWithWallets(store.getWalletsSync()); } this.initPromise = this.init(); } public getCurrentUserAccount(): UserAccount | undefined { return this.currentAccountInternal$.getValue(); } public getUserAccounts(): readonly UserAccount[] { return this.accountsInternal$.getValue(); } public get wallets(): readonly LocalWallet[] { return flattenWallets(this.walletsObj); } public async sign({ account, message, }: { readonly account: UserAccountID; readonly message: string; }): Promise<string> { await this.initPromise; return this.capture(async () => { const privateKey = this.getPrivateKey(account); return crypto .sign({ message: Buffer.from(message, 'hex'), privateKey: common.stringToPrivateKey(privateKey) }) .toString('hex'); }, 'neo_sign'); } public async selectUserAccount(id?: UserAccountID): Promise<void> { if (id === undefined) { this.currentAccountInternal$.next(undefined); this.newCurrentAccount(); } else { const { userAccount } = this.getWallet(id); this.currentAccountInternal$.next(userAccount); } } public async updateUserAccountName({ id, name }: UpdateAccountNameOptions): Promise<void> { return this.capture(async () => { await this.initPromise; const wallet = this.getWallet(id); let newWallet: LocalWallet; const userAccount = { id: wallet.userAccount.id, name, publicKey: wallet.userAccount.publicKey, contract: wallet.userAccount.contract, }; if (wallet.type === 'locked') { newWallet = { type: 'locked', userAccount, nep2: wallet.nep2, }; } else { newWallet = { type: 'unlocked', userAccount, privateKey: wallet.privateKey, nep2: wallet.nep2, }; } await this.capture(async () => this.store.saveWallet(newWallet), 'neo_save_wallet'); this.updateWallet(newWallet); }, 'neo_update_account_name'); } public getWallet({ address, network }: UserAccountID): LocalWallet { const wallets = this.walletsObj[network]; if (wallets === undefined) { throw new UnknownAccountError(address); } const wallet = wallets[address]; if (wallet === undefined) { throw new UnknownAccountError(address); } return wallet; } public getWallet$({ address, network }: UserAccountID): Observable<LocalWallet | undefined> { return this.walletsInternal$.pipe( map((wallets) => { const networkWallets = wallets[network]; if (networkWallets === undefined) { return undefined; } return networkWallets[address]; }), ); } public async addUserAccount({ network, privateKey: privateKeyIn, name, password, nep2: nep2In, }: { readonly network: NetworkType; readonly privateKey?: BufferString; readonly name?: string; readonly password?: string; readonly nep2?: string; }): Promise<LocalWallet> { await this.initPromise; return this.capture(async () => { let pk = privateKeyIn; let nep2 = nep2In; if (pk === undefined) { if (nep2 === undefined || password === undefined) { throw new Error('Expected private key or password and NEP-2 key'); } pk = await decryptNEP2({ encryptedKey: nep2, password }); } const privateKey = args.assertPrivateKey('privateKey', pk); const publicKey = privateKeyToPublicKey(privateKey); const address = publicKeyToAddress(publicKey); if (nep2 === undefined && password !== undefined) { nep2 = await encryptNEP2({ privateKey, password }); } const contract = AccountContract.createSignatureContract(common.stringToECPoint(publicKey)); const userAccount = { id: { network, address, }, name: name === undefined ? address : name, publicKey, contract, }; const unlockedWallet: UnlockedWallet = { type: 'unlocked', userAccount, nep2, privateKey, }; let wallet: LocalWallet = unlockedWallet; if (nep2 !== undefined) { wallet = { type: 'locked', userAccount, nep2 }; } await this.capture(async () => this.store.saveWallet(wallet), 'neo_save_wallet'); this.updateWallet(unlockedWallet); if (this.currentAccount === undefined) { this.currentAccountInternal$.next(wallet.userAccount); } return unlockedWallet; }, 'neo_add_account'); } /** * not a true implementation, just serves as a helper for private net. * @internal */ public async addMultiSigUserAccount({ network, privateKeys: privateKeysIn, name, }: { readonly network: NetworkType; readonly privateKeys: readonly BufferString[]; readonly name?: string; }): Promise<LocalWallet> { await this.initPromise; return this.capture(async () => { const pk = privateKeysIn[0]; const privateKey = args.assertPrivateKey('privateKey', pk); const publicKey = privateKeyToPublicKey(privateKey); const ecPoint = common.stringToECPoint(publicKey); const address = crypto.scriptHashToAddress({ addressVersion: common.NEO_ADDRESS_VERSION, scriptHash: crypto.toScriptHash(crypto.createMultiSignatureVerificationScript(1, [ecPoint])), }); const contract = AccountContract.createMultiSigContract(1, [ecPoint]); const userAccount = { id: { network, address, }, name: name === undefined ? address : name, publicKey, contract, }; const unlockedWallet: UnlockedWallet = { type: 'unlocked', userAccount, privateKey, }; const wallet: LocalWallet = unlockedWallet; await this.capture(async () => this.store.saveWallet(wallet), 'neo_save_wallet'); this.updateWallet(unlockedWallet); if (this.currentAccount === undefined) { this.currentAccountInternal$.next(wallet.userAccount); } return unlockedWallet; }, 'neo_add_account'); } public async deleteUserAccount(id: UserAccountID): Promise<void> { await this.initPromise; return this.capture(async () => { const { walletsObj: wallets } = this; const networkWalletsIn = wallets[id.network]; if (networkWalletsIn === undefined) { return; } const { [id.address]: wallet, ...networkWallets } = networkWalletsIn; if (wallet === undefined) { return; } await this.capture(async () => this.store.deleteWallet(wallet), 'neo_delete_wallet'); this.walletsInternal$.next({ ...wallets, [id.network]: networkWallets, }); if ( this.currentAccount !== undefined && this.currentAccount.id.network === id.network && this.currentAccount.id.address === id.address ) { this.newCurrentAccount(); } }, 'neo_delete_account'); } public async unlockWallet({ id, password, }: { readonly id: UserAccountID; readonly password: string; }): Promise<void> { await this.initPromise; return this.capture(async () => { const wallet = this.getWallet(id); if (wallet.type === 'unlocked') { return; } const privateKey = await decryptNEP2({ encryptedKey: wallet.nep2, password, }); this.updateWallet({ type: 'unlocked', userAccount: wallet.userAccount, privateKey, nep2: wallet.nep2, }); }, 'neo_unlock_wallet'); } public async lockWallet(id: UserAccountID): Promise<void> { await this.initPromise; const wallet = this.getWallet(id); if (wallet.type === 'locked' || wallet.nep2 === undefined) { return; } this.updateWallet({ type: 'locked', userAccount: wallet.userAccount, nep2: wallet.nep2, }); } private async init(): Promise<void> { const walletsList = await this.store.getWallets(); this.initWithWallets(walletsList); } private initWithWallets(walletsList: readonly LocalWallet[]): void { const wallets = walletsList.reduce<Wallets>( (acc, wallet) => ({ ...acc, [wallet.userAccount.id.network]: { ...(acc[wallet.userAccount.id.network] === undefined ? {} : acc[wallet.userAccount.id.network]), [wallet.userAccount.id.address]: wallet, }, }), {}, ); this.walletsInternal$.next(wallets); this.newCurrentAccount(); } private getPrivateKey(id: UserAccountID): BufferString { const wallet = this.getWallet({ network: id.network, address: id.address, }); if (wallet.type === 'locked') { throw new LockedAccountError(id.address); } return wallet.privateKey; } private updateWallet(wallet: LocalWallet): void { const { walletsObj: wallets } = this; this.walletsInternal$.next({ ...wallets, [wallet.userAccount.id.network]: { ...(wallets[wallet.userAccount.id.network] === undefined ? {} : wallets[wallet.userAccount.id.network]), [wallet.userAccount.id.address]: wallet, }, }); } private newCurrentAccount(): void { const allAccounts = this.wallets.map(({ userAccount: value }) => value); const account = allAccounts[0]; this.currentAccountInternal$.next(account); } private async capture<T>(func: () => Promise<T>, title: string): Promise<T> { try { const result = await func(); logger('%o', { title, level: 'debug' }); return result; } catch (error) { logger('%o', { title, level: 'error', error: error.message }); throw error; } } private get walletsObj(): Wallets { return this.walletsInternal$.getValue(); } private get currentAccount(): UserAccount | undefined { return this.currentAccountInternal$.getValue(); } }
the_stack
import {Flo} from 'spring-flo'; import {convertParseResponseToJsonGraph} from './text-to-graph'; import {JsonGraph, TextToGraphConverter} from './text-to-graph'; import {Parser} from '../shared/service/parser'; describe('text-to-graph', () => { let parseResult: Parser.ParseResult; let graph: JsonGraph.Graph; let node: JsonGraph.Node; let link: JsonGraph.Link; let fakemetamodel: Map<string, Map<string, Flo.ElementMetadata>>; beforeAll(() => { const fakeTimeMetadata: Flo.ElementMetadata = { group: 'fake', name: 'time', get(property: string): Promise<Flo.PropertyMetadata> { return Promise.resolve(null); }, properties(): Promise<Map<string, Flo.PropertyMetadata>> { return Promise.resolve(new Map()); } }; const fakeTime: Map<string, Flo.ElementMetadata> = new Map(); fakeTime['time'] = fakeTimeMetadata; fakemetamodel = new Map(); fakemetamodel['fake'] = fakeTime; }); // First set of tests don't require a fake Flo - they convert DSL to a JSON graph (not a jointjs graph) it('jsongraph: nograph', () => { const dsl = ''; parseResult = Parser.parse(dsl, 'stream'); const holder: JsonGraph.GraphHolder = convertParseResponseToJsonGraph(dsl, parseResult); expect(holder.errors.length).toEqual(0); expect(holder.graph).toBeNull(); }); it('jsongraph: error - no more data', () => { const dsl = 'time | '; parseResult = Parser.parse(dsl, 'stream'); const holder: JsonGraph.GraphHolder = convertParseResponseToJsonGraph(dsl, parseResult); expect(holder.errors[0].message).toEqual('Out of data'); }); it('jsongraph: two streams sharing a destination', () => { graph = getGraph('time > :abc\nfile > :abc'); expect(graph.streamdefs[0].def).toEqual('time > :abc'); expect(graph.streamdefs[1].def).toEqual('file > :abc'); expect(graph.nodes[0].name).toEqual('time'); expect(graph.nodes[0]['stream-id']).toEqual(1); expect(graph.nodes[1].name).toEqual('destination'); expect(graph.nodes[1]['stream-id']).toBeUndefined(); expect(graph.nodes[2].name).toEqual('file'); expect(graph.nodes[2]['stream-id']).toEqual(2); expect(graph.links.length).toEqual(2); expect(graph.links[0].from).toEqual(0); expect(graph.links[0].to).toEqual(1); expect(graph.links[1].from).toEqual(2); expect(graph.links[1].to).toEqual(1); }); it('jsongraph: two separate apps should be unconnected', () => { graph = getGraph('aaa|| bbb'); expect(graph.streamdefs.length).toEqual(1); expect(graph.streamdefs[0].def).toEqual('aaa || bbb'); expect(graph.nodes[0].name).toEqual('aaa'); expect(graph.nodes[0].group).toEqual('app'); expect(graph.nodes[1].name).toEqual('bbb'); expect(graph.nodes[1].group).toEqual('app'); expect(graph.links.length).toEqual(0); }); it('jsongraph: app properties computed dsl', () => { const dsl = 'aaa --server.port=9002 --server.addr=uuu||bbb --server.port=4567'; graph = getGraph('aaa --server.port=9002 --server.addr=uuu||bbb --server.port=4567'); expect(graph.links.length).toEqual(0); expect(graph.streamdefs.length).toEqual(1); expect(graph.streamdefs[0].def).toEqual('aaa --server.port=9002 --server.addr=uuu || bbb --server.port=4567'); }); it('jsongraph: two separate apps should be unconnected: 2', () => { graph = getGraph('aaa || bbb'); expect(graph.streamdefs.length).toEqual(1); expect(graph.streamdefs[0].def).toEqual('aaa || bbb'); expect(graph.nodes[0].name).toEqual('aaa'); expect(graph.nodes[0].group).toEqual('app'); expect(graph.nodes[1].name).toEqual('bbb'); expect(graph.nodes[1].group).toEqual('app'); expect(graph.links.length).toEqual(0); }); it('jsongraph: tapping a stream', () => { graph = getGraph('aaaa= time | log\n:aaaa.time>log'); expect(graph.streamdefs[0].def).toEqual('time | log'); expect(graph.streamdefs[0].name).toEqual('aaaa'); expect(graph.streamdefs[1].def).toEqual(':aaaa.time > log'); expect(graph.nodes[0].name).toEqual('time'); expect(graph.nodes[0]['stream-name']).toEqual('aaaa'); expect(graph.nodes[1].name).toEqual('log'); expect(graph.nodes[1]['stream-id']).toBeUndefined(); expect(graph.nodes[2].name).toEqual('log'); expect(graph.nodes[2]['stream-id']).toEqual(2); expect(graph.links.length).toEqual(2); expect(graph.links[0].from).toEqual(0); expect(graph.links[0].to).toEqual(1); expect(graph.links[1].from).toEqual(0); expect(graph.links[1].to).toEqual(2); expect(graph.links[1].linkType).toEqual('tap'); }); it('jsongraph: tapping a non-existent stream', () => { graph = getGraph(':aaaa.time>log'); expect(graph.streamdefs[0].def).toEqual(':aaaa.time > log'); expect(graph.nodes[0].name).toEqual('tap'); expect(graph.nodes[0].properties.get('name')).toEqual('aaaa.time'); expect(graph.nodes[0]['stream-id']).toBeUndefined(); expect(graph.nodes[1].name).toEqual('log'); expect(graph.nodes[1]['stream-id']).toEqual(1); expect(graph.links.length).toEqual(1); expect(graph.links[0].from).toEqual(0); expect(graph.links[0].to).toEqual(1); }); it('jsongraph: incomplete stream with tap', () => { graph = getGraph('STREAM-1=time\n:STREAM-1.time > log'); expect(graph.streamdefs[0].def).toEqual('time'); expect(graph.streamdefs[1].def).toEqual(':STREAM-1.time > log'); expect(graph.nodes[0].name).toEqual('time'); expect(graph.nodes[0]['stream-id']).toEqual(1); expect(graph.nodes[1].name).toEqual('log'); expect(graph.nodes[1]['stream-id']).toEqual(2); expect(graph.links.length).toEqual(1); expect(graph.links[0].from).toEqual(0); expect(graph.links[0].to).toEqual(1); expect(graph.links[0].linkType).toEqual('tap'); }); it('jsongraph: name set on sink channel in some cases', () => { graph = getGraph(':aaa > :foo\n:aaa > :bar'); expect(graph.streamdefs[0].def).toEqual(':aaa > :foo'); expect(graph.streamdefs[1].def).toEqual(':aaa > :bar'); node = graph.nodes[0]; expect(node.name).toEqual('destination'); expect(node.properties.get('name')).toEqual('aaa'); expect(node['stream-id']).toBeUndefined(); node = graph.nodes[1]; expect(node.name).toEqual('destination'); expect(node.properties.get('name')).toEqual('foo'); expect(node['stream-id']).toEqual(1); node = graph.nodes[2]; expect(node.name).toEqual('destination'); expect(node.properties.get('name')).toEqual('bar'); expect(node['stream-id']).toEqual(2); expect(graph.links.length).toEqual(2); expect(graph.links[0].from).toEqual(0); expect(graph.links[0].to).toEqual(1); expect(graph.links[1].from).toEqual(0); expect(graph.links[1].to).toEqual(2); }); it('jsongraph: basic', () => { graph = getGraph('time | log'); expect(graph.format).toEqual('scdf'); expect(graph.errors).toBeUndefined(); expect(graph.nodes.length).toEqual(2); expect(graph.links.length).toEqual(1); expect(graph.streamdefs[0].name).toEqual(''); expect(graph.streamdefs[0].def).toEqual('time | log'); node = graph.nodes[0]; expect(node.id).toEqual(0); expect(node.name).toEqual('time'); expect(node['stream-id']).toEqual(1); expectRange(node.range, 0, 0, 4, 0); node = graph.nodes[1]; expect(node.id).toEqual(1); expect(node.name).toEqual('log'); expect(node['stream-id']).toBeUndefined(); expectRange(node.range, 7, 0, 10, 0); link = graph.links[0]; expect(link.from).toEqual(0); expect(link.to).toEqual(1); }); it('jsongraph: basic labels', () => { graph = getGraph('aaa: time | bbb: log'); expect(graph.format).toEqual('scdf'); expect(graph.errors).toBeUndefined(); expect(graph.nodes.length).toEqual(2); expect(graph.links.length).toEqual(1); expect(graph.streamdefs[0].name).toEqual(''); expect(graph.streamdefs[0].def).toEqual('aaa: time | bbb: log'); node = graph.nodes[0]; expect(node.id).toEqual(0); expect(node.name).toEqual('time'); expect(node.label).toEqual('aaa'); expect(node['stream-id']).toEqual(1); expectRange(node.range, 0, 0, 9, 0); node = graph.nodes[1]; expect(node.id).toEqual(1); expect(node.name).toEqual('log'); expect(node.label).toEqual('bbb'); expect(node['stream-id']).toBeUndefined(); expectRange(node.range, 12, 0, 20, 0); link = graph.links[0]; expect(link.from).toEqual(0); expect(link.to).toEqual(1); }); it('jsongraph: properties', () => { graph = getGraph('time --aaa=bbb --ccc=ddd | log'); expect(graph.errors).toBeUndefined(); expect(graph.nodes.length).toEqual(2); expect(graph.links.length).toEqual(1); expect(graph.streamdefs[0].name).toEqual(''); expect(graph.streamdefs[0].def).toEqual('time --aaa=bbb --ccc=ddd | log'); node = graph.nodes[0]; expect(node.id).toEqual(0); expect(node.name).toEqual('time'); expect(node['stream-id']).toEqual(1); expect(node.properties.get('aaa')).toEqual('bbb'); expectRange(node.propertiesranges.get('aaa'), 5, 0, 14, 0); expect(node.properties.get('ccc')).toEqual('ddd'); expect(node.properties.get('fff')).toBeUndefined(); expectRange(node.propertiesranges.get('ccc'), 15, 0, 24, 0); expectRange(node.range, 0, 0, 4, 0); node = graph.nodes[1]; expect(node.id).toEqual(1); expect(node.name).toEqual('log'); expect(node['stream-id']).toBeUndefined(); expectRange(node.range, 27, 0, 30, 0); link = graph.links[0]; expect(link.from).toEqual(0); expect(link.to).toEqual(1); }); it('jsongraph: source channel', () => { graph = getGraph(':abc > log'); expect(graph.format).toEqual('scdf'); expect(graph.errors).toBeUndefined(); expect(graph.nodes.length).toEqual(2); expect(graph.links.length).toEqual(1); expect(graph.streamdefs[0].name).toEqual(''); expect(graph.streamdefs[0].def).toEqual(':abc > log'); node = graph.nodes[0]; expect(node.id).toEqual(0); expect(node.name).toEqual('destination'); expect(node.properties.get('name')).toEqual('abc'); expect(node['stream-id']).toBeUndefined(); // destination source doesn't get an ID expect(node.range).toBeUndefined(); // this is not set right now for channels node = graph.nodes[1]; expect(node.id).toEqual(1); expect(node.name).toEqual('log'); expect(node['stream-id']).toEqual(1); expectRange(node.range, 7, 0, 10, 0); link = graph.links[0]; expect(link.from).toEqual(0); expect(link.to).toEqual(1); }); it('incorrect tap link - gh514', () => { graph = getGraph( 'STREAM-1=ftp | filter > :foo\n' + 'STREAM-2=:STREAM-1.ftp > splitter > :foo\n' + 'STREAM-3=:foo > log' ); expect(graph.format).toEqual('scdf'); expect(graph.errors).toBeUndefined(); expect(graph.nodes.length).toEqual(5); expect(graph.links.length).toEqual(5); expect(graph.nodes[0].name).toEqual('ftp'); expect(graph.nodes[1].name).toEqual('filter'); expect(graph.nodes[2].name).toEqual('destination'); expect(graph.nodes[2].properties.get('name')).toEqual('foo'); expect(graph.nodes[3].name).toEqual('splitter'); expect(graph.nodes[4].name).toEqual('log'); expect(toString(graph.links[0])).toEqual('0 -> 1'); expect(toString(graph.links[1])).toEqual('1 -> 2'); expect(toString(graph.links[2])).toEqual('0 -> 3 [tap]'); expect(toString(graph.links[3])).toEqual('3 -> 2'); expect(toString(graph.links[4])).toEqual('2 -> 4'); }); function toString(aLink: JsonGraph.Link): string { return aLink.from + ' -> ' + aLink.to + (aLink.linkType === 'tap' ? ' [tap]' : ''); } it('jsongraph: sink channel', () => { graph = getGraph('time > :abc'); expect(graph.format).toEqual('scdf'); expect(graph.errors).toBeUndefined(); expect(graph.nodes.length).toEqual(2); expect(graph.links.length).toEqual(1); expect(graph.streamdefs[0].name).toEqual(''); expect(graph.streamdefs[0].def).toEqual('time > :abc'); node = graph.nodes[0]; expect(node.id).toEqual(0); expect(node.name).toEqual('time'); expect(node['stream-id']).toEqual(1); expectRange(node.range, 0, 0, 4, 0); node = graph.nodes[1]; expect(node.id).toEqual(1); expect(node.name).toEqual('destination'); expect(node.properties.get('name')).toEqual('abc'); expect(node['stream-id']).toBeUndefined(); expect(node.range).toBeUndefined(); link = graph.links[0]; expect(link.from).toEqual(0); expect(link.to).toEqual(1); }); it('group selection', () => { const m: Map<string, Map<string, Flo.ElementMetadata>> = new Map<string, Map<string, Flo.ElementMetadata>>(); m.set('processor', new Map<string, Flo.ElementMetadata>([['counter', createEntry('processor', 'counter')]])); m.set('source', new Map<string, Flo.ElementMetadata>([['counter', createEntry('source', 'counter')]])); m.set('sink', new Map<string, Flo.ElementMetadata>([['counter', createEntry('sink', 'counter')]])); const converter: any = new TextToGraphConverter('', null, m); expect(converter.matchGroup('counter', 1, 1)).toEqual('processor'); expect(converter.matchGroup('counter', 3, 2)).toEqual('processor'); expect(converter.matchGroup('counter', 1, 0)).toEqual('sink'); expect(converter.matchGroup('counter', 3, 0)).toEqual('sink'); expect(converter.matchGroup('counter', 0, 1)).toEqual('source'); expect(converter.matchGroup('counter', 0, 3)).toEqual('source'); }); function getGraph(dsl: string) { parseResult = Parser.parse(dsl, 'stream'); return convertParseResponseToJsonGraph(dsl, parseResult).graph; } function expectRange(range: JsonGraph.Range, startChar: number, startLine: number, endChar: number, endLine: number) { expect(range.start.ch).toEqual(startChar); expect(range.start.line).toEqual(startLine); expect(range.end.ch).toEqual(endChar); expect(range.end.line).toEqual(endLine); } function createEntry(group: string, name: string): Flo.ElementMetadata { return { group: group, name: name, get(property: string): Promise<Flo.PropertyMetadata> { return Promise.resolve(null); }, properties(): Promise<Map<string, Flo.PropertyMetadata>> { return Promise.resolve(new Map()); } }; } });
the_stack
import classNames from "classnames"; import * as React from "react"; import { polyfill } from "react-lifecycles-compat"; import { AbstractComponent2, DISPLAYNAME_PREFIX, Hotkey, Hotkeys, HotkeysTarget, IRef, Utils as CoreUtils, } from "@blueprintjs/core"; import { ICellProps } from "./cell/cell"; import { Column, IColumnProps } from "./column"; import { IFocusedCellCoordinates } from "./common/cell"; import * as Classes from "./common/classes"; import { columnInteractionBarContextTypes, IColumnInteractionBarContextTypes } from "./common/context"; import * as Errors from "./common/errors"; import { Grid, ICellMapper } from "./common/grid"; import * as FocusedCellUtils from "./common/internal/focusedCellUtils"; import * as ScrollUtils from "./common/internal/scrollUtils"; import { Rect } from "./common/rect"; import { RenderMode } from "./common/renderMode"; import { Utils } from "./common/utils"; import { ColumnHeader } from "./headers/columnHeader"; import { ColumnHeaderCell, IColumnHeaderCellProps } from "./headers/columnHeaderCell"; import { renderDefaultRowHeader, RowHeader } from "./headers/rowHeader"; import { ResizeSensor } from "./interactions/resizeSensor"; import { GuideLayer } from "./layers/guides"; import { RegionStyler, RegionLayer } from "./layers/regions"; import { Locator } from "./locator"; import { QuadrantType } from "./quadrants/tableQuadrant"; import { TableQuadrantStack } from "./quadrants/tableQuadrantStack"; import { ColumnLoadingOption, IRegion, RegionCardinality, Regions, SelectionModes, TableLoadingOption, } from "./regions"; import { IResizeRowsByApproximateHeightOptions, resizeRowsByApproximateHeight, resizeRowsByTallestCell, } from "./resizeRows"; import { TableBody } from "./tableBody"; import { TableHotkeys } from "./tableHotkeys"; import type { TableProps } from "./tableProps"; import type { TableState, TableSnapshot } from "./tableState"; import { clampNumFrozenColumns, clampNumFrozenRows, hasLoadingOption } from "./tableUtils"; /* eslint-disable deprecation/deprecation */ /** @deprecated use Table2, which supports usage of the new hotkeys API in the same application */ @HotkeysTarget @polyfill export class Table extends AbstractComponent2<TableProps, TableState, TableSnapshot> { public static displayName = `${DISPLAYNAME_PREFIX}.Table`; public static defaultProps: TableProps = { defaultColumnWidth: 150, defaultRowHeight: 20, enableFocusedCell: false, enableGhostCells: false, enableMultipleSelection: true, enableRowHeader: true, forceRerenderOnSelectionChange: false, loadingOptions: [], minColumnWidth: 50, minRowHeight: 20, numFrozenColumns: 0, numFrozenRows: 0, numRows: 0, renderMode: RenderMode.BATCH_ON_UPDATE, rowHeaderCellRenderer: renderDefaultRowHeader, selectionModes: SelectionModes.ALL, }; public static childContextTypes: React.ValidationMap<IColumnInteractionBarContextTypes> = columnInteractionBarContextTypes; public static getDerivedStateFromProps(props: TableProps, state: TableState) { const { children, defaultColumnWidth, defaultRowHeight, enableFocusedCell, focusedCell, numRows, selectedRegions, selectionModes, } = props; // assign values from state if uncontrolled let { columnWidths, rowHeights } = props; if (columnWidths == null) { columnWidths = state.columnWidths; } if (rowHeights == null) { rowHeights = state.rowHeights; } const newChildrenArray = React.Children.toArray(children) as Array<React.ReactElement<IColumnProps>>; const didChildrenChange = newChildrenArray !== state.childrenArray; const numCols = newChildrenArray.length; let newColumnWidths = columnWidths; if (columnWidths !== state.columnWidths || didChildrenChange) { // Try to maintain widths of columns by looking up the width of the // column that had the same `ID` prop. If none is found, use the // previous width at the same index. const previousColumnWidths = newChildrenArray.map( (child: React.ReactElement<IColumnProps>, index: number) => { const mappedIndex = state.columnIdToIndex[child.props.id]; return state.columnWidths[mappedIndex != null ? mappedIndex : index]; }, ); // Make sure the width/height arrays have the correct length, but keep // as many existing widths/heights as possible. Also, apply the // sparse width/heights from props. newColumnWidths = Utils.arrayOfLength(newColumnWidths, numCols, defaultColumnWidth); newColumnWidths = Utils.assignSparseValues(newColumnWidths, previousColumnWidths); newColumnWidths = Utils.assignSparseValues(newColumnWidths, columnWidths); } let newRowHeights = rowHeights; if (rowHeights !== state.rowHeights || numRows !== state.rowHeights.length) { newRowHeights = Utils.arrayOfLength(newRowHeights, numRows, defaultRowHeight); newRowHeights = Utils.assignSparseValues(newRowHeights, rowHeights); } let newSelectedRegions = selectedRegions; if (selectedRegions == null) { // if we're in uncontrolled mode, filter out all selected regions that don't // fit in the current new table dimensions newSelectedRegions = state.selectedRegions.filter(region => { const regionCardinality = Regions.getRegionCardinality(region); return ( Table.isSelectionModeEnabled(props, regionCardinality, selectionModes) && Regions.isRegionValidForTable(region, numRows, numCols) ); }); } const newFocusedCell = FocusedCellUtils.getInitialFocusedCell( enableFocusedCell, focusedCell, state.focusedCell, newSelectedRegions, ); const nextState = { childrenArray: newChildrenArray, columnIdToIndex: didChildrenChange ? Table.createColumnIdIndex(newChildrenArray) : state.columnIdToIndex, columnWidths: newColumnWidths, focusedCell: newFocusedCell, numFrozenColumnsClamped: clampNumFrozenColumns(props), numFrozenRowsClamped: clampNumFrozenRows(props), rowHeights: newRowHeights, selectedRegions: newSelectedRegions, }; if (!CoreUtils.deepCompareKeys(state, nextState, Table.SHALLOW_COMPARE_STATE_KEYS_DENYLIST)) { return nextState; } return null; } private static SHALLOW_COMPARE_PROP_KEYS_DENYLIST = [ "selectedRegions", // (intentionally omitted; can be deeply compared to save on re-renders in controlled mode) ] as Array<keyof TableProps>; private static SHALLOW_COMPARE_STATE_KEYS_DENYLIST = [ "selectedRegions", // (intentionally omitted; can be deeply compared to save on re-renders in uncontrolled mode) "viewportRect", ] as Array<keyof TableState>; private static createColumnIdIndex(children: Array<React.ReactElement<any>>) { const columnIdToIndex: { [key: string]: number } = {}; for (let i = 0; i < children.length; i++) { const key = children[i].props.id; if (key != null) { columnIdToIndex[String(key)] = i; } } return columnIdToIndex; } private static isSelectionModeEnabled( props: TableProps, selectionMode: RegionCardinality, selectionModes = props.selectionModes, ) { const { children, numRows } = props; const numColumns = React.Children.count(children); return selectionModes.indexOf(selectionMode) >= 0 && numRows > 0 && numColumns > 0; } private hotkeysImpl: TableHotkeys; public grid: Grid; public locator: Locator; private resizeSensorDetach: () => void; private refHandlers = { cellContainer: (ref: HTMLElement) => (this.cellContainerElement = ref), columnHeader: (ref: HTMLElement) => (this.columnHeaderElement = ref), quadrantStack: (ref: TableQuadrantStack) => (this.quadrantStackInstance = ref), rootTable: (ref: HTMLElement) => (this.rootTableElement = ref), rowHeader: (ref: HTMLElement) => (this.rowHeaderElement = ref), scrollContainer: (ref: HTMLElement) => (this.scrollContainerElement = ref), }; private cellContainerElement: HTMLElement; private columnHeaderElement: HTMLElement; private quadrantStackInstance: TableQuadrantStack; private rootTableElement: HTMLElement; private rowHeaderElement: HTMLElement; private scrollContainerElement: HTMLElement; /* * This value is set to `true` when all cells finish mounting for the first * time. It serves as a signal that we can switch to batch rendering. */ private didCompletelyMount = false; public constructor(props: TableProps, context?: any) { super(props, context); const { children, columnWidths, defaultRowHeight, defaultColumnWidth, numRows, rowHeights } = this.props; const childrenArray = React.Children.toArray(children) as Array<React.ReactElement<IColumnProps>>; const columnIdToIndex = Table.createColumnIdIndex(childrenArray); // Create height/width arrays using the lengths from props and // children, the default values from props, and finally any sparse // arrays passed into props. let newColumnWidths = childrenArray.map(() => defaultColumnWidth); newColumnWidths = Utils.assignSparseValues(newColumnWidths, columnWidths); let newRowHeights = Utils.times(numRows, () => defaultRowHeight); newRowHeights = Utils.assignSparseValues(newRowHeights, rowHeights); const selectedRegions = props.selectedRegions == null ? ([] as IRegion[]) : props.selectedRegions; const focusedCell = FocusedCellUtils.getInitialFocusedCell( props.enableFocusedCell, props.focusedCell, undefined, selectedRegions, ); this.state = { childrenArray, columnIdToIndex, columnWidths: newColumnWidths, focusedCell, isLayoutLocked: false, isReordering: false, numFrozenColumnsClamped: clampNumFrozenColumns(props), numFrozenRowsClamped: clampNumFrozenRows(props), rowHeights: newRowHeights, selectedRegions, }; this.hotkeysImpl = new TableHotkeys(props, this.state, this.grid, { getEnabledSelectionHandler: this.getEnabledSelectionHandler, handleFocus: this.handleFocus, handleSelection: this.handleSelection, syncViewportPosition: this.syncViewportPosition, }); } // Instance methods // ================ /** * __Experimental!__ Resizes all rows in the table to the approximate * maximum height of wrapped cell content in each row. Works best when each * cell contains plain text of a consistent font style (though font style * may vary between cells). Since this function uses approximate * measurements, results may not be perfect. * * Approximation parameters can be configured for the entire table or on a * per-cell basis. Default values are fine-tuned to work well with default * Table font styles. */ public resizeRowsByApproximateHeight( getCellText: ICellMapper<string>, options?: IResizeRowsByApproximateHeightOptions, ) { const rowHeights = resizeRowsByApproximateHeight( this.props.numRows, this.state.columnWidths, getCellText, options, ); this.invalidateGrid(); this.setState({ rowHeights }); } /** * Resize all rows in the table to the height of the tallest visible cell in the specified columns. * If no indices are provided, default to using the tallest visible cell from all columns in view. */ public resizeRowsByTallestCell(columnIndices?: number | number[]) { const rowHeights = resizeRowsByTallestCell( this.grid, this.state.viewportRect, this.locator, this.state.rowHeights.length, columnIndices, ); this.invalidateGrid(); this.setState({ rowHeights }); } /** * Scrolls the table to the target region in a fashion appropriate to the target region's * cardinality: * * - CELLS: Scroll the top-left cell in the target region to the top-left corner of the viewport. * - FULL_ROWS: Scroll the top-most row in the target region to the top of the viewport. * - FULL_COLUMNS: Scroll the left-most column in the target region to the left side of the viewport. * - FULL_TABLE: Scroll the top-left cell in the table to the top-left corner of the viewport. * * If there are active frozen rows and/or columns, the target region will be positioned in the * top-left corner of the non-frozen area (unless the target region itself is in the frozen * area). * * If the target region is close to the bottom-right corner of the table, this function will * simply scroll the target region as close to the top-left as possible until the bottom-right * corner is reached. */ public scrollToRegion(region: IRegion) { const { numFrozenColumnsClamped: numFrozenColumns, numFrozenRowsClamped: numFrozenRows } = this.state; const { left: currScrollLeft, top: currScrollTop } = this.state.viewportRect; const { scrollLeft, scrollTop } = ScrollUtils.getScrollPositionForRegion( region, currScrollLeft, currScrollTop, this.grid.getCumulativeWidthBefore, this.grid.getCumulativeHeightBefore, numFrozenRows, numFrozenColumns, ); const correctedScrollLeft = this.shouldDisableHorizontalScroll() ? 0 : scrollLeft; const correctedScrollTop = this.shouldDisableVerticalScroll() ? 0 : scrollTop; // defer to the quadrant stack to keep all quadrant positions in sync this.quadrantStackInstance.scrollToPosition(correctedScrollLeft, correctedScrollTop); } // React lifecycle // =============== public getChildContext(): IColumnInteractionBarContextTypes { return { enableColumnInteractionBar: this.props.enableColumnInteractionBar, }; } public shouldComponentUpdate(nextProps: TableProps, nextState: TableState) { const propKeysDenylist = { exclude: Table.SHALLOW_COMPARE_PROP_KEYS_DENYLIST }; const stateKeysDenylist = { exclude: Table.SHALLOW_COMPARE_STATE_KEYS_DENYLIST }; return ( !CoreUtils.shallowCompareKeys(this.props, nextProps, propKeysDenylist) || !CoreUtils.shallowCompareKeys(this.state, nextState, stateKeysDenylist) || !CoreUtils.deepCompareKeys(this.props, nextProps, Table.SHALLOW_COMPARE_PROP_KEYS_DENYLIST) || !CoreUtils.deepCompareKeys(this.state, nextState, Table.SHALLOW_COMPARE_STATE_KEYS_DENYLIST) ); } public render() { const { children, className, enableRowHeader, loadingOptions, numRows, enableColumnInteractionBar, } = this.props; const { horizontalGuides, numFrozenColumnsClamped, numFrozenRowsClamped, verticalGuides } = this.state; if (!this.gridDimensionsMatchProps()) { // Ensure we're rendering the correct number of rows & columns this.invalidateGrid(); } this.validateGrid(); const classes = classNames( Classes.TABLE_CONTAINER, { [Classes.TABLE_REORDERING]: this.state.isReordering, [Classes.TABLE_NO_VERTICAL_SCROLL]: this.shouldDisableVerticalScroll(), [Classes.TABLE_NO_HORIZONTAL_SCROLL]: this.shouldDisableHorizontalScroll(), [Classes.TABLE_SELECTION_ENABLED]: Table.isSelectionModeEnabled(this.props, RegionCardinality.CELLS), [Classes.TABLE_NO_ROWS]: numRows === 0, }, className, ); return ( <div className={classes} ref={this.refHandlers.rootTable} onScroll={this.handleRootScroll}> <TableQuadrantStack bodyRef={this.refHandlers.cellContainer} bodyRenderer={this.renderBody} columnHeaderCellRenderer={this.renderColumnHeader} columnHeaderRef={this.refHandlers.columnHeader} enableColumnInteractionBar={enableColumnInteractionBar} enableRowHeader={enableRowHeader} grid={this.grid} handleColumnResizeGuide={this.handleColumnResizeGuide} handleColumnsReordering={this.handleColumnsReordering} handleRowResizeGuide={this.handleRowResizeGuide} handleRowsReordering={this.handleRowsReordering} isHorizontalScrollDisabled={this.shouldDisableHorizontalScroll()} isVerticalScrollDisabled={this.shouldDisableVerticalScroll()} loadingOptions={loadingOptions} numColumns={React.Children.count(children)} numFrozenColumns={numFrozenColumnsClamped} numFrozenRows={numFrozenRowsClamped} numRows={numRows} onScroll={this.handleBodyScroll} ref={this.refHandlers.quadrantStack} menuRenderer={this.renderMenu} rowHeaderCellRenderer={this.renderRowHeader} rowHeaderRef={this.refHandlers.rowHeader} scrollContainerRef={this.refHandlers.scrollContainer} /> <div className={classNames(Classes.TABLE_OVERLAY_LAYER, Classes.TABLE_OVERLAY_REORDERING_CURSOR)} /> <GuideLayer className={Classes.TABLE_RESIZE_GUIDES} verticalGuides={verticalGuides} horizontalGuides={horizontalGuides} /> </div> ); } public renderHotkeys() { const hotkeys = [ this.maybeRenderCopyHotkey(), this.maybeRenderSelectAllHotkey(), this.maybeRenderFocusHotkeys(), this.maybeRenderSelectionResizeHotkeys(), ]; return <Hotkeys>{hotkeys.filter(element => element !== undefined)}</Hotkeys>; } /** * When the component mounts, the HTML Element refs will be available, so * we constructor the Locator, which queries the elements' bounding * ClientRects. */ public componentDidMount() { this.validateGrid(); this.locator = new Locator(this.rootTableElement, this.scrollContainerElement, this.cellContainerElement); this.updateLocator(); this.updateViewportRect(this.locator.getViewportRect()); this.resizeSensorDetach = ResizeSensor.attach(this.rootTableElement, () => { if (!this.state.isLayoutLocked) { this.updateViewportRect(this.locator.getViewportRect()); } }); } public componentWillUnmount() { if (this.resizeSensorDetach != null) { this.resizeSensorDetach(); delete this.resizeSensorDetach; } this.didCompletelyMount = false; } public getSnapshotBeforeUpdate() { const { viewportRect } = this.state; this.validateGrid(); const tableBottom = this.grid.getCumulativeHeightAt(this.grid.numRows - 1); const tableRight = this.grid.getCumulativeWidthAt(this.grid.numCols - 1); const nextScrollTop = tableBottom < viewportRect.top + viewportRect.height ? // scroll the last row into view Math.max(0, tableBottom - viewportRect.height) : undefined; const nextScrollLeft = tableRight < viewportRect.left + viewportRect.width ? // scroll the last column into view Math.max(0, tableRight - viewportRect.width) : undefined; // these will only be defined if they differ from viewportRect return { nextScrollLeft, nextScrollTop }; } public componentDidUpdate(prevProps: TableProps, prevState: TableState, snapshot: TableSnapshot) { super.componentDidUpdate(prevProps, prevState, snapshot); this.hotkeysImpl.setState(this.state); this.hotkeysImpl.setProps(this.props); const didChildrenChange = (React.Children.toArray(this.props.children) as Array<React.ReactElement<IColumnProps>>) !== this.state.childrenArray; const shouldInvalidateGrid = didChildrenChange || this.props.columnWidths !== prevState.columnWidths || this.props.rowHeights !== prevState.rowHeights || this.props.numRows !== prevProps.numRows || (this.props.forceRerenderOnSelectionChange && this.props.selectedRegions !== prevProps.selectedRegions); if (shouldInvalidateGrid) { this.invalidateGrid(); } if (this.locator != null) { this.validateGrid(); this.updateLocator(); } // When true, we'll need to imperatively synchronize quadrant views after // the update. This check lets us avoid expensively diff'ing columnWidths // and rowHeights in <TableQuadrantStack> on each update. const didUpdateColumnOrRowSizes = !CoreUtils.arraysEqual(this.state.columnWidths, prevState.columnWidths) || !CoreUtils.arraysEqual(this.state.rowHeights, prevState.rowHeights); if (didUpdateColumnOrRowSizes) { this.quadrantStackInstance.synchronizeQuadrantViews(); this.syncViewportPosition(snapshot); } } protected validateProps(props: TableProps) { const { children, columnWidths, numFrozenColumns, numFrozenRows, numRows, rowHeights } = props; const numColumns = React.Children.count(children); // do cheap error-checking first. if (numRows != null && numRows < 0) { throw new Error(Errors.TABLE_NUM_ROWS_NEGATIVE); } if (numFrozenRows != null && numFrozenRows < 0) { throw new Error(Errors.TABLE_NUM_FROZEN_ROWS_NEGATIVE); } if (numFrozenColumns != null && numFrozenColumns < 0) { throw new Error(Errors.TABLE_NUM_FROZEN_COLUMNS_NEGATIVE); } if (numRows != null && rowHeights != null && rowHeights.length !== numRows) { throw new Error(Errors.TABLE_NUM_ROWS_ROW_HEIGHTS_MISMATCH); } if (numColumns != null && columnWidths != null && columnWidths.length !== numColumns) { throw new Error(Errors.TABLE_NUM_COLUMNS_COLUMN_WIDTHS_MISMATCH); } React.Children.forEach(children, child => { if (!CoreUtils.isElementOfType(child, Column)) { throw new Error(Errors.TABLE_NON_COLUMN_CHILDREN_WARNING); } }); // these are recoverable scenarios, so just print a warning. if (numFrozenRows != null && numRows != null && numFrozenRows > numRows) { console.warn(Errors.TABLE_NUM_FROZEN_ROWS_BOUND_WARNING); } if (numFrozenColumns != null && numFrozenColumns > numColumns) { console.warn(Errors.TABLE_NUM_FROZEN_COLUMNS_BOUND_WARNING); } } private gridDimensionsMatchProps() { const { children, numRows } = this.props; return ( this.grid != null && this.grid.numCols === React.Children.count(children) && this.grid.numRows === numRows ); } // Hotkeys // ======= private maybeRenderCopyHotkey() { const { getCellClipboardData } = this.props; if (getCellClipboardData != null) { return ( <Hotkey key="copy-hotkey" label="Copy selected table cells" group="Table" combo="mod+c" onKeyDown={this.hotkeysImpl.handleCopy} /> ); } else { return undefined; } } private maybeRenderSelectionResizeHotkeys() { const { enableMultipleSelection, selectionModes } = this.props; const isSomeSelectionModeEnabled = selectionModes.length > 0; if (enableMultipleSelection && isSomeSelectionModeEnabled) { return [ <Hotkey key="resize-selection-up" label="Resize selection upward" group="Table" combo="shift+up" onKeyDown={this.hotkeysImpl.handleSelectionResizeUp} />, <Hotkey key="resize-selection-down" label="Resize selection downward" group="Table" combo="shift+down" onKeyDown={this.hotkeysImpl.handleSelectionResizeDown} />, <Hotkey key="resize-selection-left" label="Resize selection leftward" group="Table" combo="shift+left" onKeyDown={this.hotkeysImpl.handleSelectionResizeLeft} />, <Hotkey key="resize-selection-right" label="Resize selection rightward" group="Table" combo="shift+right" onKeyDown={this.hotkeysImpl.handleSelectionResizeRight} />, ]; } else { return undefined; } } private maybeRenderFocusHotkeys() { const { enableFocusedCell } = this.props; if (enableFocusedCell != null) { return [ <Hotkey key="move left" label="Move focus cell left" group="Table" combo="left" onKeyDown={this.hotkeysImpl.handleFocusMoveLeft} />, <Hotkey key="move right" label="Move focus cell right" group="Table" combo="right" onKeyDown={this.hotkeysImpl.handleFocusMoveRight} />, <Hotkey key="move up" label="Move focus cell up" group="Table" combo="up" onKeyDown={this.hotkeysImpl.handleFocusMoveUp} />, <Hotkey key="move down" label="Move focus cell down" group="Table" combo="down" onKeyDown={this.hotkeysImpl.handleFocusMoveDown} />, <Hotkey key="move tab" label="Move focus cell tab" group="Table" combo="tab" onKeyDown={this.hotkeysImpl.handleFocusMoveRightInternal} allowInInput={true} />, <Hotkey key="move shift-tab" label="Move focus cell shift tab" group="Table" combo="shift+tab" onKeyDown={this.hotkeysImpl.handleFocusMoveLeftInternal} allowInInput={true} />, <Hotkey key="move enter" label="Move focus cell enter" group="Table" combo="enter" onKeyDown={this.hotkeysImpl.handleFocusMoveDownInternal} allowInInput={true} />, <Hotkey key="move shift-enter" label="Move focus cell shift enter" group="Table" combo="shift+enter" onKeyDown={this.hotkeysImpl.handleFocusMoveUpInternal} allowInInput={true} />, ]; } else { return []; } } private maybeRenderSelectAllHotkey() { if (Table.isSelectionModeEnabled(this.props, RegionCardinality.FULL_TABLE)) { return ( <Hotkey key="select-all-hotkey" label="Select all" group="Table" combo="mod+a" onKeyDown={this.hotkeysImpl.handleSelectAllHotkey} /> ); } else { return undefined; } } // Quadrant refs // ============= private shouldDisableVerticalScroll() { const { enableGhostCells } = this.props; const { viewportRect } = this.state; const rowIndices = this.grid.getRowIndicesInRect(viewportRect, enableGhostCells); const isViewportUnscrolledVertically = viewportRect != null && viewportRect.top === 0; const areRowHeadersLoading = hasLoadingOption(this.props.loadingOptions, TableLoadingOption.ROW_HEADERS); const areGhostRowsVisible = enableGhostCells && this.grid.isGhostIndex(rowIndices.rowIndexEnd, 0); return areGhostRowsVisible && (isViewportUnscrolledVertically || areRowHeadersLoading); } private shouldDisableHorizontalScroll() { const { enableGhostCells } = this.props; const { viewportRect } = this.state; const columnIndices = this.grid.getColumnIndicesInRect(viewportRect, enableGhostCells); const isViewportUnscrolledHorizontally = viewportRect != null && viewportRect.left === 0; const areGhostColumnsVisible = enableGhostCells && this.grid.isGhostColumn(columnIndices.columnIndexEnd); const areColumnHeadersLoading = hasLoadingOption(this.props.loadingOptions, TableLoadingOption.COLUMN_HEADERS); return areGhostColumnsVisible && (isViewportUnscrolledHorizontally || areColumnHeadersLoading); } private renderMenu = (refHandler: IRef<HTMLDivElement>) => { const classes = classNames(Classes.TABLE_MENU, { [Classes.TABLE_SELECTION_ENABLED]: Table.isSelectionModeEnabled(this.props, RegionCardinality.FULL_TABLE), }); return ( <div className={classes} ref={refHandler} onMouseDown={this.handleMenuMouseDown}> {this.maybeRenderRegions(this.styleMenuRegion)} </div> ); }; private handleMenuMouseDown = (e: React.MouseEvent<HTMLDivElement>) => { // the shift+click interaction expands the region from the focused cell. // thus, if shift is pressed we shouldn't move the focused cell. this.selectAll(!e.shiftKey); }; private selectAll = (shouldUpdateFocusedCell: boolean) => { const selectionHandler = this.getEnabledSelectionHandler(RegionCardinality.FULL_TABLE); // clicking on upper left hand corner sets selection to "all" // regardless of current selection state (clicking twice does not deselect table) selectionHandler([Regions.table()]); if (shouldUpdateFocusedCell) { const newFocusedCellCoordinates = Regions.getFocusCellCoordinatesFromRegion(Regions.table()); this.handleFocus(FocusedCellUtils.toFullCoordinates(newFocusedCellCoordinates)); } }; private getColumnProps(columnIndex: number) { const column = this.state.childrenArray[columnIndex] as React.ReactElement<IColumnProps>; return column === undefined ? undefined : column.props; } private columnHeaderCellRenderer = (columnIndex: number) => { const props = this.getColumnProps(columnIndex); if (props === undefined) { return null; } const { id, loadingOptions, cellRenderer, columnHeaderCellRenderer, ...spreadableProps } = props; const columnLoading = hasLoadingOption(loadingOptions, ColumnLoadingOption.HEADER); if (columnHeaderCellRenderer != null) { const columnHeaderCell = columnHeaderCellRenderer(columnIndex); const columnHeaderCellLoading = columnHeaderCell.props.loading; const columnHeaderCellProps: IColumnHeaderCellProps = { loading: columnHeaderCellLoading != null ? columnHeaderCellLoading : columnLoading, }; return React.cloneElement(columnHeaderCell, columnHeaderCellProps); } const baseProps: IColumnHeaderCellProps = { index: columnIndex, loading: columnLoading, ...spreadableProps, }; if (props.name != null) { return <ColumnHeaderCell {...baseProps} />; } else { return <ColumnHeaderCell {...baseProps} name={Utils.toBase26Alpha(columnIndex)} />; } }; private renderColumnHeader = ( refHandler: IRef<HTMLDivElement>, resizeHandler: (verticalGuides: number[]) => void, reorderingHandler: (oldIndex: number, newIndex: number, length: number) => void, showFrozenColumnsOnly: boolean = false, ) => { const { focusedCell, selectedRegions, viewportRect } = this.state; const { enableMultipleSelection, enableGhostCells, enableColumnReordering, enableColumnResizing, loadingOptions, maxColumnWidth, minColumnWidth, selectedRegionTransform, } = this.props; const classes = classNames(Classes.TABLE_COLUMN_HEADERS, { [Classes.TABLE_SELECTION_ENABLED]: Table.isSelectionModeEnabled(this.props, RegionCardinality.FULL_COLUMNS), }); const columnIndices = this.grid.getColumnIndicesInRect(viewportRect, enableGhostCells); const columnIndexStart = showFrozenColumnsOnly ? 0 : columnIndices.columnIndexStart; const columnIndexEnd = showFrozenColumnsOnly ? this.getMaxFrozenColumnIndex() : columnIndices.columnIndexEnd; return ( <div className={classes}> <ColumnHeader enableMultipleSelection={enableMultipleSelection} cellRenderer={this.columnHeaderCellRenderer} focusedCell={focusedCell} grid={this.grid} isReorderable={enableColumnReordering} isResizable={enableColumnResizing} loading={hasLoadingOption(loadingOptions, TableLoadingOption.COLUMN_HEADERS)} locator={this.locator} maxColumnWidth={maxColumnWidth} measurableElementRef={refHandler} minColumnWidth={minColumnWidth} onColumnWidthChanged={this.handleColumnWidthChanged} onFocusedCell={this.handleFocus} onLayoutLock={this.handleLayoutLock} onReordered={this.handleColumnsReordered} onReordering={reorderingHandler} onResizeGuide={resizeHandler} onSelection={this.getEnabledSelectionHandler(RegionCardinality.FULL_COLUMNS)} selectedRegions={selectedRegions} selectedRegionTransform={selectedRegionTransform} columnIndexStart={columnIndexStart} columnIndexEnd={columnIndexEnd} > {this.props.children} </ColumnHeader> {this.maybeRenderRegions(this.styleColumnHeaderRegion)} </div> ); }; private renderRowHeader = ( refHandler: IRef<HTMLDivElement>, resizeHandler: (verticalGuides: number[]) => void, reorderingHandler: (oldIndex: number, newIndex: number, length: number) => void, showFrozenRowsOnly: boolean = false, ) => { const { focusedCell, selectedRegions, viewportRect } = this.state; const { enableMultipleSelection, enableGhostCells, enableRowReordering, enableRowResizing, loadingOptions, maxRowHeight, minRowHeight, rowHeaderCellRenderer, selectedRegionTransform, } = this.props; const classes = classNames(Classes.TABLE_ROW_HEADERS, { [Classes.TABLE_SELECTION_ENABLED]: Table.isSelectionModeEnabled(this.props, RegionCardinality.FULL_ROWS), }); const rowIndices = this.grid.getRowIndicesInRect(viewportRect, enableGhostCells); const rowIndexStart = showFrozenRowsOnly ? 0 : rowIndices.rowIndexStart; const rowIndexEnd = showFrozenRowsOnly ? this.getMaxFrozenRowIndex() : rowIndices.rowIndexEnd; return ( <div className={classes} ref={refHandler}> <RowHeader enableMultipleSelection={enableMultipleSelection} focusedCell={focusedCell} grid={this.grid} locator={this.locator} isReorderable={enableRowReordering} isResizable={enableRowResizing} loading={hasLoadingOption(loadingOptions, TableLoadingOption.ROW_HEADERS)} maxRowHeight={maxRowHeight} minRowHeight={minRowHeight} onFocusedCell={this.handleFocus} onLayoutLock={this.handleLayoutLock} onResizeGuide={resizeHandler} onReordered={this.handleRowsReordered} onReordering={reorderingHandler} onRowHeightChanged={this.handleRowHeightChanged} onSelection={this.getEnabledSelectionHandler(RegionCardinality.FULL_ROWS)} rowHeaderCellRenderer={rowHeaderCellRenderer} selectedRegions={selectedRegions} selectedRegionTransform={selectedRegionTransform} rowIndexStart={rowIndexStart} rowIndexEnd={rowIndexEnd} /> {this.maybeRenderRegions(this.styleRowHeaderRegion)} </div> ); }; private bodyCellRenderer = (rowIndex: number, columnIndex: number) => { const columnProps = this.getColumnProps(columnIndex); if (columnProps === undefined) { return null; } const { id, loadingOptions, cellRenderer, columnHeaderCellRenderer, name, nameRenderer, ...restColumnProps } = columnProps; const cell = cellRenderer(rowIndex, columnIndex); const { loading = hasLoadingOption(loadingOptions, ColumnLoadingOption.CELLS) } = cell.props; const cellProps: ICellProps = { ...restColumnProps, loading, }; return React.cloneElement(cell, cellProps); }; private renderBody = ( quadrantType: QuadrantType, showFrozenRowsOnly: boolean = false, showFrozenColumnsOnly: boolean = false, ) => { const { focusedCell, numFrozenColumnsClamped: numFrozenColumns, numFrozenRowsClamped: numFrozenRows, selectedRegions, viewportRect, } = this.state; const { enableMultipleSelection, enableGhostCells, loadingOptions, bodyContextMenuRenderer, selectedRegionTransform, } = this.props; const rowIndices = this.grid.getRowIndicesInRect(viewportRect, enableGhostCells); const columnIndices = this.grid.getColumnIndicesInRect(viewportRect, enableGhostCells); // start beyond the frozen area if rendering unrelated quadrants, so we // don't render duplicate cells underneath the frozen ones. const columnIndexStart = showFrozenColumnsOnly ? 0 : columnIndices.columnIndexStart + numFrozenColumns; const rowIndexStart = showFrozenRowsOnly ? 0 : rowIndices.rowIndexStart + numFrozenRows; // if rendering frozen rows/columns, subtract one to convert to // 0-indexing. if the 1-indexed value is 0, this sets the end index // to -1, which avoids rendering absent frozen rows/columns at all. const columnIndexEnd = showFrozenColumnsOnly ? numFrozenColumns - 1 : columnIndices.columnIndexEnd; const rowIndexEnd = showFrozenRowsOnly ? numFrozenRows - 1 : rowIndices.rowIndexEnd; // the main quadrant contains all cells in the table, so listen only to that quadrant const onCompleteRender = quadrantType === QuadrantType.MAIN ? this.handleCompleteRender : undefined; return ( <div> <TableBody enableMultipleSelection={enableMultipleSelection} cellRenderer={this.bodyCellRenderer} focusedCell={focusedCell} grid={this.grid} loading={hasLoadingOption(loadingOptions, TableLoadingOption.CELLS)} locator={this.locator} onCompleteRender={onCompleteRender} onFocusedCell={this.handleFocus} onSelection={this.getEnabledSelectionHandler(RegionCardinality.CELLS)} bodyContextMenuRenderer={bodyContextMenuRenderer} renderMode={this.getNormalizedRenderMode()} selectedRegions={selectedRegions} selectedRegionTransform={selectedRegionTransform} viewportRect={viewportRect} columnIndexStart={columnIndexStart} columnIndexEnd={columnIndexEnd} rowIndexStart={rowIndexStart} rowIndexEnd={rowIndexEnd} numFrozenColumns={showFrozenColumnsOnly ? numFrozenColumns : undefined} numFrozenRows={showFrozenRowsOnly ? numFrozenRows : undefined} /> {this.maybeRenderRegions(this.styleBodyRegion, quadrantType)} </div> ); }; private isGuidesShowing() { return this.state.verticalGuides != null || this.state.horizontalGuides != null; } private getEnabledSelectionHandler = (selectionMode: RegionCardinality) => { if (!Table.isSelectionModeEnabled(this.props, selectionMode)) { // If the selection mode isn't enabled, return a callback that // will clear the selection. For example, if row selection is // disabled, clicking on the row header will clear the table's // selection. If all selection modes are enabled, clicking on the // same region twice will clear the selection. return this.clearSelection; } else { return this.handleSelection; } }; private invalidateGrid() { this.grid = null; } private validateGrid() { if (this.grid == null) { const { defaultRowHeight, defaultColumnWidth } = this.props; const { rowHeights, columnWidths } = this.state; this.grid = new Grid(rowHeights, columnWidths, Grid.DEFAULT_BLEED, defaultRowHeight, defaultColumnWidth); this.invokeOnVisibleCellsChangeCallback(this.state.viewportRect); this.hotkeysImpl.setGrid(this.grid); } } /** * Renders a `RegionLayer`, applying styles to the regions using the * supplied `RegionStyler`. `RegionLayer` is a `PureRender` component, so * the `RegionStyler` should be a new instance on every render if we * intend to redraw the region layer. */ private maybeRenderRegions(getRegionStyle: RegionStyler, quadrantType?: QuadrantType) { if (this.isGuidesShowing() && !this.state.isReordering) { // we want to show guides *and* the selection styles when reordering rows or columns return undefined; } const regionGroups = Regions.joinStyledRegionGroups( this.state.selectedRegions, this.props.styledRegionGroups, this.state.focusedCell, ); return regionGroups.map((regionGroup, index) => { const regionStyles = regionGroup.regions.map(region => getRegionStyle(region, quadrantType)); return ( <RegionLayer className={classNames(regionGroup.className)} key={index} regions={regionGroup.regions} regionStyles={regionStyles} /> ); }); } private handleCompleteRender = () => { // the first onCompleteRender is triggered before the viewportRect is // defined and the second after the viewportRect has been set. the cells // will only actually render once the viewportRect is defined though, so // we defer invoking onCompleteRender until that check passes. if (this.state.viewportRect != null) { this.props.onCompleteRender?.(); this.didCompletelyMount = true; } }; private styleBodyRegion = (region: IRegion, quadrantType: QuadrantType): React.CSSProperties => { const { numFrozenColumns } = this.props; const cardinality = Regions.getRegionCardinality(region); const style = this.grid.getRegionStyle(region); // ensure we're not showing borders at the boundary of the frozen-columns area const canHideRightBorder = (quadrantType === QuadrantType.TOP_LEFT || quadrantType === QuadrantType.LEFT) && numFrozenColumns != null && numFrozenColumns > 0; const fixedHeight = this.grid.getHeight(); const fixedWidth = this.grid.getWidth(); // include a correction in some cases to hide borders along quadrant boundaries const alignmentCorrection = 1; const alignmentCorrectionString = `-${alignmentCorrection}px`; switch (cardinality) { case RegionCardinality.CELLS: return style; case RegionCardinality.FULL_COLUMNS: style.top = alignmentCorrectionString; style.height = fixedHeight + alignmentCorrection; return style; case RegionCardinality.FULL_ROWS: style.left = alignmentCorrectionString; style.width = fixedWidth + alignmentCorrection; if (canHideRightBorder) { style.right = alignmentCorrectionString; } return style; case RegionCardinality.FULL_TABLE: style.left = alignmentCorrectionString; style.top = alignmentCorrectionString; style.width = fixedWidth + alignmentCorrection; style.height = fixedHeight + alignmentCorrection; if (canHideRightBorder) { style.right = alignmentCorrectionString; } return style; default: return { display: "none" }; } }; private styleMenuRegion = (region: IRegion): React.CSSProperties => { const { viewportRect } = this.state; if (viewportRect == null) { return {}; } const cardinality = Regions.getRegionCardinality(region); const style = this.grid.getRegionStyle(region); switch (cardinality) { case RegionCardinality.FULL_TABLE: style.right = "0px"; style.bottom = "0px"; style.top = "0px"; style.left = "0px"; style.borderBottom = "none"; style.borderRight = "none"; return style; default: return { display: "none" }; } }; private styleColumnHeaderRegion = (region: IRegion): React.CSSProperties => { const { viewportRect } = this.state; if (viewportRect == null) { return {}; } const cardinality = Regions.getRegionCardinality(region); const style = this.grid.getRegionStyle(region); switch (cardinality) { case RegionCardinality.FULL_TABLE: style.left = "-1px"; style.borderLeft = "none"; style.bottom = "-1px"; return style; case RegionCardinality.FULL_COLUMNS: style.bottom = "-1px"; return style; default: return { display: "none" }; } }; private styleRowHeaderRegion = (region: IRegion): React.CSSProperties => { const { viewportRect } = this.state; if (viewportRect == null) { return {}; } const cardinality = Regions.getRegionCardinality(region); const style = this.grid.getRegionStyle(region); switch (cardinality) { case RegionCardinality.FULL_TABLE: style.top = "-1px"; style.borderTop = "none"; style.right = "-1px"; return style; case RegionCardinality.FULL_ROWS: style.right = "-1px"; return style; default: return { display: "none" }; } }; private handleColumnWidthChanged = (columnIndex: number, width: number) => { const selectedRegions = this.state.selectedRegions; const columnWidths = this.state.columnWidths.slice(); if (Regions.hasFullTable(selectedRegions)) { for (let col = 0; col < columnWidths.length; col++) { columnWidths[col] = width; } } if (Regions.hasFullColumn(selectedRegions, columnIndex)) { Regions.eachUniqueFullColumn(selectedRegions, (col: number) => { columnWidths[col] = width; }); } else { columnWidths[columnIndex] = width; } this.invalidateGrid(); this.setState({ columnWidths }); const { onColumnWidthChanged } = this.props; if (onColumnWidthChanged != null) { onColumnWidthChanged(columnIndex, width); } }; private handleRowHeightChanged = (rowIndex: number, height: number) => { const selectedRegions = this.state.selectedRegions; const rowHeights = this.state.rowHeights.slice(); if (Regions.hasFullTable(selectedRegions)) { for (let row = 0; row < rowHeights.length; row++) { rowHeights[row] = height; } } if (Regions.hasFullRow(selectedRegions, rowIndex)) { Regions.eachUniqueFullRow(selectedRegions, (row: number) => { rowHeights[row] = height; }); } else { rowHeights[rowIndex] = height; } this.invalidateGrid(); this.setState({ rowHeights }); const { onRowHeightChanged } = this.props; if (onRowHeightChanged != null) { onRowHeightChanged(rowIndex, height); } }; private handleRootScroll = (_event: React.UIEvent<HTMLElement>) => { // Bug #211 - Native browser text selection events can cause the root // element to scroll even though it has a overflow:hidden style. The // only viable solution to this is to unscroll the element after the // browser scrolls it. if (this.rootTableElement != null) { this.rootTableElement.scrollLeft = 0; this.rootTableElement.scrollTop = 0; } }; private handleBodyScroll = (event: React.SyntheticEvent<HTMLElement>) => { // Prevent the event from propagating to avoid a resize event on the // resize sensor. event.stopPropagation(); if (this.locator != null && !this.state.isLayoutLocked) { const viewportRect = this.locator.getViewportRect(); this.updateViewportRect(viewportRect); } }; private clearSelection = (_selectedRegions: IRegion[]) => { this.handleSelection([]); }; private syncViewportPosition = ({ nextScrollLeft, nextScrollTop }: TableSnapshot) => { const { viewportRect } = this.state; if (nextScrollLeft !== undefined || nextScrollTop !== undefined) { // we need to modify the scroll container explicitly for the viewport to shift. in so // doing, we add the size of the header elements, which are not technically part of the // "grid" concept (the grid only consists of body cells at present). if (nextScrollTop !== undefined) { const topCorrection = this.shouldDisableVerticalScroll() ? 0 : this.columnHeaderElement.clientHeight; this.scrollContainerElement.scrollTop = nextScrollTop + topCorrection; } if (nextScrollLeft !== undefined) { const leftCorrection = this.shouldDisableHorizontalScroll() || this.rowHeaderElement == null ? 0 : this.rowHeaderElement.clientWidth; this.scrollContainerElement.scrollLeft = nextScrollLeft + leftCorrection; } const nextViewportRect = new Rect(nextScrollLeft, nextScrollTop, viewportRect.width, viewportRect.height); this.updateViewportRect(nextViewportRect); } }; private handleFocus = (focusedCell: IFocusedCellCoordinates) => { if (!this.props.enableFocusedCell) { // don't set focus state if focus is not allowed return; } // only set focused cell state if not specified in props if (this.props.focusedCell == null) { this.setState({ focusedCell }); } this.props.onFocusedCell?.(focusedCell); }; private handleSelection = (selectedRegions: IRegion[]) => { // only set selectedRegions state if not specified in props if (this.props.selectedRegions == null) { this.setState({ selectedRegions }); } const { onSelection } = this.props; if (onSelection != null) { onSelection(selectedRegions); } }; private handleColumnsReordering = (verticalGuides: number[]) => { this.setState({ isReordering: true, verticalGuides }); }; private handleColumnsReordered = (oldIndex: number, newIndex: number, length: number) => { this.setState({ isReordering: false, verticalGuides: undefined }); this.props.onColumnsReordered?.(oldIndex, newIndex, length); }; private handleRowsReordering = (horizontalGuides: number[]) => { this.setState({ isReordering: true, horizontalGuides }); }; private handleRowsReordered = (oldIndex: number, newIndex: number, length: number) => { this.setState({ isReordering: false, horizontalGuides: undefined }); this.props.onRowsReordered?.(oldIndex, newIndex, length); }; private handleLayoutLock = (isLayoutLocked = false) => { this.setState({ isLayoutLocked }); }; private updateLocator() { this.locator .setGrid(this.grid) .setNumFrozenRows(this.state.numFrozenRowsClamped) .setNumFrozenColumns(this.state.numFrozenColumnsClamped); } private updateViewportRect = (nextViewportRect: Rect) => { const { viewportRect } = this.state; this.setState({ viewportRect: nextViewportRect }); const didViewportChange = (viewportRect != null && !viewportRect.equals(nextViewportRect)) || (viewportRect == null && nextViewportRect != null); if (didViewportChange) { this.invokeOnVisibleCellsChangeCallback(nextViewportRect); } }; private invokeOnVisibleCellsChangeCallback(viewportRect: Rect) { const columnIndices = this.grid.getColumnIndicesInRect(viewportRect); const rowIndices = this.grid.getRowIndicesInRect(viewportRect); this.props.onVisibleCellsChange?.(rowIndices, columnIndices); } private getMaxFrozenColumnIndex = () => { const { numFrozenColumnsClamped: numFrozenColumns } = this.state; return numFrozenColumns != null ? numFrozenColumns - 1 : undefined; }; private getMaxFrozenRowIndex = () => { const { numFrozenRowsClamped: numFrozenRows } = this.state; return numFrozenRows != null ? numFrozenRows - 1 : undefined; }; /** * Normalizes RenderMode.BATCH_ON_UPDATE into RenderMode.{BATCH,NONE}. We do * this because there are actually multiple updates required before the * <Table> is considered fully "mounted," and adding that knowledge to child * components would lead to tight coupling. Thus, keep it simple for them. */ private getNormalizedRenderMode(): RenderMode.BATCH | RenderMode.NONE { const { renderMode } = this.props; const shouldBatchRender = renderMode === RenderMode.BATCH || (renderMode === RenderMode.BATCH_ON_UPDATE && this.didCompletelyMount); return shouldBatchRender ? RenderMode.BATCH : RenderMode.NONE; } private handleColumnResizeGuide = (verticalGuides: number[]) => { this.setState({ verticalGuides }); }; private handleRowResizeGuide = (horizontalGuides: number[]) => { this.setState({ horizontalGuides }); }; }
the_stack
import { EditorState, NodeSelection, Selection, TextSelection, Transaction, } from 'prosemirror-state'; import { wrapIn as wrapInPM, setBlockType as setBlockTypePM, toggleMark as toggleMarkPM, selectParentNode, } from 'prosemirror-commands'; import { wrapInList as wrapInListPM, liftListItem } from 'prosemirror-schema-list'; import { MarkType, NodeType, Node, Fragment, Schema, NodeRange } from 'prosemirror-model'; import { Nodes, nodeNames, createId } from '@curvenote/schema'; import { replaceSelectedNode, selectParentNodeOfType, ContentNodeWithPos } from 'prosemirror-utils'; import { liftTarget } from 'prosemirror-transform'; import { dispatchCommentAction } from '../../prosemirror/plugins/comments'; import { AppThunk } from '../types'; import { getEditorState, getSelectedEditorAndViews, getEditorUI, selectionIsChildOf, getSelectedView, getEditorView, } from '../selectors'; import { focusEditorView, focusSelectedEditorView } from '../ui/actions'; import { applyProsemirrorTransaction } from '../state/actions'; import { getNodeIfSelected } from '../ui/utils'; export function updateNodeAttrs( stateKey: any, viewId: string | null, node: Pick<ContentNodeWithPos, 'node' | 'pos'>, attrs: { [index: string]: any }, select: boolean | 'after' | 'inside' = true, ): AppThunk<boolean> { return (dispatch, getState) => { const editorState = getEditorState(getState(), stateKey)?.state; if (editorState == null) return false; const tr = editorState.tr.setNodeMarkup(node.pos, undefined, { ...node.node.attrs, ...attrs }); if (select === true) tr.setSelection(NodeSelection.create(tr.doc, node.pos)); if (select === 'after') { const sel = TextSelection.create(tr.doc, node.pos + node.node.nodeSize); tr.setSelection(sel); } if (select === 'inside') { const sel = TextSelection.create(tr.doc, node.pos + 1); tr.setSelection(sel); } const result = dispatch(applyProsemirrorTransaction(stateKey, viewId, tr, Boolean(select))); return result; }; } export function deleteNode( stateKey: any, viewId: string | null, node: Pick<ContentNodeWithPos, 'node' | 'pos'>, ): AppThunk<boolean> { return (dispatch, getState) => { const editorState = getEditorState(getState(), stateKey)?.state; if (editorState == null) return false; const tr = editorState.tr.delete(node.pos, node.pos + node.node.nodeSize); const result = dispatch(applyProsemirrorTransaction(stateKey, viewId, tr)); if (result && viewId) dispatch(focusEditorView(viewId, true)); return result; }; } export function liftContentOutOfNode( stateKey: any, viewId: string | null, node: Pick<ContentNodeWithPos, 'node' | 'pos'>, ): AppThunk<boolean> { return (dispatch, getState) => { const editorState = getEditorState(getState(), stateKey)?.state; if (editorState == null) return false; const $from = editorState.doc.resolve(node.pos + 1); const $to = editorState.doc.resolve(node.pos + node.node.nodeSize - 1); const range = new NodeRange($from, $to, 1); const target = liftTarget(range); if (target == null) return false; const tr = editorState.tr.lift(range, target); const result = dispatch(applyProsemirrorTransaction(stateKey, viewId, tr)); if (result && viewId) dispatch(focusEditorView(viewId, true)); return result; }; } export function toggleMark( stateKey: any, viewId: string | null, mark?: MarkType, attrs?: { [key: string]: any }, ): AppThunk<boolean> { return (dispatch, getState) => { const editorState = getEditorState(getState(), stateKey)?.state; if (editorState == null || !mark) return false; const action = toggleMarkPM(mark, attrs); const result = action(editorState, (tr: Transaction) => dispatch(applyProsemirrorTransaction(stateKey, viewId, tr)), ); if (result) dispatch(focusEditorView(viewId, true)); return result; }; } export function removeMark( stateKey: any, viewId: string | null, mark: MarkType, from: number, to: number, ): AppThunk<boolean> { return (dispatch, getState) => { const editorState = getEditorState(getState(), stateKey)?.state; if (editorState == null || !mark) return false; const tr = editorState.tr.removeMark(from, to, mark); const result = dispatch(applyProsemirrorTransaction(stateKey, viewId, tr)); if (result) dispatch(focusEditorView(viewId, true)); return result; }; } export function wrapInList( stateKey: string, viewId: string | null, node: NodeType, test = false, ): AppThunk<boolean> { return (dispatch, getState) => { const editorState = getEditorState(getState(), stateKey)?.state; if (editorState == null) return false; const action = selectionIsChildOf(getState(), stateKey, { node }).node ? liftListItem(editorState.schema.nodes.list_item) : wrapInListPM(node); if (test) return action(editorState); const result = action(editorState, (tr: Transaction) => dispatch(applyProsemirrorTransaction(stateKey, viewId, tr)), ); if (result) dispatch(focusEditorView(viewId, true)); return result; }; } export function wrapIn(node: NodeType): AppThunk<boolean> { return (dispatch, getState) => { const editor = getSelectedEditorAndViews(getState()); if (editor.state == null || !editor.key) return false; const isList = node === editor.state.schema.nodes.ordered_list || node === editor.state.schema.nodes.bullet_list; if (isList) { const { viewId } = getEditorUI(getState()); return dispatch(wrapInList(editor.key, viewId, node)); } const action = wrapInPM(node); const result = action(editor.state, (tr: Transaction) => dispatch(applyProsemirrorTransaction(editor.key, editor.viewId, tr)), ); if (result) dispatch(focusSelectedEditorView(true)); return result; }; } function getContent(state: EditorState, content?: Node) { let nodeContent = content; if (!nodeContent && !state.selection.empty) { const { from, to } = state.selection; const text = state.doc.textBetween(from, to); nodeContent = state.schema.text(text); } return nodeContent; } export function selectNode(tr: Transaction, select: boolean | 'after' = true) { if (!select) return tr; const nodeSize = tr.selection.$anchor.nodeBefore?.nodeSize ?? 0; const resolvedPos = tr.doc.resolve(tr.selection.anchor - nodeSize); try { return tr.setSelection(new NodeSelection(resolvedPos)); } catch (error) { return tr; } } export function replaceSelection( node: NodeType, attrs?: { [index: string]: any }, content?: Node, ): AppThunk<boolean> { return (dispatch, getState) => { const editor = getSelectedEditorAndViews(getState()); if (editor.state == null) return false; const nodeContent = getContent(editor.state, content); const { nodes } = editor.state.schema; const selectParagraph = selectParentNodeOfType(nodes.paragraph); const replaceWithNode = replaceSelectedNode(node.create(attrs, nodeContent)); let tr = replaceWithNode(selectParagraph(editor.state.tr)); if (node.name === nodes.code_block.name) { const pos = tr.doc.resolve(tr.selection.from + 1); const sel = new Selection(pos, pos); tr = tr.setSelection(sel); } return dispatch(applyProsemirrorTransaction(editor.key, editor.viewId, tr)); }; } function setBlockType(node: NodeType, attrs?: { [index: string]: any }): AppThunk<boolean> { return (dispatch, getState) => { const editor = getSelectedEditorAndViews(getState()); if (editor.state == null) return false; const action = setBlockTypePM(node, attrs); const result = action(editor.state, (tr: Transaction) => dispatch(applyProsemirrorTransaction(editor.key, editor.viewId, tr)), ); if (result) dispatch(focusSelectedEditorView(true)); return result; }; } export function insertNode( node: NodeType, attrs?: { [index: string]: any }, content?: Node, ): AppThunk<boolean> { return (dispatch, getState) => { const editor = getSelectedEditorAndViews(getState()); if (editor.state == null) return false; const tr = editor.state.tr .insert(editor.state.tr.selection.$from.pos, node.create(attrs, content)) .scrollIntoView(); dispatch(applyProsemirrorTransaction(editor.key, editor.viewId, selectNode(tr))); return true; }; } export function insertInlineNode( node?: NodeType, attrs?: { [index: string]: any }, content?: Node, select: boolean | 'after' = true, ): AppThunk<boolean> { return (dispatch, getState) => { const editor = getSelectedEditorAndViews(getState()); if (editor.state == null || !node) return false; const nodeContent = getContent(editor.state, content); const tr = editor.state.tr .replaceSelectionWith(node.create(attrs, nodeContent), false) .scrollIntoView(); dispatch(applyProsemirrorTransaction(editor.key, editor.viewId, selectNode(tr, select))); // TODO: This should go in a better place, not passing the dom here, should be a better action // dispatch(setAttributeEditor(true)); return true; }; } export function insertText(text: string): AppThunk<boolean> { return (dispatch, getState) => { const editor = getSelectedEditorAndViews(getState()); if (editor.state == null) return false; const tr = editor.state.tr.insertText(text); dispatch(applyProsemirrorTransaction(editor.key, editor.viewId, tr)); return true; }; } export const wrapInHeading = (schema: Schema, level: number) => { if (level === 0) return setBlockType(schema.nodes.paragraph); return setBlockType(schema.nodes.heading, { level, id: createId() }); }; export const insertVariable = ( schema: Schema, attrs: Nodes.Variable.Attrs = { name: 'myVar', value: '0', valueFunction: '' }, ) => replaceSelection(schema.nodes.variable, attrs); export function addComment(viewId: string, commentId: string): AppThunk<boolean> { return (dispatch, getState) => { const { view } = getEditorView(getState(), viewId); if (!view) return false; dispatchCommentAction(view, { type: 'add', commentId }); return true; }; } export function removeComment(viewId: string, commentId: string): AppThunk<boolean> { return (dispatch, getState) => { const { view } = getEditorView(getState(), viewId); if (!view) return false; dispatchCommentAction(view, { type: 'remove', commentId }); return true; }; } export function addCommentToSelectedView(commentId: string): AppThunk<boolean> { return (dispatch, getState) => { const { viewId } = getSelectedView(getState()); if (!viewId) return false; dispatch(addComment(viewId, commentId)); return true; }; } export function toggleCitationBrackets(): AppThunk<boolean> { return (dispatch, getState) => { const editor = getSelectedEditorAndViews(getState()); if (editor.state == null) return false; const { schema } = editor.state; const node = getNodeIfSelected(editor.state, nodeNames.cite); if (!node) return false; const { parent } = editor.state.selection.$from; const hasParenthesis = parent.type.name === schema.nodes.cite_group.name; if (hasParenthesis) { const nodes: Node[] = []; parent.forEach((n) => nodes.push(n)); const frag = Fragment.from(nodes); selectParentNode(editor.state, (tr) => { const tr2 = tr.deleteSelection().insert(tr.selection.head, frag).scrollIntoView(); dispatch(applyProsemirrorTransaction(editor.key, editor.viewId, tr2)); }); return true; } const wrapped = schema.nodes.cite_group.createAndFill({}, Fragment.from([node])); if (!wrapped) return false; const tr = editor.state.tr.replaceSelectionWith(wrapped).scrollIntoView(); dispatch(applyProsemirrorTransaction(editor.key, editor.viewId, tr)); return true; }; }
the_stack
/// <reference types="jquery" /> import htmlString = JQuery.htmlString; interface FullPageJsOptions { /** * (default false) A selector can be used to specify the menu to link with the sections. This way the scrolling of the sections will activate the corresponding element in the menu using the class active. This won't generate a menu but will just add the active class to the element in the given menu with the corresponding anchor links. In order to link the elements of the menu with the sections, an HTML 5 data-tag (data-menuanchor) will be needed to use with the same anchor links as used within the sections. */ menu?: string | undefined; /** * (default false). Determines whether anchors in the URL will have any effect at all in the plugin. You can still using anchors internally for your own functions and callbacks, but they won't have any effect in the scrolling of the site. Useful if you want to combine fullPage.js with other plugins using anchor in the URL. */ lockAnchors?: boolean | undefined; /** * (default []) Defines the anchor links (#example) to be shown on the URL for each section. Anchors value should be unique. The position of the anchors in the array will define to which sections the anchor is applied. (second position for second section and so on). Using anchors forward and backward navigation will also be possible through the browser. This option also allows users to bookmark a specific section or slide. Be careful! anchors can not have the same value as any ID element on the site (or NAME element for IE). Now anchors can be defined directly in the HTML structure by using the attribute data-anchor as explained here. */ anchors?: string[] | undefined; /** * (default false) If set to true, it will show a navigation bar made up of small circles. */ navigation?: boolean | undefined; /** * (default none) It can be set to left or right and defines which position the navigation bar will be shown (if using one). */ navigationPosition?: string | undefined; /** * (default []) Defines the tooltips to show for the navigation circles in case they are being used. Example: navigationTooltips: ['firstSlide', 'secondSlide']. */ navigationTooltips?: string[] | undefined; /** * (default false) Shows a persistent tooltip for the actively viewed section in the vertical navigation. */ showActiveTooltip?: boolean | undefined; /** * (default false) If set to true it will show a navigation bar made up of small circles for each landscape slider on the site. */ slidesNavigation?: boolean | undefined; /** * (default bottom) Defines the position for the landscape navigation bar for sliders. Admits top and bottom as values. You may want to modify the CSS styles to determine the distance from the top or bottom as well as any other style such as color. */ slidesNavPosition?: string | undefined; // Scrolling /** * (default true). Defines whether to use JavaScript or CSS3 transforms to scroll within sections and slides. Useful to speed up the movement in tablet and mobile devices with browsers supporting CSS3. If this option is set to true and the browser doesn't support CSS3, a jQuery fallback will be used instead. */ css3?: boolean | undefined; /** * (default 700) Speed in milliseconds for the scrolling transitions. */ scrollingSpeed?: number | undefined; /** * (default true) Defines whether to use the "automatic" scrolling or the "normal" one. It also has affects the way the sections fit in the browser/device window in tablets and mobile phones. */ autoScrolling?: boolean | undefined; /** * (default true). Determines whether or not to fit sections to the viewport or not. When set to true the current active section will always fill the whole viewport. Otherwise the user will be free to stop in the middle of a section (when ) */ fitToSection?: boolean | undefined; /** * (default 1000). If fitToSection is set to true, this delays the fitting by the configured milliseconds. */ fitToSectionDelay?: number | undefined; /** * (default false). Determines whether to use scrollbar for the site or not. In case of using scroll bar, the autoScrolling functionality will still working as expected. The user will also be free to scroll the site with the scroll bar and fullPage.js will fit the section in the screen when scrolling finishes. */ scrollBar?: boolean | undefined; /** * (default easeInOutCubic) Defines the transition effect to use for the vertical and horizontal scrolling. It requires the file vendors/jquery.easings.min.js or jQuery UI for using some of its transitions. Other libraries could be used instead. */ easing?: string | undefined; /** * (default ease) Defines the transition effect to use in case of using css3:true. You can use the pre-defined ones (such as linear, ease-out...) or create your own ones using the cubic-bezier function. You might want to use Matthew Lein CSS Easing Animation Tool for it. */ easingcss3?: string | undefined; /** * (default false) Defines whether scrolling down in the last section should scroll to the first one or not. */ loopBottom?: boolean | undefined; /** * (default false) Defines whether scrolling up in the first section should scroll to the last one or not. */ loopTop?: boolean | undefined; /** * (default true) Defines whether horizontal sliders will loop after reaching the last or previous slide or not. */ loopHorizontal?: boolean | undefined; /** * (default false) Defines whether scrolling down in the last section should scroll down to the first one or not, and if scrolling up in the first section should scroll up to the last one or not. Not compatible with loopTop or loopBottom. */ continuousVertical?: boolean | undefined; /** * (default false) Extension of fullpage.js. Defines whether sliding right in the last slide should slide right to the first one or not, and if scrolling left in the first slide should slide left to the last one or not. Not compatible with loopHorizontal. Requires fullpage.js >= 2.8.3. */ continuousHorizontal?: boolean | undefined; /** * (default false) Extension of fullpage.js. Defines whether to slide horizontally within sliders by using the mouse wheel or trackpad. Ideal for story telling. Requires fullpage.js >= 2.8.3. */ scrollHorizontally?: boolean | undefined; /** * (default false) Extension of fullpage.js. Determines whether moving one horizontal slider will force the sliding of sliders in other section in the same direction. Possible values are true, false or an array with the interlocked sections. For example [1,3,5] starting by 1. Requires fullpage.js >= 2.8.3. */ interlockedSlides?: boolean | number[] | undefined; /** * Enables or disables the dragging and flicking of sections and slides by using mouse or fingers. Requires fullpage.js >= 2.8.9. Possible values are: * true: enables the feature. * false: disables the feature. * vertical: enables the feature only vertically. * horizontal: enables the feature only horizontally. * fingersonly: enables the feature for touch devices only. * mouseonly: enables the feature for desktop devices only (mouse and trackpad). */ dragAndMove?: boolean | 'vertical' | 'horizontal' | 'fingersonly' | 'mouseonly' | undefined; /** * (default false)Extension of fullpage.js. Provides a way to use non full screen sections based on percentage. Ideal to show visitors there's more content in the site by showing part of the next or previous section. Requires fullPage.js >= 2.8.8 To define the percentage of each section the attribute data-percentage must be used. The centering of the section in the viewport can be determined by using a boolean value in the attribute data-centered (default to true if not specified). For example: */ offsetSections?: boolean | undefined; /** * (default false). Extension of fullpage.js. Defines whether or not to reset every slider after leaving its section. Requires fullpage.js >= 2.8.3. */ resetSliders?: boolean | undefined; /** * Defines whether to use a fading effect or not instead of the default scrolling one. Possible values are true, false, sections, slides. It can therefore be applied just vertically or horizontally, or to both at the time. Requires fullpage.js >= 2.8.6. */ fadingEffect?: boolean | 'sections' | 'slides' | undefined; /** * (default null) If you want to avoid the auto scroll when scrolling over some elements, this is the option you need to use. (useful for maps, scrolling divs etc.) It requires a string with the jQuery selectors for those elements. (For example: normalScrollElements: '#element1, .element2') */ normalScrollElements?: string | undefined; /** * (default false) defines whether or not to create a scroll for the section/slide in case its content is bigger than the height of it. When set to true, your content will be wrapped by the plugin. Consider using delegation or load your other scripts in the afterRender callback. In case of setting it to true, it requires the vendor library scrolloverflow.min.js and it should be loaded before the fullPage.js plugin. */ scrollOverflow?: boolean | undefined; /** * when using scrollOverflow:true fullpage.js will make use of a forked and modified version of iScroll.js libary. You can customize the scrolling behaviour by providing fullpage.js with the iScroll.js options you want to use. Check its documentation for more info. */ scrollOverflowOptions?: any; /** * When set to true it scrolls up the content of the section/slide with scroll bar when leaving to another vertical section. This way the section/slide will always show the start of its content even when scrolling from a section under it */ scrollOverflowReset?: boolean | undefined; /** * (default 5) Defines a percentage of the browsers window width/height, and how far a swipe must measure for navigating to the next section / slide */ touchSensitivity?: number | undefined; /** * (default 5) Defines the threshold for the number of hops up the html node tree Fullpage will test to see if normalScrollElements is a match to allow scrolling functionality on divs on a touch device. (For example: normalScrollElementTouchThreshold: 3) */ normalScrollElementTouchThreshold?: number | undefined; /** * Defines how to scroll to a section which size is bigger than the viewport. By default fullPage.js scrolls to the top if you come from a section above the destination one and to the bottom if you come from a section below the destination one. */ bigSectionsDestination?: 'top' | 'bottom' | null | undefined; // Accessibility /** * (default true) Defines if the content can be navigated using the keyboard */ keyboardScrolling?: boolean | undefined; /** * (default true) Defines whether the load of the site when given an anchor (#) will scroll with animation to its destination or will directly load on the given section. */ animateAnchor?: boolean | undefined; /** * (default true) Defines whether to push the state of the site to the browser's history. When set to true each section/slide of the site will act as a new page and the back and forward buttons of the browser will scroll the sections/slides to reach the previous or next state of the site. When set to false, the URL will keep changing but will have no effect on the browser's history. This option is automatically turned off when using autoScrolling:false. */ recordHistory?: boolean | undefined; // Design /** * (default: true) Determines whether to use control arrows for the slides to move right or left. */ controlArrows?: boolean | undefined; /** * (default true) Vertically centering of the content within sections. When set to true, your content will be wrapped by the plugin. Consider using delegation or load your other scripts in the afterRender callback. */ verticalCentered?: boolean | undefined; resize ?: boolean | undefined; /** * (default none) Define the CSS background-color property for each section */ sectionsColor ?: string[] | undefined; /** * (default 0) Defines the top padding for each section with a numerical value and its measure (paddingTop: '10px', paddingTop: '10em'...) Useful in case of using a fixed header. */ paddingTop?: string | undefined; /** * (default 0) Defines the bottom padding for each section with a numerical value and its measure (paddingBottom: '10px', paddingBottom: '10em'...). Useful in case of using a fixed footer. */ paddingBottom?: string | undefined; /** * (default null) Defines which elements will be taken off the scrolling structure of the plugin which is necessary when using the css3 option to keep them fixed. It requires a string with the jQuery selectors for those elements. (For example: fixedElements: '#element1, .element2') */ fixedElements?: string | undefined; /** * (default 0) A normal scroll (autoScrolling:false) will be used under the defined width in pixels. A class fp-responsive is added to the body tag in case the user wants to use it for their own responsive CSS. For example, if set to 900, whenever the browser's width is less than 900 the plugin will scroll like a normal site. */ responsiveWidth?: number | undefined; /** * (default 0) A normal scroll (autoScrolling:false) will be used under the defined height in pixels. A class fp-responsive is added to the body tag in case the user wants to use it for their own responsive CSS. For example, if set to 900, whenever the browser's height is less than 900 the plugin will scroll like a normal site. */ responsiveHeight?: number | undefined; /** * When set to true slides will be turned into vertical sections when responsive mode is fired. (by using the responsiveWidth or responsiveHeight options detailed above). Requires fullpage.js >= 2.8.5. */ responsiveSlides?: boolean | undefined; /** * When set to true slides will be turned into vertical sections when responsive mode is fired. (by using the responsiveWidth or responsiveHeight options detailed above). Requires fullpage.js >= 2.8.5. */ parallax?: boolean | undefined; /** * Allows to configure the parameters for the parallax backgrounds effect when using the option parallax:true. */ parallaxOptions?: { type?: 'cover' | 'reveal' | undefined, percentage?: number | undefined, property?: string | undefined, } | undefined; /** * Extension of fullpage.js. Defines whether or not to use the cards effect on sections/slides * @default false */ cards?: boolean | undefined; /** * Allows you to configure the parameters for the cards effect when using the option `cards:true` */ cardsOptions?: { /** * @default 100 */ perspective?: number | undefined; /** * @default true */ fadeContent?: boolean | undefined; /** * @default true */ fadeBackground?: boolean | undefined; } | undefined /** * Lazy loading is active by default which means it will lazy load any media element containing the attribute data-src as detailed in the Lazy Loading docs . If you want to use any other lazy loading library you can disable this fullpage.js feature. */ lazyLoading?: boolean | undefined; // Custom selectors /** * (default .section) Defines the jQuery selector used for the plugin sections. It might need to be changed sometimes to avoid problem with other plugins using the same selectors as fullpage.js. */ sectionSelector?: string | undefined; /** * (default .slide) Defines the jQuery selector used for the plugin slides. It might need to be changed sometimes to avoid problem with other plugins using the same selectors as fullpage.js. */ slideSelector?: string | undefined; // Events /** * This callback is fired once the user leaves a section, in the transition to the new section. Returning false will cancel the move before it takes place. * @param index index of the leaving section. Starting from 1. * @param nextIndex index of the destination section. Starting from 1. * @param direction it will take the values up or down depending on the scrolling direction. */ onLeave?: ((index: number, nextIndex: number, direction: string) => void) | undefined; /** * Callback fired once the sections have been loaded, after the scrolling has ended. * @param anchorLink anchorLink corresponding to the section. * @param index index of the section. Starting from 1. */ afterLoad?: ((anchorLink: string, index: number) => void) | undefined; /** * This callback is fired just after the structure of the page is generated. This is the callback you want to use to initialize other plugins or fire any code which requires the document to be ready (as this plugin modifies the DOM to create the resulting structure). */ afterRender?: (() => void) | undefined; /** * This callback is fired after resizing the browser's window. Just after the sections are resized. */ afterResize?: (() => void) | undefined; /** * This callback is fired after fullpage.js changes from normal to responsive mode or from responsive mode to normal mode. * @param {boolean} isResponsive boolean that determines if it enters into responsive mode (true) or goes back to normal mode (false) */ afterResponsive?: ((isResponsive: boolean) => void) | undefined; /** * Callback fired once the slide of a section have been loaded, after the scrolling has ended. * * In case of not having anchorLinks defined for the slide or slides the slideIndex parameter would be the only one to use. * * Parameters: * * @param anchorLink anchorLink corresponding to the section. * @param index index of the section. Starting from 1. * @param slideAnchor anchor corresponding to the slide (in case there is) * @param slideIndex index of the slide. Starting from 1. (the default slide doesn't count as slide, but as a section) */ afterSlideLoad?: ((anchorLink: string, index: number, slideAnchor: string, slideIndex: number) => void) | undefined; /** * This callback is fired once the user leaves an slide to go to another, in the transition to the new slide. Returning false will cancel the move before it takes place. * @param anchorLink: anchorLink corresponding to the section. * @param index index of the section. Starting from 1. * @param slideIndex index of the slide. Starting from 0. * @param direction takes the values right or left depending on the scrolling direction. * @param nextSlideIndex index of the destination slide. Starting from 0. */ onSlideLeave?: ((anchorLink: string, index: number, slideIndex: number, direction: string, nextSlideIndex: number) => void) | undefined; } interface FullPageJSGlobalOptions { options: FullPageJsOptions; } interface FullPageJsMethods { (options?: FullPageJsOptions): any; /** * Sets the scrolling configuration in real time. * Defines the way the page scrolling behaves. * If it is set to true, it will use the "automatic" scrolling, * otherwise, it will use the "manual" or "normal" scrolling of the site. */ setAutoScrolling(active: boolean): void; /** * Defines whether to record the history for each hash change in the URL. */ setRecordHistory(active: boolean): void; /** * Defines the scrolling speed in milliseconds. */ setScrollingSpeed(speed: number): void; /** * Sets the value for the option fitToSection * determining whether to fit the section in the screen or not. */ setFitToSection(active: boolean): void; /** * Adds or remove the possibility of scrolling through sections * by using the mouse wheel or the trackpad. */ setLockAnchors(active: boolean): void; /** * Adds or remove the possibility of scrolling through sections * by using the mouse wheel or the trackpad. */ setMouseWheelScrolling(active: boolean): void; /** * Adds or remove the possibility of scrolling through sections * by using the mouse wheel/trackpad or touch gestures. * Optionally a second parameter can be used to specify the direction * for which the action will be applied. */ setAllowScrolling(active: boolean, directions?: string): void; /** * Adds or remove the possibility of scrolling through sections * by using the keyboard arrow keys */ setKeyboardScrolling(active: boolean, directions?: string): void; /** * Scrolls one section up */ moveSectionUp(): void; /** * Scrolls one section down */ moveSectionDown(): void; /** * Moves the page to the given section and slide with no animation. * Anchors or index positions can be used as params. */ silentMoveTo(sectionAnchor: number | string, slideAnchor?: number | string): void; /** * Scrolls the page to the given section and slide. * The first slide, the visible one by default, will have index 0. */ moveTo(sectionAnchor: number | string, slideAnchor?: number | string): void; /** * Slides right the slider of the active section. * Optional `section` param. */ moveSlideRight(section?: number | string): void; /** * Slides left the slider of the active section. * Optional `section` param. */ moveSlideLeft(section?: number | string): void; /** * When resizing is finished, we adjust the slides sizes and positions */ reBuild(): void; /** * Sets the responsive mode of the page. * When set to true the autoScrolling will be turned off * and the result will be exactly the same one as when * the responsiveWidth or responsiveHeight options * get fired. */ setResponsive(active: boolean): void; /** * Sets the value for the option fitToSection * determining whether to fit the section * in the screen or not. */ setFitToSection(active?: boolean): void; /** * Scrolls to the nearest active section fitting it in the viewport. */ fitToSection(): void; /** * Adds or remove the possibility of scrolling through sections/slides * by using the mouse wheel/trackpad or touch gestures * (which is active by default). * * Note this won't disable the keyboard scrolling. You would need to * use setKeyboardScrolling for it. */ setAllowScrolling(allow: boolean, direction?: string): void; /** * Destroys the plugin events and optionally its HTML markup and styles. * Ideal to use when using AJAX to load content. * * If 'all' is passed, the HTML markup * and styles used by fullpage.js will be removed. This way the * original HTML markup, the one used before any plugin * modification is made, will be maintained. * * @param {"all" | undefined} type */ destroy(type?: 'all'): void; responsiveSlides: { /** * Extension of fullpage.js. Requires fullpage.js >= 2.8.5. * Turns horizontal slides into vertical sections. */ toSections(): void; /** * Extension of fullpage.js. Requires fullpage.js >= 2.8.5. * Turns back the original slides (now converted into * vertical sections) into horizontal slides again. */ toSlides(): void; } } interface FullPageJs extends FullPageJSGlobalOptions, FullPageJsMethods {} interface JQueryStatic { fullpage: FullPageJsMethods; } interface JQuery { fullpage: FullPageJs; }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Resources } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ResourceManagementClient } from "../resourceManagementClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { GenericResourceExpanded, ResourcesListByResourceGroupNextOptionalParams, ResourcesListByResourceGroupOptionalParams, ResourcesListNextOptionalParams, ResourcesListOptionalParams, ResourcesListByResourceGroupResponse, ResourcesMoveInfo, ResourcesMoveResourcesOptionalParams, ResourcesValidateMoveResourcesOptionalParams, ResourcesListResponse, ResourcesCheckExistenceOptionalParams, ResourcesDeleteOptionalParams, GenericResource, ResourcesCreateOrUpdateOptionalParams, ResourcesCreateOrUpdateResponse, ResourcesUpdateOptionalParams, ResourcesUpdateResponse, ResourcesGetOptionalParams, ResourcesGetResponse, ResourcesCheckExistenceByIdOptionalParams, ResourcesDeleteByIdOptionalParams, ResourcesCreateOrUpdateByIdOptionalParams, ResourcesCreateOrUpdateByIdResponse, ResourcesUpdateByIdOptionalParams, ResourcesUpdateByIdResponse, ResourcesGetByIdOptionalParams, ResourcesGetByIdResponse, ResourcesListByResourceGroupNextResponse, ResourcesListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Resources operations. */ export class ResourcesImpl implements Resources { private readonly client: ResourceManagementClient; /** * Initialize a new instance of the class Resources class. * @param client Reference to the service client */ constructor(client: ResourceManagementClient) { this.client = client; } /** * Get all the resources for a resource group. * @param resourceGroupName The resource group with the resources to get. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: ResourcesListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<GenericResourceExpanded> { 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?: ResourcesListByResourceGroupOptionalParams ): AsyncIterableIterator<GenericResourceExpanded[]> { 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?: ResourcesListByResourceGroupOptionalParams ): AsyncIterableIterator<GenericResourceExpanded> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Get all the resources in a subscription. * @param options The options parameters. */ public list( options?: ResourcesListOptionalParams ): PagedAsyncIterableIterator<GenericResourceExpanded> { const iter = this.listPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(options); } }; } private async *listPagingPage( options?: ResourcesListOptionalParams ): AsyncIterableIterator<GenericResourceExpanded[]> { let result = await this._list(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( options?: ResourcesListOptionalParams ): AsyncIterableIterator<GenericResourceExpanded> { for await (const page of this.listPagingPage(options)) { yield* page; } } /** * Get all the resources for a resource group. * @param resourceGroupName The resource group with the resources to get. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: ResourcesListByResourceGroupOptionalParams ): Promise<ResourcesListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * The resources to move must be in the same source resource group. The target resource group may be in * a different subscription. When moving resources, both the source group and the target group are * locked for the duration of the operation. Write and delete operations are blocked on the groups * until the move completes. * @param sourceResourceGroupName The name of the resource group containing the resources to move. * @param parameters Parameters for moving resources. * @param options The options parameters. */ async beginMoveResources( sourceResourceGroupName: string, parameters: ResourcesMoveInfo, options?: ResourcesMoveResourcesOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { 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, { sourceResourceGroupName, parameters, options }, moveResourcesOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * The resources to move must be in the same source resource group. The target resource group may be in * a different subscription. When moving resources, both the source group and the target group are * locked for the duration of the operation. Write and delete operations are blocked on the groups * until the move completes. * @param sourceResourceGroupName The name of the resource group containing the resources to move. * @param parameters Parameters for moving resources. * @param options The options parameters. */ async beginMoveResourcesAndWait( sourceResourceGroupName: string, parameters: ResourcesMoveInfo, options?: ResourcesMoveResourcesOptionalParams ): Promise<void> { const poller = await this.beginMoveResources( sourceResourceGroupName, parameters, options ); return poller.pollUntilDone(); } /** * This operation checks whether the specified resources can be moved to the target. The resources to * move must be in the same source resource group. The target resource group may be in a different * subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation * fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the * Location header value to check the result of the long-running operation. * @param sourceResourceGroupName The name of the resource group containing the resources to validate * for move. * @param parameters Parameters for moving resources. * @param options The options parameters. */ async beginValidateMoveResources( sourceResourceGroupName: string, parameters: ResourcesMoveInfo, options?: ResourcesValidateMoveResourcesOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { 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, { sourceResourceGroupName, parameters, options }, validateMoveResourcesOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * This operation checks whether the specified resources can be moved to the target. The resources to * move must be in the same source resource group. The target resource group may be in a different * subscription. If validation succeeds, it returns HTTP response code 204 (no content). If validation * fails, it returns HTTP response code 409 (Conflict) with an error message. Retrieve the URL in the * Location header value to check the result of the long-running operation. * @param sourceResourceGroupName The name of the resource group containing the resources to validate * for move. * @param parameters Parameters for moving resources. * @param options The options parameters. */ async beginValidateMoveResourcesAndWait( sourceResourceGroupName: string, parameters: ResourcesMoveInfo, options?: ResourcesValidateMoveResourcesOptionalParams ): Promise<void> { const poller = await this.beginValidateMoveResources( sourceResourceGroupName, parameters, options ); return poller.pollUntilDone(); } /** * Get all the resources in a subscription. * @param options The options parameters. */ private _list( options?: ResourcesListOptionalParams ): Promise<ResourcesListResponse> { return this.client.sendOperationRequest({ options }, listOperationSpec); } /** * Checks whether a resource exists. * @param resourceGroupName The name of the resource group containing the resource to check. The name * is case insensitive. * @param resourceProviderNamespace The resource provider of the resource to check. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type. * @param resourceName The name of the resource to check whether it exists. * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ checkExistence( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options?: ResourcesCheckExistenceOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, options }, checkExistenceOperationSpec ); } /** * Deletes a resource. * @param resourceGroupName The name of the resource group that contains the resource to delete. The * name is case insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type. * @param resourceName The name of the resource to delete. * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ async beginDelete( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options?: ResourcesDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { 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, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, options }, deleteOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Deletes a resource. * @param resourceGroupName The name of the resource group that contains the resource to delete. The * name is case insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type. * @param resourceName The name of the resource to delete. * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ async beginDeleteAndWait( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options?: ResourcesDeleteOptionalParams ): Promise<void> { const poller = await this.beginDelete( resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, options ); return poller.pollUntilDone(); } /** * Creates a resource. * @param resourceGroupName The name of the resource group for the resource. The name is case * insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type of the resource to create. * @param resourceName The name of the resource to create. * @param apiVersion The API version to use for the operation. * @param parameters Parameters for creating or updating the resource. * @param options The options parameters. */ async beginCreateOrUpdate( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, parameters: GenericResource, options?: ResourcesCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<ResourcesCreateOrUpdateResponse>, ResourcesCreateOrUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ResourcesCreateOrUpdateResponse> => { 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, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters, options }, createOrUpdateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Creates a resource. * @param resourceGroupName The name of the resource group for the resource. The name is case * insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type of the resource to create. * @param resourceName The name of the resource to create. * @param apiVersion The API version to use for the operation. * @param parameters Parameters for creating or updating the resource. * @param options The options parameters. */ async beginCreateOrUpdateAndWait( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, parameters: GenericResource, options?: ResourcesCreateOrUpdateOptionalParams ): Promise<ResourcesCreateOrUpdateResponse> { const poller = await this.beginCreateOrUpdate( resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters, options ); return poller.pollUntilDone(); } /** * Updates a resource. * @param resourceGroupName The name of the resource group for the resource. The name is case * insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type of the resource to update. * @param resourceName The name of the resource to update. * @param apiVersion The API version to use for the operation. * @param parameters Parameters for updating the resource. * @param options The options parameters. */ async beginUpdate( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, parameters: GenericResource, options?: ResourcesUpdateOptionalParams ): Promise< PollerLike< PollOperationState<ResourcesUpdateResponse>, ResourcesUpdateResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ResourcesUpdateResponse> => { 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, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters, options }, updateOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Updates a resource. * @param resourceGroupName The name of the resource group for the resource. The name is case * insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type of the resource to update. * @param resourceName The name of the resource to update. * @param apiVersion The API version to use for the operation. * @param parameters Parameters for updating the resource. * @param options The options parameters. */ async beginUpdateAndWait( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, parameters: GenericResource, options?: ResourcesUpdateOptionalParams ): Promise<ResourcesUpdateResponse> { const poller = await this.beginUpdate( resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, parameters, options ); return poller.pollUntilDone(); } /** * Gets a resource. * @param resourceGroupName The name of the resource group containing the resource to get. The name is * case insensitive. * @param resourceProviderNamespace The namespace of the resource provider. * @param parentResourcePath The parent resource identity. * @param resourceType The resource type of the resource. * @param resourceName The name of the resource to get. * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ get( resourceGroupName: string, resourceProviderNamespace: string, parentResourcePath: string, resourceType: string, resourceName: string, apiVersion: string, options?: ResourcesGetOptionalParams ): Promise<ResourcesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceProviderNamespace, parentResourcePath, resourceType, resourceName, apiVersion, options }, getOperationSpec ); } /** * Checks by ID whether a resource exists. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ checkExistenceById( resourceId: string, apiVersion: string, options?: ResourcesCheckExistenceByIdOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceId, apiVersion, options }, checkExistenceByIdOperationSpec ); } /** * Deletes a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ async beginDeleteById( resourceId: string, apiVersion: string, options?: ResourcesDeleteByIdOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { 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, { resourceId, apiVersion, options }, deleteByIdOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Deletes a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ async beginDeleteByIdAndWait( resourceId: string, apiVersion: string, options?: ResourcesDeleteByIdOptionalParams ): Promise<void> { const poller = await this.beginDeleteById(resourceId, apiVersion, options); return poller.pollUntilDone(); } /** * Create a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param parameters Create or update resource parameters. * @param options The options parameters. */ async beginCreateOrUpdateById( resourceId: string, apiVersion: string, parameters: GenericResource, options?: ResourcesCreateOrUpdateByIdOptionalParams ): Promise< PollerLike< PollOperationState<ResourcesCreateOrUpdateByIdResponse>, ResourcesCreateOrUpdateByIdResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ResourcesCreateOrUpdateByIdResponse> => { 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, { resourceId, apiVersion, parameters, options }, createOrUpdateByIdOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Create a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param parameters Create or update resource parameters. * @param options The options parameters. */ async beginCreateOrUpdateByIdAndWait( resourceId: string, apiVersion: string, parameters: GenericResource, options?: ResourcesCreateOrUpdateByIdOptionalParams ): Promise<ResourcesCreateOrUpdateByIdResponse> { const poller = await this.beginCreateOrUpdateById( resourceId, apiVersion, parameters, options ); return poller.pollUntilDone(); } /** * Updates a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param parameters Update resource parameters. * @param options The options parameters. */ async beginUpdateById( resourceId: string, apiVersion: string, parameters: GenericResource, options?: ResourcesUpdateByIdOptionalParams ): Promise< PollerLike< PollOperationState<ResourcesUpdateByIdResponse>, ResourcesUpdateByIdResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<ResourcesUpdateByIdResponse> => { 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, { resourceId, apiVersion, parameters, options }, updateByIdOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Updates a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param parameters Update resource parameters. * @param options The options parameters. */ async beginUpdateByIdAndWait( resourceId: string, apiVersion: string, parameters: GenericResource, options?: ResourcesUpdateByIdOptionalParams ): Promise<ResourcesUpdateByIdResponse> { const poller = await this.beginUpdateById( resourceId, apiVersion, parameters, options ); return poller.pollUntilDone(); } /** * Gets a resource by ID. * @param resourceId The fully qualified ID of the resource, including the resource name and resource * type. Use the format, * /subscriptions/{guid}/resourceGroups/{resource-group-name}/{resource-provider-namespace}/{resource-type}/{resource-name} * @param apiVersion The API version to use for the operation. * @param options The options parameters. */ getById( resourceId: string, apiVersion: string, options?: ResourcesGetByIdOptionalParams ): Promise<ResourcesGetByIdResponse> { return this.client.sendOperationRequest( { resourceId, apiVersion, options }, getByIdOperationSpec ); } /** * ListByResourceGroupNext * @param resourceGroupName The resource group with the resources to get. * @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?: ResourcesListByResourceGroupNextOptionalParams ): Promise<ResourcesListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } /** * ListNext * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( nextLink: string, options?: ResourcesListNextOptionalParams ): Promise<ResourcesListNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/resources", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [ Parameters.apiVersion, Parameters.filter, Parameters.top, Parameters.expand ], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const moveResourcesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{sourceResourceGroupName}/moveResources", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters3, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.sourceResourceGroupName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const validateMoveResourcesOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{sourceResourceGroupName}/validateMoveResources", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters3, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.sourceResourceGroupName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resources", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [ Parameters.apiVersion, Parameters.filter, Parameters.top, Parameters.expand ], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const checkExistenceOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}", httpMethod: "HEAD", responses: { 204: {}, 404: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceProviderNamespace, Parameters.parentResourcePath, Parameters.resourceType, Parameters.resourceName ], headerParameters: [Parameters.accept], serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceProviderNamespace, Parameters.parentResourcePath, Parameters.resourceType, Parameters.resourceName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.GenericResource }, 201: { bodyMapper: Mappers.GenericResource }, 202: { bodyMapper: Mappers.GenericResource }, 204: { bodyMapper: Mappers.GenericResource }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceProviderNamespace, Parameters.parentResourcePath, Parameters.resourceType, Parameters.resourceName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.GenericResource }, 201: { bodyMapper: Mappers.GenericResource }, 202: { bodyMapper: Mappers.GenericResource }, 204: { bodyMapper: Mappers.GenericResource }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceProviderNamespace, Parameters.parentResourcePath, Parameters.resourceType, Parameters.resourceName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{parentResourcePath}/{resourceType}/{resourceName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GenericResource }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion1], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceProviderNamespace, Parameters.parentResourcePath, Parameters.resourceType, Parameters.resourceName ], headerParameters: [Parameters.accept], serializer }; const checkExistenceByIdOperationSpec: coreClient.OperationSpec = { path: "/{resourceId}", httpMethod: "HEAD", responses: { 204: {}, 404: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion1], urlParameters: [Parameters.$host, Parameters.resourceId], headerParameters: [Parameters.accept], serializer }; const deleteByIdOperationSpec: coreClient.OperationSpec = { path: "/{resourceId}", httpMethod: "DELETE", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion1], urlParameters: [Parameters.$host, Parameters.resourceId], headerParameters: [Parameters.accept], serializer }; const createOrUpdateByIdOperationSpec: coreClient.OperationSpec = { path: "/{resourceId}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.GenericResource }, 201: { bodyMapper: Mappers.GenericResource }, 202: { bodyMapper: Mappers.GenericResource }, 204: { bodyMapper: Mappers.GenericResource }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion1], urlParameters: [Parameters.$host, Parameters.resourceId], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const updateByIdOperationSpec: coreClient.OperationSpec = { path: "/{resourceId}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.GenericResource }, 201: { bodyMapper: Mappers.GenericResource }, 202: { bodyMapper: Mappers.GenericResource }, 204: { bodyMapper: Mappers.GenericResource }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion1], urlParameters: [Parameters.$host, Parameters.resourceId], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const getByIdOperationSpec: coreClient.OperationSpec = { path: "/{resourceId}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.GenericResource }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion1], urlParameters: [Parameters.$host, Parameters.resourceId], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [ Parameters.apiVersion, Parameters.filter, Parameters.top, Parameters.expand ], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.ResourceListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [ Parameters.apiVersion, Parameters.filter, Parameters.top, Parameters.expand ], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId ], headerParameters: [Parameters.accept], serializer };
the_stack
* Create a syntax highighter with a fully declarative JSON style lexer description * using regular expressions. */ import { Token, TokenizationResult } from './token'; import { IState } from './types'; import * as monarchCommon from './common'; export interface ITokenizationSupport { getInitialState(): IState; // add offsetDelta to each of the returned indices tokenize(line: string, state: IState, offsetDelta: number): TokenizationResult; } const CACHE_STACK_DEPTH = 10; function statePart(state: string, index: number): string { return state.split('.')[index]; } /** * Reuse the same stack elements up to a certain depth. */ class MonarchStackElementFactory { private static readonly _INSTANCE = new MonarchStackElementFactory(CACHE_STACK_DEPTH); public static create(parent: MonarchStackElement | null, state: string): MonarchStackElement { return this._INSTANCE.create(parent, state); } private readonly _maxCacheDepth: number; private readonly _entries: { [stackElementId: string]: MonarchStackElement; }; constructor(maxCacheDepth: number) { this._maxCacheDepth = maxCacheDepth; this._entries = Object.create(null); } public create(parent: MonarchStackElement | null, state: string): MonarchStackElement { if (parent !== null && parent.depth >= this._maxCacheDepth) { // no caching above a certain depth return new MonarchStackElement(parent, state); } let stackElementId = MonarchStackElement.getStackElementId(parent); if (stackElementId.length > 0) { stackElementId += '|'; } stackElementId += state; let result = this._entries[stackElementId]; if (result) { return result; } result = new MonarchStackElement(parent, state); this._entries[stackElementId] = result; return result; } } class MonarchStackElement { public readonly parent: MonarchStackElement | null; public readonly state: string; public readonly depth: number; constructor(parent: MonarchStackElement | null, state: string) { this.parent = parent; this.state = state; this.depth = (this.parent ? this.parent.depth : 0) + 1; } public static getStackElementId(element: MonarchStackElement | null): string { let result = ''; while (element !== null) { if (result.length > 0) { result += '|'; } result += element.state; element = element.parent; } return result; } private static _equals(a: MonarchStackElement | null, b: MonarchStackElement | null): boolean { while (a !== null && b !== null) { if (a === b) { return true; } if (a.state !== b.state) { return false; } a = a.parent; b = b.parent; } if (a === null && b === null) { return true; } return false; } public get indent(): number { return this.state.lastIndexOf('\t') - this.state.indexOf('\t'); } public get scope(): string { return this.part(2); } public get detail(): string { return this.part(2); } public part(index: number): string { return this.state.split('.')[index] } public equals(other: MonarchStackElement): boolean { return MonarchStackElement._equals(this, other); } public push(state: string): MonarchStackElement { return MonarchStackElementFactory.create(this, state); } public pop(): MonarchStackElement | null { return this.parent; } public popall(): MonarchStackElement { let result: MonarchStackElement = this; while (result.parent) { result = result.parent; } return result; } public switchTo(state: string): MonarchStackElement { return MonarchStackElementFactory.create(this.parent, state); } } /** * Reuse the same line states up to a certain depth. */ class MonarchLineStateFactory { private static readonly _INSTANCE = new MonarchLineStateFactory(CACHE_STACK_DEPTH); public static create(stack: MonarchStackElement): MonarchLineState { return this._INSTANCE.create(stack); } private readonly _maxCacheDepth: number; private readonly _entries: { [stackElementId: string]: MonarchLineState; }; constructor(maxCacheDepth: number) { this._maxCacheDepth = maxCacheDepth; this._entries = Object.create(null); } public create(stack: MonarchStackElement): MonarchLineState { if (stack !== null && stack.depth >= this._maxCacheDepth) { // no caching above a certain depth return new MonarchLineState(stack); } let stackElementId = MonarchStackElement.getStackElementId(stack); let result = this._entries[stackElementId]; if (result) { return result; } result = new MonarchLineState(stack); this._entries[stackElementId] = result; return result; } } class MonarchLineState implements IState { public readonly stack: MonarchStackElement; constructor( stack: MonarchStackElement ) { this.stack = stack; } public clone(): IState { return MonarchLineStateFactory.create(this.stack); } public equals(other: IState): boolean { if (!(other instanceof MonarchLineState)) { return false; } if (!this.stack.equals(other.stack)) { return false; } return true; } } interface IMonarchTokensCollector { enterMode(startOffset: number, modeId: string): void; emit(startOffset: number, type: string, stack?: MonarchStackElement): Token; } class MonarchClassicTokensCollector implements IMonarchTokensCollector { private _tokens: Token[]; private _language: string | null; private _lastTokenType: string | null; private _lastToken: Token; constructor() { this._tokens = []; this._language = null; this._lastToken = new Token(0, 'start', 'imba'); this._lastTokenType = null; } public enterMode(startOffset: number, modeId: string): void { this._language = modeId; } public emit(startOffset: number, type: string, stack?: MonarchStackElement): Token { if (this._lastTokenType === type && false) { console.log('add to last token', type); return this._lastToken; } let token = new Token(startOffset, type, this._language!); this._lastTokenType = type; this._lastToken = token; this._tokens.push(token); return token; } public finalize(endState: MonarchLineState): TokenizationResult { return new TokenizationResult(this._tokens, endState); } } export type ILoadStatus = { loaded: true; } | { loaded: false; promise: Promise<void>; }; export class MonarchTokenizer implements ITokenizationSupport { private readonly _modeId: string; private readonly _lexer: monarchCommon.ILexer; public _profile: boolean; constructor(modeId: string, lexer: monarchCommon.ILexer) { this._modeId = modeId; this._lexer = lexer; this._profile = false; } public dispose(): void { } public getLoadStatus(): ILoadStatus { return { loaded: true }; } public getInitialState(): IState { let rootState = MonarchStackElementFactory.create(null, this._lexer.start!); return MonarchLineStateFactory.create(rootState); } public tokenize(line: string, lineState: IState, offsetDelta: number): TokenizationResult { let tokensCollector = new MonarchClassicTokensCollector(); let endLineState = this._tokenize(line, <MonarchLineState>lineState, offsetDelta, tokensCollector); return tokensCollector.finalize(endLineState); } private _tokenize(line: string, lineState: MonarchLineState, offsetDelta: number, collector: IMonarchTokensCollector): MonarchLineState { return this._myTokenize(line, lineState, offsetDelta, collector); } private _safeRuleName(rule: monarchCommon.IRule | null): string { if (rule) { return rule.name; } return '(unknown)'; } private _rescope(from: string, to: string, tokens: string[], toState: string): void { let a = (from || '').split('-'); // if-body let b = (to || '').split('-'); // if if (from == to) return; let diff = 1; // find out their common base while (a[diff] && a[diff] == b[diff]) { diff++ } // console.log(`rescope ${from} -> ${to}`,a.length,b.length,diff); let level = a.length; while (level > diff) { // console.log('popping',a[a.length - 1]); tokens.push('pop.' + a[--level] + '.' + level); } while (b.length > diff) { // console.log('pushing',b[diff]); let id = 'push.' + b[diff++] + '.' + (diff - 1); if (toState) { let indent = statePart(toState, 1); id += '.' + indent; } tokens.push(id); } } private _myTokenize(line: string, lineState: MonarchLineState, offsetDelta: number, tokensCollector: IMonarchTokensCollector): MonarchLineState { tokensCollector.enterMode(offsetDelta, this._modeId); const lineLength = line.length; let stack = lineState.stack; let lastToken: any = null; let pos = 0; let profile = this._profile; // regular expression group matching // these never need cloning or equality since they are only used within a line match interface GroupMatching { matches: string[]; rule: monarchCommon.IRule | null; groups: { action: monarchCommon.FuzzyAction; matched: string; }[]; } let groupMatching: GroupMatching | null = null; // See https://github.com/Microsoft/monaco-editor/issues/1235: // Evaluate rules at least once for an empty line let forceEvaluation = true; let append: string[] = []; let tries = 0; let rules: monarchCommon.IRule[] | null = []; let rulesState = null; let hangPos = -1; while (forceEvaluation || pos < lineLength) { tries++; if (tries > 1000) { if (pos == hangPos) { console.log('infinite recursion', pos, lineLength, stack, tokensCollector); throw 'infinite recursion in tokenizer?'; } else { hangPos = pos; tries = 0; } } const pos0 = pos; const stackLen0 = stack.depth; const groupLen0 = groupMatching ? groupMatching.groups.length : 0; const state = stack.state; let matches: string[] | null = null; let matched: string | null = null; let action: monarchCommon.FuzzyAction | monarchCommon.FuzzyAction[] | null = null; let rule: monarchCommon.IRule | null = null; // check if we need to process group matches first if (groupMatching) { matches = groupMatching.matches; const groupEntry = groupMatching.groups.shift()!; matched = groupEntry.matched; action = groupEntry.action; rule = groupMatching.rule; // cleanup if necessary if (groupMatching.groups.length === 0) { groupMatching = null; } } else { // otherwise we match on the token stream if (!forceEvaluation && pos >= lineLength) { // nothing to do break; } forceEvaluation = false; // if(state !== rulesState){ // get the rules for this state rules = this._lexer.tokenizer[state]; if (!rules) { rules = monarchCommon.findRules(this._lexer, state); // do parent matching if (!rules) { throw monarchCommon.createError(this._lexer, 'tokenizer state is not defined: ' + state); } } // } // try each rule until we match let restOfLine = line.substr(pos); for (const rule of rules) { if (rule.string !== undefined) { if (restOfLine[0] === rule.string) { matches = [rule.string]; matched = rule.string; action = rule.action; break; } } else if (pos === 0 || !rule.matchOnlyAtLineStart) { if (profile) { rule.stats.count++; let now = performance.now(); matches = restOfLine.match(rule.regex); rule.stats.time += (performance.now() - now); if (matches) { rule.stats.hits++; } } else { matches = restOfLine.match(rule.regex); } if (matches) { matched = matches[0]; action = rule.action; break; } } } } // We matched 'rule' with 'matches' and 'action' if (!matches) { matches = ['']; matched = ''; } if (!action) { // bad: we didn't match anything, and there is no action to take // we need to advance the stream or we get progress trouble if (pos < lineLength) { matches = [line.charAt(pos)]; matched = matches[0]; } action = this._lexer.defaultToken; } if (matched === null) { // should never happen, needed for strict null checking break; } // advance stream pos += matched.length; // maybe call action function (used for 'cases') while (monarchCommon.isFuzzyAction(action) && monarchCommon.isIAction(action) && action.test) { action = action.test(matched, matches, state, pos === lineLength); } let result: monarchCommon.FuzzyAction | monarchCommon.FuzzyAction[] | null = null; // set the result: either a string or an array of actions if (typeof action === 'string' || Array.isArray(action)) { result = action; } else if (action.group) { result = action.group; } else if (action.token !== null && action.token !== undefined) { // do $n replacements? if (action.tokenSubst) { result = monarchCommon.substituteMatches(this._lexer, action.token, matched, matches, state); } else { result = action.token; } // state transformations if (action.goBack) { // back up the stream.. pos = Math.max(0, pos - action.goBack); } if (action.switchTo && typeof action.switchTo === 'string') { // let indenting = action.switchTo.indexOf('\t') > 0; // if(indenting) tokensCollector.emit(pos0 + offsetDelta, 'push', stack); // can do a quick check just for the action? let nextState = monarchCommon.substituteMatches(this._lexer, action.switchTo, matched, matches, state); // switch state without a push... if (nextState[0] === '@') { nextState = nextState.substr(1); // peel off starting '@' } if (!monarchCommon.findRules(this._lexer, nextState)) { throw monarchCommon.createError(this._lexer, 'trying to switch to a state \'' + nextState + '\' that is undefined in rule: ' + this._safeRuleName(rule)); } else { let from = stack.scope; let to = statePart(nextState, 2); if (from !== to) this._rescope(from, to, append, nextState); stack = stack.switchTo(nextState); } } else if (action.transform && typeof action.transform === 'function') { throw monarchCommon.createError(this._lexer, 'action.transform not supported'); } else if (action.next) { if (action.next === '@push') { if (stack.depth >= this._lexer.maxStack) { throw monarchCommon.createError(this._lexer, 'maximum tokenizer stack size reached: [' + stack.state + ',' + stack.parent!.state + ',...]'); } else { stack = stack.push(state); } } else if (action.next === '@pop') { if (stack.depth <= 1) { throw monarchCommon.createError(this._lexer, 'trying to pop an empty stack in rule: ' + this._safeRuleName(rule)); } else { let prev = stack; stack = stack.pop()!; let from = statePart(prev.state, 2) let to = statePart(stack.state, 2) if (from !== to) this._rescope(from, to, append, stack.state); } } else if (action.next === '@popall') { stack = stack.popall(); } else { // let indenting = action.next.indexOf('\t') > 0; // if(indenting) tokensCollector.emit(pos0 + offsetDelta, 'push', stack); let nextState = monarchCommon.substituteMatches(this._lexer, action.next, matched, matches, state); if (nextState[0] === '@') { nextState = nextState.substr(1); // peel off starting '@' } let nextScope = statePart(nextState, 2); if (!monarchCommon.findRules(this._lexer, nextState)) { throw monarchCommon.createError(this._lexer, 'trying to set a next state \'' + nextState + '\' that is undefined in rule: ' + this._safeRuleName(rule)); } else { if (nextScope != stack.scope) this._rescope(stack.scope || '', nextScope, append, nextState); stack = stack.push(nextState); } } } if (action.log && typeof (action.log) === 'string') { monarchCommon.log(this._lexer, this._lexer.languageId + ': ' + monarchCommon.substituteMatches(this._lexer, action.log, matched, matches, state)); } if (action.mark) { tokensCollector.emit(pos0 + offsetDelta, action.mark, stack); } } // check result if (result === null) { throw monarchCommon.createError(this._lexer, 'lexer rule has no well-defined action in rule: ' + this._safeRuleName(rule)); } // is the result a group match? if (Array.isArray(result)) { if (groupMatching && groupMatching.groups.length > 0) { throw monarchCommon.createError(this._lexer, 'groups cannot be nested: ' + this._safeRuleName(rule)); } if (matches.length !== result.length + 1) { throw monarchCommon.createError(this._lexer, 'matched number of groups does not match the number of actions in rule: ' + this._safeRuleName(rule)); } let totalLen = 0; for (let i = 1; i < matches.length; i++) { totalLen += matches[i].length; } if (totalLen !== matched.length) { throw monarchCommon.createError(this._lexer, 'with groups, all characters should be matched in consecutive groups in rule: ' + this._safeRuleName(rule)); } groupMatching = { rule: rule, matches: matches, groups: [] }; for (let i = 0; i < result.length; i++) { groupMatching.groups[i] = { action: result[i], matched: matches[i + 1] }; } pos -= matched.length; // call recursively to initiate first result match continue; } else { // regular result // check for '@rematch' if (result === '@rematch') { pos -= matched.length; matched = ''; // better set the next state too.. matches = null; result = ''; } // check progress if (matched.length === 0) { if (lineLength === 0 || stackLen0 !== stack.depth || state !== stack.state || (!groupMatching ? 0 : groupMatching.groups.length) !== groupLen0) { if (typeof result == 'string' && result) tokensCollector.emit(pos + offsetDelta, result, stack); while (append.length > 0) { tokensCollector.emit(pos + offsetDelta, append.shift() as string, stack); } continue; } else { throw monarchCommon.createError(this._lexer, 'no progress in tokenizer in rule: ' + this._safeRuleName(rule)); } } // return the result (and check for brace matching) // todo: for efficiency we could pre-sanitize tokenPostfix and substitutions let tokenType: string | null = null; if (monarchCommon.isString(result) && result.indexOf('@brackets') === 0) { let rest = result.substr('@brackets'.length); let bracket = findBracket(this._lexer, matched); if (!bracket) { throw monarchCommon.createError(this._lexer, '@brackets token returned but no bracket defined as: ' + matched); } tokenType = monarchCommon.sanitize(bracket.token + rest); } else { let token = (result === '' ? '' : result + this._lexer.tokenPostfix); tokenType = monarchCommon.sanitize(token); } let token = tokensCollector.emit(pos0 + offsetDelta, tokenType, stack); token.stack = stack; if (lastToken && lastToken != token) { lastToken.value = line.slice(lastToken.offset - offsetDelta, pos0); } lastToken = token; while (append.length > 0) { tokensCollector.emit(pos + offsetDelta, append.shift() as string, stack); } } } if (lastToken && !lastToken.value) { lastToken.value = line.slice(lastToken.offset - offsetDelta); } return MonarchLineStateFactory.create(stack); } } /** * Searches for a bracket in the 'brackets' attribute that matches the input. */ function findBracket(lexer: monarchCommon.ILexer, matched: string) { if (!matched) { return null; } matched = monarchCommon.fixCase(lexer, matched); let brackets = lexer.brackets; for (const bracket of brackets) { if (bracket.open === matched) { return { token: bracket.token, bracketType: monarchCommon.MonarchBracket.Open }; } else if (bracket.close === matched) { return { token: bracket.token, bracketType: monarchCommon.MonarchBracket.Close }; } } return null; } export function createTokenizationSupport(modeId: string, lexer: monarchCommon.ILexer): ITokenizationSupport { return new MonarchTokenizer(modeId, lexer); }
the_stack
import * as assert from "assert"; import { QueueServiceClient, newPipeline, StorageSharedKeyCredential, QueueClient } from "@azure/storage-queue"; import { configLogger } from "../../../src/common/Logger"; import { StoreDestinationArray } from "../../../src/common/persistence/IExtentStore"; import QueueConfiguration from "../../../src/queue/QueueConfiguration"; import Server from "../../../src/queue/QueueServer"; import { EMULATOR_ACCOUNT_KEY, EMULATOR_ACCOUNT_NAME, getUniqueName, rmRecursive, sleep } from "../../testutils"; // Set true to enable debug log configLogger(false); describe("Messages APIs test", () => { // TODO: Create a server factory as tests utils const host = "127.0.0.1"; const port = 11001; const metadataDbPath = "__queueTestsStorage__"; const extentDbPath = "__extentTestsStorage__"; const persistencePath = "__queueTestsPersistence__"; const DEFUALT_QUEUE_PERSISTENCE_ARRAY: StoreDestinationArray = [ { locationId: "queueTest", locationPath: persistencePath, maxConcurrency: 10 } ]; const config = new QueueConfiguration( host, port, metadataDbPath, extentDbPath, DEFUALT_QUEUE_PERSISTENCE_ARRAY, false ); const baseURL = `http://${host}:${port}/devstoreaccount1`; const serviceClient = new QueueServiceClient( baseURL, newPipeline( new StorageSharedKeyCredential( EMULATOR_ACCOUNT_NAME, EMULATOR_ACCOUNT_KEY ), { retryOptions: { maxTries: 1 } } ) ); let server: Server; let queueName: string; let queueClient: QueueClient; const messageContent = "Hello World"; before(async () => { server = new Server(config); await server.start(); }); after(async () => { await server.close(); await rmRecursive(metadataDbPath); await rmRecursive(extentDbPath); await rmRecursive(persistencePath); }); beforeEach(async function () { queueName = getUniqueName("queue"); queueClient = serviceClient.getQueueClient(queueName); await queueClient.create(); }); afterEach(async () => { await queueClient.delete(); }); it("enqueue, peek, dequeue and clear message with default parameters @loki", async () => { const eResult = await queueClient.sendMessage(messageContent); assert.ok(eResult.date); assert.ok(eResult.expiresOn); assert.ok(eResult.insertedOn); assert.ok(eResult.messageId); assert.ok(eResult.popReceipt); assert.ok(eResult.requestId); assert.ok(eResult.nextVisibleOn); assert.ok(eResult.version); await queueClient.sendMessage(messageContent); const pResult = await queueClient.peekMessages(); assert.ok(pResult.date); assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageText, messageContent ); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageId, eResult.messageId ); let dqResult = await queueClient.receiveMessages(); assert.ok(dqResult.date); assert.ok(dqResult.requestId); assert.ok(dqResult.version); assert.deepStrictEqual(dqResult.receivedMessageItems.length, 1); assert.ok(dqResult.receivedMessageItems[0].popReceipt); assert.deepStrictEqual( dqResult.receivedMessageItems[0].messageText, messageContent ); assert.deepStrictEqual( dqResult.receivedMessageItems[0].messageId, eResult.messageId ); assert.equal( dqResult._response.request.headers.get("x-ms-client-request-id"), dqResult.clientRequestId ); const cResult = await queueClient.clearMessages(); assert.ok(cResult.date); assert.ok(cResult.requestId); assert.ok(cResult.version); assert.equal( cResult._response.request.headers.get("x-ms-client-request-id"), cResult.clientRequestId ); // check all messages are cleared const pResult2 = await queueClient.peekMessages(); assert.ok(pResult2.date); assert.deepStrictEqual(pResult2.peekedMessageItems.length, 0); }); it("enqueue, peek, dequeue and clear message with all parameters @loki", async () => { const eResult = await queueClient.sendMessage(messageContent, { messageTimeToLive: 40, visibilityTimeout: 0 }); assert.ok(eResult.date); assert.ok(eResult.expiresOn); assert.ok(eResult.insertedOn); assert.ok(eResult.messageId); assert.ok(eResult.popReceipt); assert.ok(eResult.requestId); assert.ok(eResult.nextVisibleOn); assert.ok(eResult.version); let eResult2 = await queueClient.sendMessage(messageContent, { messageTimeToLive: 40, visibilityTimeout: 0 }); await queueClient.sendMessage(messageContent, { messageTimeToLive: 10, visibilityTimeout: 5 }); await queueClient.sendMessage(messageContent, { messageTimeToLive: Number.MAX_SAFE_INTEGER, visibilityTimeout: 19 }); let pResult = await queueClient.peekMessages({ numberOfMessages: 2 }); assert.ok(pResult.date); assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 2); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageText, messageContent ); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageId, eResult.messageId ); assert.deepStrictEqual( pResult.peekedMessageItems[0].insertedOn, eResult.insertedOn ); assert.deepStrictEqual( pResult.peekedMessageItems[0].expiresOn, eResult.expiresOn ); assert.deepStrictEqual( pResult.peekedMessageItems[1].messageText, messageContent ); assert.deepStrictEqual(pResult.peekedMessageItems[1].dequeueCount, 0); assert.deepStrictEqual( pResult.peekedMessageItems[1].messageId, eResult2.messageId ); assert.deepStrictEqual( pResult.peekedMessageItems[1].insertedOn, eResult2.insertedOn ); assert.deepStrictEqual( pResult.peekedMessageItems[1].expiresOn, eResult2.expiresOn ); let dResult = await queueClient.receiveMessages({ visibilitytimeout: 10, numberOfMessages: 2 }); assert.ok(dResult.date); assert.ok(dResult.requestId); assert.ok(dResult.version); assert.deepStrictEqual(dResult.receivedMessageItems.length, 2); assert.deepStrictEqual( dResult.receivedMessageItems[0].messageText, messageContent ); assert.deepStrictEqual(dResult.receivedMessageItems[0].dequeueCount, 1); assert.deepStrictEqual( dResult.receivedMessageItems[0].messageId, eResult.messageId ); assert.deepStrictEqual( dResult.receivedMessageItems[0].insertedOn, eResult.insertedOn ); assert.deepStrictEqual( dResult.receivedMessageItems[0].expiresOn, eResult.expiresOn ); assert.ok(dResult.receivedMessageItems[0].popReceipt); assert.ok(dResult.receivedMessageItems[0].nextVisibleOn); assert.deepStrictEqual( pResult.peekedMessageItems[1].messageText, messageContent ); // check no message is visible let pResult2 = await queueClient.peekMessages(); assert.ok(pResult2.date); assert.deepStrictEqual(pResult2.peekedMessageItems.length, 0); }); it("enqueue, peek, dequeue empty message, and peek, dequeue with numberOfMessages > count(messages) @loki", async () => { const eResult = await queueClient.sendMessage("", { messageTimeToLive: 40, visibilityTimeout: 0 }); assert.ok(eResult.date); assert.ok(eResult.expiresOn); assert.ok(eResult.insertedOn); assert.ok(eResult.messageId); assert.ok(eResult.popReceipt); assert.ok(eResult.requestId); assert.ok(eResult.nextVisibleOn); assert.ok(eResult.version); const pResult = await queueClient.peekMessages({ numberOfMessages: 2 }); assert.ok(pResult.date); assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); assert.deepStrictEqual(pResult.peekedMessageItems[0].messageText, ""); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageId, eResult.messageId ); assert.deepStrictEqual( pResult.peekedMessageItems[0].insertedOn, eResult.insertedOn ); assert.deepStrictEqual( pResult.peekedMessageItems[0].expiresOn, eResult.expiresOn ); let dResult = await queueClient.receiveMessages({ visibilitytimeout: 10, numberOfMessages: 2 }); assert.ok(dResult.date); assert.ok(dResult.requestId); assert.ok(dResult.version); assert.deepStrictEqual(dResult.receivedMessageItems.length, 1); assert.deepStrictEqual(dResult.receivedMessageItems[0].messageText, ""); assert.deepStrictEqual(dResult.receivedMessageItems[0].dequeueCount, 1); assert.deepStrictEqual( dResult.receivedMessageItems[0].messageId, eResult.messageId ); assert.deepStrictEqual( dResult.receivedMessageItems[0].insertedOn, eResult.insertedOn ); assert.deepStrictEqual( dResult.receivedMessageItems[0].expiresOn, eResult.expiresOn ); assert.ok(dResult.receivedMessageItems[0].popReceipt); assert.ok(dResult.receivedMessageItems[0].nextVisibleOn); }); it("enqueue, peek, dequeue special characters @loki", async () => { let specialMessage = "!@#$%^&*()_+`-=[]|};'\":,./?><`~漢字㒈保ᨍ揫^p[뷁)׷񬓔7񈺝l鮍򧽶ͺ簣ڞ츊䈗㝯綞߫⯹?ÎᦡC왶żsmt㖩닡򈸱𕩣ОլFZ򃀮9tC榅ٻ컦驿Ϳ[𱿛봻烌󱰷򙥱Ռ򽒏򘤰δŊϜ췮㐦9ͽƙp퐂ʩ由巩•KFÓ֮򨾭⨿󊻅aBm󶴂旨Ϣ񓙠򻐪񇧱򆋸ջ֨ipn򒷐ꝷՆ򆊙斡賆𒚑m˞𻆕󛿓򐞺Ӯ򡗺򴜍<񐸩԰Bu)򁉂񖨞á<џɏ嗂�⨣1PJ㬵┡ḸI򰱂ˮaࢸ۳i灛ȯɨb𹺪򕕱뿶uٔ䎴񷯆Φ륽󬃨س_NƵ¦\u00E9"; let eResult = await queueClient.sendMessage(specialMessage, { messageTimeToLive: 40, visibilitytimeout: 0 }); assert.ok(eResult.date); assert.ok(eResult.expiresOn); assert.ok(eResult.insertedOn); assert.ok(eResult.messageId); assert.ok(eResult.popReceipt); assert.ok(eResult.requestId); assert.ok(eResult.nextVisibleOn); assert.ok(eResult.version); let pResult = await queueClient.peekMessages({ numberOfMessages: 2 }); assert.ok(pResult.date); assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageText, specialMessage ); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageId, eResult.messageId ); assert.deepStrictEqual( pResult.peekedMessageItems[0].insertedOn, eResult.insertedOn ); assert.deepStrictEqual( pResult.peekedMessageItems[0].expiresOn, eResult.expiresOn ); let dResult = await queueClient.receiveMessages({ visibilitytimeout: 10, numberOfMessages: 2 }); assert.ok(dResult.date); assert.ok(dResult.requestId); assert.ok(dResult.version); assert.deepStrictEqual(dResult.receivedMessageItems.length, 1); assert.deepStrictEqual( dResult.receivedMessageItems[0].messageText, specialMessage ); assert.deepStrictEqual(dResult.receivedMessageItems[0].dequeueCount, 1); assert.deepStrictEqual( dResult.receivedMessageItems[0].messageId, eResult.messageId ); assert.deepStrictEqual( dResult.receivedMessageItems[0].insertedOn, eResult.insertedOn ); assert.deepStrictEqual( dResult.receivedMessageItems[0].expiresOn, eResult.expiresOn ); assert.ok(dResult.receivedMessageItems[0].popReceipt); assert.ok(dResult.receivedMessageItems[0].nextVisibleOn); }); it("enqueue, peek, dequeue with 64KB characters size which is computed after encoding @loki", async () => { let messageContent = new Array(64 * 1024 + 1).join("a"); const eResult = await queueClient.sendMessage(messageContent, { messageTimeToLive: 40, visibilityTimeout: 0 }); assert.ok(eResult.date); assert.ok(eResult.expiresOn); assert.ok(eResult.insertedOn); assert.ok(eResult.messageId); assert.ok(eResult.popReceipt); assert.ok(eResult.requestId); assert.ok(eResult.nextVisibleOn); assert.ok(eResult.version); let pResult = await queueClient.peekMessages({ numberOfMessages: 2 }); assert.ok(pResult.date); assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageText, messageContent ); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageId, eResult.messageId ); assert.deepStrictEqual( pResult.peekedMessageItems[0].insertedOn, eResult.insertedOn ); assert.deepStrictEqual( pResult.peekedMessageItems[0].expiresOn, eResult.expiresOn ); let dResult = await queueClient.receiveMessages({ visibilitytimeout: 10, numberOfMessages: 2 }); assert.ok(dResult.date); assert.ok(dResult.requestId); assert.ok(dResult.version); assert.deepStrictEqual(dResult.receivedMessageItems.length, 1); assert.deepStrictEqual( dResult.receivedMessageItems[0].messageText, messageContent ); assert.deepStrictEqual(dResult.receivedMessageItems[0].dequeueCount, 1); assert.deepStrictEqual( dResult.receivedMessageItems[0].messageId, eResult.messageId ); assert.deepStrictEqual( dResult.receivedMessageItems[0].insertedOn, eResult.insertedOn ); assert.deepStrictEqual( dResult.receivedMessageItems[0].expiresOn, eResult.expiresOn ); assert.ok(dResult.receivedMessageItems[0].popReceipt); assert.ok(dResult.receivedMessageItems[0].nextVisibleOn); }); it("enqueue, peek and dequeue negative @loki", async () => { const eResult = await queueClient.sendMessage(messageContent, { messageTimeToLive: 40 }); assert.ok(eResult.date); assert.ok(eResult.expiresOn); assert.ok(eResult.insertedOn); assert.ok(eResult.messageId); assert.ok(eResult.popReceipt); assert.ok(eResult.requestId); assert.ok(eResult.nextVisibleOn); assert.ok(eResult.version); let error; try { await queueClient.sendMessage(messageContent, { messageTimeToLive: 30, visibilityTimeout: 30 }); } catch (err) { error = err; } assert.ok(error); let errorPeek; try { await queueClient.peekMessages({ numberOfMessages: 100 }); } catch (err) { errorPeek = err; } assert.ok(errorPeek); let pResult = await queueClient.peekMessages({ numberOfMessages: 2 }); assert.ok(pResult.date); assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageText, messageContent ); assert.deepStrictEqual(pResult.peekedMessageItems[0].dequeueCount, 0); assert.deepStrictEqual( pResult.peekedMessageItems[0].messageId, eResult.messageId ); assert.deepStrictEqual( pResult.peekedMessageItems[0].insertedOn, eResult.insertedOn ); assert.deepStrictEqual( pResult.peekedMessageItems[0].expiresOn, eResult.expiresOn ); // Note visibility time could be larger then message time to live for dequeue. await queueClient.receiveMessages({ visibilitytimeout: 40, numberOfMessages: 2 }); }); it("enqueue negative with 65537B(64KB+1B) characters size which is computed after encoding @loki", async () => { let messageContent = new Array(64 * 1024 + 2).join("a"); let error; try { await queueClient.sendMessage(messageContent, {}); } catch (err) { error = err; } assert.ok(error); assert.ok( error.message.includes( "The request body is too large and exceeds the maximum permissible limit." ) ); }); it("peek,dequeue,update,delete expired message @loki", async () => { const ttl = 2; let eResult = await queueClient.sendMessage(messageContent, { messageTimeToLive: ttl, visibilitytimeout: 1 }); assert.ok(eResult.date); assert.ok(eResult.expiresOn); assert.ok(eResult.insertedOn); assert.ok(eResult.messageId); assert.ok(eResult.popReceipt); assert.ok(eResult.requestId); assert.ok(eResult.nextVisibleOn); assert.ok(eResult.version); // peek, get, update before message expire let pResult = await queueClient.peekMessages({ numberOfMessages: 2 }); assert.ok(pResult.date); assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 1); let dResult = await queueClient.receiveMessages({ visibilitytimeout: 1, numberOfMessages: 1 }); assert.ok(dResult.date); assert.ok(dResult.requestId); assert.ok(dResult.version); assert.deepStrictEqual(dResult.receivedMessageItems.length, 1); let newMessage = ""; const uResult = await queueClient.updateMessage( dResult.receivedMessageItems[0].messageId, dResult.receivedMessageItems[0].popReceipt, newMessage, 1 ); assert.ok(uResult.version); assert.ok(uResult.nextVisibleOn); assert.ok(uResult.date); assert.ok(uResult.requestId); assert.ok(uResult.popReceipt); // wait for message expire await sleep(ttl * 1000); // peek, get, update, delete message after message expire pResult = await queueClient.peekMessages({ numberOfMessages: 2 }); assert.ok(pResult.date); assert.ok(pResult.requestId); assert.ok(pResult.version); assert.deepStrictEqual(pResult.peekedMessageItems.length, 0); let dResult2 = await queueClient.receiveMessages({ visibilitytimeout: 10, numberOfMessages: 2 }); assert.ok(dResult2.date); assert.ok(dResult2.requestId); assert.ok(dResult2.version); assert.deepStrictEqual(dResult2.receivedMessageItems.length, 0); let errorUpdate; try { await queueClient.updateMessage( dResult.receivedMessageItems[0].messageId, dResult.receivedMessageItems[0].popReceipt, newMessage, 1 ); } catch (err) { errorUpdate = err; } assert.ok(errorUpdate); let errorDelete; try { await queueClient.deleteMessage( dResult.receivedMessageItems[0].messageId, dResult.receivedMessageItems[0].popReceipt ); } catch (err) { errorDelete = err; } assert.ok(errorDelete); }); });
the_stack
import { each, some } from 'lodash'; import { PaymentActionCreator } from '../..'; import { CheckoutStore, InternalCheckoutSelectors } from '../../../checkout'; import { getBrowserInfo } from '../../../common/browser-info'; import { InvalidArgumentError, MissingDataError, MissingDataErrorType, NotInitializedError, NotInitializedErrorType, RequestError } from '../../../common/error/errors'; import { HostedForm, HostedFormFactory, HostedFormOptions } from '../../../hosted-form'; import { OrderActionCreator, OrderPaymentRequestBody, OrderRequestBody } from '../../../order'; import { PaymentArgumentInvalidError } from '../../errors'; import isVaultedInstrument from '../../is-vaulted-instrument'; import { HostedInstrument } from '../../payment'; import { PaymentInitializeOptions, PaymentRequestOptions } from '../../payment-request-options'; import PaymentStrategy from '../payment-strategy'; import { MollieClient, MollieElement } from './mollie'; import MolliePaymentInitializeOptions from './mollie-initialize-options'; import MollieScriptLoader from './mollie-script-loader'; export enum MolliePaymentMethodType { creditcard = 'credit_card', } export default class MolliePaymentStrategy implements PaymentStrategy { private _initializeOptions?: MolliePaymentInitializeOptions; private _mollieClient?: MollieClient; private _cardHolderElement?: MollieElement; private _cardNumberElement?: MollieElement; private _verificationCodeElement?: MollieElement; private _expiryDateElement?: MollieElement; private _hostedForm?: HostedForm; constructor( private _hostedFormFactory: HostedFormFactory, private _store: CheckoutStore, private _mollieScriptLoader: MollieScriptLoader, private _orderActionCreator: OrderActionCreator, private _paymentActionCreator: PaymentActionCreator ) { } async initialize(options: PaymentInitializeOptions): Promise<InternalCheckoutSelectors> { const { mollie, methodId, gatewayId } = options; if (!mollie) { throw new InvalidArgumentError('Unable to initialize payment because "options.mollie" argument is not provided.'); } if (!methodId || !gatewayId) { throw new InvalidArgumentError('Unable to initialize payment because "methodId" and/or "gatewayId" argument is not provided.'); } const state = this._store.getState(); const storeConfig = state.config.getStoreConfig(); if (!storeConfig) { throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig); } this._initializeOptions = mollie; const paymentMethods = state.paymentMethods; const paymentMethod = paymentMethods.getPaymentMethodOrThrow(methodId, gatewayId); const { config: { merchantId, testMode } } = paymentMethod; if (!merchantId) { throw new InvalidArgumentError('Unable to initialize payment because "merchantId" argument is not provided.'); } if (this.isCreditCard(methodId) && mollie.form && this.shouldShowTSVHostedForm(methodId, gatewayId)) { this._hostedForm = await this._mountCardVerificationfields(mollie.form); } else if (this.isCreditCard(methodId)) { this._mollieClient = await this._loadMollieJs(merchantId, storeConfig.storeProfile.storeLanguage, testMode); this._mountElements(); } return Promise.resolve(this._store.getState()); } async execute(payload: OrderRequestBody, options?: PaymentRequestOptions): Promise<InternalCheckoutSelectors> { const { payment , ...order} = payload; const paymentData = payment?.paymentData; if (!payment || !payment.gatewayId || !paymentData) { throw new PaymentArgumentInvalidError([ 'payment', 'gatewayId', 'paymentData' ]); } try { await this._store.dispatch(this._orderActionCreator.submitOrder(order, options)); if (isVaultedInstrument(paymentData)) { return await this.executeWithVaulted(payment); } if (this.isCreditCard(payment.methodId)) { return await this.executeWithCC(payment); } return await this.executeWithAPM(payment); } catch (error) { return this._processAdditionalAction(error); } } finalize(): Promise<InternalCheckoutSelectors> { return Promise.resolve(this._store.getState()); } deinitialize(): Promise<InternalCheckoutSelectors> { this._mollieClient = undefined; this.removeMollieComponents(); return Promise.resolve(this._store.getState()); } protected async executeWithCC(payment: OrderPaymentRequestBody): Promise<InternalCheckoutSelectors> { const paymentData = payment.paymentData; const shouldSaveInstrument = (paymentData as HostedInstrument)?.shouldSaveInstrument; const shouldSetAsDefaultInstrument = (paymentData as HostedInstrument)?.shouldSetAsDefaultInstrument; const { token, error } = await this._getMollieClient().createToken(); if (error) { return Promise.reject(error); } return await this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData: { formattedPayload: { credit_card_token: { token, }, vault_payment_instrument: shouldSaveInstrument, set_as_default_stored_instrument: shouldSetAsDefaultInstrument, browser_info: getBrowserInfo(), }, }, })); } protected async executeWithVaulted(payment: OrderPaymentRequestBody): Promise<InternalCheckoutSelectors> { if (this._isHostedPaymentFormEnabled(payment.methodId, payment.gatewayId)) { const form = this._hostedForm; if (!form) { throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized); } await form.validate(); await form.submit(payment); return await this._store.dispatch(this._orderActionCreator.loadCurrentOrder()); } else { return await this._store.dispatch(this._paymentActionCreator.submitPayment(payment)); } } protected async executeWithAPM(payment: OrderPaymentRequestBody): Promise<InternalCheckoutSelectors> { const paymentData = payment.paymentData; const issuer = paymentData && 'issuer' in paymentData ? paymentData.issuer : ''; return await this._store.dispatch(this._paymentActionCreator.submitPayment({ ...payment, paymentData: { ...paymentData, formattedPayload: { issuer, }, }, })); } private isCreditCard(methodId: string): boolean { return (methodId === MolliePaymentMethodType.creditcard); } private shouldShowTSVHostedForm(methodId: string, gatewayId: string): boolean { return (this._isHostedPaymentFormEnabled(methodId, gatewayId) && this._isHostedFieldAvailable()); } private _mountCardVerificationfields(formOptions: HostedFormOptions): Promise<HostedForm> { return new Promise(async (resolve , reject) => { try { const { config } = this._store.getState(); const bigpayBaseUrl = config.getStoreConfig()?.paymentSettings.bigpayBaseUrl; if (!bigpayBaseUrl) { throw new MissingDataError(MissingDataErrorType.MissingCheckoutConfig); } const form = this._hostedFormFactory.create(bigpayBaseUrl, formOptions); await form.attach(); resolve(form); } catch (error) { reject(error); } }); } private _isHostedPaymentFormEnabled(methodId: string, gatewayId?: string): boolean { const { paymentMethods: { getPaymentMethodOrThrow } } = this._store.getState(); const paymentMethod = getPaymentMethodOrThrow(methodId, gatewayId); return paymentMethod.config.isHostedFormEnabled === true; } private _isHostedFieldAvailable(): boolean { const options = this._getInitializeOptions(); return !!options.form?.fields; } private removeMollieComponents(): void { const mollieComponents = document.querySelectorAll('.mollie-component'); each(mollieComponents, component => component.remove()); const controllers = document.querySelectorAll('.mollie-components-controller'); each(controllers, controller => controller.remove()); } private _processAdditionalAction(error: any): Promise<InternalCheckoutSelectors> { if (!(error instanceof RequestError) || !some(error.body.errors, {code: 'additional_action_required'})) { return Promise.reject(error); } const { additional_action_required: { data : { redirect_url } } } = error.body; return new Promise(() => window.location.replace(redirect_url)); } private _getInitializeOptions(): MolliePaymentInitializeOptions { if (!this._initializeOptions) { throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized); } return this._initializeOptions; } private _loadMollieJs(merchantId: string, locale: string, testmode: boolean = false): Promise<MollieClient> { if (this._mollieClient) { return Promise.resolve(this._mollieClient); } return this._mollieScriptLoader .load(merchantId, locale, testmode); } private _getMollieClient(): MollieClient { if (!this._mollieClient) { throw new NotInitializedError(NotInitializedErrorType.PaymentNotInitialized); } return this._mollieClient; } /** * ContainerId is use in Mollie for determined either its showing or not the * container, because when Mollie has Vaulted Instruments it gets hide, * and shows an error because can't mount Provider Components * * We had to add a settimeout because Mollie sets de tab index after mounting * each component, but without a setTimeOut Mollie is not able to find the * components as they are hidden so we need to wait until they are shown */ private _mountElements() { const { containerId, cardNumberId, cardCvcId, cardExpiryId, cardHolderId, styles } = this._getInitializeOptions(); let container: HTMLElement | null; if (containerId) { container = document.getElementById(containerId); } setTimeout(() => { if (!containerId || container?.style.display !== 'none') { const mollieClient = this._getMollieClient(); this._cardHolderElement = mollieClient.createComponent('cardHolder', { styles }); this._cardHolderElement.mount(`#${cardHolderId}`); this._cardNumberElement = mollieClient.createComponent('cardNumber', { styles }); this._cardNumberElement.mount(`#${cardNumberId}`); this._verificationCodeElement = mollieClient.createComponent('verificationCode', { styles }); this._verificationCodeElement.mount(`#${cardCvcId}`); this._expiryDateElement = mollieClient.createComponent('expiryDate', { styles }); this._expiryDateElement.mount(`#${cardExpiryId}`); } }, 0); } }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { ConfigureLogsCommand, ConfigureLogsCommandInput, ConfigureLogsCommandOutput, } from "./commands/ConfigureLogsCommand"; import { CreateAssetCommand, CreateAssetCommandInput, CreateAssetCommandOutput } from "./commands/CreateAssetCommand"; import { CreatePackagingConfigurationCommand, CreatePackagingConfigurationCommandInput, CreatePackagingConfigurationCommandOutput, } from "./commands/CreatePackagingConfigurationCommand"; import { CreatePackagingGroupCommand, CreatePackagingGroupCommandInput, CreatePackagingGroupCommandOutput, } from "./commands/CreatePackagingGroupCommand"; import { DeleteAssetCommand, DeleteAssetCommandInput, DeleteAssetCommandOutput } from "./commands/DeleteAssetCommand"; import { DeletePackagingConfigurationCommand, DeletePackagingConfigurationCommandInput, DeletePackagingConfigurationCommandOutput, } from "./commands/DeletePackagingConfigurationCommand"; import { DeletePackagingGroupCommand, DeletePackagingGroupCommandInput, DeletePackagingGroupCommandOutput, } from "./commands/DeletePackagingGroupCommand"; import { DescribeAssetCommand, DescribeAssetCommandInput, DescribeAssetCommandOutput, } from "./commands/DescribeAssetCommand"; import { DescribePackagingConfigurationCommand, DescribePackagingConfigurationCommandInput, DescribePackagingConfigurationCommandOutput, } from "./commands/DescribePackagingConfigurationCommand"; import { DescribePackagingGroupCommand, DescribePackagingGroupCommandInput, DescribePackagingGroupCommandOutput, } from "./commands/DescribePackagingGroupCommand"; import { ListAssetsCommand, ListAssetsCommandInput, ListAssetsCommandOutput } from "./commands/ListAssetsCommand"; import { ListPackagingConfigurationsCommand, ListPackagingConfigurationsCommandInput, ListPackagingConfigurationsCommandOutput, } from "./commands/ListPackagingConfigurationsCommand"; import { ListPackagingGroupsCommand, ListPackagingGroupsCommandInput, ListPackagingGroupsCommandOutput, } from "./commands/ListPackagingGroupsCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { UpdatePackagingGroupCommand, UpdatePackagingGroupCommandInput, UpdatePackagingGroupCommandOutput, } from "./commands/UpdatePackagingGroupCommand"; import { MediaPackageVodClient } from "./MediaPackageVodClient"; /** * AWS Elemental MediaPackage VOD */ export class MediaPackageVod extends MediaPackageVodClient { /** * Changes the packaging group's properities to configure log subscription */ public configureLogs( args: ConfigureLogsCommandInput, options?: __HttpHandlerOptions ): Promise<ConfigureLogsCommandOutput>; public configureLogs( args: ConfigureLogsCommandInput, cb: (err: any, data?: ConfigureLogsCommandOutput) => void ): void; public configureLogs( args: ConfigureLogsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ConfigureLogsCommandOutput) => void ): void; public configureLogs( args: ConfigureLogsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ConfigureLogsCommandOutput) => void), cb?: (err: any, data?: ConfigureLogsCommandOutput) => void ): Promise<ConfigureLogsCommandOutput> | void { const command = new ConfigureLogsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Creates a new MediaPackage VOD Asset resource. */ public createAsset(args: CreateAssetCommandInput, options?: __HttpHandlerOptions): Promise<CreateAssetCommandOutput>; public createAsset(args: CreateAssetCommandInput, cb: (err: any, data?: CreateAssetCommandOutput) => void): void; public createAsset( args: CreateAssetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateAssetCommandOutput) => void ): void; public createAsset( args: CreateAssetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateAssetCommandOutput) => void), cb?: (err: any, data?: CreateAssetCommandOutput) => void ): Promise<CreateAssetCommandOutput> | void { const command = new CreateAssetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Creates a new MediaPackage VOD PackagingConfiguration resource. */ public createPackagingConfiguration( args: CreatePackagingConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<CreatePackagingConfigurationCommandOutput>; public createPackagingConfiguration( args: CreatePackagingConfigurationCommandInput, cb: (err: any, data?: CreatePackagingConfigurationCommandOutput) => void ): void; public createPackagingConfiguration( args: CreatePackagingConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreatePackagingConfigurationCommandOutput) => void ): void; public createPackagingConfiguration( args: CreatePackagingConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreatePackagingConfigurationCommandOutput) => void), cb?: (err: any, data?: CreatePackagingConfigurationCommandOutput) => void ): Promise<CreatePackagingConfigurationCommandOutput> | void { const command = new CreatePackagingConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Creates a new MediaPackage VOD PackagingGroup resource. */ public createPackagingGroup( args: CreatePackagingGroupCommandInput, options?: __HttpHandlerOptions ): Promise<CreatePackagingGroupCommandOutput>; public createPackagingGroup( args: CreatePackagingGroupCommandInput, cb: (err: any, data?: CreatePackagingGroupCommandOutput) => void ): void; public createPackagingGroup( args: CreatePackagingGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreatePackagingGroupCommandOutput) => void ): void; public createPackagingGroup( args: CreatePackagingGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreatePackagingGroupCommandOutput) => void), cb?: (err: any, data?: CreatePackagingGroupCommandOutput) => void ): Promise<CreatePackagingGroupCommandOutput> | void { const command = new CreatePackagingGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Deletes an existing MediaPackage VOD Asset resource. */ public deleteAsset(args: DeleteAssetCommandInput, options?: __HttpHandlerOptions): Promise<DeleteAssetCommandOutput>; public deleteAsset(args: DeleteAssetCommandInput, cb: (err: any, data?: DeleteAssetCommandOutput) => void): void; public deleteAsset( args: DeleteAssetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteAssetCommandOutput) => void ): void; public deleteAsset( args: DeleteAssetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteAssetCommandOutput) => void), cb?: (err: any, data?: DeleteAssetCommandOutput) => void ): Promise<DeleteAssetCommandOutput> | void { const command = new DeleteAssetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Deletes a MediaPackage VOD PackagingConfiguration resource. */ public deletePackagingConfiguration( args: DeletePackagingConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<DeletePackagingConfigurationCommandOutput>; public deletePackagingConfiguration( args: DeletePackagingConfigurationCommandInput, cb: (err: any, data?: DeletePackagingConfigurationCommandOutput) => void ): void; public deletePackagingConfiguration( args: DeletePackagingConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeletePackagingConfigurationCommandOutput) => void ): void; public deletePackagingConfiguration( args: DeletePackagingConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeletePackagingConfigurationCommandOutput) => void), cb?: (err: any, data?: DeletePackagingConfigurationCommandOutput) => void ): Promise<DeletePackagingConfigurationCommandOutput> | void { const command = new DeletePackagingConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Deletes a MediaPackage VOD PackagingGroup resource. */ public deletePackagingGroup( args: DeletePackagingGroupCommandInput, options?: __HttpHandlerOptions ): Promise<DeletePackagingGroupCommandOutput>; public deletePackagingGroup( args: DeletePackagingGroupCommandInput, cb: (err: any, data?: DeletePackagingGroupCommandOutput) => void ): void; public deletePackagingGroup( args: DeletePackagingGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeletePackagingGroupCommandOutput) => void ): void; public deletePackagingGroup( args: DeletePackagingGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeletePackagingGroupCommandOutput) => void), cb?: (err: any, data?: DeletePackagingGroupCommandOutput) => void ): Promise<DeletePackagingGroupCommandOutput> | void { const command = new DeletePackagingGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Returns a description of a MediaPackage VOD Asset resource. */ public describeAsset( args: DescribeAssetCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeAssetCommandOutput>; public describeAsset( args: DescribeAssetCommandInput, cb: (err: any, data?: DescribeAssetCommandOutput) => void ): void; public describeAsset( args: DescribeAssetCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeAssetCommandOutput) => void ): void; public describeAsset( args: DescribeAssetCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeAssetCommandOutput) => void), cb?: (err: any, data?: DescribeAssetCommandOutput) => void ): Promise<DescribeAssetCommandOutput> | void { const command = new DescribeAssetCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Returns a description of a MediaPackage VOD PackagingConfiguration resource. */ public describePackagingConfiguration( args: DescribePackagingConfigurationCommandInput, options?: __HttpHandlerOptions ): Promise<DescribePackagingConfigurationCommandOutput>; public describePackagingConfiguration( args: DescribePackagingConfigurationCommandInput, cb: (err: any, data?: DescribePackagingConfigurationCommandOutput) => void ): void; public describePackagingConfiguration( args: DescribePackagingConfigurationCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribePackagingConfigurationCommandOutput) => void ): void; public describePackagingConfiguration( args: DescribePackagingConfigurationCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribePackagingConfigurationCommandOutput) => void), cb?: (err: any, data?: DescribePackagingConfigurationCommandOutput) => void ): Promise<DescribePackagingConfigurationCommandOutput> | void { const command = new DescribePackagingConfigurationCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Returns a description of a MediaPackage VOD PackagingGroup resource. */ public describePackagingGroup( args: DescribePackagingGroupCommandInput, options?: __HttpHandlerOptions ): Promise<DescribePackagingGroupCommandOutput>; public describePackagingGroup( args: DescribePackagingGroupCommandInput, cb: (err: any, data?: DescribePackagingGroupCommandOutput) => void ): void; public describePackagingGroup( args: DescribePackagingGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribePackagingGroupCommandOutput) => void ): void; public describePackagingGroup( args: DescribePackagingGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribePackagingGroupCommandOutput) => void), cb?: (err: any, data?: DescribePackagingGroupCommandOutput) => void ): Promise<DescribePackagingGroupCommandOutput> | void { const command = new DescribePackagingGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Returns a collection of MediaPackage VOD Asset resources. */ public listAssets(args: ListAssetsCommandInput, options?: __HttpHandlerOptions): Promise<ListAssetsCommandOutput>; public listAssets(args: ListAssetsCommandInput, cb: (err: any, data?: ListAssetsCommandOutput) => void): void; public listAssets( args: ListAssetsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAssetsCommandOutput) => void ): void; public listAssets( args: ListAssetsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAssetsCommandOutput) => void), cb?: (err: any, data?: ListAssetsCommandOutput) => void ): Promise<ListAssetsCommandOutput> | void { const command = new ListAssetsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Returns a collection of MediaPackage VOD PackagingConfiguration resources. */ public listPackagingConfigurations( args: ListPackagingConfigurationsCommandInput, options?: __HttpHandlerOptions ): Promise<ListPackagingConfigurationsCommandOutput>; public listPackagingConfigurations( args: ListPackagingConfigurationsCommandInput, cb: (err: any, data?: ListPackagingConfigurationsCommandOutput) => void ): void; public listPackagingConfigurations( args: ListPackagingConfigurationsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListPackagingConfigurationsCommandOutput) => void ): void; public listPackagingConfigurations( args: ListPackagingConfigurationsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListPackagingConfigurationsCommandOutput) => void), cb?: (err: any, data?: ListPackagingConfigurationsCommandOutput) => void ): Promise<ListPackagingConfigurationsCommandOutput> | void { const command = new ListPackagingConfigurationsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Returns a collection of MediaPackage VOD PackagingGroup resources. */ public listPackagingGroups( args: ListPackagingGroupsCommandInput, options?: __HttpHandlerOptions ): Promise<ListPackagingGroupsCommandOutput>; public listPackagingGroups( args: ListPackagingGroupsCommandInput, cb: (err: any, data?: ListPackagingGroupsCommandOutput) => void ): void; public listPackagingGroups( args: ListPackagingGroupsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListPackagingGroupsCommandOutput) => void ): void; public listPackagingGroups( args: ListPackagingGroupsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListPackagingGroupsCommandOutput) => void), cb?: (err: any, data?: ListPackagingGroupsCommandOutput) => void ): Promise<ListPackagingGroupsCommandOutput> | void { const command = new ListPackagingGroupsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Returns a list of the tags assigned to the specified resource. */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Adds tags to the specified resource. You can specify one or more tags to add. */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Removes tags from the specified resource. You can specify one or more tags to remove. */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * Updates a specific packaging group. You can't change the id attribute or any other system-generated attributes. */ public updatePackagingGroup( args: UpdatePackagingGroupCommandInput, options?: __HttpHandlerOptions ): Promise<UpdatePackagingGroupCommandOutput>; public updatePackagingGroup( args: UpdatePackagingGroupCommandInput, cb: (err: any, data?: UpdatePackagingGroupCommandOutput) => void ): void; public updatePackagingGroup( args: UpdatePackagingGroupCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdatePackagingGroupCommandOutput) => void ): void; public updatePackagingGroup( args: UpdatePackagingGroupCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdatePackagingGroupCommandOutput) => void), cb?: (err: any, data?: UpdatePackagingGroupCommandOutput) => void ): Promise<UpdatePackagingGroupCommandOutput> | void { const command = new UpdatePackagingGroupCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import { Input, InputObject, FloatLabelType, TextBox, InputEventArgs } from '@syncfusion/ej2-inputs';import { createCheckBox } from '@syncfusion/ej2-buttons';import { NotifyPropertyChanges, INotifyPropertyChanged, Property, Event, EmitType } from '@syncfusion/ej2-base';import { Component, EventHandler, attributes, formatUnit, ChildProperty, remove, L10n, extend } from '@syncfusion/ej2-base';import { addClass, removeClass, detach, prepend, Complex, closest, setValue, getValue, compile, append } from '@syncfusion/ej2-base';import { select, selectAll, isNullOrUndefined as isNOU, matches, Browser, KeyboardEvents, KeyboardEventArgs } from '@syncfusion/ej2-base';import { DataManager, Query, DataUtil } from '@syncfusion/ej2-data';import { Popup } from '@syncfusion/ej2-popups';import { TreeView, NodeSelectEventArgs, DataBoundEventArgs, FieldsSettingsModel, NodeClickEventArgs } from '@syncfusion/ej2-navigations';import { NodeCheckEventArgs, FailureEventArgs} from '@syncfusion/ej2-navigations'; import {Mode,ExpandOn,TreeFilterType,SortOrder,DdtBeforeOpenEventArgs,DdtChangeEventArgs,DdtPopupEventArgs,DdtDataBoundEventArgs,DdtFilteringEventArgs,DdtFocusEventArgs,DdtKeyPressEventArgs,DdtSelectEventArgs} from "./drop-down-tree"; import {ComponentModel} from '@syncfusion/ej2-base'; /** * Interface for a class Fields */ export interface FieldsModel { /** * This field specifies the child items or mapping field for the nested child items that contains an array of JSON objects. */ child?: string | FieldsModel; /** * Specifies the array of JavaScript objects or instance of Data Manager to populate the dropdown tree items. * * @default [] */ /* eslint-disable */ dataSource?: DataManager | { [key: string]: Object }[]; /** * This fields specifies the mapping field to define the expanded state of a Dropdown tree item. */ expanded?: string; /** * This field specifies the mapping field to indicate whether the Dropdown tree item has children or not. */ hasChildren?: string; /** * Specifies the mapping field for htmlAttributes to be added to the Dropdown Tree item. */ htmlAttributes?: string; /** * Specifies the mapping field for icon class of each Dropdown Tree item that will be added before the text. */ iconCss?: string; /** * Specifies the mapping field for image URL of each Dropdown Tree item where image will be added before the text. */ imageUrl?: string; /** * Specifies the parent value field mapped in the data source. */ parentValue?: string; /** * Defines the external [`Query`](https://ej2.syncfusion.com/documentation/api/data/query/) * that will execute along with the data processing. * * @default null */ query?: Query; /** * Specifies the mapping field for the selected state of the Dropdown Tree item. */ selected?: string; /** * Specifies the table name used to fetch data from a specific table in the server. */ tableName?: string; /** * Specifies the mapping field for text displayed as Dropdown Tree items display text. */ text?: string; /** * Specifies the mapping field for tooltip that will be displayed as hovering text of the Dropdown Tree item. */ tooltip?: string; /** * Specifies the value(ID) field mapped in the data source. */ value?: string; } /** * Interface for a class TreeSettings */ export interface TreeSettingsModel { /** * Specifies whether the child and parent tree items check states are dependent over each other when checkboxes are enabled. * * @default false */ autoCheck?: boolean; /** * Specifies the action on which the parent items in the pop-up should expand or collapse. The available actions are * * `Auto` - In desktop, the expand or collapse operation happens when you double-click the node, * and in mobile devices it happens on single-tap. * * `Click` - The expand or collapse operation happens when you perform single-click/tap * on the pop-up item in both desktop and mobile devices. * * `DblClick` - The expand or collapse operation happens when you perform a double-click/tap * on the pop-up item in both desktop and mobile devices. * * `None` - The expand or collapse operation will not happen when you perform single-click/tap * or double-click/tap on the pop-up items in both desktop and mobile devices. * * @default 'Auto' */ expandOn?: ExpandOn; /** * By default, the load on demand (Lazy load) is set to false. * Enabling this property will render only the parent tree items in the popup and * the child items will be rendered on demand when expanding the corresponding parent node. * * @default false */ loadOnDemand?: boolean; } /** * Interface for a class DropDownTree */ export interface DropDownTreeModel extends ComponentModel{ /** * Specifies the template that renders to the popup list content of the * Dropdown Tree component when the data fetch request from the remote server fails. * * @default 'The Request Failed' */ actionFailureTemplate?: string; /** * When allowFiltering is set to true, it shows the filter bar (search text box) of the component. * The filter action retrieves matched items through the **filtering** event based on the characters typed in the search text box. * If no match is found, the value of the **noRecordsTemplate** property will be displayed. * * @default false */ allowFiltering?: boolean; /** * Enables or disables the multi-selection of items. To select multiple items: * * Select the items by holding down the **CTRL** key when clicking on the items. * * Select consecutive items by clicking the first item to select and hold down the **SHIFT** key and click the last item to select. * * @default false */ allowMultiSelection?: boolean; /** * By default, the Dropdown Tree component fires the change event while focusing out the component. * If you want to fire the change event on every value selection and remove, then disable this property. * * @default true */ changeOnBlur?: boolean; /** * Specifies the CSS classes to be added with the root and popup element of the Dropdown Tree component. * that allows customization of appearance. * * @default '' */ cssClass?: string; /** * This property is used to customize the display text of the selected items in the Dropdown Tree. The given custom template is * added to the input instead of the selected item text in the Dropdown Tree when the multi-selection or checkbox support is enabled. * * @default "${value.length} item(s) selected" */ customTemplate?: string; /** * Defines the value separator character in the input element when multi-selection or checkbox is enabled in the Dropdown Tree. * The delimiter character is applicable only for **default** and **delimiter** visibility modes. * * @default "," */ delimiterChar?: string; /** * Specifies a value that indicates whether the Dropdown Tree component is enabled or not. * * @default true */ enabled?: boolean; /** * Specifies the data source and mapping fields to render Dropdown Tree items. * * @default {value: 'value', text: 'text', dataSource: [], child: 'child', parentValue: 'parentValue', hasChildren: 'hasChildren', * expanded: 'expanded', htmlAttributes: 'htmlAttributes', iconCss: 'iconCss', imageUrl: 'imageUrl', * query: null, selected: 'selected', tableName: null, tooltip: 'tooltip'} */ fields?: FieldsModel; /** * Accepts the value to be displayed as a watermark text on the filter bar. * * @default null */ filterBarPlaceholder?: string; /** * Determines on which filter type, the component needs to be considered on search action. * The **TreeFilterType** and its supported data types are, * * <table> * <tr> * <td colSpan=1 rowSpan=1><b> * TreeFilterType</b></td><td colSpan=1 rowSpan=1><b> * Description</b></td><td colSpan=1 rowSpan=1><b> * Supported Types</b></td></tr> * <tr> * <td colSpan=1 rowSpan=1> * StartsWith<br/></td><td colSpan=1 rowSpan=1> * Checks whether a value begins with the specified value.<br/></td><td colSpan=1 rowSpan=1> * String<br/></td></tr> * <tr> * <td colSpan=1 rowSpan=1> * EndsWith<br/></td><td colSpan=1 rowSpan=1> * Checks whether a value ends with the specified value.<br/></td><td colSpan=1 rowSpan=1> * String<br/></td></tr> * <tr> * <td colSpan=1 rowSpan=1> * Contains<br/></td><td colSpan=1 rowSpan=1> * Checks whether a value contains with specified value.<br/></td><td colSpan=1 rowSpan=1> * String<br/></td></tr> * </table> * * The default value set to **StartsWith**, all the suggestion items which starts with typed characters to listed in the * suggestion popup. * * @default 'StartsWith' */ filterType?: TreeFilterType; /** * Specifies whether to display the floating label above the input element. * Possible values are: * * Never: The label will never float in the input when the placeholder is available. * * Always: The floating label will always float above the input. * * Auto: The floating label will float above the input after focusing or entering a value in the input. * * @default Syncfusion.EJ2.Inputs.FloatLabelType.Never * @isEnumeration true */ floatLabelType?: FloatLabelType; /** * Specifies the template that renders a customized footer container at the bottom of the pop-up list. * By default, the footerTemplate will be null and there will be no footer container for the pop-up list. * * @default null */ footerTemplate?: string; /** * When **ignoreAccent** is set to true, then it ignores the diacritic characters or accents when filtering. */ ignoreAccent?: boolean; /** * When set to false, consider the case-sensitive on performing the search to find suggestions. By default, consider the casing. * * @default true */ ignoreCase?: boolean; /** * Specifies the template that renders a customized header container at the top of the pop-up list. * By default, the headerTemplate will be null and there will be no header container for the pop-up list. * * @default null */ headerTemplate?: string; /** * Allows additional HTML attributes such as title, name, etc., and accepts n number of attributes in a key-value pair format. * * @default {} */ htmlAttributes?: { [key: string]: string; }; /** * Specifies a template to render customized content for all the items. * If the **itemTemplate** property is set, the template content overrides the displayed item text. * The property accepts [template string](https://ej2.syncfusion.com/documentation/common/template-engine/) * or HTML element ID holding the content. * * @default null */ itemTemplate?: string; /** * Configures visibility mode for component interaction when allowMultiSelection or checkbox is enabled. * Different modes are: * * Box : Selected items will be visualized in chip. * * Delimiter : Selected items will be visualized in the text content. * * Default : On focus in component will act in the box mode. On blur component will act in the delimiter mode. * * Custom : Selected items will be visualized with the given custom template value. The given custom template * is added to the input instead of the selected item text in the Dropdown Tree when the multi-selection or checkbox support is enabled. */ mode?: Mode; /** * Specifies the template that renders a customized pop-up list content when there is no data available * to be displayed within the pop-up. * * @default 'No Records Found' */ noRecordsTemplate?: string; /** * Specifies a short hint that describes the expected value of the Dropdown Tree component. * * @default null */ placeholder?: string; /** * Specifies the height of the pop-up list. * * @default '300px' */ popupHeight?: string | number; /** * Specifies the width of the popup list. By default, the popup width sets based on the width of the Dropdown Tree element. * * @default '100%' */ popupWidth?: string | number; /** * When set to true, the user interactions on the component will be disabled. * * @default false */ readonly?: boolean; /** * Specifies whether to show or hide the selectAll checkbox in the pop-up which allows you to select all the items in the pop-up. * * @default false */ showSelectAll?: boolean; /** * Specifies the display text for the selectAll checkbox in the pop-up. * * @default 'Select All' */ selectAllText?: string; /** * Enables or disables the checkbox option in the Dropdown Tree component. * If enabled, the Checkbox will be displayed next to the expand or collapse icon of the tree items. * * @default false */ showCheckBox?: boolean; /** * Specifies whether to show or hide the clear icon in textbox. * When the clear button is clicked, `value`, `text` properties will be reset to null. * * @default true */ showClearButton?: boolean; /** * Specifies whether to show or hide the Dropdown button. * * @default true */ showDropDownIcon?: boolean; /** * Specifies a value that indicates whether the items are sorted in the ascending or descending order, or not sorted at all. * The available types of sort order are, * * `None` - The items are not sorted. * * `Ascending` - The items are sorted in the ascending order. * * `Descending` - The items are sorted in the descending order. * * @default 'None' */ sortOrder?: SortOrder; /** * Gets or sets the display text of the selected item which maps the data **text** field in the component. * * @default null */ text?: string; /** * Configures the pop-up tree settings. * * @default {autoCheck: false, expandOn: 'Auto', loadOnDemand: false} */ treeSettings?: TreeSettingsModel; /** * Specifies the display text for the unselect all checkbox in the pop-up. * * @default 'Unselect All' */ unSelectAllText?: string; /** * Gets or sets the value of selected item(s) which maps the data **value** field in the component. * * @default null * @aspType Object */ value?: string[]; /** * Specifies the width of the component. By default, the component width sets based on the width of its parent container. * You can also set the width in pixel values. * * @default '100%' */ width?: string | number; /** * Specifies the z-index value of the pop-up element. * * @default 1000 */ zIndex?: number; /** * Defines whether to enable or disable the feature called wrap the selected items into multiple lines when the selected item's text * content exceeded the input width limit. * * @default false */ wrapText?: boolean; /** * Triggers when the data fetch request from the remote server fails. * * @event */ /* eslint-disable */ actionFailure?: EmitType<Object>; /** * Fires when popup opens before animation. * * @event */ beforeOpen?: EmitType<DdtBeforeOpenEventArgs>; /** * Triggers when an item in a popup is selected or when the model value is changed by user. * * @event */ change?: EmitType<DdtChangeEventArgs>; /** * Fires when popup close after animation completion. * * @event */ close?: EmitType<DdtPopupEventArgs>; /** * Triggers when the Dropdown Tree input element gets focus-out. * * @event */ /* eslint-disable */ blur?: EmitType<Object>; /** * Triggers when the Dropdown Tree is created successfully. * * @event */ /* eslint-disable */ created?: EmitType<Object>; /**      * Triggers when data source is populated in the Dropdown Tree. *      * @event      */ dataBound?: EmitType<DdtDataBoundEventArgs>; /** * Triggers when the Dropdown Tree is destroyed successfully. * * @event */ /* eslint-disable */ destroyed?: EmitType<Object>; /** * Triggers on typing a character in the filter bar when the **allowFiltering** is enabled. * * @event */ filtering?: EmitType<DdtFilteringEventArgs>; /** * Triggers when the Dropdown Tree input element is focused. * * @event */ focus?: EmitType<DdtFocusEventArgs>; /** * Triggers when key press is successful. It helps to customize the operations at key press. * * @event */ keyPress?: EmitType<DdtKeyPressEventArgs>; /** * Fires when popup opens after animation completion. * * @event */ open?: EmitType<DdtPopupEventArgs>; /** * Triggers when an item in the popup is selected by the user either with mouse/tap or with keyboard navigation. * * @event */ select?: EmitType<DdtSelectEventArgs>; }
the_stack
const MANIFEST_UPDATE_TYPE = { Full: 0, Partial: 1, }; describe("Manifest - replacePeriods", () => { beforeEach(() => { jest.resetModules(); }); // Case 1 : // // old periods : p1, p2 // new periods : p2 it("should remove old period", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p1" }, { id: "p2" }, ] as any; const newPeriods = [ { id: "p2" }, ] as any; const replacePeriods = require("../update_periods").replacePeriods; replacePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(1); expect(oldPeriods[0].id).toBe("p2"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(1); expect(fakeUpdatePeriodInPlace).toHaveBeenNthCalledWith(1, { id: "p2" }, { id: "p2" }, 0); }); // Case 2 : // // old periods : p1 // new periods : p1, p2 it("should add new period", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p2" }, ] as any; const newPeriods = [ { id: "p2" }, { id: "p3" }, ] as any; const replacePeriods = require("../update_periods").replacePeriods; replacePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(2); expect(oldPeriods[0].id).toBe("p2"); expect(oldPeriods[1].id).toBe("p3"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(1); expect(fakeUpdatePeriodInPlace).toHaveBeenNthCalledWith(1, { id: "p2" }, { id: "p2" }, 0); }); // Case 3 : // // old periods: p1 // new periods: p2 it("should replace period", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p1" }, ] as any; const newPeriods = [ { id: "p2" }, ] as any; const replacePeriods = require("../update_periods").replacePeriods; replacePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(1); expect(oldPeriods[0].id).toBe("p2"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(0); }); // Case 4 : // // old periods: p0, p1, p2 // new periods: p1, a, b, p2, p3 it("should handle more complex period replacement", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p0" }, { id: "p1" }, { id: "p2", start: 0 }, ] as any; const newPeriods = [ { id: "p1" }, { id: "a" }, { id: "b" }, { id: "p2", start: 2 }, { id: "p3" }, ] as any; const replacePeriods = require("../update_periods").replacePeriods; replacePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(5); expect(oldPeriods[0].id).toBe("p1"); expect(oldPeriods[1].id).toBe("a"); expect(oldPeriods[2].id).toBe("b"); expect(oldPeriods[3].id).toBe("p2"); expect(oldPeriods[4].id).toBe("p3"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(2); expect(fakeUpdatePeriodInPlace).toHaveBeenNthCalledWith(1, { id: "p1" }, { id: "p1" }, 0); expect(fakeUpdatePeriodInPlace).toHaveBeenNthCalledWith(2, { id: "p2", start: 0 }, { id: "p2", start: 2 }, 0); }); // Case 5 : // // old periods : p2 // new periods : p1, p2 it("should add new period before", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p2" }, ] as any; const newPeriods = [ { id: "p1" }, { id: "p2" }, ] as any; const replacePeriods = require("../update_periods").replacePeriods; replacePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(2); expect(oldPeriods[0].id).toBe("p1"); expect(oldPeriods[1].id).toBe("p2"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(1); expect(fakeUpdatePeriodInPlace).toHaveBeenNthCalledWith(1, { id: "p2" }, { id: "p2" }, 0); }); // Case 6 : // // old periods : p1, p2 // new periods : No periods it("should remove all periods", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p1" }, { id: "p2" }, ] as any; const newPeriods = [] as any; const replacePeriods = require("../update_periods").replacePeriods; replacePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(0); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(0); }); // Case 7 : // // old periods : No periods // new periods : p1, p2 it("should add all periods to empty array", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [] as any; const newPeriods = [ { id: "p1" }, { id: "p2" }, ] as any; const replacePeriods = require("../update_periods").replacePeriods; replacePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(2); expect(oldPeriods[0].id).toBe("p1"); expect(oldPeriods[1].id).toBe("p2"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(0); }); }); describe("updatePeriods", () => { beforeEach(() => { jest.resetModules(); }); // Case 1 : // // old periods : p1, p2 // new periods : p2 it("should not remove old period", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p1", start: 50, end: 60 }, { id: "p2", start: 60 } ] as any; const newPeriods = [ { id: "p2", start: 60 } ] as any; const updatePeriods = require("../update_periods").updatePeriods; updatePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(2); expect(oldPeriods[0].id).toBe("p1"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(1); expect(fakeUpdatePeriodInPlace).toHaveBeenNthCalledWith(1, { id: "p2", start: 60 }, { id: "p2", start: 60 }, MANIFEST_UPDATE_TYPE.Partial); }); // Case 2 : // // old periods : p1 // new periods : p1, p2 it("should add new period", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p2", start: 60 } ] as any; const newPeriods = [ { id: "p2", start: 60, end: 80 }, { id: "p3", start: 80 } ] as any; const updatePeriods = require("../update_periods").updatePeriods; updatePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(2); expect(oldPeriods[0].id).toBe("p2"); expect(oldPeriods[1].id).toBe("p3"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(1); expect(fakeUpdatePeriodInPlace) .toHaveBeenNthCalledWith(1, { id: "p2", start: 60 }, { id: "p2", start: 60, end: 80 }, MANIFEST_UPDATE_TYPE.Partial); }); // Case 3 : // // old periods: p1 // new periods: p3 it("should throw when encountering two distant Periods", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p1", start: 50, end: 60 } ] as any; const newPeriods = [ { id: "p3", start: 70, end: 80 } ] as any; const updatePeriods = require("../update_periods").updatePeriods; let error = null; try { updatePeriods(oldPeriods, newPeriods); } catch (e) { error = e; } expect(error).toBeInstanceOf(Error); // Impossible check to shut-up TypeScript if (!(error instanceof Error)) { throw new Error("Impossible: already checked it was an Error instance"); } expect((error as { type? : string }).type).toEqual("MEDIA_ERROR"); expect((error as { code? : string }).code).toEqual("MANIFEST_UPDATE_ERROR"); expect(error.message).toEqual( "MediaError (MANIFEST_UPDATE_ERROR) Cannot perform partial update: not enough data" ); expect(oldPeriods.length).toBe(1); expect(oldPeriods[0].id).toBe("p1"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(0); }); // Case 4 : // // old periods: p0, p1, p2 // new periods: p1, a, b, p2, p3 it("should handle more complex period replacement", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace })); const oldPeriods = [ { id: "p0", start: 50, end: 60 }, { id: "p1", start: 60, end: 70 }, { id: "p2", start: 70 } ] as any; const newPeriods = [ { id: "p1", start: 60, end: 65 }, { id: "a", start: 65, end: 68 }, { id: "b", start: 68, end: 70 }, { id: "p2", start: 70, end: 80 }, { id: "p3", start: 80 } ] as any; const updatePeriods = require("../update_periods").updatePeriods; updatePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(6); expect(oldPeriods[0].id).toBe("p0"); expect(oldPeriods[1].id).toBe("p1"); expect(oldPeriods[2].id).toBe("a"); expect(oldPeriods[3].id).toBe("b"); expect(oldPeriods[4].id).toBe("p2"); expect(oldPeriods[5].id).toBe("p3"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(1); expect(fakeUpdatePeriodInPlace) .toHaveBeenNthCalledWith(1, { id: "p1", start: 60, end: 70 }, { id: "p1", start: 60, end: 65 }, MANIFEST_UPDATE_TYPE.Partial); }); // Case 5 : // // old periods : p2 // new periods : p1, p2 it("should throw when the first period is not encountered", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace })); const oldPeriods = [ { id: "p2", start: 70 } ] as any; const newPeriods = [ { id: "p1", start: 50, end: 70 }, { id: "p2", start: 70 } ] as any; const updatePeriods = require("../update_periods").updatePeriods; let error = null; try { updatePeriods(oldPeriods, newPeriods); } catch (e) { error = e; } expect(error).toBeInstanceOf(Error); // Impossible check to shut-up TypeScript if (!(error instanceof Error)) { throw new Error("Impossible: already checked it was an Error instance"); } expect((error as { type? : string }).type).toEqual("MEDIA_ERROR"); expect((error as { code? : string }).code).toEqual("MANIFEST_UPDATE_ERROR"); expect(error.message).toEqual( "MediaError (MANIFEST_UPDATE_ERROR) Cannot perform partial update: incoherent data" ); expect(oldPeriods.length).toBe(1); expect(oldPeriods[0].id).toBe("p2"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(0); }); // Case 6 : // // old periods : p1, p2 // new periods : No periods it("should keep old periods if no new Period is available", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace })); const oldPeriods = [ { id: "p1" }, { id: "p2" } ] as any; const newPeriods = [] as any; const updatePeriods = require("../update_periods").updatePeriods; updatePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(2); expect(oldPeriods[0].id).toBe("p1"); expect(oldPeriods[1].id).toBe("p2"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(0); }); // Case 7 : // // old periods : No periods // new periods : p1, p2 it("should set only new Periods if none were available before", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace })); const oldPeriods = [] as any; const newPeriods = [ { id: "p1" }, { id: "p2" } ] as any; const updatePeriods = require("../update_periods").updatePeriods; updatePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(2); expect(oldPeriods[0].id).toBe("p1"); expect(oldPeriods[1].id).toBe("p2"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(0); }); // Case 8 : // // old periods : p0, p1 // new periods : p4, p5 it("should throw if the new periods come strictly after", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace })); const updatePeriods = require("../update_periods").updatePeriods; const oldPeriods = [ { id: "p0", start: 50, end: 60 }, { id: "p1", start: 60, end: 70 } ] as any; const newPeriods = [ { id: "p3", start: 80 } ] as any; let error = null; try { updatePeriods(oldPeriods, newPeriods); } catch (e) { error = e; } expect(error).toBeInstanceOf(Error); // Impossible check to shut-up TypeScript if (!(error instanceof Error)) { throw new Error("Impossible: already checked it was an Error instance"); } expect((error as { type? : string }).type).toEqual("MEDIA_ERROR"); expect((error as { code? : string }).code).toEqual("MANIFEST_UPDATE_ERROR"); expect(error.message).toEqual( "MediaError (MANIFEST_UPDATE_ERROR) Cannot perform partial update: not enough data" ); expect(oldPeriods.length).toBe(2); expect(oldPeriods[0].id).toBe("p0"); expect(oldPeriods[1].id).toBe("p1"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(0); }); // Case 9 : // // old periods: p1 // new periods: p2 it("should concatenate consecutive periods", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p1", start: 50, end: 60 } ] as any; const newPeriods = [ { id: "p2", start: 60, end: 80 } ] as any; const updatePeriods = require("../update_periods").updatePeriods; updatePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(2); expect(oldPeriods[0].id).toBe("p1"); expect(oldPeriods[1].id).toBe("p2"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(0); }); // Case 10 : // // old periods: p1 // new periods: px /* eslint-disable max-len */ it("should throw when encountering two completely different Periods with the same start", () => { /* eslint-enable max-len */ const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace, })); const oldPeriods = [ { id: "p1", start: 50, end: 60 } ] as any; const newPeriods = [ { id: "px", start: 50, end: 70 } ] as any; const updatePeriods = require("../update_periods").updatePeriods; let error = null; try { updatePeriods(oldPeriods, newPeriods); } catch (e) { error = e; } expect(error).toBeInstanceOf(Error); // Impossible check to shut-up TypeScript if (!(error instanceof Error)) { throw new Error("Impossible: already checked it was an Error instance"); } expect((error as { type? : string }).type).toEqual("MEDIA_ERROR"); expect((error as { code? : string }).code).toEqual("MANIFEST_UPDATE_ERROR"); expect(error.message).toEqual( "MediaError (MANIFEST_UPDATE_ERROR) Cannot perform partial update: incoherent data" ); expect(oldPeriods.length).toBe(1); expect(oldPeriods[0].id).toBe("p1"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(0); }); // Case 11 : // // old periods: p0, p1, p2 // new periods: p1, p2, p3 it("should handle more complex period replacement", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace })); const oldPeriods = [ { id: "p0", start: 50, end: 60 }, { id: "p1", start: 60, end: 70 }, { id: "p2", start: 70 } ] as any; const newPeriods = [ { id: "p1", start: 60, end: 65 }, { id: "p2", start: 65, end: 80 }, { id: "p3", start: 80 } ] as any; const updatePeriods = require("../update_periods").updatePeriods; updatePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(4); expect(oldPeriods[0].id).toBe("p0"); expect(oldPeriods[1].id).toBe("p1"); expect(oldPeriods[2].id).toBe("p2"); expect(oldPeriods[3].id).toBe("p3"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(2); expect(fakeUpdatePeriodInPlace) .toHaveBeenNthCalledWith(1, { id: "p1", start: 60, end: 70 }, { id: "p1", start: 60, end: 65 }, MANIFEST_UPDATE_TYPE.Partial); expect(fakeUpdatePeriodInPlace) .toHaveBeenNthCalledWith(2, { id: "p2", start: 70 }, { id: "p2", start: 65, end: 80 }, MANIFEST_UPDATE_TYPE.Full); }); // Case 12 : // // old periods: p0, p1, p2, p3 // new periods: p1, p3 it("should handle more complex period replacement", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace })); const oldPeriods = [ { id: "p0", start: 50, end: 60 }, { id: "p1", start: 60, end: 70 }, { id: "p2", start: 70, end: 80 }, { id: "p3", start: 80 } ] as any; const newPeriods = [ { id: "p1", start: 60, end: 70 }, { id: "p3", start: 80 } ] as any; const updatePeriods = require("../update_periods").updatePeriods; updatePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(3); expect(oldPeriods[0].id).toBe("p0"); expect(oldPeriods[1].id).toBe("p1"); expect(oldPeriods[2].id).toBe("p3"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(2); expect(fakeUpdatePeriodInPlace) .toHaveBeenNthCalledWith(1, { id: "p1", start: 60, end: 70 }, { id: "p1", start: 60, end: 70 }, MANIFEST_UPDATE_TYPE.Partial); expect(fakeUpdatePeriodInPlace) .toHaveBeenNthCalledWith(2, { id: "p3", start: 80 }, { id: "p3", start: 80 }, MANIFEST_UPDATE_TYPE.Full); }); // Case 13 : // // old periods: p0, p1, p2, p3, p4 // new periods: p1, p3 it("should remove periods not included in the new Periods", () => { const fakeUpdatePeriodInPlace = jest.fn(() => { return; }); jest.mock("../update_period_in_place", () => ({ __esModule: true as const, default: fakeUpdatePeriodInPlace })); const oldPeriods = [ { id: "p0", start: 50, end: 60 }, { id: "p1", start: 60, end: 70 }, { id: "p2", start: 70, end: 80 }, { id: "p3", start: 80, end: 90 }, { id: "p4", start: 90 } ] as any; const newPeriods = [ { id: "p1", start: 60, end: 70 }, { id: "p3", start: 80, end: 90 } ] as any; const updatePeriods = require("../update_periods").updatePeriods; updatePeriods(oldPeriods, newPeriods); expect(oldPeriods.length).toBe(3); expect(oldPeriods[0].id).toBe("p0"); expect(oldPeriods[1].id).toBe("p1"); expect(oldPeriods[2].id).toBe("p3"); expect(fakeUpdatePeriodInPlace).toHaveBeenCalledTimes(2); expect(fakeUpdatePeriodInPlace) .toHaveBeenNthCalledWith(1, { id: "p1", start: 60, end: 70 }, { id: "p1", start: 60, end: 70 }, MANIFEST_UPDATE_TYPE.Partial); expect(fakeUpdatePeriodInPlace) .toHaveBeenNthCalledWith(2, { id: "p3", start: 80, end: 90 }, { id: "p3", start: 80, end: 90 }, MANIFEST_UPDATE_TYPE.Full); }); });
the_stack
import { LimitOrder } from '@0x/asset-swapper'; import { LimitOrderFields } from '@0x/protocol-utils'; import * as _ from 'lodash'; import { Connection, In, MoreThanOrEqual } from 'typeorm'; import { DB_ORDERS_UPDATE_CHUNK_SIZE, SRA_ORDER_EXPIRATION_BUFFER_SECONDS, SRA_PERSISTENT_ORDER_POSTING_WHITELISTED_API_KEYS, } from '../config'; import { ONE_SECOND_MS } from '../constants'; import { PersistentSignedOrderV4Entity, SignedOrderV4Entity } from '../entities'; import { ValidationError, ValidationErrorCodes, ValidationErrorReasons } from '../errors'; import { alertOnExpiredOrders } from '../logger'; import { OrderbookResponse, OrderEventEndState, PaginatedCollection, SignedLimitOrder, SRAOrder } from '../types'; import { orderUtils } from '../utils/order_utils'; import { OrderWatcherInterface } from '../utils/order_watcher'; import { paginationUtils } from '../utils/pagination_utils'; export class OrderBookService { private readonly _connection: Connection; private readonly _orderWatcher: OrderWatcherInterface; public static isAllowedPersistentOrders(apiKey: string): boolean { return SRA_PERSISTENT_ORDER_POSTING_WHITELISTED_API_KEYS.includes(apiKey); } public async getOrderByHashIfExistsAsync(orderHash: string): Promise<SRAOrder | undefined> { let signedOrderEntity; signedOrderEntity = await this._connection.manager.findOne(SignedOrderV4Entity, orderHash); if (!signedOrderEntity) { signedOrderEntity = await this._connection.manager.findOne(PersistentSignedOrderV4Entity, orderHash); } if (signedOrderEntity === undefined) { return undefined; } else { return orderUtils.deserializeOrderToSRAOrder(signedOrderEntity as Required<SignedOrderV4Entity>); } } // tslint:disable-next-line:prefer-function-over-method public async getOrderBookAsync( page: number, perPage: number, baseToken: string, quoteToken: string, ): Promise<OrderbookResponse> { const orderEntities = await this._connection.manager.find(SignedOrderV4Entity, { where: { takerToken: In([baseToken, quoteToken]), makerToken: In([baseToken, quoteToken]), }, }); const bidSignedOrderEntities = orderEntities.filter( (o) => o.takerToken === baseToken && o.makerToken === quoteToken, ); const askSignedOrderEntities = orderEntities.filter( (o) => o.takerToken === quoteToken && o.makerToken === baseToken, ); const bidApiOrders: SRAOrder[] = (bidSignedOrderEntities as Required<SignedOrderV4Entity>[]) .map(orderUtils.deserializeOrderToSRAOrder) .filter(orderUtils.isFreshOrder) .sort((orderA, orderB) => orderUtils.compareBidOrder(orderA.order, orderB.order)); const askApiOrders: SRAOrder[] = (askSignedOrderEntities as Required<SignedOrderV4Entity>[]) .map(orderUtils.deserializeOrderToSRAOrder) .filter(orderUtils.isFreshOrder) .sort((orderA, orderB) => orderUtils.compareAskOrder(orderA.order, orderB.order)); const paginatedBidApiOrders = paginationUtils.paginate(bidApiOrders, page, perPage); const paginatedAskApiOrders = paginationUtils.paginate(askApiOrders, page, perPage); return { bids: paginatedBidApiOrders, asks: paginatedAskApiOrders, }; } // tslint:disable-next-line:prefer-function-over-method public async getOrdersAsync( page: number, perPage: number, orderFieldFilters: Partial<SignedOrderV4Entity>, additionalFilters: { isUnfillable?: boolean; trader?: string }, ): Promise<PaginatedCollection<SRAOrder>> { // Validation if (additionalFilters.isUnfillable === true && orderFieldFilters.maker === undefined) { throw new ValidationError([ { field: 'maker', code: ValidationErrorCodes.RequiredField, reason: ValidationErrorReasons.UnfillableRequiresMakerAddress, }, ]); } // Each array element in `filters` is an OR subclause const filters = []; // Pre-filters; exists in the entity verbatim const columnNames = this._connection.getMetadata(SignedOrderV4Entity).columns.map((x) => x.propertyName); const orderFilter = _.pickBy(orderFieldFilters, (v, k) => { return columnNames.includes(k); }); // Post-filters; filters that don't exist verbatim if (additionalFilters.trader) { filters.push({ ...orderFilter, maker: additionalFilters.trader, }); filters.push({ ...orderFilter, taker: additionalFilters.trader, }); } else { filters.push(orderFilter); } // Add an expiry time check to all filters const minExpiryTime = Math.floor(Date.now() / ONE_SECOND_MS) + SRA_ORDER_EXPIRATION_BUFFER_SECONDS; const filtersWithExpirationCheck = filters.map((filter) => ({ ...filter, expiry: MoreThanOrEqual(minExpiryTime), })); const [signedOrderCount, signedOrderEntities] = await Promise.all([ this._connection.manager.count(SignedOrderV4Entity, { where: filtersWithExpirationCheck, }), this._connection.manager.find(SignedOrderV4Entity, { where: filtersWithExpirationCheck, ...paginationUtils.paginateDBFilters(page, perPage), order: { hash: 'ASC', }, }), ]); const apiOrders = (signedOrderEntities as Required<SignedOrderV4Entity>[]).map( orderUtils.deserializeOrderToSRAOrder, ); // Join with persistent orders let persistentOrders: SRAOrder[] = []; let persistentOrdersCount = 0; if (additionalFilters.isUnfillable === true) { const removedStates = [ OrderEventEndState.Cancelled, OrderEventEndState.Expired, OrderEventEndState.FullyFilled, OrderEventEndState.Invalid, OrderEventEndState.StoppedWatching, OrderEventEndState.Unfunded, ]; const filtersWithoutDuplicateSignedOrders = filters.map((filter) => ({ ...filter, orderState: In(removedStates), })); let persistentOrderEntities = []; [persistentOrdersCount, persistentOrderEntities] = await Promise.all([ this._connection.manager.count(PersistentSignedOrderV4Entity, { where: filtersWithoutDuplicateSignedOrders, }), this._connection.manager.find(PersistentSignedOrderV4Entity, { where: filtersWithoutDuplicateSignedOrders, ...paginationUtils.paginateDBFilters(page, perPage), order: { hash: 'ASC', }, }), ]); persistentOrders = (persistentOrderEntities as Required<PersistentSignedOrderV4Entity>[]).map( orderUtils.deserializeOrderToSRAOrder, ); } const allOrders = apiOrders.concat(persistentOrders); const total = signedOrderCount + persistentOrdersCount; // Paginate const paginatedApiOrders = paginationUtils.paginateSerialize(allOrders, total, page, perPage); return paginatedApiOrders; } public async getBatchOrdersAsync( page: number, perPage: number, makerTokens: string[], takerTokens: string[], ): Promise<PaginatedCollection<SRAOrder>> { const filterObject = { makerToken: In(makerTokens), takerToken: In(takerTokens), }; const signedOrderEntities = (await this._connection.manager.find(SignedOrderV4Entity, { where: filterObject, })) as Required<SignedOrderV4Entity>[]; const apiOrders = signedOrderEntities.map(orderUtils.deserializeOrderToSRAOrder); // check for expired orders const { fresh, expired } = orderUtils.groupByFreshness(apiOrders, SRA_ORDER_EXPIRATION_BUFFER_SECONDS); alertOnExpiredOrders(expired); const paginatedApiOrders = paginationUtils.paginate(fresh, page, perPage); return paginatedApiOrders; } constructor(connection: Connection, orderWatcher: OrderWatcherInterface) { this._connection = connection; this._orderWatcher = orderWatcher; } public async addOrderAsync(signedOrder: SignedLimitOrder): Promise<void> { await this._orderWatcher.postOrdersAsync([signedOrder]); } public async addOrdersAsync(signedOrders: SignedLimitOrder[]): Promise<void> { await this._orderWatcher.postOrdersAsync(signedOrders); } public async addPersistentOrdersAsync(signedOrders: SignedLimitOrder[]): Promise<void> { await this._orderWatcher.postOrdersAsync(signedOrders); // Figure out which orders were accepted by looking for them in the database. const hashes = signedOrders.map((o) => { const limitOrder = new LimitOrder(o as LimitOrderFields); return limitOrder.getHash(); }); const addedOrders = await this._connection.manager.find(SignedOrderV4Entity, { where: { hash: In(hashes) }, }); // MAX SQL variable size is 999. This limit is imposed via Sqlite. // The SELECT query is not entirely effecient and pulls in all attributes // so we need to leave space for the attributes on the model represented // as SQL variables in the "AS" syntax. We leave 99 free for the // signedOrders model await this._connection .getRepository(PersistentSignedOrderV4Entity) .save(addedOrders, { chunk: DB_ORDERS_UPDATE_CHUNK_SIZE }); } }
the_stack
import { Point } from './../primitives/point'; import { Size } from './../primitives/size'; import { PointModel } from './../primitives/point-model'; import { RectAttributes, PathAttributes, TextAttributes } from './canvas-interface'; import { pathSegmentCollection, processPathData } from './../utility/path-util'; import { PathSegment, ImageAttributes, StyleAttributes } from './canvas-interface'; import { BaseAttributes, LineAttributes, CircleAttributes, SubTextElement, TextBounds } from './canvas-interface'; import { LinearGradientModel, RadialGradientModel, StopModel } from './../core/appearance-model'; import { IRenderer } from './../rendering/IRenderer'; import { setAttributeSvg, setChildPosition } from './../utility/dom-util'; import { overFlow, wordBreakToString, cornersPointsBeforeRotation } from './../utility/base-util'; import { CanvasRenderer } from './../rendering/canvas-renderer'; import { DiagramNativeElement } from '../core/elements/native-element'; import { DiagramHtmlElement } from '../core/elements/html-element'; import { TransformFactor as Transforms } from '../interaction/scroller'; import { createSvgElement, createHtmlElement, getBackgroundLayerSvg } from '../utility/dom-util'; import { removeGradient, checkBrowserInfo } from '../utility/diagram-util'; import { Container } from '../core/containers/container'; import { isBlazor } from '@syncfusion/ej2-base'; /** * SVG Renderer */ /** @private */ export class SvgRenderer implements IRenderer { /** * Draw the shawdow for the rectangle shape in diagram \ * * @returns {void} Draw the shawdow for the rectangle shape in diagram .\ * * @param { SVGElement} options - Provide the base attributes . * @param { RectAttributes} canvas - Provide the canvas values . * @param { string} collection - Provide the collection value. * @param { boolean} parentSvg - Provide the parent SVG values . * @private */ public renderShadow(options: BaseAttributes, canvas: SVGElement, collection: Object[] = null, parentSvg?: SVGSVGElement): void { const pointModel: PointModel = { x: 0, y: 0 }; const point: PointModel = Point.transform(pointModel, options.shadow.angle, options.shadow.distance); //const tX: number = options.x + point.x; const tY: number = options.y + point.y; //let pivotX: number = tX + options.width * options.pivotX; //let pivotY: number = tY + options.height * options.pivotY; let type: string; let shadowElement: SVGPathElement | SVGRectElement; if (parentSvg) { shadowElement = parentSvg.getElementById(canvas.id + '_shadow') as SVGPathElement; } if (!shadowElement) { type = collection ? 'path' : 'rect'; shadowElement = document.createElementNS('http://www.w3.org/2000/svg', type) as SVGRectElement | SVGPathElement; canvas.appendChild(shadowElement); } const attr: Object = { 'id': canvas.id + '_shadow', 'fill': options.shadow.color, 'stroke': options.shadow.color, 'opacity': options.shadow.opacity.toString(), 'transform': 'rotate(' + options.angle + ',' + (options.x + options.width * options.pivotX) + ',' + (options.y + options.height * options.pivotY) + ')' + 'translate(' + (options.x + point.x) + ',' + (options.y + point.y) + ')' }; if (parentSvg) { const svgContainer: HTMLElement = parentSvg.getElementById(canvas.id) as HTMLElement; if (svgContainer) { svgContainer.insertBefore(shadowElement, svgContainer.firstChild); } } setAttributeSvg(shadowElement, attr); if (!collection) { setAttributeSvg(shadowElement, { 'width': options.width, 'height': options.height }); } else if (collection) { this.renderPath(shadowElement, options as PathAttributes, collection); } } /** * Return the dashed array values \ * * @returns {number[]} Return the dashed array values .\ * @param { SVGElement} dashArray - Return the dashed array values . * @private */ // eslint-disable-next-line @typescript-eslint/no-unused-vars public parseDashArray(dashArray: string): number[] { const dashes: number[] = []; return dashes; } /** * Draw the Rectangle for the diagram \ * * @returns {void} Draw the Rectangle for the diagram .\ * * @param { SVGElement} svg - Provide the SVG . * @param { RectAttributes} options - Provide the Rect attributes . * @param { string} diagramId - Provide the diagram id . * @param { boolean} onlyRect - Provide the boolean attribute for the shawdow rendering . * @param { boolean} isSelector - Provide the selector possobilities . * @param { SVGSVGElement} parentSvg - Provide the parent svg element . * @param { Object} ariaLabel - Provide the Arial label attributes . * @private */ public drawRectangle( svg: SVGElement, options: RectAttributes, diagramId: string, onlyRect?: boolean, isSelector?: boolean, parentSvg?: SVGSVGElement, ariaLabel?: Object): void { if (options.shadow && !onlyRect) { this.renderShadow(options, svg, undefined, parentSvg); } let id: string; if (options.id === svg.id) { id = options.id + '_container'; } else { id = options.id; } let rect: SVGElement; if (parentSvg) { rect = (parentSvg as SVGSVGElement).getElementById(id) as SVGElement; } if (!rect || isSelector) { rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); svg.appendChild(rect); } let shadowElement: HTMLElement; if (parentSvg && !options.shadow) { shadowElement = parentSvg.getElementById(options.id + '_groupElement_shadow') as HTMLElement; if (shadowElement) { shadowElement.parentNode.removeChild(shadowElement); } } const attr: Object = { 'id': id, 'x': options.x.toString(), 'y': options.y.toString(), 'width': options.width.toString(), 'height': options.height.toString(), 'visibility': options.visible ? 'visible' : 'hidden', 'transform': 'rotate(' + options.angle + ',' + (options.x + options.width * options.pivotX) + ',' + (options.y + options.height * options.pivotY) + ')', 'rx': options.cornerRadius || 0, 'ry': options.cornerRadius || 0, 'opacity': options.opacity, 'aria-label': ariaLabel ? ariaLabel : '' }; if (options.class) { attr['class'] = options.class; } const poiterEvents: string = 'pointer-events'; if (!ariaLabel) { attr[poiterEvents] = 'none'; } setAttributeSvg(rect, attr); this.setSvgStyle(rect, options as StyleAttributes, diagramId); } /** * Update the diagram selection region \ * * @returns {void} Update the diagram selection region .\ * * @param { SVGElement} gElement - Provide the element type. * @param { RectAttributes} options - Provide the Rect attributes . * @private */ public updateSelectionRegion(gElement: SVGElement, options: RectAttributes): void { let rect: SVGElement; rect = (gElement.parentNode as SVGSVGElement).getElementById(options.id) as SVGElement; const attr: Object = { 'id': options.id, 'x': options.x.toString(), 'y': options.y.toString(), 'width': options.width.toString(), 'height': options.height.toString(), 'transform': 'rotate(' + options.angle + ',' + (options.x + options.width * options.pivotX) + ',' + (options.y + options.height * options.pivotY) + ')', class: 'e-diagram-selected-region' }; if (!rect) { rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); gElement.appendChild(rect); } this.setSvgStyle(rect, options as StyleAttributes); setAttributeSvg(rect, attr); } /** * Create the g element for the diagram \ * * @returns {SVGGElement} Create the g element for the diagram .\ * * @param { SVGElement} elementType - Provide the element type. * @param { Object} attribute - Provide the attributes for the g element. * @private */ public createGElement(elementType: string, attribute: Object): SVGGElement { const gElement: SVGGElement = createSvgElement(elementType, attribute) as SVGGElement; return gElement; } /** * Draw the line for the diagram\ * * @returns {void} Draw the line for the diagram .\ * * @param { SVGElement} gElement - Provide the g element . * @param { LineAttributes} options - Provide the line element attributes . * @private */ public drawLine(gElement: SVGElement, options: LineAttributes): void { const line: SVGElement = document.createElementNS('http://www.w3.org/2000/svg', 'line'); this.setSvgStyle(line, options as StyleAttributes); const pivotX: number = options.x + options.width * options.pivotX; const pivotY: number = options.y + options.height * options.pivotY; //const kk: string = ''; const attr: Object = { 'id': options.id, 'x1': options.startPoint.x + options.x, 'y1': options.startPoint.y + options.y, 'x2': options.endPoint.x + options.x, 'y2': options.endPoint.y + options.y, 'stroke': options.stroke, 'stroke-width': options.strokeWidth.toString(), 'opacity': options.opacity.toString(), 'transform': 'rotate(' + options.angle + ' ' + pivotX + ' ' + pivotY + ')', 'visibility': options.visible ? 'visible' : 'hidden' }; if (options.class) { attr['class'] = options.class; } setAttributeSvg(line, attr); gElement.appendChild(line); } /** * Draw the circle for the diagram\ * * @returns {void} Draw the circle for the diagram .\ * * @param { SVGElement} gElement - Provide the g element . * @param { CircleAttributes} options - Provide the circle element attributes . * @param {string} enableSelector - Provide the selector constraints string . * @param {Object} ariaLabel - Provide arial label value . * @private */ public drawCircle(gElement: SVGElement, options: CircleAttributes, enableSelector?: number, ariaLabel?: Object): void { const circle: SVGElement = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); this.setSvgStyle(circle, options as StyleAttributes); let classval: string = options.class || ''; if (!enableSelector) { classval += ' e-disabled'; } const attr: Object = { 'id': options.id, 'cx': options.centerX, 'cy': options.centerY, 'r': options.radius, 'visibility': options.visible ? 'visible' : 'hidden', 'class': classval, 'aria-label': ariaLabel ? ariaLabel['aria-label'] : '' }; circle.style.display = options.visible ? 'block' : 'none'; setAttributeSvg(circle, attr); gElement.appendChild(circle); } /** * Draw the path element for the diagram\ * * @returns {void} Draw the path element for the diagram .\ * * @param { SVGElement} svg - Provide the SVG element . * @param { PathAttributes} options - Provide the path element attributes . * @param {string} diagramId - Provide the diagram id . * @param {boolean} isSelector - Provide selector boolean value . * @param {SVGSVGElement} parentSvg - Provide the parent SVG element . * @param {Object} ariaLabel - Provide arial label value . * @private */ public drawPath( svg: SVGElement, options: PathAttributes, diagramId: string, isSelector?: boolean, parentSvg?: SVGSVGElement, ariaLabel?: Object): void { // eslint-disable-next-line @typescript-eslint/no-unused-vars const x: number = Math.floor((Math.random() * 10) + 1); //const id: string = svg.id + '_shape' + x.toString(); let collection: Object[] = []; collection = processPathData(options.data); collection = pathSegmentCollection(collection); if (options.shadow) { this.renderShadow(options, svg, collection, parentSvg); } let shadowElement: HTMLElement; if (parentSvg && !options.shadow) { shadowElement = parentSvg.getElementById(options.id + '_groupElement_shadow') as HTMLElement; if (shadowElement) { shadowElement.parentNode.removeChild(shadowElement); } } let path: SVGPathElement; if (parentSvg) { path = (parentSvg as SVGSVGElement).getElementById(options.id) as SVGPathElement; } if (!path || isSelector) { path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); svg.appendChild(path); } this.renderPath(path, options, collection); const attr: Object = { 'id': options.id, 'transform': 'rotate(' + options.angle + ',' + (options.x + options.width * options.pivotX) + ',' + (options.y + options.height * options.pivotY) + ')' + 'translate(' + (options.x) + ',' + (options.y) + ')', 'visibility': options.visible ? 'visible' : 'hidden', 'opacity': options.opacity, 'aria-label': ariaLabel ? ariaLabel : '' }; if (options.class) { attr['class'] = options.class; } setAttributeSvg(path, attr); this.setSvgStyle(path, options as StyleAttributes, diagramId); } /** * Draw the path element for the diagram\ * * @returns {void} Draw the path element for the diagram .\ * * @param { SVGElement} svg - Provide the SVG element . * @param {PathAttributes} options - Provide the path element attributes . * @param {Object[]} collection - Provide the parent SVG element . * @private */ public renderPath(svg: SVGElement, options: PathAttributes, collection: Object[]): void { let x1: number; let y1: number; let x2: number; let y2: number; let x: number; let y: number; let length: number; let i: number; const segments: Object[] = collection; let d: string = ''; for (x = 0, y = 0, i = 0, length = segments.length; i < length; ++i) { const obj: Object = segments[i]; const segment: PathSegment = obj; const char: string = segment.command; if ('x1' in segment) { x1 = segment.x1; } if ('x2' in segment) { x2 = segment.x2; } if ('y1' in segment) { y1 = segment.y1; } if ('y2' in segment) { y2 = segment.y2; } if ('x' in segment) { x = segment.x; } if ('y' in segment) { y = segment.y; } switch (char) { case 'M': d = d + 'M' + x.toString() + ',' + y.toString() + ' '; break; case 'L': d = d + 'L' + x.toString() + ',' + y.toString() + ' '; break; case 'C': d = d + 'C' + x1.toString() + ',' + y1.toString() + ',' + x2.toString() + ',' + y2.toString() + ','; d += x.toString() + ',' + y.toString() + ' '; break; case 'Q': d = d + 'Q' + x1.toString() + ',' + y1.toString() + ',' + x.toString() + ',' + y.toString() + ' '; break; case 'A': d = d + 'A' + segment.r1.toString() + ',' + segment.r2.toString() + ',' + segment.angle.toString() + ','; d += segment.largeArc.toString() + ',' + segment.sweep + ',' + x.toString() + ',' + y.toString() + ' '; break; case 'Z': case 'z': d = d + 'Z' + ' '; break; } } svg.setAttribute('d', d); } private setSvgFontStyle(text: SVGTextElement, options: TextAttributes): void { text.style.fontStyle = options.italic ? 'italic' : 'normal'; text.style.fontWeight = options.bold ? 'bold' : 'normal'; text.style.fontSize = options.fontSize.toString() + 'px'; text.style.fontFamily = options.fontFamily; } /** * Draw the text element for the diagram\ * * @returns {void} Draw the text element for the diagram .\ * * @param { SVGElement} canvas - Provide the SVG element . * @param {TextAttributes} options - Provide the text element attributes . * @param {SVGSVGElement} parentSvg - Provide the parent SVG element . * @param {Object} ariaLabel - Provide the label properties . * @param {string} diagramId - Provide the diagram id . * @param {number} scaleValue - Provide the scale value . * @param {Container} parentNode - Provide the parent node . * @private */ public drawText( canvas: SVGElement, options: TextAttributes, parentSvg?: SVGSVGElement, ariaLabel?: Object, diagramId?: string, scaleValue?: number, parentNode?: Container): void { if (options.content !== undefined) { let textNode: Text; let childNodes: SubTextElement[]; let wrapBounds: TextBounds; let position: PointModel; let child: SubTextElement; let tspanElement: SVGElement; let offsetX: number = 0; let offsetY: number = 0; let i: number = 0; let text: SVGTextElement; if (parentSvg) { text = parentSvg.getElementById(options.id + '_text') as SVGTextElement; } if (text) { if (options.doWrap) { while (text.firstChild) { text.removeChild(text.firstChild); } } } else { options.doWrap = true; text = document.createElementNS('http://www.w3.org/2000/svg', 'text'); if (options.whiteSpace === 'pre-wrap') { text.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve'); } canvas.appendChild(text); } let pivotX: number = options.x + options.width * options.pivotX; let pivotY: number = options.y + options.height * options.pivotY; let childNodesHeight: number = 0; if (options.doWrap || options.textOverflow !== 'Wrap') { const innerHtmlTextElement: HTMLElement = document.getElementById(options.id + '_text'); if (innerHtmlTextElement) { innerHtmlTextElement.innerHTML = ''; } this.setSvgStyle(text, options as StyleAttributes, diagramId); this.setSvgFontStyle(text, options); textNode = document.createTextNode(options.content); childNodes = options.childNodes; wrapBounds = options.wrapBounds; position = this.svgLabelAlign(options, wrapBounds, childNodes); if (wrapBounds.width > options.width && options.textOverflow !== 'Wrap' && options.textWrapping === 'NoWrap') { childNodes[0].text = overFlow(options.content, options); } for (i = 0; i < childNodes.length; i++) { tspanElement = document.createElementNS('http://www.w3.org/2000/svg', 'tspan'); textNode = document.createTextNode(childNodes[i].text); child = childNodes[i]; child.x = setChildPosition(child, childNodes, i, options); offsetX = position.x + child.x - wrapBounds.x; offsetY = position.y + child.dy * (i) + ((options.fontSize) * 0.8); if ((options.textOverflow === 'Clip' || options.textOverflow === 'Ellipsis') && (options.textWrapping === 'WrapWithOverflow' || options.textWrapping === 'Wrap') && parentNode) { const size: number = (options.isHorizontalLane) ? parentNode.actualSize.width : parentNode.actualSize.height; if (offsetY < size) { if (options.textOverflow === 'Ellipsis' && childNodes[i + 1]) { const temp: SubTextElement = childNodes[i + 1]; const y: number = position.y + temp.dy * (i + 1) + ((options.fontSize) * 0.8); if (y > size) { child.text = child.text.slice(0, child.text.length - 3); child.text = child.text.concat('...'); textNode.data = child.text; } } this.setText(text, tspanElement, child, textNode, offsetX, offsetY); childNodesHeight += child.dy; } else { break; } } else { this.setText(text, tspanElement, child, textNode, offsetX, offsetY); } } } if (childNodesHeight && options.isHorizontalLane) { pivotX = options.parentOffsetX + options.pivotX; pivotY = options.parentOffsetY + options.pivotY; options.y = options.parentOffsetY - childNodesHeight * options.pivotY + 0.5; } if (options.textDecoration && options.textDecoration === 'LineThrough') { options.textDecoration = wordBreakToString(options.textDecoration); } const attr: Object = { 'id': options.id + '_text', 'fill': options.color, 'visibility': options.visible ? 'visible' : 'hidden', 'text-decoration': options.textDecoration, 'transform': 'rotate(' + options.angle + ',' + (pivotX) + ',' + (pivotY) + ')' + 'translate(' + (options.x) + ',' + (options.y) + ')', 'opacity': options.opacity, 'aria-label': ariaLabel ? ariaLabel : '' }; setAttributeSvg(text, attr); } } private setText( text: SVGTextElement, tspanElement: SVGElement, child: SubTextElement, textNode: Text, offsetX: number, offsetY: number): void { setAttributeSvg(tspanElement, { 'x': offsetX.toString(), 'y': offsetY.toString() }); text.setAttribute('fill', child.text); tspanElement.appendChild(textNode); text.appendChild(tspanElement); } /** * Draw the image element for the diagram\ * * @returns {void} Draw the image element for the diagram . * @param { SVGElement | HTMLCanvasElement} canvas - Provide the SVG element . * @param {ImageAttributes} obj - Provide the image attributes . * @param {SVGSVGElement} parentSvg - Provide the parent SVG element . * @param {boolean} fromPalette - Provide the pointer event value . * @private */ // eslint-disable-next-line @typescript-eslint/no-unused-vars public drawImage(canvas: SVGElement | HTMLCanvasElement, obj: ImageAttributes, parentSvg?: SVGSVGElement, fromPalette?: boolean): void { ///const id: string = obj.id + '_image'; let image: SVGImageElement; if (parentSvg) { image = parentSvg.getElementById(obj.id + 'image') as SVGImageElement; } if (!image) { image = document.createElementNS('http://www.w3.org/2000/svg', 'image'); canvas.appendChild(image); } const imageObj: HTMLImageElement = new Image(); imageObj.src = obj.source; let scale: string = obj.scale !== 'None' ? obj.scale : ''; if (isBlazor() && obj.alignment === 'None' && scale === 'Stretch') { scale = ''; } const imgAlign: string = obj.alignment; let aspectRatio: string = imgAlign.charAt(0).toLowerCase() + imgAlign.slice(1); if (scale !== 'Stretch') { aspectRatio += ' ' + scale.charAt(0).toLowerCase() + scale.slice(1); } const attr: Object = { 'id': obj.id + 'image', 'x': obj.x.toString(), 'y': obj.y.toString(), 'transform': 'rotate(' + obj.angle + ',' + (obj.x + obj.width * obj.pivotX) + ',' + (obj.y + obj.height * obj.pivotY) + ')', 'width': obj.width.toString(), 'visibility': obj.visible ? 'visible' : 'hidden', 'height': obj.height.toString(), 'preserveAspectRatio': aspectRatio, 'opacity': (obj.opacity || 1).toString() }; setAttributeSvg(image, attr); image.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', imageObj.src.toString()); } /** * Draw the HTML element for the diagram\ * * @returns {void} Draw the native element for the diagram. * @param {DiagramHtmlElement} element - Provide the element . * @param {HTMLElement} canvas - Provide the canvas element . * @param {Transforms} transform - Provide the transform value . * @param {boolean} value - Provide the pointer event value . * @param {number} indexValue - Provide the index value . * @private */ public drawHTMLContent( element: DiagramHtmlElement, canvas: HTMLElement, transform?: Transforms, value?: boolean, indexValue?: number): void { let htmlElement: HTMLElement; let parentHtmlElement: HTMLElement; if (canvas) { let i: number; let j: number; let parentElement: HTMLElement; for (i = 0; i < canvas.childNodes.length; i++) { parentElement = canvas.childNodes[i] as HTMLElement; for (j = 0; j < parentElement.childNodes.length; j++) { if ((parentElement.childNodes[j] as HTMLElement).id === element.id + '_html_element') { htmlElement = parentElement.childNodes[j] as HTMLElement; break; } } } } if (!htmlElement) { parentHtmlElement = canvas.querySelector(('#' + element.id + '_html_element')) || canvas.querySelector(('#' + element.nodeId + '_html_element')); if (!parentHtmlElement) { const attr: Object = { 'id': element.nodeId + '_html_element', 'class': 'foreign-object' }; parentHtmlElement = createHtmlElement('div', attr); } const attr: Object = { 'id': element.id + '_html_element', 'class': 'foreign-object' }; htmlElement = createHtmlElement('div', attr); let isOverviewLayer: boolean = false; if (canvas.parentNode && canvas.parentNode.parentNode && canvas.parentNode.parentNode.parentNode && (canvas.parentNode.parentNode.parentNode as any).classList.contains('e-overview')) { isOverviewLayer = true; } if (isOverviewLayer) { htmlElement.appendChild(element.template.cloneNode(true)); } else { // eslint-disable-next-line @typescript-eslint/no-unused-expressions element.isTemplate ? htmlElement.appendChild(element.template) : htmlElement.appendChild(element.template.cloneNode(true)); } if (indexValue !== undefined && canvas.childNodes.length > indexValue) { canvas.insertBefore(htmlElement, canvas.childNodes[indexValue]); } parentHtmlElement.appendChild(htmlElement); canvas.appendChild(parentHtmlElement); } const point: PointModel = cornersPointsBeforeRotation(element).topLeft; htmlElement.setAttribute( 'style', 'height:' + (element.actualSize.height) + 'px; width:' + (element.actualSize.width) + 'px;left:' + point.x + 'px; top:' + point.y + 'px;' + 'position:absolute;transform:rotate(' + (element.rotateAngle + element.parentTransform) + 'deg);' + 'pointer-events:' + (value ? 'all' : 'none') + ';visibility:' + ((element.visible) ? 'visible' : 'hidden') + ';opacity:' + element.style.opacity + ';' ); } /** * Draw the native element for the diagram\ * * @returns {void} Draw the native element for the diagram. * @param {DiagramNativeElement} element - Provide the node element . * @param {HTMLCanvasElement} canvas - Provide the SVG element . * @param {number} height - Provide the height for the shape . * @param {number} width - Provide the width for the shape . * @param {SVGSVGElement} parentSvg - Provide the parent svg for the shape . * @private */ public drawNativeContent( element: DiagramNativeElement, canvas: HTMLCanvasElement | SVGElement, height: number, width: number, parentSvg: SVGSVGElement): void { let nativeElement: SVGElement; let clipPath: SVGClipPathElement; if (parentSvg) { nativeElement = parentSvg.getElementById(element.id + '_native_element') as SVGPathElement; clipPath = parentSvg.getElementById(element.id + '_clip') as SVGClipPathElement; } if (!nativeElement) { nativeElement = document.createElementNS('http://www.w3.org/2000/svg', 'g'); nativeElement.setAttribute('id', element.id + '_native_element'); nativeElement.appendChild(element.template.cloneNode(true)); canvas.appendChild(nativeElement); } if (clipPath) { nativeElement.removeChild(clipPath); } nativeElement.setAttribute('style', 'visibility:' + ((element.visible) ? 'visible' : 'hidden') + ';opacity:' + element.style.opacity + ';'); this.setNativTransform(element, nativeElement, height, width); if (element.scale === 'Slice') { this.drawClipPath(element, nativeElement, height, width, parentSvg); } setAttributeSvg(nativeElement, element.description ? { 'aria-label': element.description } : {}); } private setNativTransform(element: DiagramNativeElement, nativeElement: SVGElement, height: number, width: number): void { //let angle: number; const contentWidth: number = element.contentSize.width !== 0 ? element.contentSize.width : 1; const contentHeight: number = element.contentSize.height !== 0 ? element.contentSize.height : 1; const x: number = element.templatePosition.x * width / contentWidth; const y: number = element.templatePosition.y * height / contentHeight; nativeElement.setAttribute('transform', 'rotate(' + element.parentTransform + ',' + element.offsetX + ',' + element.offsetY + ') translate(' + (element.offsetX - x - width * element.pivot.x) + ',' + (element.offsetY - y - height * element.pivot.y) + ') scale(' + (width / contentWidth) + ',' + (height / contentHeight) + ')' ); } /** *used to crop the given native element into a rectangle of the given size .\ * * @returns {SVGElement} used to crop the given native element into a rectangle of the given size. * @param {DiagramNativeElement} node - Provide the node element . * @param {SVGElement} group - Provide the SVG element . * @param {number} height - Provide the height for the shape . * @param {number} width - Provide the width for the shape . * @param {SVGSVGElement} parentSvg - Provide the parent svg for the shape . * @private */ public drawClipPath( node: DiagramNativeElement, group: SVGElement, height: number, width: number, parentSvg: SVGSVGElement ): SVGElement { const contentWidth: number = node.contentSize.width; const contentHeight: number = node.contentSize.height; //let actualWidth: number = node.actualSize.width; //let actualHeight: number = node.actualSize.height; const clipWidth: number = node.width / (width / contentWidth); const clipHeight: number = node.height / (height / contentHeight); const x: number = node.templatePosition.x + (node.width >= node.height ? 0 : (contentWidth - clipWidth) / 2); const y: number = node.templatePosition.y + (node.height >= node.width ? 0 : (contentHeight - clipHeight) / 2); let clipPath: SVGClipPathElement = parentSvg.getElementById(node.id + '_clip') as SVGClipPathElement; clipPath = document.createElementNS('http://www.w3.org/2000/svg', 'clipPath'); clipPath.setAttribute('id', node.id + '_clip'); group.appendChild(clipPath); let rect: SVGRectElement = parentSvg.getElementById(node.id + '_clip_rect') as SVGRectElement; rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); clipPath.appendChild(rect); const attr: Object = { 'id': node.id + '_clip_rect', 'width': clipWidth.toString(), 'height': clipHeight.toString(), 'x': x.toString(), 'y': y.toString() }; setAttributeSvg(rect, attr); if (checkBrowserInfo()) { group.setAttribute('clip-path', 'url(' + location.protocol + '//' + location.host + location.pathname + '#' + node.id + '_clip)'); } else { group.setAttribute('clip-path', 'url(#' + node.id + '_clip)'); } return group; } /** * Draw the gradient for the diagram shapes .\ * * @returns {SVGElement} Draw the gradient for the diagram shapes. * @param {StyleAttributes} options - Provide the options for the gradient element . * @param {SVGElement} svg - Provide the SVG element . * @param {string} diagramId - Provide the diagram id . * @private */ public renderGradient(options: StyleAttributes, svg: SVGElement, diagramId?: string): SVGElement { let max: number; let min: number; let grd: SVGElement; const svgContainer: SVGSVGElement = getBackgroundLayerSvg(diagramId); let defs: SVGElement = svgContainer.getElementById(diagramId + 'gradient_pattern') as SVGElement; if (!defs) { defs = createSvgElement('defs', { id: diagramId + 'gradient_pattern' }) as SVGGElement; svgContainer.insertBefore(defs, svgContainer.firstChild); } let radial: RadialGradientModel; let linear: LinearGradientModel; //let stop: StopModel; let offset: number; removeGradient(svg.id); if (options.gradient.type !== 'None') { for (let i: number = 0; i < options.gradient.stops.length; i++) { max = !max ? options.gradient.stops[i].offset : Math.max(max, options.gradient.stops[i].offset); min = !min ? options.gradient.stops[i].offset : Math.min(min, options.gradient.stops[i].offset); } if (options.gradient.type === 'Linear') { linear = options.gradient; linear.id = svg.id + '_linear'; grd = this.createLinearGradient(linear); defs.appendChild(grd); } else { radial = options.gradient; radial.id = svg.id + '_radial'; grd = this.createRadialGradient(radial); defs.appendChild(grd); } for (let i: number = 0; i < options.gradient.stops.length; i++) { const stop: StopModel = options.gradient.stops[i]; const offset: number = min < 0 ? (max + stop.offset) / (2 * max) : stop.offset / max; const stopElement: SVGElement = document.createElementNS('http://www.w3.org/2000/svg', 'stop'); setAttributeSvg(stopElement, { 'offset': offset.toString(), 'style': 'stop-color:' + stop.color }); grd.appendChild(stopElement); } } return grd; } /** * Draw the Linear gradient for the diagram .\ * * @returns {SVGElement} Draw the Linear gradient for the diagram. * @param {LinearGradientModel} linear - Provide the objects for the gradient element . * @private */ public createLinearGradient(linear: LinearGradientModel): SVGElement { const lineargradient: SVGElement = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient'); const attr: Object = { 'id': linear.id, 'x1': linear.x1 + '%', 'y1': linear.y1 + '%', 'x2': linear.x2 + '%', 'y2': linear.y2 + '%' }; setAttributeSvg(lineargradient, attr); return lineargradient; } /** * Draw the radial gradient for the diagram .\ * * @returns {SVGElement} Draw the radial gradient for the diagram. * @param {RadialGradientModel} radial - Provide the objects for the gradient element . * @private */ public createRadialGradient(radial: RadialGradientModel): SVGElement { const radialgradient: SVGElement = document.createElementNS('http://www.w3.org/2000/svg', 'radialGradient'); const attr: Object = { 'id': radial.id, 'cx': radial.cx + '%', 'cy': radial.cy + '%', 'r': radial.r + '%', 'fx': radial.fx + '%', 'fy': radial.fy + '%' }; setAttributeSvg(radialgradient, attr); return radialgradient; } /** * Set the SVG style for the SVG elements in the diagram.\ * * @returns {void} * @param {SVGElement} svg - Provide the canvas element . * @param {StyleAttributes} style - Provide the canvas element . * @param {string} diagramId - Provide the canvas element . * @private */ public setSvgStyle(svg: SVGElement, style: StyleAttributes, diagramId?: string): void { if ((style as BaseAttributes).canApplyStyle || (style as BaseAttributes).canApplyStyle === undefined) { if (style.fill === 'none') { style.fill = 'transparent'; } if (style.stroke === 'none') { style.stroke = 'transparent'; } let dashArray: number[] = []; let fill: string; if (style.dashArray) { const canvasRenderer: CanvasRenderer = new CanvasRenderer(); dashArray = canvasRenderer.parseDashArray(style.dashArray); } if (style.gradient && style.gradient.type !== 'None' && diagramId) { const grd: SVGElement = this.renderGradient(style, svg, diagramId); if (checkBrowserInfo()) { fill = 'url(' + location.protocol + '//' + location.host + location.pathname + '#' + grd.id + ')'; } else { fill = 'url(#' + grd.id + ')'; } } else { fill = style.fill; } if (style.stroke) { svg.setAttribute('stroke', style.stroke); } if (style.strokeWidth !== undefined && style.strokeWidth !== null) { svg.setAttribute('stroke-width', style.strokeWidth.toString()); } if (dashArray) { svg.setAttribute('stroke-dasharray', dashArray.toString() || 'none'); } if (fill) { svg.setAttribute('fill', fill); } } } //end region // text utility /** * Draw the SVG label.\ * * @returns {PointModel} Draw the SVG label . * @param {TextAttributes} text - Provide the canvas element . * @param {Object} wrapBound - Provide the canvas element . * @param {SubTextElement []} childNodes - Provide the canvas element . * @private */ public svgLabelAlign(text: TextAttributes, wrapBound: TextBounds, childNodes: SubTextElement[]): PointModel { const bounds: Size = new Size(wrapBound.width, childNodes.length * (text.fontSize * 1.2)); const pos: PointModel = { x: 0, y: 0 }; const x: number = 0; const y: number = 1.2; const offsetX: number = text.width * 0.5; const offsety: number = text.height * 0.5; let pointX: number = offsetX; const pointY: number = offsety; if (text.textAlign === 'left') { pointX = 0; } else if (text.textAlign === 'center') { if (wrapBound.width > text.width && (text.textOverflow === 'Ellipsis' || text.textOverflow === 'Clip')) { if (text.textWrapping === 'NoWrap') { pointX = 0; } else { pointX = text.width * 0.5; } } else { pointX = text.width * 0.5; } } else if (text.textAlign === 'right') { pointX = (text.width * 1); } pos.x = x + pointX + (wrapBound ? wrapBound.x : 0); pos.y = y + pointY - bounds.height / 2; return pos; } //end region }
the_stack
import { Driver } from "./Driver"; import { Invoke } from "./Invoke"; import { Pair } from "tstl/utility/Pair"; import { HashMap } from "tstl/container/HashMap"; import { ConditionVariable } from "tstl/thread/ConditionVariable"; import { Exception } from "tstl/exception/Exception"; import { DomainError } from "tstl/exception/DomainError"; import { RuntimeError } from "tstl/exception/RuntimeError"; import serializeError from "serialize-error"; /** * The basic communicator. * * The `Communicator` is an abstract class taking full charge of network communication. * Protocolized communicators like {@link WebConnector} are realized by extending this * `Communicator` class. * * You want to make your own communicator using special protocol, extends this `Communicator` * class. After the extending, implement your special communicator by overriding those methods. * * - {@link inspectReady} * - {@link replyData} * - {@link sendData} * * @template Provider Type of features provided for remote system. * @author Jeongho Nam - https://github.com/samchon */ export abstract class Communicator<Provider> { /** * @hidden */ private static SEQUENCE: number = 0; /** * @hidden */ protected provider_: Provider; /** * @hidden */ private driver_: Driver<object, true|false>; /** * @hidden */ private promises_: HashMap<number, Pair<Function, Function>>; /** * @hidden */ private join_cv_: ConditionVariable; /* ---------------------------------------------------------------- CONSTRUCTORS ---------------------------------------------------------------- */ /** * Initializer Constructor. * * @param provider An object providing features for remote system. */ protected constructor(provider: Provider) { // PROVIDER & DRIVER this.provider_ = provider; this.driver_ = new Proxy<object>(new Driver(), { get: ({}, name: string) => { if (name === "then") return null; else return this._Proxy_func(name); } }) as any; // OTHER MEMBERS this.promises_ = new HashMap(); this.join_cv_ = new ConditionVariable(); } /** * Destory the communicator. * * A destory function must be called when the network communication has been closed. * It would destroy all function calls in the remote system (by `Driver<Controller>`), * which are not returned yet. * * The *error* instance would be thrown to those function calls. If the disconnection is * abnormal, then write the detailed reason why into the *error* instance. * * @param error An error instance to be thrown to the unreturned functions. */ protected async destructor(error?: Error): Promise<void> { // REJECT UNRETURNED FUNCTIONS const rejectError: Error = error ? error : new RuntimeError("Connection has been closed."); for (const entry of this.promises_) { const reject: Function = entry.second.second; reject(rejectError); } // CLEAR PROMISES this.promises_.clear(); // RESOLVE JOINERS await this.join_cv_.notify_all(); } /** * A predicator inspects whether the *network communication* is on ready. * * @param method The method name for tracing. */ protected abstract inspectReady(method: string): Error | null; /** * @hidden */ private _Proxy_func(name: string): Function { const func = (...params: any[]) => this._Call_function(name, ...params); return new Proxy(func, { get: ({}, newName: string) => { if (newName === "bind") return (thisArg: any, ...args: any[]) => func.bind(thisArg, ...args); else if (newName === "call") return (thisArg: any, ...args: any[]) => func.call(thisArg, ...args); else if (newName === "apply") return (thisArg: any, args: any[]) => func.apply(thisArg, args); return this._Proxy_func(`${name}.${newName}`); } }); } /** * @hidden */ private _Call_function(name: string, ...params: any[]): Promise<any> { return new Promise((resolve, reject) => { // READY TO SEND ? const error: Error | null = this.inspectReady("Communicator._Call_fuction"); if (error) { reject(error); return; } // CONSTRUCT INVOKE MESSAGE const invoke: Invoke.IFunction = { uid: ++Communicator.SEQUENCE, listener: name, parameters: params.map(p => ({ type: typeof p, value: p })) }; // DO SEND WITH PROMISE this.promises_.emplace(invoke.uid, new Pair(resolve, reject)); this.sendData(invoke); }); } /* ---------------------------------------------------------------- ACCESSORS ---------------------------------------------------------------- */ /** * Set `Provider` * * @param obj An object would be provided for remote system. */ public setProvider(obj: Provider): void { this.provider_ = obj; } /** * Get current `Provider`. * * Get an object providing features (functions & objects) for remote system. The remote * system would call the features (`Provider`) by using its `Driver<Controller>`. * * @return Current `Provider` object */ public getProvider(): Provider { return this.provider_; } /** * Get Driver for RFC (Remote Function Call). * * The `Controller` is an interface who defines provided functions from the remote * system. The `Driver` is an object who makes to call remote functions, defined in * the `Controller` and provided by `Provider` in the remote system, possible. * * In other words, calling a functions in the `Driver<Controller>`, it means to call * a matched function in the remote system's `Provider` object. * * - `Controller`: Definition only * - `Driver`: Remote Function Call * * @template Controller An interface for provided features (functions & objects) from the remote system (`Provider`). * @template UseParametric Whether to convert type of function parameters to be compatible with their pritimive. * @return A Driver for the RFC. */ public getDriver<Controller extends object, UseParametric extends boolean = false>(): Driver<Controller, UseParametric> { return this.driver_ as Driver<Controller, UseParametric>; } /** * Join connection. * * Wait until the connection to be closed. */ public join(): Promise<void>; /** * Join connection or timeout. * * Wait until the connection to be clsoed until timeout. * * @param ms The maximum milliseconds for joining. * @return Whether awaken by disconnection or timeout. */ public join(ms: number): Promise<boolean>; /** * Join connection or time expiration. * * Wait until the connection to be closed until time expiration. * * @param at The maximum time point to join. * @return Whether awaken by disconnection or time expiration. */ public join(at: Date): Promise<boolean>; public async join(param?: number | Date): Promise<void|boolean> { // IS JOINABLE ? const error: Error | null = this.inspectReady(`${this.constructor.name}.join`); if (error) throw error; // FUNCTION OVERLOADINGS if (param === undefined) await this.join_cv_.wait(); else if (param instanceof Date) return await this.join_cv_.wait_until(param); else return await this.join_cv_.wait_for(param); } /* ================================================================ COMMUNICATORS - REPLIER - SENDER =================================================================== REPLIER ---------------------------------------------------------------- */ /** * Data Reply Function. * * A function should be called when data has come from the remote system. * * When you receive a message from the remote system, then parse the message with your * special protocol and covert it to be an *Invoke* object. After the conversion, call * this method. * * @param invoke Structured data converted by your special protocol. */ protected replyData(invoke: Invoke): void { if ((invoke as Invoke.IFunction).listener) this._Handle_function(invoke as Invoke.IFunction); else this._Handle_return(invoke as Invoke.IReturn); } /** * @hidden */ private async _Handle_function(invoke: Invoke.IFunction): Promise<void> { const uid: number = invoke.uid; try { //---- // FIND FUNCTION //---- if (this.provider_ === undefined) // PROVIDER MUST BE throw new RuntimeError(`Error on Communicator._Handle_function(): the provider is not specified yet.`); else if (this.provider_ === null) throw new DomainError("Error on Communicator._Handle_function(): the provider would not be."); // FIND FUNCTION (WITH THIS-ARG) let func: Function = this.provider_ as any; let thisArg: any = undefined; const routes: string[] = invoke.listener.split("."); for (const name of routes) { thisArg = func; func = thisArg[name]; // SECURITY-ERRORS if (name[0] === "_") throw new RuntimeError(`Error on Communicator._Handle_function(): RFC does not allow access to a member starting with the underscore: Provider.${invoke.listener}()`); else if (name[name.length - 1] === "_") throw new RuntimeError(`Error on Communicator._Handle_function(): RFC does not allow access to a member ending with the underscore: Provider.${invoke.listener}().`); else if (name === "toString" && func === Function.toString) throw new RuntimeError(`Error on Communicator._Handle_function(): RFC on Function.toString() is not allowed: Provider.${invoke.listener}().`); else if (name === "constructor" || name === "prototype") throw new RuntimeError(`Error on Communicator._Handle_function(): RFC does not allow access to ${name}: Provider.${invoke.listener}().`); } func = func.bind(thisArg); //---- // RETURN VALUE //---- // CALL FUNCTION const parameters: any[] = invoke.parameters.map(p => p.value); const ret: any = await func(...parameters); this._Send_return(uid, true, ret); } catch (exp) { this._Send_return(uid, false, exp); } } /** * @hidden */ private _Handle_return(invoke: Invoke.IReturn): void { // GET THE PROMISE OBJECT const it = this.promises_.find(invoke.uid); if (it.equals(this.promises_.end())) return; // RETURNS const func: Function = invoke.success ? it.second.first : it.second.second; this.promises_.erase(it); func(invoke.value); } /* ---------------------------------------------------------------- SENDER ---------------------------------------------------------------- */ /** * A function sending data to the remote system. * * @param invoke Structured data to send. */ protected abstract sendData(invoke: Invoke): void; /** * @hidden */ private _Send_return(uid: number, flag: boolean, val: any): void { // SPECIAL LOGIC FOR ERROR -> FOR CLEAR JSON ENCODING if (flag === false && val instanceof Error) { if ((val as Exception).toJSON instanceof Function) val = (val as Exception).toJSON(); else val = serializeError(val); } // RETURNS let ret: Invoke.IReturn = { uid: uid, success: flag, value: val }; this.sendData(ret); } }
the_stack
import { Index, Datastore } from "../../src"; import { getDate } from "../../src/utils"; import { MockStorageDriver } from "../example"; import * as fs from "fs"; beforeAll(() => { const cwd = process.cwd(); const datastores = fs.readdirSync(`${cwd}/spec/fixtures/db/users`); if (!fs.existsSync(`${cwd}/spec/example/db/users`)) { fs.mkdirSync(`${cwd}/spec/example/db/users`); } datastores.map((file) => { const data = fs.readFileSync(`${cwd}/spec/fixtures/db/users/${file}`); fs.writeFileSync(`${cwd}/spec/example/db/users/${file}`, data); }); }); describe("testing the datastore, testing loading in and querying persisted data", () => { // loads initial users db const CWD = process.cwd(); const UserStorage = new MockStorageDriver("users"); const Users = new Datastore({storage: UserStorage}); test("loading users name index into the datastore from disk", () => { expect.assertions(1); let index: any[]; return UserStorage.fetchIndex("name") .then((indexArray) => { index = indexArray; return Users.ensureIndex({fieldName: "name", unique: true}); }) .then(() => { return Users.insertIndex("name", index); }) .then(() => { return Users.getIndices(); }) .then((indices: any): any => { const ind: Index = indices.get("name"); if (ind) { return ind.toJSON(); } }) .then((res: any) => { const nameJSON: string = JSON.parse(res); expect(nameJSON).toEqual(expect.arrayContaining([{ key: "Marcus", value: ["T2VUQVJWd0JBQUE9VTNrcTlIMSt4Qjg9R0RvWVl2SkhXMmc9TkUzZlF6a2ZxaDA9"]}, { key: "Scott", value: ["UGVUQVJWd0JBQUE9R2JkWG9UUlErcDg9cUdSOU5CMnNwR0U9ZmpkUzVuZmhIWE09"]}, { key: "Gavin", value: ["UHVUQVJWd0JBQUE9TVJpdzRYUUtZMGc9Wk1tM0Rla0hvem89UXBXaTRETjgxVHc9"]}, { key: "Smith", value: ["UCtUQVJWd0JBQUE9cHE1SmpnSE44eDQ9Rko2RmlJeHJrR1E9ZkN4cjROblB1WEU9"]}, { key: "Kevin", value: ["UHVUQVJWd0JBQUE9QVlxckkraExMWUU9VkxGZjUyZi9OMmc9S0NFVy85bHlnMHM9"]}, { key: "Mark", value: ["UHVUQVJWd0JBQUE9ZkZTNFRzQ0YwRVE9QTBRaUpUWjFJQ0U9UlRsNVg3MHNPcFE9"]}, { key: "Francis", value: ["UE9UQVJWd0JBQUE9cmZ4Y2MxVzNlOFk9TXV4dmJ0WU5JUFk9d0FkMW1oSHY2SWs9"]}, { key: "Luke", value: ["UCtUQVJWd0JBQUE9TVMrYjRpWVUrTEk9cWpON01RWGlQWjA9c1NWQzBacFNqakE9"]}, { key: "Morgan", value: ["UCtUQVJWd0JBQUE9dnVrRm1xWmJDVTQ9aGR2VjN0Z1gvK009dVpUVzMrY3N4eDg9"]}])); }); }); test("loading users age index into the datastore from disk", () => { expect.assertions(1); let index: any[]; // will hold the array of objects of indices return UserStorage.fetchIndex("age") .then((indexArray) => { index = indexArray; return Users.ensureIndex({fieldName: "age", unique: true}); }) .then(() => { return Users.insertIndex("age", index); }) .then(() => { return Users.getIndices(); }) .then((indices) => { const ind: Index = indices.get("age"); if (ind) { return ind.toJSON(); } else { throw new Error("No index for age"); } }) .then((res) => { const ageJSON: string = JSON.parse(res); expect(ageJSON).toEqual(expect.arrayContaining([{ key: 27, value: ["UHVUQVJWd0JBQUE9ZkZTNFRzQ0YwRVE9QTBRaUpUWjFJQ0U9UlRsNVg3MHNPcFE9"]}, { key: 35, value: ["UCtUQVJWd0JBQUE9cHE1SmpnSE44eDQ9Rko2RmlJeHJrR1E9ZkN4cjROblB1WEU9"]}, { key: 22, value: ["UHVUQVJWd0JBQUE9QVlxckkraExMWUU9VkxGZjUyZi9OMmc9S0NFVy85bHlnMHM9"]}, { key: 39, value: ["UGVUQVJWd0JBQUE9R2JkWG9UUlErcDg9cUdSOU5CMnNwR0U9ZmpkUzVuZmhIWE09"]}, { key: 25, value: ["UHVUQVJWd0JBQUE9TVJpdzRYUUtZMGc9Wk1tM0Rla0hvem89UXBXaTRETjgxVHc9"]}, { key: 28, value: ["UE9UQVJWd0JBQUE9cmZ4Y2MxVzNlOFk9TXV4dmJ0WU5JUFk9d0FkMW1oSHY2SWs9"]}, { key: 0, value: ["T2VUQVJWd0JBQUE9VTNrcTlIMSt4Qjg9R0RvWVl2SkhXMmc9TkUzZlF6a2ZxaDA9"]}, { key: 26, value: ["UCtUQVJWd0JBQUE9dnVrRm1xWmJDVTQ9aGR2VjN0Z1gvK009dVpUVzMrY3N4eDg9"]}, { key: 1, value: ["UCtUQVJWd0JBQUE9TVMrYjRpWVUrTEk9cWpON01RWGlQWjA9c1NWQzBacFNqakE9"]}])); }); }); test("getting a user object and a friend", () => { expect.assertions(6); return Users.getIndices() .then((indices) => { const IndexName = indices.get("name"); if (IndexName) { return IndexName.search("Scott"); } else { throw new Error("No Index for name"); } }) .then((id) => { return UserStorage.getItem(id[0]); }) .then((user) => { expect(user.name).toEqual("Scott"); expect(user.age).toEqual(39); expect(user.friends).toEqual(expect.arrayContaining(["UHVUQVJWd0JBQUE9ZkZTNFRzQ0YwRVE9QTBRaUpUWjFJQ0U9UlRsNVg3MHNPcFE9", "UCtUQVJWd0JBQUE9TVMrYjRpWVUrTEk9cWpON01RWGlQWjA9c1NWQzBacFNqakE9"])); return UserStorage.getItem(user.friends[0]); }) .then((user) => { expect(user.name).toEqual("Mark"); expect(user.age).toEqual(27); expect(user.friends).toEqual(expect.arrayContaining(["UCtUQVJWd0JBQUE9TVMrYjRpWVUrTEk9cWpON01RWGlQWjA9c1NWQzBacFNqakE9", "UGVUQVJWd0JBQUE9R2JkWG9UUlErcDg9cUdSOU5CMnNwR0U9ZmpkUzVuZmhIWE09"])); }); }); test("retrieving generated _id Date of user", () => { expect.assertions(2); return Users.find({ name: "Francis"}) .exec() .then((res: any[]) => { const idDate = getDate(res[0]._id); expect(idDate).toBeInstanceOf(Date); expect(idDate).toEqual(new Date("2017-05-26T17:14:48.252Z")); }); }); test("inserting a new user", () => { expect.assertions(2); return Users.insert({ name: "Joshua", age: 49}) .then((res) => { expect(res.name).toEqual("Joshua"); expect(res.age).toEqual(49); }); }); test("update all", () => { return Users.update({}, { $set: { isSynced: false, }, }, {returnUpdatedDocs: true, multi: true}) .then((res) => { expect(res.length > 8).toEqual(true); }); }); test("upserting a test user to update", () => { expect.assertions(4); return Users.update({ name: "tester", age: 100, isSynced: false, }, { $set: { isSynced: true, }, }, { upsert: true, returnUpdatedDocs: true, exactObjectFind: true, }) .then((res) => { expect(res[0].name).toEqual("tester"); expect(res[0].age).toEqual(100); expect(res[0].isSynced).toEqual(true); return Users.getIndices(); }) .then((indices) => { const promises: Array<Promise<null>> = []; indices.forEach((v: Index, k: string) => { promises.push(Users.saveIndex(k)); }); return Promise.all(promises); }) .then(() => { return UserStorage.fetchIndex("name"); }) .then((res) => { expect(res.length).toEqual(11); }); }); test("finding a user", () => { expect.assertions(2); return Users.find({name: "Joshua"}) .exec() .then((res: any[]) => { const joshua = res[0]; expect(joshua.name).toEqual("Joshua"); expect(joshua.age).toEqual(49); }); }); test("removing a user", () => { expect.assertions(2); return Users.remove({name: "Joshua"}) .then((res) => { expect(res).toBe(1); return Users.sanitize(); }) .then(() => Users.getIndices()) .then((indices) => { const promises: Array<Promise<null>> = []; indices.forEach((v: Index, k: string) => { promises.push(Users.saveIndex(k)); }); return Promise.all(promises); }) .then(() => { return UserStorage.fetchIndex("name"); }) .then((res) => { expect(res.length).toEqual(10); }); }); test("finding all users age 22-28", () => { expect.assertions(1); return Users.find({age: {$gte: 22, $lte: 28}}) .exec() .then((res) => { res = res as any[]; expect(res.length).toEqual(5); }); }); test("finding all users", () => { expect.assertions(1); return Users.find() .exec() .then((res) => { res = res as any[]; expect(res.length).toEqual(10); }); }); test("finding $or", () => { expect.assertions(2); return Users.find({$or: [{name: "Marcus"}, {name: "Gavin"}]}) .exec() .then((res) => { res = res as any[]; expect(res.length).toEqual(2); expect(res).toEqual((expect.arrayContaining([{ _id: "T2VUQVJWd0JBQUE9VTNrcTlIMSt4Qjg9R0RvWVl2SkhXMmc9TkUzZlF6a2ZxaDA9", name: "Marcus", age: 0, friends: [ "UHVUQVJWd0JBQUE9QVlxckkraExMWUU9VkxGZjUyZi9OMmc9S0NFVy85bHlnMHM9", "UHVUQVJWd0JBQUE9TVJpdzRYUUtZMGc9Wk1tM0Rla0hvem89UXBXaTRETjgxVHc9" ], isSynced: false }, { _id: "UHVUQVJWd0JBQUE9TVJpdzRYUUtZMGc9Wk1tM0Rla0hvem89UXBXaTRETjgxVHc9", name: "Gavin", age: 25, friends: [ "T2VUQVJWd0JBQUE9VTNrcTlIMSt4Qjg9R0RvWVl2SkhXMmc9TkUzZlF6a2ZxaDA9", "UHVUQVJWd0JBQUE9QVlxckkraExMWUU9VkxGZjUyZi9OMmc9S0NFVy85bHlnMHM9"], isSynced: false}]))); }); }); test("nested $and searches", () => { expect.assertions(1); return Users.find({$and: [{age: {$gt: 25}}, {age: {$ne: 28}}, {age: {$lte: 35}}]}) .exec() .then((res) => { res = res as any[]; expect(res.length).toEqual(3); }); }); test("finding $and", () => { expect.assertions(2); return Users.find({$and: [{name: "Gavin"}, {age: 25}]}) .exec() .then((res) => { res = res as any[]; expect(res.length).toEqual(1); expect(res).toEqual(expect.arrayContaining([{_id: "UHVUQVJWd0JBQUE9TVJpdzRYUUtZMGc9Wk1tM0Rla0hvem89UXBXaTRETjgxVHc9", age: 25, friends: ["T2VUQVJWd0JBQUE9VTNrcTlIMSt4Qjg9R0RvWVl2SkhXMmc9TkUzZlF6a2ZxaDA9", "UHVUQVJWd0JBQUE9QVlxckkraExMWUU9VkxGZjUyZi9OMmc9S0NFVy85bHlnMHM9"], isSynced: false, name: "Gavin"}])); }); }); test("finding one user by ID", () => { expect.assertions(1); return Users.find({_id: "T2VUQVJWd0JBQUE9VTNrcTlIMSt4Qjg9R0RvWVl2SkhXMmc9TkUzZlF6a2ZxaDA9"}) .exec() .then((res) => { expect(res).toEqual(expect.arrayContaining([{_id: "T2VUQVJWd0JBQUE9VTNrcTlIMSt4Qjg9R0RvWVl2SkhXMmc9TkUzZlF6a2ZxaDA9", age: 0, friends: ["UHVUQVJWd0JBQUE9QVlxckkraExMWUU9VkxGZjUyZi9OMmc9S0NFVy85bHlnMHM9", "UHVUQVJWd0JBQUE9TVJpdzRYUUtZMGc9Wk1tM0Rla0hvem89UXBXaTRETjgxVHc9"], isSynced: false, name: "Marcus"}])); }); }); test("the cursor no index", () => { expect.assertions(2); return Users.find({}) .sort({age: -1}) .skip(1) .limit(2) .exec() .then((res) => { res = res as any[]; expect(res).toEqual(expect.arrayContaining([{_id: "UGVUQVJWd0JBQUE9R2JkWG9UUlErcDg9cUdSOU5CMnNwR0U9ZmpkUzVuZmhIWE09", age: 39, friends: ["UHVUQVJWd0JBQUE9ZkZTNFRzQ0YwRVE9QTBRaUpUWjFJQ0U9UlRsNVg3MHNPcFE9", "UCtUQVJWd0JBQUE9TVMrYjRpWVUrTEk9cWpON01RWGlQWjA9c1NWQzBacFNqakE9"], isSynced: false, name: "Scott"}, {_id: "UHVUQVJWd0JBQUE9TVJpdzRYUUtZMGc9Wk1tM0Rla0hvem89UXBXaTRETjgxVHc9", age: 25, friends: ["T2VUQVJWd0JBQUE9VTNrcTlIMSt4Qjg9R0RvWVl2SkhXMmc9TkUzZlF6a2ZxaDA9", "UHVUQVJWd0JBQUE9QVlxckkraExMWUU9VkxGZjUyZi9OMmc9S0NFVy85bHlnMHM9"], isSynced: false, name: "Gavin"}])); expect(res.length).toEqual(2); }); }); test("finding with $created_at", () => { expect.assertions(8); return Users.find({}) .limit(3) .sort({$created_at: -1}) .exec() .then((res) => { res = res as any[]; expect(res.length).toEqual(3); expect(res[0].name).toEqual("Gavin"); expect(res[1].name).toEqual("Scott"); expect(res[2].name).toEqual("Marcus"); return Users.find({}) .limit(3) .sort({$created_at: 1}) .exec(); }) .then((res) => { res = res as any[]; expect(res.length).toEqual(3); expect(res[0].name).toEqual("Marcus"); expect(res[1].name).toEqual("Scott"); expect(res[2].name).toEqual("Gavin"); }); }); test("the cursor with index", () => { expect.assertions(2); return Users.find({age: {$gt: 1}}) .sort({age: 1}) .skip(1) .limit(2) .exec() .then((res) => { res = res as any[]; expect(res).toEqual(expect.arrayContaining([ { _id: "UHVUQVJWd0JBQUE9TVJpdzRYUUtZMGc9Wk1tM0Rla0hvem89UXBXaTRETjgxVHc9", name: "Gavin", age: 25, friends: [ "T2VUQVJWd0JBQUE9VTNrcTlIMSt4Qjg9R0RvWVl2SkhXMmc9TkUzZlF6a2ZxaDA9", "UHVUQVJWd0JBQUE9QVlxckkraExMWUU9VkxGZjUyZi9OMmc9S0NFVy85bHlnMHM9" ], isSynced: false}, { _id: "UCtUQVJWd0JBQUE9dnVrRm1xWmJDVTQ9aGR2VjN0Z1gvK009dVpUVzMrY3N4eDg9", name: "Morgan", age: 26, friends: [ "UE9UQVJWd0JBQUE9cmZ4Y2MxVzNlOFk9TXV4dmJ0WU5JUFk9d0FkMW1oSHY2SWs9", "UCtUQVJWd0JBQUE9cHE1SmpnSE44eDQ9Rko2RmlJeHJrR1E9ZkN4cjROblB1WEU9"], isSynced: false}])); expect(res.length).toEqual(2); }); }); test("clear the datastore users", () => { expect.assertions(1); return UserStorage.clear() .then(() => { const exists = fs.existsSync(`${CWD}/spec/example/db/users`); expect(exists).toBe(false); }); }); });
the_stack
import { builders } from "prettier/doc"; import embed from "./embed"; import type { ContentCstNode, Doc, IToken, Path, Printer } from "./types"; const { fill, group, hardline, indent, join, line, literalline, softline } = builders; const ignoreStartComment = "<!-- prettier-ignore-start -->"; const ignoreEndComment = "<!-- prettier-ignore-end -->"; function hasIgnoreRanges(comments: IToken[]) { if (!comments || comments.length === 0) { return false; } comments.sort((left, right) => left.startOffset - right.startOffset); let startFound = false; for (let idx = 0; idx < comments.length; idx += 1) { if (comments[idx].image === ignoreStartComment) { startFound = true; } else if (startFound && comments[idx].image === ignoreEndComment) { return true; } } return false; } function isWhitespaceIgnorable(node: ContentCstNode) { const { CData, Comment, reference } = node.children; return !CData && !reference && !hasIgnoreRanges(Comment); } type Fragment = { offset: number; printed: Doc; startLine?: number; endLine?: number; }; function printIToken(path: Path<IToken>): Fragment { const node = path.getValue(); return { offset: node.startOffset, startLine: node.startLine, endLine: node.endLine, printed: node.image }; } function replaceNewlinesWithLiteralLines(content: string) { return content .split(/(\n)/g) .map((value, idx) => (idx % 2 === 0 ? value : literalline)); } const printer: Printer = { embed, print(path, opts, print) { const node = path.getValue(); switch (node.name) { case "attribute": { const { Name, EQUALS, STRING } = node.children; return [Name[0].image, EQUALS[0].image, STRING[0].image]; } case "chardata": { const { SEA_WS, TEXT } = node.children; const [{ image }] = SEA_WS || TEXT; return image .split(/(\n)/g) .map((value, index) => (index % 2 === 0 ? value : literalline)); } case "content": { const nodePath = path as Path<typeof node>; let fragments = nodePath.call((childrenPath) => { let response: Fragment[] = []; const children = childrenPath.getValue(); if (children.CData) { response = response.concat(childrenPath.map(printIToken, "CData")); } if (children.Comment) { response = response.concat( childrenPath.map(printIToken, "Comment") ); } if (children.chardata) { response = response.concat( childrenPath.map( (charDataPath) => ({ offset: charDataPath.getValue().location!.startOffset, printed: print(charDataPath) }), "chardata" ) ); } if (children.element) { response = response.concat( childrenPath.map( (elementPath) => ({ offset: elementPath.getValue().location!.startOffset, printed: print(elementPath) }), "element" ) ); } if (children.PROCESSING_INSTRUCTION) { response = response.concat( childrenPath.map(printIToken, "PROCESSING_INSTRUCTION") ); } if (children.reference) { response = response.concat( childrenPath.map((referencePath) => { const referenceNode = referencePath.getValue(); return { offset: referenceNode.location!.startOffset, printed: (referenceNode.children.CharRef || referenceNode.children.EntityRef)[0].image }; }, "reference") ); } return response; }, "children"); const { Comment } = node.children; if (hasIgnoreRanges(Comment)) { Comment.sort((left, right) => left.startOffset - right.startOffset); const ignoreRanges: { start: number; end: number }[] = []; let ignoreStart: IToken | null = null; // Build up a list of ignored ranges from the original text based on the // special prettier-ignore-* comments Comment.forEach((comment) => { if (comment.image === ignoreStartComment) { ignoreStart = comment; } else if (ignoreStart && comment.image === ignoreEndComment) { ignoreRanges.push({ start: ignoreStart.startOffset, end: comment.endOffset! }); ignoreStart = null; } }); // Filter the printed children to only include the ones that are outside // of each of the ignored ranges fragments = fragments.filter((fragment) => ignoreRanges.every( ({ start, end }) => fragment.offset < start || fragment.offset > end ) ); // Push each of the ignored ranges into the child list as its own element // so that the original content is still included ignoreRanges.forEach(({ start, end }) => { const content = opts.originalText.slice(start, end + 1); fragments.push({ offset: start, printed: replaceNewlinesWithLiteralLines(content) }); }); } fragments.sort((left, right) => left.offset - right.offset); return group(fragments.map(({ printed }) => printed)); } case "docTypeDecl": { const { DocType, Name, externalID, CLOSE } = node.children; const parts: Doc[] = [DocType[0].image, " ", Name[0].image]; if (externalID) { parts.push(" ", path.call(print, "children", "externalID", 0)); } return group([...parts, CLOSE[0].image]); } case "document": { const { docTypeDecl, element, misc, prolog } = node.children; const fragments: Fragment[] = []; if (docTypeDecl) { fragments.push({ offset: docTypeDecl[0].location!.startOffset, printed: path.call(print, "children", "docTypeDecl", 0) }); } if (prolog) { fragments.push({ offset: prolog[0].location!.startOffset, printed: path.call(print, "children", "prolog", 0) }); } if (misc) { misc.forEach((node) => { if (node.children.PROCESSING_INSTRUCTION) { fragments.push({ offset: node.location!.startOffset, printed: node.children.PROCESSING_INSTRUCTION[0].image }); } else if (node.children.Comment) { fragments.push({ offset: node.location!.startOffset, printed: node.children.Comment[0].image }); } }); } if (element) { fragments.push({ offset: element[0].location!.startOffset, printed: path.call(print, "children", "element", 0) }); } fragments.sort((left, right) => left.offset - right.offset); return [ join( hardline, fragments.map(({ printed }) => printed) ), hardline ]; } case "element": { const { OPEN, Name, attribute, START_CLOSE, content, SLASH_OPEN, END_NAME, END, SLASH_CLOSE } = node.children; const parts: Doc[] = [OPEN[0].image, Name[0].image]; if (attribute) { parts.push( indent([line, join(line, path.map(print, "children", "attribute"))]) ); } // Determine the value that will go between the <, name, and attributes // of an element and the /> of an element. const space: Doc = opts.xmlSelfClosingSpace ? line : softline; if (SLASH_CLOSE) { return group([...parts, space, SLASH_CLOSE[0].image]); } if (Object.keys(content[0].children).length === 0) { return group([...parts, space, "/>"]); } const openTag = group([ ...parts, opts.bracketSameLine ? "" : softline, START_CLOSE[0].image ]); const closeTag = group([ SLASH_OPEN[0].image, END_NAME[0].image, END[0].image ]); if ( opts.xmlWhitespaceSensitivity === "ignore" && isWhitespaceIgnorable(content[0]) ) { const nodePath = path as Path<typeof node>; const fragments = nodePath.call( (childrenPath) => { const children = childrenPath.getValue(); let response: Fragment[] = []; if (children.Comment) { response = response.concat( childrenPath.map(printIToken, "Comment") ); } if (children.chardata) { childrenPath.each((charDataPath) => { const chardata = charDataPath.getValue(); if (!chardata.children.TEXT) { return; } const content = chardata.children.TEXT[0].image.trim(); const printed = group( content.split(/(\n)/g).map((value) => { if (value === "\n") { return literalline; } return fill( value .split(/( )/g) .map((segment, index) => index % 2 === 0 ? segment : line ) ); }) ); const location = chardata.location!; response.push({ offset: location.startOffset, startLine: location.startLine, endLine: location.endLine!, printed }); }, "chardata"); } if (children.element) { response = response.concat( childrenPath.map((elementPath) => { const location = elementPath.getValue().location!; return { offset: location.startOffset, startLine: location.startLine, endLine: location.endLine!, printed: print(elementPath) }; }, "element") ); } if (children.PROCESSING_INSTRUCTION) { response = response.concat( childrenPath.map(printIToken, "PROCESSING_INSTRUCTION") ); } return response; }, "children", "content", 0, "children" ); fragments.sort((left, right) => left.offset - right.offset); // If the only content of this tag is chardata, then use a softline so // that we won't necessarily break (to allow <foo>bar</foo>). if ( fragments.length === 1 && (content[0].children.chardata || []).filter( (chardata) => chardata.children.TEXT ).length === 1 ) { return group([ openTag, indent([softline, fragments[0].printed]), softline, closeTag ]); } if (fragments.length === 0) { return group([...parts, space, "/>"]); } const docs: Doc[] = []; let lastLine: number = fragments[0].startLine!; fragments.forEach((node) => { if (node.startLine! - lastLine >= 2) { docs.push(hardline, hardline); } else { docs.push(hardline); } docs.push(node.printed); lastLine = node.endLine!; }); return group([openTag, indent(docs), hardline, closeTag]); } return group([ openTag, indent(path.call(print, "children", "content", 0)), closeTag ]); } case "externalID": { const { Public, PubIDLiteral, System, SystemLiteral } = node.children; if (System) { return group([ System[0].image, indent([line, SystemLiteral[0].image]) ]); } return group([ group([Public[0].image, indent([line, PubIDLiteral[0].image])]), indent([line, SystemLiteral[0].image]) ]); } case "prolog": { const { XMLDeclOpen, attribute, SPECIAL_CLOSE } = node.children; const parts: Doc[] = [XMLDeclOpen[0].image]; if (attribute) { parts.push( indent([ softline, join(line, path.map(print, "children", "attribute")) ]) ); } const space = opts.xmlSelfClosingSpace ? line : softline; return group([...parts, space, SPECIAL_CLOSE[0].image]); } } } }; export default printer;
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "../types"; import * as utilities from "../utilities"; /** * Provides an AppStream fleet. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as aws from "@pulumi/aws"; * * const testFleet = new aws.appstream.Fleet("test_fleet", { * computeCapacity: { * desiredInstances: 1, * }, * description: "test fleet", * displayName: "test-fleet", * enableDefaultInternetAccess: false, * fleetType: "ON_DEMAND", * idleDisconnectTimeoutInSeconds: 15, * imageName: "Amazon-AppStream2-Sample-Image-02-04-2019", * instanceType: "stream.standard.large", * maxUserDurationInSeconds: 600, * tags: { * TagName: "tag-value", * }, * vpcConfig: { * subnetIds: ["subnet-06e9b13400c225127"], * }, * }); * ``` * * ## Import * * `aws_appstream_fleet` can be imported using the id, e.g. * * ```sh * $ pulumi import aws:appstream/fleet:Fleet example fleetNameExample * ``` */ export class Fleet extends pulumi.CustomResource { /** * Get an existing Fleet 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?: FleetState, opts?: pulumi.CustomResourceOptions): Fleet { return new Fleet(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'aws:appstream/fleet:Fleet'; /** * Returns true if the given object is an instance of Fleet. 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 Fleet { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Fleet.__pulumiType; } /** * ARN of the appstream fleet. */ public /*out*/ readonly arn!: pulumi.Output<string>; /** * Configuration block for the desired capacity of the fleet. See below. */ public readonly computeCapacity!: pulumi.Output<outputs.appstream.FleetComputeCapacity>; /** * Date and time, in UTC and extended RFC 3339 format, when the fleet was created. */ public /*out*/ readonly createdTime!: pulumi.Output<string>; /** * Description to display. */ public readonly description!: pulumi.Output<string>; /** * Amount of time that a streaming session remains active after users disconnect. */ public readonly disconnectTimeoutInSeconds!: pulumi.Output<number>; /** * Human-readable friendly name for the AppStream fleet. */ public readonly displayName!: pulumi.Output<string>; /** * Configuration block for the name of the directory and organizational unit (OU) to use to join the fleet to a Microsoft Active Directory domain. See below. */ public readonly domainJoinInfo!: pulumi.Output<outputs.appstream.FleetDomainJoinInfo>; /** * Enables or disables default internet access for the fleet. */ public readonly enableDefaultInternetAccess!: pulumi.Output<boolean>; /** * Fleet type. Valid values are: `ON_DEMAND`, `ALWAYS_ON` */ public readonly fleetType!: pulumi.Output<string>; /** * ARN of the IAM role to apply to the fleet. */ public readonly iamRoleArn!: pulumi.Output<string>; /** * Amount of time that users can be idle (inactive) before they are disconnected from their streaming session and the `disconnectTimeoutInSeconds` time interval begins. */ public readonly idleDisconnectTimeoutInSeconds!: pulumi.Output<number | undefined>; /** * ARN of the public, private, or shared image to use. */ public readonly imageArn!: pulumi.Output<string>; /** * Name of the image used to create the fleet. */ public readonly imageName!: pulumi.Output<string>; /** * Instance type to use when launching fleet instances. */ public readonly instanceType!: pulumi.Output<string>; /** * Maximum amount of time that a streaming session can remain active, in seconds. */ public readonly maxUserDurationInSeconds!: pulumi.Output<number>; /** * Unique name for the fleet. */ public readonly name!: pulumi.Output<string>; /** * State of the fleet. Can be `STARTING`, `RUNNING`, `STOPPING` or `STOPPED` */ public /*out*/ readonly state!: pulumi.Output<string>; /** * AppStream 2.0 view that is displayed to your users when they stream from the fleet. When `APP` is specified, only the windows of applications opened by users display. When `DESKTOP` is specified, the standard desktop that is provided by the operating system displays. */ public readonly streamView!: pulumi.Output<string>; /** * Map of tags to attach to AppStream instances. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; public readonly tagsAll!: pulumi.Output<{[key: string]: string}>; /** * Configuration block for the VPC configuration for the image builder. See below. */ public readonly vpcConfig!: pulumi.Output<outputs.appstream.FleetVpcConfig>; /** * Create a Fleet 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: FleetArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: FleetArgs | FleetState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as FleetState | undefined; inputs["arn"] = state ? state.arn : undefined; inputs["computeCapacity"] = state ? state.computeCapacity : undefined; inputs["createdTime"] = state ? state.createdTime : undefined; inputs["description"] = state ? state.description : undefined; inputs["disconnectTimeoutInSeconds"] = state ? state.disconnectTimeoutInSeconds : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["domainJoinInfo"] = state ? state.domainJoinInfo : undefined; inputs["enableDefaultInternetAccess"] = state ? state.enableDefaultInternetAccess : undefined; inputs["fleetType"] = state ? state.fleetType : undefined; inputs["iamRoleArn"] = state ? state.iamRoleArn : undefined; inputs["idleDisconnectTimeoutInSeconds"] = state ? state.idleDisconnectTimeoutInSeconds : undefined; inputs["imageArn"] = state ? state.imageArn : undefined; inputs["imageName"] = state ? state.imageName : undefined; inputs["instanceType"] = state ? state.instanceType : undefined; inputs["maxUserDurationInSeconds"] = state ? state.maxUserDurationInSeconds : undefined; inputs["name"] = state ? state.name : undefined; inputs["state"] = state ? state.state : undefined; inputs["streamView"] = state ? state.streamView : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["tagsAll"] = state ? state.tagsAll : undefined; inputs["vpcConfig"] = state ? state.vpcConfig : undefined; } else { const args = argsOrState as FleetArgs | undefined; if ((!args || args.computeCapacity === undefined) && !opts.urn) { throw new Error("Missing required property 'computeCapacity'"); } if ((!args || args.instanceType === undefined) && !opts.urn) { throw new Error("Missing required property 'instanceType'"); } inputs["computeCapacity"] = args ? args.computeCapacity : undefined; inputs["description"] = args ? args.description : undefined; inputs["disconnectTimeoutInSeconds"] = args ? args.disconnectTimeoutInSeconds : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["domainJoinInfo"] = args ? args.domainJoinInfo : undefined; inputs["enableDefaultInternetAccess"] = args ? args.enableDefaultInternetAccess : undefined; inputs["fleetType"] = args ? args.fleetType : undefined; inputs["iamRoleArn"] = args ? args.iamRoleArn : undefined; inputs["idleDisconnectTimeoutInSeconds"] = args ? args.idleDisconnectTimeoutInSeconds : undefined; inputs["imageArn"] = args ? args.imageArn : undefined; inputs["imageName"] = args ? args.imageName : undefined; inputs["instanceType"] = args ? args.instanceType : undefined; inputs["maxUserDurationInSeconds"] = args ? args.maxUserDurationInSeconds : undefined; inputs["name"] = args ? args.name : undefined; inputs["streamView"] = args ? args.streamView : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["tagsAll"] = args ? args.tagsAll : undefined; inputs["vpcConfig"] = args ? args.vpcConfig : undefined; inputs["arn"] = undefined /*out*/; inputs["createdTime"] = undefined /*out*/; inputs["state"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Fleet.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Fleet resources. */ export interface FleetState { /** * ARN of the appstream fleet. */ arn?: pulumi.Input<string>; /** * Configuration block for the desired capacity of the fleet. See below. */ computeCapacity?: pulumi.Input<inputs.appstream.FleetComputeCapacity>; /** * Date and time, in UTC and extended RFC 3339 format, when the fleet was created. */ createdTime?: pulumi.Input<string>; /** * Description to display. */ description?: pulumi.Input<string>; /** * Amount of time that a streaming session remains active after users disconnect. */ disconnectTimeoutInSeconds?: pulumi.Input<number>; /** * Human-readable friendly name for the AppStream fleet. */ displayName?: pulumi.Input<string>; /** * Configuration block for the name of the directory and organizational unit (OU) to use to join the fleet to a Microsoft Active Directory domain. See below. */ domainJoinInfo?: pulumi.Input<inputs.appstream.FleetDomainJoinInfo>; /** * Enables or disables default internet access for the fleet. */ enableDefaultInternetAccess?: pulumi.Input<boolean>; /** * Fleet type. Valid values are: `ON_DEMAND`, `ALWAYS_ON` */ fleetType?: pulumi.Input<string>; /** * ARN of the IAM role to apply to the fleet. */ iamRoleArn?: pulumi.Input<string>; /** * Amount of time that users can be idle (inactive) before they are disconnected from their streaming session and the `disconnectTimeoutInSeconds` time interval begins. */ idleDisconnectTimeoutInSeconds?: pulumi.Input<number>; /** * ARN of the public, private, or shared image to use. */ imageArn?: pulumi.Input<string>; /** * Name of the image used to create the fleet. */ imageName?: pulumi.Input<string>; /** * Instance type to use when launching fleet instances. */ instanceType?: pulumi.Input<string>; /** * Maximum amount of time that a streaming session can remain active, in seconds. */ maxUserDurationInSeconds?: pulumi.Input<number>; /** * Unique name for the fleet. */ name?: pulumi.Input<string>; /** * State of the fleet. Can be `STARTING`, `RUNNING`, `STOPPING` or `STOPPED` */ state?: pulumi.Input<string>; /** * AppStream 2.0 view that is displayed to your users when they stream from the fleet. When `APP` is specified, only the windows of applications opened by users display. When `DESKTOP` is specified, the standard desktop that is provided by the operating system displays. */ streamView?: pulumi.Input<string>; /** * Map of tags to attach to AppStream instances. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Configuration block for the VPC configuration for the image builder. See below. */ vpcConfig?: pulumi.Input<inputs.appstream.FleetVpcConfig>; } /** * The set of arguments for constructing a Fleet resource. */ export interface FleetArgs { /** * Configuration block for the desired capacity of the fleet. See below. */ computeCapacity: pulumi.Input<inputs.appstream.FleetComputeCapacity>; /** * Description to display. */ description?: pulumi.Input<string>; /** * Amount of time that a streaming session remains active after users disconnect. */ disconnectTimeoutInSeconds?: pulumi.Input<number>; /** * Human-readable friendly name for the AppStream fleet. */ displayName?: pulumi.Input<string>; /** * Configuration block for the name of the directory and organizational unit (OU) to use to join the fleet to a Microsoft Active Directory domain. See below. */ domainJoinInfo?: pulumi.Input<inputs.appstream.FleetDomainJoinInfo>; /** * Enables or disables default internet access for the fleet. */ enableDefaultInternetAccess?: pulumi.Input<boolean>; /** * Fleet type. Valid values are: `ON_DEMAND`, `ALWAYS_ON` */ fleetType?: pulumi.Input<string>; /** * ARN of the IAM role to apply to the fleet. */ iamRoleArn?: pulumi.Input<string>; /** * Amount of time that users can be idle (inactive) before they are disconnected from their streaming session and the `disconnectTimeoutInSeconds` time interval begins. */ idleDisconnectTimeoutInSeconds?: pulumi.Input<number>; /** * ARN of the public, private, or shared image to use. */ imageArn?: pulumi.Input<string>; /** * Name of the image used to create the fleet. */ imageName?: pulumi.Input<string>; /** * Instance type to use when launching fleet instances. */ instanceType: pulumi.Input<string>; /** * Maximum amount of time that a streaming session can remain active, in seconds. */ maxUserDurationInSeconds?: pulumi.Input<number>; /** * Unique name for the fleet. */ name?: pulumi.Input<string>; /** * AppStream 2.0 view that is displayed to your users when they stream from the fleet. When `APP` is specified, only the windows of applications opened by users display. When `DESKTOP` is specified, the standard desktop that is provided by the operating system displays. */ streamView?: pulumi.Input<string>; /** * Map of tags to attach to AppStream instances. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Configuration block for the VPC configuration for the image builder. See below. */ vpcConfig?: pulumi.Input<inputs.appstream.FleetVpcConfig>; }
the_stack
'use strict'; // tslint:disable no-unused-expression import * as vscode from 'vscode'; import * as chai from 'chai'; import * as sinon from 'sinon'; import * as sinonChai from 'sinon-chai'; import { TestUtil } from '../TestUtil'; import { UserInputUtil } from '../../extension/commands/UserInputUtil'; import { ExtensionCommands } from '../../ExtensionCommands'; import { VSCodeBlockchainOutputAdapter } from '../../extension/logging/VSCodeBlockchainOutputAdapter'; import { DeployView } from '../../extension/webview/DeployView'; import { FabricEnvironmentManager } from '../../extension/fabric/environments/FabricEnvironmentManager'; import { FabricEnvironmentConnection } from 'ibm-blockchain-platform-environment-v1'; import { FabricEnvironmentRegistryEntry, FabricEnvironmentRegistry, FabricRuntimeUtil, LogType, FabricSmartContractDefinition } from 'ibm-blockchain-platform-common'; import { PackageRegistry } from '../../extension/registries/PackageRegistry'; import { PackageRegistryEntry } from '../../extension/registries/PackageRegistryEntry'; chai.use(sinonChai); chai.should(); describe('OpenDeployView', () => { let mySandBox: sinon.SinonSandbox = sinon.createSandbox(); let executeCommandStub: sinon.SinonStub; let logStub: sinon.SinonStub; let openViewStub: sinon.SinonStub; let showFabricEnvironmentQuickPickBoxStub: sinon.SinonStub; let showChannelQuickPickBoxStub: sinon.SinonStub; let fabricEnvironmentManager: FabricEnvironmentManager; let getConnectionStub: sinon.SinonStub; let localEnvironmentConnectionMock: sinon.SinonStubbedInstance<FabricEnvironmentConnection>; let otherEnvironmentConnectionMock: sinon.SinonStubbedInstance<FabricEnvironmentConnection>; let getWorkspaceFoldersStub: sinon.SinonStub; let getAllPackagesStub: sinon.SinonStub; let packageOne: PackageRegistryEntry; let packageTwo: PackageRegistryEntry; before(async () => { await TestUtil.setupTests(mySandBox); await TestUtil.setupLocalFabric(); }); describe('OpenDeployView', () => { beforeEach(async () => { mySandBox = sinon.createSandbox(); logStub = mySandBox.stub(VSCodeBlockchainOutputAdapter.instance(), 'log').resolves(); executeCommandStub = mySandBox.stub(vscode.commands, 'executeCommand'); executeCommandStub.callThrough(); executeCommandStub.withArgs(ExtensionCommands.CONNECT_TO_ENVIRONMENT).resolves(); executeCommandStub.withArgs(ExtensionCommands.DISCONNECT_ENVIRONMENT).resolves(); showFabricEnvironmentQuickPickBoxStub = mySandBox.stub(UserInputUtil, 'showFabricEnvironmentQuickPickBox'); showChannelQuickPickBoxStub = mySandBox.stub(UserInputUtil, 'showChannelQuickPickBox'); const map: Map<string, Array<string>> = new Map<string, Array<string>>(); map.set('mychannel', ['Org1Peer1']); map.set('otherchannel', ['Org1Peer1']); const contractDefinitions: FabricSmartContractDefinition[] = [ { name: 'mycontract', version: '0.0.1', sequence: 1 } ]; localEnvironmentConnectionMock = mySandBox.createStubInstance(FabricEnvironmentConnection); localEnvironmentConnectionMock.environmentName = FabricRuntimeUtil.LOCAL_FABRIC; localEnvironmentConnectionMock.createChannelMap.resolves(map); localEnvironmentConnectionMock.getCommittedSmartContractDefinitions.resolves(contractDefinitions); localEnvironmentConnectionMock.getAllDiscoveredPeerNames.resolves(['Org1Peer1', 'Org2Peer1']); localEnvironmentConnectionMock.getChannelCapabilityFromPeer.resolves(['V2_0']); const orgMap: Map<string, string[]> = new Map(); orgMap.set('Org1MSP', ['Org1Peer1']); orgMap.set('Org2MSP', ['Org2Peer1']); localEnvironmentConnectionMock.getDiscoveredOrgs.resolves(orgMap); otherEnvironmentConnectionMock = mySandBox.createStubInstance(FabricEnvironmentConnection); otherEnvironmentConnectionMock.environmentName = 'otherEnvironment'; otherEnvironmentConnectionMock.createChannelMap.resolves(map); localEnvironmentConnectionMock.getCommittedSmartContractDefinitions.resolves(contractDefinitions); fabricEnvironmentManager = FabricEnvironmentManager.instance(); getConnectionStub = mySandBox.stub(fabricEnvironmentManager, 'getConnection'); openViewStub = mySandBox.stub(DeployView.prototype, 'openView').resolves(); const workspaceOne: vscode.WorkspaceFolder = { name: 'workspaceOne', uri: vscode.Uri.file('myPath'), index: 0 }; const workspaceTwo: vscode.WorkspaceFolder = { name: 'workspaceTwo', uri: vscode.Uri.file('otherPath'), index: 1 }; getWorkspaceFoldersStub = mySandBox.stub(UserInputUtil, 'getWorkspaceFolders').returns([workspaceOne, workspaceTwo]); getAllPackagesStub = mySandBox.stub(PackageRegistry.instance(), 'getAll'); packageOne = new PackageRegistryEntry(); packageOne.name = 'myPackage'; packageOne.path = 'myPath.cds'; packageOne.version = '0.0.1'; packageTwo = new PackageRegistryEntry(); packageTwo.name = 'otherPackage'; packageTwo.path = 'otherPath.tgz'; packageTwo.version = '0.0.1'; getAllPackagesStub.resolves([packageOne, packageTwo]); }); afterEach(async () => { mySandBox.restore(); }); it('should return if no environment selected', async () => { showFabricEnvironmentQuickPickBoxStub.resolves(); await vscode.commands.executeCommand(ExtensionCommands.OPEN_DEPLOY_PAGE); showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment', false, false); getConnectionStub.should.not.have.been.called; localEnvironmentConnectionMock.createChannelMap.should.not.have.been.called; localEnvironmentConnectionMock.getCommittedSmartContractDefinitions.should.not.have.been.called; showChannelQuickPickBoxStub.should.not.have.been.called; openViewStub.should.not.have.been.called; localEnvironmentConnectionMock.getAllDiscoveredPeerNames.should.not.have.been.called; localEnvironmentConnectionMock.getDiscoveredOrgs.should.not.have.been.called; logStub.should.not.have.been.called; getWorkspaceFoldersStub.should.not.have.been.called; }); it('should connect to an environment and open the deploy view', async () => { const localEnvironmentRegistryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricRuntimeUtil.LOCAL_FABRIC); showFabricEnvironmentQuickPickBoxStub.resolves({ label: FabricRuntimeUtil.LOCAL_FABRIC, data: localEnvironmentRegistryEntry }); getConnectionStub.onCall(0).returns(undefined); getConnectionStub.onCall(1).returns(localEnvironmentConnectionMock); showChannelQuickPickBoxStub.resolves({ label: 'mychannel', data: ['Org1Peer1'] }); await vscode.commands.executeCommand(ExtensionCommands.OPEN_DEPLOY_PAGE); showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment', false, false); getConnectionStub.should.have.been.calledTwice; localEnvironmentConnectionMock.createChannelMap.should.have.been.calledOnce; localEnvironmentConnectionMock.getCommittedSmartContractDefinitions.should.have.been.calledOnceWithExactly(['Org1Peer1'], 'mychannel'); executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, localEnvironmentRegistryEntry); showChannelQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select a channel'); openViewStub.should.have.been.calledOnce; localEnvironmentConnectionMock.getAllDiscoveredPeerNames.should.have.been.calledOnceWithExactly('mychannel'); localEnvironmentConnectionMock.getDiscoveredOrgs.should.have.been.calledOnceWithExactly('mychannel'); logStub.should.not.have.been.called; getWorkspaceFoldersStub.should.have.been.calledOnce; }); it('should connect to an environment and open the deploy view from the tree', async () => { const localEnvironmentRegistryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricRuntimeUtil.LOCAL_FABRIC); getConnectionStub.onCall(0).returns(undefined); getConnectionStub.onCall(1).returns(localEnvironmentConnectionMock); await vscode.commands.executeCommand(ExtensionCommands.OPEN_DEPLOY_PAGE, localEnvironmentRegistryEntry, 'mychannel'); showFabricEnvironmentQuickPickBoxStub.should.not.have.been.called; getConnectionStub.should.have.been.calledTwice; localEnvironmentConnectionMock.createChannelMap.should.have.been.calledOnce; localEnvironmentConnectionMock.getCommittedSmartContractDefinitions.should.have.been.calledOnceWithExactly(['Org1Peer1'], 'mychannel'); executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, localEnvironmentRegistryEntry); showChannelQuickPickBoxStub.should.not.have.been.called; openViewStub.should.have.been.calledOnce; localEnvironmentConnectionMock.getAllDiscoveredPeerNames.should.have.been.calledOnceWithExactly('mychannel'); localEnvironmentConnectionMock.getDiscoveredOrgs.should.have.been.calledOnceWithExactly('mychannel'); logStub.should.not.have.been.called; getWorkspaceFoldersStub.should.have.been.calledOnce; }); it('should open the deploy view if already connected to the chosen environment', async () => { const localEnvironmentRegistryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricRuntimeUtil.LOCAL_FABRIC); showFabricEnvironmentQuickPickBoxStub.resolves({ label: FabricRuntimeUtil.LOCAL_FABRIC, data: localEnvironmentRegistryEntry }); getConnectionStub.returns(localEnvironmentConnectionMock); showChannelQuickPickBoxStub.resolves({ label: 'mychannel', data: ['Org1Peer1'] }); await vscode.commands.executeCommand(ExtensionCommands.OPEN_DEPLOY_PAGE); showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment', false, false); getConnectionStub.should.have.been.calledOnce; localEnvironmentConnectionMock.createChannelMap.should.have.been.calledOnce; localEnvironmentConnectionMock.getCommittedSmartContractDefinitions.should.have.been.calledOnceWithExactly(['Org1Peer1'], 'mychannel'); executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, localEnvironmentRegistryEntry); showChannelQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select a channel'); openViewStub.should.have.been.calledOnce; localEnvironmentConnectionMock.getAllDiscoveredPeerNames.should.have.been.calledOnceWithExactly('mychannel'); localEnvironmentConnectionMock.getDiscoveredOrgs.should.have.been.calledOnceWithExactly('mychannel'); logStub.should.not.have.been.called; getWorkspaceFoldersStub.should.have.been.calledOnce; }); it('should disconnect and connect to the selected environment, then open the deploy view', async () => { const localEnvironmentRegistryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricRuntimeUtil.LOCAL_FABRIC); showFabricEnvironmentQuickPickBoxStub.resolves({ label: FabricRuntimeUtil.LOCAL_FABRIC, data: localEnvironmentRegistryEntry }); getConnectionStub.onCall(0).returns(otherEnvironmentConnectionMock); getConnectionStub.onCall(1).returns(localEnvironmentConnectionMock); showChannelQuickPickBoxStub.resolves({ label: 'mychannel', data: ['Org1Peer1'] }); await vscode.commands.executeCommand(ExtensionCommands.OPEN_DEPLOY_PAGE); showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment', false, false); getConnectionStub.should.have.been.calledTwice; localEnvironmentConnectionMock.createChannelMap.should.have.been.calledOnce; localEnvironmentConnectionMock.getCommittedSmartContractDefinitions.should.have.been.calledOnceWithExactly(['Org1Peer1'], 'mychannel'); executeCommandStub.should.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT); executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, localEnvironmentRegistryEntry); showChannelQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select a channel'); openViewStub.should.have.been.calledOnce; localEnvironmentConnectionMock.getAllDiscoveredPeerNames.should.have.been.calledOnceWithExactly('mychannel'); localEnvironmentConnectionMock.getDiscoveredOrgs.should.have.been.calledOnceWithExactly('mychannel'); logStub.should.not.have.been.called; getWorkspaceFoldersStub.should.have.been.calledOnce; }); it('should open the deploy view if the channel has v1 capabilities', async () => { localEnvironmentConnectionMock.getChannelCapabilityFromPeer.resolves(['V1_4_2']); const localEnvironmentRegistryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricRuntimeUtil.LOCAL_FABRIC); showFabricEnvironmentQuickPickBoxStub.resolves({ label: FabricRuntimeUtil.LOCAL_FABRIC, data: localEnvironmentRegistryEntry }); getConnectionStub.returns(localEnvironmentConnectionMock); showChannelQuickPickBoxStub.resolves({ label: 'mychannel', data: ['Org1Peer1'] }); await vscode.commands.executeCommand(ExtensionCommands.OPEN_DEPLOY_PAGE); showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment', false, false); getConnectionStub.should.have.been.calledOnce; localEnvironmentConnectionMock.createChannelMap.should.have.been.calledOnce; localEnvironmentConnectionMock.getCommittedSmartContractDefinitions.should.have.been.calledOnceWithExactly(['Org1Peer1'], 'mychannel'); executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, localEnvironmentRegistryEntry); showChannelQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select a channel'); openViewStub.should.have.been.calledOnce; localEnvironmentConnectionMock.getAllDiscoveredPeerNames.should.have.been.calledOnceWithExactly('mychannel'); localEnvironmentConnectionMock.getDiscoveredOrgs.should.have.been.calledOnceWithExactly('mychannel'); logStub.should.not.have.been.called; getWorkspaceFoldersStub.should.have.been.calledOnce; }); it('should return if no channel is selected', async () => { const localEnvironmentRegistryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricRuntimeUtil.LOCAL_FABRIC); showFabricEnvironmentQuickPickBoxStub.resolves({ label: FabricRuntimeUtil.LOCAL_FABRIC, data: localEnvironmentRegistryEntry }); getConnectionStub.returns(localEnvironmentConnectionMock); showChannelQuickPickBoxStub.resolves(); await vscode.commands.executeCommand(ExtensionCommands.OPEN_DEPLOY_PAGE); showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment', false, false); getConnectionStub.should.have.been.calledOnce; localEnvironmentConnectionMock.createChannelMap.should.not.have.been.called; localEnvironmentConnectionMock.getCommittedSmartContractDefinitions.should.not.have.been.called; executeCommandStub.should.not.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, localEnvironmentRegistryEntry); showChannelQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select a channel'); openViewStub.should.not.have.been.called; localEnvironmentConnectionMock.getAllDiscoveredPeerNames.should.not.have.been.called; localEnvironmentConnectionMock.getDiscoveredOrgs.should.not.have.been.called; logStub.should.not.have.been.called; getWorkspaceFoldersStub.should.not.have.been.called; }); it('should throw an error if unable to connect to the selected environment', async () => { const localEnvironmentRegistryEntry: FabricEnvironmentRegistryEntry = await FabricEnvironmentRegistry.instance().get(FabricRuntimeUtil.LOCAL_FABRIC); showFabricEnvironmentQuickPickBoxStub.resolves({ label: FabricRuntimeUtil.LOCAL_FABRIC, data: localEnvironmentRegistryEntry }); getConnectionStub.onCall(0).returns(otherEnvironmentConnectionMock); getConnectionStub.onCall(1).returns(undefined); await vscode.commands.executeCommand(ExtensionCommands.OPEN_DEPLOY_PAGE); showFabricEnvironmentQuickPickBoxStub.should.have.been.calledOnceWithExactly('Select an environment', false, false); getConnectionStub.should.have.been.calledTwice; localEnvironmentConnectionMock.createChannelMap.should.not.have.been.called; localEnvironmentConnectionMock.getCommittedSmartContractDefinitions.should.not.have.been.called; executeCommandStub.should.have.been.calledWith(ExtensionCommands.DISCONNECT_ENVIRONMENT); executeCommandStub.should.have.been.calledWith(ExtensionCommands.CONNECT_TO_ENVIRONMENT, localEnvironmentRegistryEntry); openViewStub.should.not.have.been.calledOnce; localEnvironmentConnectionMock.getAllDiscoveredPeerNames.should.not.have.been.called; localEnvironmentConnectionMock.getDiscoveredOrgs.should.not.have.been.called; showChannelQuickPickBoxStub.should.not.have.been.called; getWorkspaceFoldersStub.should.not.have.been.called; const error: Error = new Error(`Unable to connect to environment: ${FabricRuntimeUtil.LOCAL_FABRIC}`); logStub.should.have.been.calledOnceWithExactly(LogType.ERROR, error.message, error.toString()); }); }); });
the_stack
import { OnDestroy, ChangeDetectorRef, NgZone } from '@angular/core'; import { BsModalService } from 'ngx-bootstrap/modal'; import { Subscription } from 'rxjs'; import { WidgetService } from '../../../widget.service'; import { NotificationService, Base64Service, Principal, WidgetEventBusService } from '../../../../../shared'; import { JhiEventManager } from 'ng-jhipster'; import { AbstractPieChartWidgetComponent } from './abstract-pie-chart-widget.component'; import { DataSourceService } from '../../../../data-source/data-source.service'; import { SecondaryWidget } from '../../secondary-widget'; import { SubsetSelectionChangeMessage, SubsetSelectionChangeMessageContent, DatasetUpdatedMessageContent, DatasetPropagationRequestMessageContent, DatasetPropagationRequestMessage, MessageType } from '../../..'; import { Router } from '@angular/router'; import { WidgetType } from 'app/entities/widget/widget.model'; /** * This component allows a tabular analysis of data fetched from the datasource * through queries, full text search, class scan loading. */ export abstract class AbstractSecondaryPieChartWidgetComponent extends AbstractPieChartWidgetComponent implements SecondaryWidget, OnDestroy { datasetUpdatedSubscription: Subscription; // dataset currentDataset: Object = { elements: [] }; constructor( protected ngZone: NgZone, protected principal: Principal, protected widgetService: WidgetService, protected notificationService: NotificationService, protected dataSourceService: DataSourceService, protected eventManager: JhiEventManager, protected cdr: ChangeDetectorRef, protected modalService: BsModalService, protected base64Service: Base64Service, protected widgetEventBusService: WidgetEventBusService, protected router: Router) { super(ngZone, principal, widgetService, notificationService, dataSourceService, eventManager, cdr, modalService, base64Service, widgetEventBusService, router); this.subscribeToEventBus(); } ngAfterViewInit() { this.performAdditionalInit(); // sidebar height if (!this.embedded) { this.maxSidebarHeight = this.widgetHeight; } else { this.adjustWidgetHeightToEmbeddingIframeHeight(); } if (this.minimizedView) { this.requestDatasetPropagation(); } } attachPieChartEvents() { super.attachPieChartEvents(); this.pieChart.on('pieselectchanged', (event) => { if (this.minimizedView) { const class2property: Object[] = [{ className: this.selectedClass, property: this.selectedProperty }]; const propertyValues: string[] = []; Object.keys(event.selected).forEach((valueProperty) => { if (event.selected[valueProperty] === true) { propertyValues.push(valueProperty); } }); const content: SubsetSelectionChangeMessageContent = { primaryWidgetId: this.widget.primaryWidgetId, secondaryWidgetId: this.widget.id, class2property: class2property, propertyValues: propertyValues }; this.widgetEventBusService.publish(MessageType.SUBSET_SELECTION_CHANGE, new SubsetSelectionChangeMessage(content)); } }); } subscribeToEventBus() { this.datasetUpdatedSubscription = this.widgetEventBusService.getMessage(MessageType.DATASET_UPDATED_MESSAGE).subscribe((message) => { const content = message.data; if (content['primaryWidgetId'] === this.widget['primaryWidgetId']) { if (content['secondaryWidgetId']) { // message is directed to just one widget, then check the current instance if (content['secondaryWidgetId'] === this.widget['id']) { this.runDatasetUpdateAfterSnapshotLoading(content); } } else { // message is multi cast, then accept the new dataset this.runDatasetUpdateAfterSnapshotLoading(content); } } }); } requestDatasetPropagation() { const content: DatasetPropagationRequestMessageContent = { primaryWidgetId: this.widget.primaryWidgetId, secondaryWidgetId: this.widget.id }; this.widgetEventBusService.publish(MessageType.DATASET_PROPAGATION_REQUEST, new DatasetPropagationRequestMessage(content)); } runDatasetUpdateAfterSnapshotLoading(messageContent: DatasetUpdatedMessageContent) { if (this.oldSnapshotToLoad) { // wait for snapshot is loaded if (this.snapshotLoaded) { this.onDatasetUpdate(messageContent['data'], messageContent['metadata']); } else { setTimeout(() => { this.runDatasetUpdateAfterSnapshotLoading(messageContent); }, 20); } } else { this.onDatasetUpdate(messageContent['data'], messageContent['metadata']); } } unsubscribeToEventBus() { this.datasetUpdatedSubscription.unsubscribe(); } ngOnDestroy() { this.eventManager.destroy(this.dashboardPanelResizedSubscriber); this.unsubscribeToEventBus(); } /** * Abstract methods */ abstract handleSelectedPropertyModelChanging(): void; abstract performSeriesComputationForCurrentDataset(saveAfterUpdate?: boolean): void; // @Override updatePieChartWidgetFromSnapshot(snapshot) { super.updatePieChartWidgetFromSnapshot(snapshot); if (snapshot['currentDataset']) { this.currentDataset = snapshot['currentDataset']; } } /** * Event bus methods */ onDatasetUpdate(data: Object, metadata: Object) { this.stopSpinner(); this.updateWidgetDataset(data); this.updateSecondaryMetadataFromPrimaryMetadata(metadata); // updating the class properties, as after metadata update could be some properties not present before super.updateSelectedClassProperties(); if (this.widget.type !== WidgetType.SECONDARY_QUERY_PIE_CHART) { // if the selected class was removed from the metadata we need to set the selectedClass to undefined if (this.selectedClass && !metadata['nodesClasses'][this.selectedClass] && !metadata['edgesClasses'][this.selectedClass]) { this.selectedClass = undefined; this.selectedProperty = undefined; } } let saved: boolean = false; if (this.currentDataset['elements'].length > 0) { if (this.selectedClass) { if (this.selectedProperty) { this.performSeriesComputationForCurrentDataset(true); saved = true; } else { console.log('[PieChartWidget-id: ' + this.widget.id + ']: cannot perform series computation as no properties are selcted.'); } } else { console.log('[PieChartWidget-id: ' + this.widget.id + ']: cannot perform series computation as no class are selcted.'); } } else { // clean the pie chart this.pieChartData = []; this.updatePieChart(); } if (!saved && this.principal.hasAnyAuthorityDirect(['ROLE_ADMIN', 'ROLE_EDITOR'])) { // even though we did not save the widget as we did not perform the series computation, we have to save the new current dataset and metadata this.saveAll(true); } } /** * It adds data elements (single vertices and edges) * to the instance variables if not present yet. * @param data */ updateWidgetDataset(data): void { if (data) { /* * Elements */ // saving class name inside data object and setting 'selectable' with the default value (true) data.forEach((elem) => { elem['data']['class'] = elem['classes']; elem['selectable'] = true; // whether the selection state is mutable (default true) }); this.currentDataset['elements'] = data; } } /** * It updates the current metadata for the secondary widget according to the primary widget metadata, * by performing some filtering in order to show just info about classes with element in the current dataset. * Moreover the cardinalities are changed with the actual number of elements present in the current dataset. */ updateSecondaryMetadataFromPrimaryMetadata(metadata: Object): void { this.dataSourceMetadata = metadata; } /** * Auxiliary functions */ // unused getAllClassNamesWithElementsInCurrentDataset(): string[] { const classNames = new Set(); this.currentDataset['elements'].forEach((elem) => { classNames.add(elem['data']['class']); }); return Array.from(classNames); } // unused getElementsOfClass(className: string, type?: string): string[] { const elements: string[] = []; let groupType: string; if (type) { if (type === 'node') { groupType = 'nodes'; } else { groupType = 'edges'; } } if (groupType) { for (const element of this.currentDataset['elements']) { if (element['group'] === groupType && element['classes'] === className) { elements.push(element); } } } else { for (const element of this.currentDataset['elements']) { if (element['classes'] === className) { elements.push(element); } } } return elements; } /** * Save */ // saves both data and metadata saveAll(hideNotification?: boolean) { let infoNotification; if (!hideNotification) { infoNotification = this.notificationService.push('info', 'Save', 'Saving the widget...', 3000, 'fa fa-spinner fa-spin'); } const delay: number = 10; setTimeout(() => { // just to avoid the saving ops block the first notification message const jsonForSnapshotSaving = this.buildSnapshotObject(); super.callSnapshotSave(jsonForSnapshotSaving, infoNotification); }, delay); } buildSnapshotObject(): Object { const jsonForSnapshotSaving = { pieChartData: this.pieChartData, pieChartLegendData: this.pieChartLegendData, pieChartLegendDataSelected: this.pieChartLegendDataSelected, currentDataset: this.currentDataset, dataSourceMetadata: this.dataSourceMetadata, currentFaceting: this.currentFaceting, selectedClass: this.selectedClass, limitEnabled: this.limitEnabled, limitForNodeFetching: this.limitForNodeFetching, selectedClassProperties: this.selectedClassProperties, selectedProperty: this.selectedProperty, showLegend: this.showLegend, showLabels: this.showLabels, labelPosition: this.labelPosition, minDocCount: this.minDocCount, maxValuesPerField: this.maxValuesPerField, minDocCountSliderUpperValue: this.minDocCountSliderUpperValue, maxValuesPerFieldSliderUpperValue: this.maxValuesPerFieldSliderUpperValue }; const perspective: Object = { pieChartTabActive: this.pieChartTabActive, datasourceTabActive: this.datasourceTabActive, }; jsonForSnapshotSaving['perspective'] = perspective; return jsonForSnapshotSaving; } }
the_stack
import * as angular from 'angular'; import { ChoicefieldType } from './choicefieldTypeEnum'; /** * @ngdoc interface * @name IChoicefieldOptionScope * @module officeuifabric.components.choicefield * * @description * This is the scope used by the choicefield option directive. * * * @property {string=} ngModel - Set the ng-model * @property {string=} ngTrueValue - Set the ng-true-value. Can only be used with checkbox * @property {string=} ngFalseValue - Set the ng-false-value. Can only be used with checkbox * @property {boolean=} disabled - Set to disable the element * @property {choicefieldType=} uifType - Radio or Checkbox */ export interface IChoicefieldOptionScope extends angular.IScope { ngModel: angular.INgModelController; ngTrueValue: string; ngFalseValue: string; disabled: boolean; uifType: ChoicefieldType; } /** * @ngdoc interface * @name IChoicefieldGroupScope * @module officeuifabric.components.choicefield * * @description * This is the scope used by the choicefield group directive. * * * @property {string=} ngModel - Set the ng-model * @property {boolean=} disabled - Set to disable the element */ export interface IChoicefieldGroupScope extends angular.IScope { ngModel: angular.INgModelController; disabled: boolean; } /** * @ngdoc class * @name ChoicefieldOptionController * @module officeuifabric.components.choicefield * * @description * This is the controller for the <uif-choicefield-option> directive */ export class ChoicefieldOptionController { public static $inject: string[] = ['$log']; constructor(public $log: angular.ILogService) { } } /** * @ngdoc directive * @name uifChoicefieldOption * @module officeuifabric.components.choicefield * * @restrict E * * @description * `<uif-choicefield-option>` is an option directive (radio or checkbox) * Can be used in uif-choicefield-group, or as a single element * * @usage * * <uif-choicefield-option uif-type="checkbox" value="Option1" * ng-model="selectedValue" ng-true-value="\'TRUEVALUE\'" ng-false-value="\'FALSEVALUE\'">Option 1</uif-choicefield> */ export class ChoicefieldOptionDirective implements angular.IDirective { public template: string = '<div class="ms-ChoiceField">' + '<input id="{{::$id}}" class="ms-ChoiceField-input" type="{{uifType}}" value="{{value}}" ng-disabled="disabled" ' + 'ng-model="ngModel" ng-true-value="{{ngTrueValue}}" ng-false-value="{{ngFalseValue}}" />' + '<label for="{{::$id}}" class="ms-ChoiceField-field"><span class="ms-Label" ng-transclude></span></label>' + '</div>'; public restrict: string = 'E'; public require: string[] = ['uifChoicefieldOption', '^?uifChoicefieldGroup']; public replace: boolean = true; public transclude: boolean = true; public scope: {} = { ngFalseValue: '@', ngModel: '=', ngTrueValue: '@', uifType: '@', value: '@' }; public controller: typeof ChoicefieldOptionController = ChoicefieldOptionController; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new ChoicefieldOptionDirective(); return directive; } public compile( templateElement: angular.IAugmentedJQuery, templateAttributes: angular.IAttributes, transclude: angular.ITranscludeFunction): angular.IDirectivePrePost { let input: angular.IAugmentedJQuery = templateElement.find('input'); if (!('ngModel' in templateAttributes)) { // remove ng-model, as this is an optional attribute. // if not removed, this will have unwanted side effects input.removeAttr('ng-model'); } return { pre: this.preLink }; } private preLink( scope: IChoicefieldOptionScope, instanceElement: angular.IAugmentedJQuery, attrs: any, ctrls: any[], transclude: angular.ITranscludeFunction): void { let choicefieldOptionController: ChoicefieldOptionController = ctrls[0]; let choicefieldGroupController: ChoicefieldGroupController = ctrls[1]; scope.$watch('uifType', (newValue: string, oldValue: string) => { if (ChoicefieldType[newValue] === undefined) { choicefieldOptionController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.choicefield - "' + newValue + '" is not a valid value for uifType. ' + 'Supported options are listed here: ' + 'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/choicefield/choicefieldTypeEnum.ts'); } }); if (choicefieldGroupController != null) { let render: () => void = (): void => { let checked: boolean = (choicefieldGroupController.getViewValue() === attrs.value); instanceElement.find('input').prop('checked', checked); }; choicefieldGroupController.addRender(render); attrs.$observe('value', render); instanceElement .on('$destroy', function (): void { choicefieldGroupController.removeRender(render); }); } let parentScope: IChoicefieldGroupScope = <IChoicefieldGroupScope>scope.$parent.$parent; let checkDisabled: () => void = () => { scope.disabled = 'disabled' in attrs && attrs.disabled; scope.disabled = scope.disabled || (parentScope != null && parentScope.disabled); }; scope.$watch( () => { return instanceElement.attr('disabled'); }, ((newValue) => { checkDisabled(); })); scope.$watch( () => { return parentScope == null ? '' : parentScope.disabled; }, ((newValue) => { checkDisabled(); })); checkDisabled(); instanceElement .on('click', (ev: JQueryEventObject) => { if (scope.disabled) { return; } if (choicefieldGroupController != null) { choicefieldGroupController.setTouched(); } scope.$apply(() => { if (choicefieldGroupController != null) { choicefieldGroupController.setViewValue(attrs.value, ev); } }); }); } } /** * @ngdoc directive * @name uifChoicefieldGroupTitle * @module officeuifabric.components.choicefield * * @restrict E * * @description * `<uif-choicefield-group-title>` is a choicefield group title directive * to render the title component of a choicefield group */ export class ChoicefieldGroupTitleDirective implements angular.IDirective { public template: string = '<div class="ms-ChoiceFieldGroup-title"><ng-transclude /></div>'; public transclude: boolean = true; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new ChoicefieldGroupTitleDirective(); return directive; } } /** * @ngdoc class * @name ChoicefieldgroupController * @module officeuifabric.components.choicefield * * @restrict E * * @description * ChoicefieldGroupController is the controller for the <uif-choicefield-group> directive * */ export class ChoicefieldGroupController { public static $inject: string[] = ['$element', '$scope']; private renderFns: Function[] = []; public constructor(public $element: JQuery, public $scope: IChoicefieldGroupScope) { } public init(): void { if (typeof this.$scope.ngModel !== 'undefined' && this.$scope.ngModel != null) { this.$scope.ngModel.$render = () => { this.render(); }; this.render(); } } public addRender(fn: Function): void { this.renderFns.push(fn); } public removeRender(fn: Function): void { this.renderFns.splice(this.renderFns.indexOf(fn)); } public setViewValue(value: string, eventType: any): void { if (typeof this.$scope.ngModel !== 'undefined' && this.$scope.ngModel != null) { if (this.getViewValue() !== value) { this.$scope.ngModel.$setDirty(); } this.$scope.ngModel.$setViewValue(value, eventType); this.render(); // update all inputs checked/not checked } } public setTouched(): void { if (typeof this.$scope.ngModel !== 'undefined' && this.$scope.ngModel != null) { this.$scope.ngModel.$setTouched(); } } public getViewValue(): string { if (typeof this.$scope.ngModel !== 'undefined' && this.$scope.ngModel != null) { return this.$scope.ngModel.$viewValue; } } private render(): void { for (let i: number = 0; i < this.renderFns.length; i++) { this.renderFns[i](); } } } /** * @ngdoc directive * @name uifChoicefieldGroup * @module officeuifabric.components.choicefield * * @restrict E * * @description * `<uif-choicefield>` is a choicefield directive * @see https://github.com/OfficeDev/Office-UI-Fabric/tree/master/src/components/Choicefield * * @usage * * <uif-choicefield-group ng-model="selectedValue"> * <uif-choicefield-group-title><label class="ms-Label is-required">Pick one</label></uif-choicefield-group-title> * <uif-choicefield-option uif-type="radio" ng-repeat="option in options" * value="{{option.value}}">{{option.text}}</uif-choicefield-option> * </uif-choicefield-group> */ export class ChoicefieldGroupDirective implements angular.IDirective { public template: string = '<div class="ms-ChoiceFieldGroup">' + '<ng-transclude />' + '</div>'; public restrict: string = 'E'; public transclude: boolean = true; public require: string[] = ['uifChoicefieldGroup', '?ngModel']; public controller: typeof ChoicefieldGroupController = ChoicefieldGroupController; // make sure we have an isolate scope public scope: {} = {}; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new ChoicefieldGroupDirective(); return directive; } public compile( templateElement: angular.IAugmentedJQuery, templateAttributes: angular.IAttributes, transclude: angular.ITranscludeFunction): angular.IDirectivePrePost { return { pre: this.preLink }; } private preLink( scope: IChoicefieldGroupScope, instanceElement: angular.IAugmentedJQuery, instanceAttributes: angular.IAttributes, ctrls: {}): void { let choicefieldGroupController: ChoicefieldGroupController = ctrls[0]; let modelController: angular.INgModelController = ctrls[1]; scope.ngModel = modelController; choicefieldGroupController.init(); scope.$watch( () => { return instanceElement.attr('disabled'); }, ((newValue) => { scope.disabled = typeof newValue !== 'undefined'; })); scope.disabled = 'disabled' in instanceAttributes; } } /** * @ngdoc module * @name officeuifabric.components.choicefield * * @description * ChoiceField * */ export let module: angular.IModule = angular.module('officeuifabric.components.choicefield', [ 'officeuifabric.components' ]) .directive('uifChoicefieldOption', ChoicefieldOptionDirective.factory()) .directive('uifChoicefieldGroup', ChoicefieldGroupDirective.factory()) .directive('uifChoicefieldGroupTitle', ChoicefieldGroupTitleDirective.factory());
the_stack
import * as PropTypes from 'prop-types'; import * as React from 'react'; import FocusManagerBase from './utils/FocusManager'; import { Types } from './Interfaces'; import { Dimensions, PopupPosition } from './Types'; export interface PopupContainerViewBaseProps<C> extends Types.CommonProps<C> { hidden?: boolean; } export interface PopupContainerViewContext { focusManager?: FocusManagerBase; } export interface PopupComponent { onShow: () => void; onHide: () => void; } export interface RecalcResult { // Absolute window location of the popup popupY: number; popupX: number; // Top or left offset of the popup relative to the center of the anchor anchorOffset: number; // Position of popup relative to its anchor (top, bottom, left, right) anchorPosition: PopupPosition; // Constrained dimensions of the popup once it is placed constrainedPopupWidth: number; constrainedPopupHeight: number; } // Width of the "alley" around popups so they don't get too close to the boundary of the screen boundary. const ALLEY_WIDTH = 2; // How close to the edge of the popup should we allow the anchor offset to get before // attempting a different position? const MIN_ANCHOR_OFFSET = 16; // Undefined response means to dismiss the popup export function recalcPositionFromLayoutData(windowDims: Dimensions, anchorRect: ClientRect, popupRect: Dimensions, positionPriorities?: PopupPosition[], useInnerPositioning?: boolean): RecalcResult | undefined { // If the anchor has disappeared, dismiss the popup. if (!(anchorRect.width > 0 && anchorRect.height > 0)) { return undefined; } // If the anchor is no longer in the window's bounds, cancel the popup. if (anchorRect.left >= windowDims.width || anchorRect.right <= 0 || anchorRect.bottom <= 0 || anchorRect.top >= windowDims.height) { return undefined; } let positionsToTry = positionPriorities; if (!positionsToTry || positionsToTry.length === 0) { positionsToTry = ['bottom', 'right', 'top', 'left']; } if (positionsToTry.length === 1 && positionsToTry[0] === 'context') { // Context only works with exact matches, so fall back to walking around the compass if it doesn't fit exactly. positionsToTry.push('bottom', 'right', 'top', 'left'); } if (useInnerPositioning) { // If the popup is meant to be shown inside the anchor we need to recalculate // the position differently. return recalcInnerPosition(anchorRect, positionsToTry[0], popupRect.width, popupRect.height); } // Start by assuming that we'll be unconstrained. const result: RecalcResult = { popupX: 0, popupY: 0, anchorOffset: 0, anchorPosition: 'top', constrainedPopupWidth: popupRect.width, constrainedPopupHeight: popupRect.height, }; let foundPerfectFit = false; let foundPartialFit = false; positionsToTry.forEach(pos => { if (!foundPerfectFit) { let absX = 0; let absY = 0; let anchorOffset = 0; let constrainedWidth = 0; let constrainedHeight = 0; switch (pos) { case 'bottom': absY = anchorRect.bottom; absX = anchorRect.left + (anchorRect.width - popupRect.width) / 2; anchorOffset = popupRect.width / 2; if (popupRect.height <= windowDims.height - ALLEY_WIDTH - anchorRect.bottom) { foundPerfectFit = true; } else if (!foundPartialFit) { constrainedHeight = windowDims.height - ALLEY_WIDTH - anchorRect.bottom; } break; case 'top': absY = anchorRect.top - popupRect.height; absX = anchorRect.left + (anchorRect.width - popupRect.width) / 2; anchorOffset = popupRect.width / 2; if (popupRect.height <= anchorRect.top - ALLEY_WIDTH) { foundPerfectFit = true; } else if (!foundPartialFit) { constrainedHeight = anchorRect.top - ALLEY_WIDTH; } break; case 'right': absX = anchorRect.right; absY = anchorRect.top + (anchorRect.height - popupRect.height) / 2; anchorOffset = popupRect.height / 2; if (popupRect.width <= windowDims.width - ALLEY_WIDTH - anchorRect.right) { foundPerfectFit = true; } else if (!foundPartialFit) { constrainedWidth = windowDims.width - ALLEY_WIDTH - anchorRect.right; } break; case 'left': absX = anchorRect.left - popupRect.width; absY = anchorRect.top + (anchorRect.height - popupRect.height) / 2; anchorOffset = popupRect.height / 2; if (popupRect.width <= anchorRect.left - ALLEY_WIDTH) { foundPerfectFit = true; } else if (!foundPartialFit) { constrainedWidth = anchorRect.left - ALLEY_WIDTH; } break; case 'context': { // Search for perfect fits on the LR, LL, TR, and TL corners. const fitsAbove = anchorRect.top - popupRect.height >= ALLEY_WIDTH; const fitsBelow = anchorRect.top + anchorRect.height + popupRect.height <= windowDims.height - ALLEY_WIDTH; const fitsLeft = anchorRect.left - popupRect.width >= ALLEY_WIDTH; const fitsRight = anchorRect.left + anchorRect.width + popupRect.width <= windowDims.width - ALLEY_WIDTH; if (fitsBelow && fitsRight) { foundPerfectFit = true; absX = anchorRect.left + anchorRect.width; absY = anchorRect.top + anchorRect.height; } else if (fitsBelow && fitsLeft) { foundPerfectFit = true; absX = anchorRect.left - popupRect.width; absY = anchorRect.top + anchorRect.height; } else if (fitsAbove && fitsRight) { foundPerfectFit = true; absX = anchorRect.left + anchorRect.width; absY = anchorRect.top - popupRect.height; } else if (fitsAbove && fitsLeft) { foundPerfectFit = true; absX = anchorRect.left - popupRect.width; absY = anchorRect.top - popupRect.height; } break; } } const effectiveWidth = constrainedWidth || popupRect.width; const effectiveHeight = constrainedHeight || popupRect.height; // Make sure we're not hanging off the bounds of the window. if (absX < ALLEY_WIDTH) { if (pos === 'top' || pos === 'bottom') { anchorOffset -= ALLEY_WIDTH - absX; if (anchorOffset < MIN_ANCHOR_OFFSET || anchorOffset > effectiveWidth - MIN_ANCHOR_OFFSET) { foundPerfectFit = false; } } absX = ALLEY_WIDTH; } else if (absX > windowDims.width - ALLEY_WIDTH - effectiveWidth) { if (pos === 'top' || pos === 'bottom') { anchorOffset -= (windowDims.width - ALLEY_WIDTH - effectiveWidth - absX); if (anchorOffset < MIN_ANCHOR_OFFSET || anchorOffset > effectiveWidth - MIN_ANCHOR_OFFSET) { foundPerfectFit = false; } } absX = windowDims.width - ALLEY_WIDTH - effectiveWidth; } if (absY < ALLEY_WIDTH) { if (pos === 'right' || pos === 'left') { anchorOffset += absY - ALLEY_WIDTH; if (anchorOffset < MIN_ANCHOR_OFFSET || anchorOffset > effectiveHeight - MIN_ANCHOR_OFFSET) { foundPerfectFit = false; } } absY = ALLEY_WIDTH; } else if (absY > windowDims.height - ALLEY_WIDTH - effectiveHeight) { if (pos === 'right' || pos === 'left') { anchorOffset -= (windowDims.height - ALLEY_WIDTH - effectiveHeight - absY); if (anchorOffset < MIN_ANCHOR_OFFSET || anchorOffset > effectiveHeight - MIN_ANCHOR_OFFSET) { foundPerfectFit = false; } } absY = windowDims.height - ALLEY_WIDTH - effectiveHeight; } if (foundPerfectFit || effectiveHeight > 0 || effectiveWidth > 0) { result.popupY = absY; result.popupX = absX; result.anchorOffset = anchorOffset; result.anchorPosition = pos; result.constrainedPopupWidth = effectiveWidth; result.constrainedPopupHeight = effectiveHeight; foundPartialFit = true; } } }); return result; } function recalcInnerPosition(anchorRect: ClientRect, positionToUse: PopupPosition, popupWidth: number, popupHeight: number) { // For inner popups we only accept the first position of the priorities since there // should always be room for the bubble. let popupX = 0; let popupY = 0; let anchorOffset = 0; switch (positionToUse) { case 'top': popupY = anchorRect.top + anchorRect.height - popupHeight; popupX = anchorRect.left + anchorRect.height / 2 - popupWidth / 2; anchorOffset = popupWidth / 2; break; case 'bottom': popupY = anchorRect.top + popupHeight; popupX = anchorRect.left + anchorRect.height / 2 - popupWidth / 2; anchorOffset = popupWidth / 2; break; case 'left': popupY = anchorRect.top + anchorRect.height / 2 - popupHeight / 2; popupX = anchorRect.left + anchorRect.width - popupWidth; anchorOffset = popupHeight / 2; break; case 'right': popupY = anchorRect.top + anchorRect.height / 2 - popupHeight / 2; popupX = anchorRect.left; anchorOffset = popupHeight / 2; break; case 'context': throw new Error('Context popup mode not allowed with inner positioning'); } const result: RecalcResult = { popupX, popupY, anchorOffset, anchorPosition: positionToUse, constrainedPopupWidth: popupWidth, constrainedPopupHeight: popupHeight, }; return result; } export abstract class PopupContainerViewBase<P extends PopupContainerViewBaseProps<C>, S, C> extends React.Component<P, S> { static contextTypes: React.ValidationMap<any> = { focusManager: PropTypes.object, }; static childContextTypes: React.ValidationMap<any> = { focusManager: PropTypes.object, popupContainer: PropTypes.object, }; private _popupComponentStack: PopupComponent[] = []; constructor(props: P, context?: PopupContainerViewContext) { super(props, context); } getChildContext() { return { focusManager: this.context.focusManager, popupContainer: this as PopupContainerViewBase<P, S, C>, }; } registerPopupComponent(onShow: () => void, onHide: () => void): PopupComponent { const component = { onShow, onHide, }; this._popupComponentStack.push(component); return component; } unregisterPopupComponent(component: PopupComponent) { this._popupComponentStack = this._popupComponentStack.filter(c => c !== component); } isHidden(): boolean { return !!this.props.hidden; } componentDidUpdate(prevProps: P, prevState: S) { if (prevProps.hidden && !this.props.hidden) { // call onShow on all registered components (iterate front to back) for (let i = 0; i < this._popupComponentStack.length; i++) { this._popupComponentStack[i].onShow(); } } if (!prevProps.hidden && this.props.hidden) { // call onHide on all registered components (iterate back to front) for (let i = this._popupComponentStack.length - 1; i >= 0; i--) { this._popupComponentStack[i].onHide(); } } } abstract render(): JSX.Element; } export default PopupContainerViewBase;
the_stack
import { ConfigServiceInterface, EnvironmentVariablesService } from '../../../src/config'; import { injectLambdaContext } from '../../../src/middleware/middy'; import { Logger } from './../../../src'; import middy from '@middy/core'; import { PowertoolLogFormatter } from '../../../src/formatter'; import { Console } from 'console'; const mockDate = new Date(1466424490000); const dateSpy = jest.spyOn(global, 'Date').mockImplementation(() => mockDate as unknown as string); describe('Middy middleware', () => { const ENVIRONMENT_VARIABLES = process.env; beforeEach(() => { jest.resetModules(); dateSpy.mockClear(); jest.spyOn(process.stdout, 'write').mockImplementation(() => null as unknown as boolean); process.env = { ...ENVIRONMENT_VARIABLES }; }); afterAll(() => { process.env = ENVIRONMENT_VARIABLES; }); describe('injectLambdaContext', () => { describe('Feature: add context data', () => { test('when a logger object is passed, it adds the context to the logger instance', async () => { // Prepare const logger = new Logger(); const lambdaHandler = (): void => { logger.info('This is an INFO log with some context'); }; const handler = middy(lambdaHandler).use(injectLambdaContext(logger)); const event = { foo: 'bar' }; const getRandomInt = (): number => Math.floor(Math.random() * 1000000000); const awsRequestId = getRandomInt().toString(); const context = { callbackWaitsForEmptyEventLoop: true, functionVersion: '$LATEST', functionName: 'foo-bar-function', memoryLimitInMB: '128', logGroupName: '/aws/lambda/foo-bar-function', logStreamName: '2021/03/09/[$LATEST]abcdef123456abcdef123456abcdef123456', invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function', awsRequestId: awsRequestId, getRemainingTimeInMillis: () => 1234, done: () => console.log('Done!'), fail: () => console.log('Failed!'), succeed: () => console.log('Succeeded!'), }; // Act await handler(event, context, () => console.log('Lambda invoked!')); // Assess expect(logger).toEqual(expect.objectContaining({ logsSampled: false, persistentLogAttributes: {}, powertoolLogData: { sampleRateValue: undefined, awsRegion: 'eu-west-1', environment: '', lambdaContext: { awsRequestId: awsRequestId, coldStart: true, functionName: 'foo-bar-function', functionVersion: '$LATEST', invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function', memoryLimitInMB: 128, }, serviceName: 'hello-world', }, envVarsService: expect.any(EnvironmentVariablesService), customConfigService: undefined, logLevel: 'DEBUG', logFormatter: expect.any(PowertoolLogFormatter), })); }); test('when a logger array is passed, it adds the context to all logger instances', async () => { // Prepare const logger = new Logger(); const anotherLogger = new Logger(); const lambdaHandler = (): void => { logger.info('This is an INFO log with some context'); anotherLogger.info('This is an INFO log with some context'); }; const handler = middy(lambdaHandler).use(injectLambdaContext([ logger, anotherLogger ])); const event = { foo: 'bar' }; const getRandomInt = (): number => Math.floor(Math.random() * 1000000000); const awsRequestId = getRandomInt().toString(); const context = { callbackWaitsForEmptyEventLoop: true, functionVersion: '$LATEST', functionName: 'foo-bar-function', memoryLimitInMB: '128', logGroupName: '/aws/lambda/foo-bar-function', logStreamName: '2021/03/09/[$LATEST]abcdef123456abcdef123456abcdef123456', invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function', awsRequestId: awsRequestId, getRemainingTimeInMillis: () => 1234, done: () => console.log('Done!'), fail: () => console.log('Failed!'), succeed: () => console.log('Succeeded!'), }; // Act await handler(event, context, () => console.log('Lambda invoked!')); // Assess const expectation = expect.objectContaining({ logsSampled: false, persistentLogAttributes: {}, powertoolLogData: { sampleRateValue: undefined, awsRegion: 'eu-west-1', environment: '', lambdaContext: { awsRequestId: awsRequestId, coldStart: true, functionName: 'foo-bar-function', functionVersion: '$LATEST', invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function', memoryLimitInMB: 128, }, serviceName: 'hello-world', }, envVarsService: expect.any(EnvironmentVariablesService), customConfigService: undefined, logLevel: 'DEBUG', logFormatter: expect.any(PowertoolLogFormatter), console: expect.any(Console), }); expect(logger).toEqual(expectation); expect(anotherLogger).toEqual(expectation); }); }); test('when a logger is passed with option logEvent set to true, it logs the event', async () => { // Prepare const logger = new Logger(); const consoleSpy = jest.spyOn(logger['console'], 'info').mockImplementation(); const lambdaHandler = (): void => { logger.info('This is an INFO log with some context'); }; const handler = middy(lambdaHandler).use(injectLambdaContext(logger , { logEvent: true })); const event = { foo: 'bar' }; const getRandomInt = (): number => Math.floor(Math.random() * 1000000000); const awsRequestId = getRandomInt().toString(); const context = { callbackWaitsForEmptyEventLoop: true, functionVersion: '$LATEST', functionName: 'foo-bar-function', memoryLimitInMB: '128', logGroupName: '/aws/lambda/foo-bar-function', logStreamName: '2021/03/09/[$LATEST]abcdef123456abcdef123456abcdef123456', invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function', awsRequestId: awsRequestId, getRemainingTimeInMillis: () => 1234, done: () => console.log('Done!'), fail: () => console.log('Failed!'), succeed: () => console.log('Succeeded!'), }; // Act await handler(event, context, () => console.log('Lambda invoked!')); // Assess expect(consoleSpy).toBeCalledTimes(2); expect(consoleSpy).toHaveBeenNthCalledWith(1, JSON.stringify({ cold_start: true, function_arn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function', function_memory_size: 128, function_name: 'foo-bar-function', function_request_id: awsRequestId, level: 'INFO', message: 'Lambda invocation event', service: 'hello-world', timestamp: '2016-06-20T12:08:10.000Z', xray_trace_id: '1-5759e988-bd862e3fe1be46a994272793', event: { foo: 'bar' } })); }); test('when a logger is passed with option logEvent set to true, it logs the event', async () => { // Prepare const configService: ConfigServiceInterface = { get(name: string): string { return `a-string-from-${name}`; }, getCurrentEnvironment(): string { return 'dev'; }, getLogEvent(): boolean { return true; }, getLogLevel(): string { return 'INFO'; }, getSampleRateValue(): number | undefined { return undefined; }, getServiceName(): string { return 'my-backend-service'; }, }; // Prepare const logger = new Logger({ customConfigService: configService, }); const consoleSpy = jest.spyOn(logger['console'], 'info').mockImplementation(); const lambdaHandler = (): void => { logger.info('This is an INFO log with some context'); }; const handler = middy(lambdaHandler).use(injectLambdaContext(logger , { logEvent: true })); const event = { foo: 'bar' }; const getRandomInt = (): number => Math.floor(Math.random() * 1000000000); const awsRequestId = getRandomInt().toString(); const context = { callbackWaitsForEmptyEventLoop: true, functionVersion: '$LATEST', functionName: 'foo-bar-function', memoryLimitInMB: '128', logGroupName: '/aws/lambda/foo-bar-function', logStreamName: '2021/03/09/[$LATEST]abcdef123456abcdef123456abcdef123456', invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function', awsRequestId: awsRequestId, getRemainingTimeInMillis: () => 1234, done: () => console.log('Done!'), fail: () => console.log('Failed!'), succeed: () => console.log('Succeeded!'), }; // Act await handler(event, context, () => console.log('Lambda invoked!')); // Assess expect(consoleSpy).toBeCalledTimes(2); expect(consoleSpy).toHaveBeenNthCalledWith(1, JSON.stringify({ cold_start: true, function_arn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function', function_memory_size: 128, function_name: 'foo-bar-function', function_request_id: awsRequestId, level: 'INFO', message: 'Lambda invocation event', service: 'my-backend-service', timestamp: '2016-06-20T12:08:10.000Z', xray_trace_id: '1-5759e988-bd862e3fe1be46a994272793', event: { foo: 'bar' } })); }); }); describe('Feature: clear state', () => { test('when enabled, the persistent log attributes added in the handler are removed after the handler\'s code is executed', async () => { // Prepare const logger = new Logger({ logLevel: 'DEBUG', persistentLogAttributes: { foo: 'bar', biz: 'baz' } }); const context = { callbackWaitsForEmptyEventLoop: true, functionVersion: '$LATEST', functionName: 'foo-bar-function', memoryLimitInMB: '128', logGroupName: '/aws/lambda/foo-bar-function', logStreamName: '2021/03/09/[$LATEST]abcdef123456abcdef123456abcdef123456', invokedFunctionArn: 'arn:aws:lambda:eu-west-1:123456789012:function:foo-bar-function', awsRequestId: 'abcdef123456abcdef123456', getRemainingTimeInMillis: () => 1234, done: () => console.log('Done!'), fail: () => console.log('Failed!'), succeed: () => console.log('Succeeded!'), }; const lambdaHandler = (event: { user_id: string }): void => { // Only add these persistent for the scope of this lambda handler logger.appendKeys({ details: { user_id: event['user_id'] } }); logger.debug('This is a DEBUG log with the user_id'); logger.debug('This is another DEBUG log with the user_id'); }; const handler = middy(lambdaHandler).use(injectLambdaContext(logger, { clearState: true })); const persistentAttribs = { ...logger.getPersistentLogAttributes() }; // Act await handler({ user_id: '123456' }, context, () => console.log('Lambda invoked!')); const persistentAttribsAfterInvocation = { ...logger.getPersistentLogAttributes() }; // Assess expect(persistentAttribs).toEqual({ foo: 'bar', biz: 'baz' }); expect(persistentAttribsAfterInvocation).toEqual(persistentAttribs); }); }); });
the_stack
import assert from "assert"; import fs from "fs/promises"; import path from "path"; import { CorePlugin, Request, Response, Scheduler } from "@miniflare/core"; import { Compatibility, NoOpLog, PluginContext, STRING_SCRIPT_PATH, } from "@miniflare/shared"; import { logPluginOptions, parsePluginArgv, parsePluginWranglerConfig, useServer, useTmp, } from "@miniflare/shared-test"; import test, { ThrowsExpectation } from "ava"; import { File, FormData } from "undici"; const log = new NoOpLog(); const compat = new Compatibility(); const rootPath = process.cwd(); const ctx: PluginContext = { log, compat, rootPath, globalAsyncIO: true }; test("CorePlugin: parses options from argv", (t) => { let options = parsePluginArgv(CorePlugin, [ "script.js", "--wrangler-config", "wrangler.custom.toml", "--wrangler-env", "dev", "--package", "package.custom.json", "--modules", "--modules-rule", "Text=*.txt", "--modules-rule", "Data=*.png", "--compat-date", "2021-10-23", "--compat-flag", "fetch_refuses_unknown_protocols", "--compat-flag", "durable_object_fetch_allows_relative_url", "--upstream", "https://github.com/mrbbot", "--watch", "--debug", "--verbose", "--root", "root", "--mount", "api=./api", "--mount", "site=./site@dev", "--name", "worker", "--route", "https://miniflare.dev/*", "--route", "dev.miniflare.dev/*", "--global-async-io", "--global-timers", "--global-random", ]); t.deepEqual(options, { scriptPath: "script.js", wranglerConfigPath: "wrangler.custom.toml", wranglerConfigEnv: "dev", packagePath: "package.custom.json", modules: true, modulesRules: [ { type: "Text", include: ["*.txt"], fallthrough: true }, { type: "Data", include: ["*.png"], fallthrough: true }, ], compatibilityDate: "2021-10-23", compatibilityFlags: [ "fetch_refuses_unknown_protocols", "durable_object_fetch_allows_relative_url", ], upstream: "https://github.com/mrbbot", watch: true, debug: true, verbose: true, rootPath: "root", mounts: { api: { rootPath: "./api", wranglerConfigEnv: undefined, packagePath: true, envPathDefaultFallback: true, wranglerConfigPath: true, }, site: { rootPath: "./site", wranglerConfigEnv: "dev", packagePath: true, envPathDefaultFallback: true, wranglerConfigPath: true, }, }, name: "worker", routes: ["https://miniflare.dev/*", "dev.miniflare.dev/*"], globalAsyncIO: true, globalTimers: true, globalRandom: true, }); options = parsePluginArgv(CorePlugin, [ "-c", "wrangler.custom.toml", "-m", "-u", "https://miniflare.dev", "-wdV", ]); t.deepEqual(options, { wranglerConfigPath: "wrangler.custom.toml", modules: true, upstream: "https://miniflare.dev", watch: true, debug: true, verbose: true, }); }); test("CorePlugin: parses options from wrangler config", async (t) => { const configDir = await useTmp(t); let options = parsePluginWranglerConfig( CorePlugin, { name: "test-service", compatibility_date: "2021-10-23", compatibility_flags: [ "fetch_refuses_unknown_protocols", "durable_object_fetch_allows_relative_url", ], build: { upload: { format: "modules", main: "script.mjs", dir: "src", rules: [ { type: "Text", globs: ["*.txt"], fallthrough: true }, { type: "Data", globs: ["*.png"] }, ], }, }, route: "miniflare.dev/*", routes: ["dev.miniflare.dev/*"], miniflare: { upstream: "https://miniflare.dev", watch: true, update_check: false, mounts: { api: "./api", site: "./site@dev" }, route: "http://localhost:8787/*", routes: ["miniflare.mf:8787/*"], global_async_io: true, global_timers: true, global_random: true, }, }, configDir ); t.deepEqual(options, { script: undefined, wranglerConfigPath: undefined, wranglerConfigEnv: undefined, packagePath: undefined, scriptPath: path.resolve(configDir, "src", "script.mjs"), modules: true, modulesRules: [ { type: "Text", include: ["*.txt"], fallthrough: true }, { type: "Data", include: ["*.png"], fallthrough: undefined }, ], compatibilityDate: "2021-10-23", compatibilityFlags: [ "fetch_refuses_unknown_protocols", "durable_object_fetch_allows_relative_url", ], upstream: "https://miniflare.dev", watch: true, debug: undefined, verbose: undefined, updateCheck: false, rootPath: undefined, mounts: { api: { rootPath: path.resolve(configDir, "api"), wranglerConfigEnv: undefined, packagePath: true, envPathDefaultFallback: true, wranglerConfigPath: true, }, site: { rootPath: path.resolve(configDir, "site"), wranglerConfigEnv: "dev", packagePath: true, envPathDefaultFallback: true, wranglerConfigPath: true, }, }, name: "test-service", routes: [ "miniflare.dev/*", "dev.miniflare.dev/*", "http://localhost:8787/*", "miniflare.mf:8787/*", ], logUnhandledRejections: undefined, globalAsyncIO: true, globalTimers: true, globalRandom: true, }); // Check build upload dir defaults to dist options = parsePluginWranglerConfig( CorePlugin, { build: { upload: { main: "script.js" } } }, configDir ); t.is(options.scriptPath, path.resolve(configDir, "dist", "script.js")); t.is(options.routes, undefined); }); test("CorePlugin: logs options", (t) => { let logs = logPluginOptions(CorePlugin, { script: "console.log('Hello!')", scriptPath: "script.js", wranglerConfigPath: "wrangler.custom.toml", wranglerConfigEnv: "dev", packagePath: "package.custom.json", modules: true, modulesRules: [ { type: "Text", include: ["*.txt"], fallthrough: true }, { type: "Data", include: ["*.png", "*.jpg"] }, ], upstream: "https://miniflare.dev", watch: true, debug: true, verbose: true, rootPath: "root", mounts: { api: "./api", site: "./site" }, name: "worker", routes: ["https://miniflare.dev/*", "dev.miniflare.dev/*"], globalAsyncIO: true, globalTimers: true, globalRandom: true, }); t.deepEqual(logs, [ // script is OptionType.NONE so omitted "Script Path: script.js", "Wrangler Config Path: wrangler.custom.toml", "Wrangler Environment: dev", "Package Path: package.custom.json", "Modules: true", "Modules Rules: {Text: *.txt}, {Data: *.png, *.jpg}", "Upstream: https://miniflare.dev", "Watch: true", "Debug: true", "Verbose: true", "Root Path: root", "Mounts: api, site", "Name: worker", "Routes: https://miniflare.dev/*, dev.miniflare.dev/*", "Allow Global Async I/O: true", "Allow Global Timers: true", "Allow Global Secure Random: true", ]); // Check logs default wrangler config/package paths logs = logPluginOptions(CorePlugin, { wranglerConfigPath: true, packagePath: true, }); t.deepEqual(logs, [ "Wrangler Config Path: wrangler.toml", "Package Path: package.json", ]); // Check doesn't log wrangler config/package paths if explicitly disabled logs = logPluginOptions(CorePlugin, {}); t.deepEqual(logs, []); logs = logPluginOptions(CorePlugin, { wranglerConfigPath: false, packagePath: false, }); t.deepEqual(logs, []); }); test("CorePlugin: setup: includes web standards", async (t) => { const plugin = new CorePlugin(ctx); const { globals } = await plugin.setup(); assert(globals); t.true(typeof globals.console === "object"); t.true(typeof globals.setTimeout === "function"); t.true(typeof globals.setInterval === "function"); t.true(typeof globals.clearTimeout === "function"); t.true(typeof globals.clearInterval === "function"); t.true(typeof globals.queueMicrotask === "function"); t.true(typeof globals.scheduler.wait === "function"); t.true(typeof globals.atob === "function"); t.true(typeof globals.btoa === "function"); t.true(typeof globals.crypto === "object"); t.true(typeof globals.CryptoKey === "function"); t.true(typeof globals.TextDecoder === "function"); t.true(typeof globals.TextEncoder === "function"); t.true(typeof globals.fetch === "function"); t.true(typeof globals.Headers === "function"); t.true(typeof globals.Request === "function"); t.true(typeof globals.Response === "function"); t.true(typeof globals.FormData === "function"); t.true(typeof globals.Blob === "function"); t.true(typeof globals.File === "function"); t.true(typeof globals.URL === "function"); t.true(typeof globals.URLSearchParams === "function"); t.true(typeof globals.URLPattern === "function"); t.true(typeof globals.ByteLengthQueuingStrategy === "function"); t.true(typeof globals.CountQueuingStrategy === "function"); t.true(typeof globals.ReadableByteStreamController === "function"); t.true(typeof globals.ReadableStream === "function"); t.true(typeof globals.ReadableStreamBYOBReader === "function"); t.true(typeof globals.ReadableStreamBYOBRequest === "function"); t.true(typeof globals.ReadableStreamDefaultController === "function"); t.true(typeof globals.ReadableStreamDefaultReader === "function"); t.true(typeof globals.TransformStream === "function"); t.true(typeof globals.TransformStreamDefaultController === "function"); t.true(typeof globals.WritableStream === "function"); t.true(typeof globals.WritableStreamDefaultController === "function"); t.true(typeof globals.WritableStreamDefaultWriter === "function"); t.true(typeof globals.FixedLengthStream === "function"); t.true(typeof globals.Event === "function"); t.true(typeof globals.EventTarget === "function"); t.true(typeof globals.AbortController === "function"); t.true(typeof globals.AbortSignal === "function"); t.true(typeof globals.FetchEvent === "function"); t.true(typeof globals.ScheduledEvent === "function"); t.true(typeof globals.DOMException === "function"); t.true(typeof globals.WorkerGlobalScope === "function"); t.true(typeof globals.structuredClone === "function"); t.true(typeof globals.ArrayBuffer === "function"); t.true(typeof globals.Atomics === "object"); t.true(typeof globals.BigInt64Array === "function"); t.true(typeof globals.BigUint64Array === "function"); t.true(typeof globals.DataView === "function"); t.true(typeof globals.Date === "function"); t.true(typeof globals.Float32Array === "function"); t.true(typeof globals.Float64Array === "function"); t.true(typeof globals.Int8Array === "function"); t.true(typeof globals.Int16Array === "function"); t.true(typeof globals.Int32Array === "function"); t.true(typeof globals.Map === "function"); t.true(typeof globals.Set === "function"); t.true(typeof globals.SharedArrayBuffer === "function"); t.true(typeof globals.Uint8Array === "function"); t.true(typeof globals.Uint8ClampedArray === "function"); t.true(typeof globals.Uint16Array === "function"); t.true(typeof globals.Uint32Array === "function"); t.true(typeof globals.WeakMap === "function"); t.true(typeof globals.WeakSet === "function"); t.true(typeof globals.WebAssembly === "object"); t.true(globals.MINIFLARE); }); test("CorePlugin: setup: timer operations throw outside request handler unless globalTimers set", async (t) => { interface Globals { setTimeout: typeof setTimeout; clearTimeout: typeof clearTimeout; setInterval: typeof setInterval; clearInterval: typeof clearInterval; scheduler: Scheduler; } let plugin = new CorePlugin(ctx); let globals = (await plugin.setup()).globals as Globals; const expectations: ThrowsExpectation = { instanceOf: Error, message: /^Some functionality, such as asynchronous I\/O/, }; // Get an instance of Node's stranger Timeout type const timeout = setTimeout(() => {}); t.throws(() => globals.setTimeout(() => {}), expectations); t.throws(() => globals.clearTimeout(timeout), expectations); t.throws(() => globals.setInterval(() => {}), expectations); t.throws(() => globals.clearInterval(timeout), expectations); await t.throwsAsync(async () => globals.scheduler.wait(0), expectations); // Check with globalTimers set plugin = new CorePlugin(ctx, { globalTimers: true }); globals = (await plugin.setup()).globals as Globals; globals.clearTimeout(globals.setTimeout(() => {})); globals.clearInterval(globals.setInterval(() => {})); await globals.scheduler.wait(0); }); test("CorePlugin: setup: secure random operations throw outside request handler unless globalRandom set", async (t) => { type Crypto = typeof import("crypto").webcrypto; let plugin = new CorePlugin(ctx); let crypto = (await plugin.setup()).globals?.crypto as Crypto; const expectations: ThrowsExpectation = { instanceOf: Error, message: /^Some functionality, such as asynchronous I\/O/, }; const args: Parameters<typeof crypto.subtle.generateKey> = [ { name: "aes-gcm", length: 256 } as any, true, ["encrypt", "decrypt"], ]; t.throws(() => crypto.getRandomValues(new Uint8Array(8)), expectations); t.throws(() => crypto.subtle.generateKey(...args), expectations); // Check with globalRandom set plugin = new CorePlugin(ctx, { globalRandom: true }); crypto = (await plugin.setup()).globals?.crypto as Crypto; crypto.getRandomValues(new Uint8Array(8)); await crypto.subtle.generateKey(...args); }); test("CorePlugin: setup: fetch refuses unknown protocols only if compatibility flag enabled", async (t) => { const upstream = (await useServer(t, (req, res) => res.end("upstream"))).http; upstream.protocol = "ftp:"; let plugin = new CorePlugin(ctx); let { globals } = await plugin.setup(); const res = await globals?.fetch(upstream); t.is(await res.text(), "upstream"); const compat = new Compatibility(undefined, [ "fetch_refuses_unknown_protocols", ]); plugin = new CorePlugin({ log, compat, rootPath, globalAsyncIO: true }); globals = (await plugin.setup()).globals; await t.throwsAsync(async () => globals?.fetch(upstream), { instanceOf: TypeError, message: `Fetch API cannot load: ${upstream.toString()}`, }); }); test("CorePlugin: setup: fetch throws outside request handler unless globalAsyncIO set", async (t) => { const upstream = (await useServer(t, (req, res) => res.end("upstream"))).http; let plugin = new CorePlugin({ log, compat, rootPath }); let { globals } = await plugin.setup(); await t.throwsAsync(globals?.fetch(upstream), { instanceOf: Error, message: /^Some functionality, such as asynchronous I\/O/, }); plugin = new CorePlugin({ log, compat, rootPath, globalAsyncIO: true }); globals = (await plugin.setup()).globals; await globals?.fetch(upstream); }); test("CorePlugin: setup: Request parses files in FormData as File objects only if compatibility flag enabled", async (t) => { const formData = new FormData(); formData.append("file", new File(["test"], "test.txt")); let plugin = new CorePlugin(ctx); let CompatRequest: typeof Request = (await plugin.setup()).globals?.Request; let req = new CompatRequest("http://localhost", { method: "POST", body: formData, }); let reqFormData = await req.formData(); t.is(reqFormData.get("file"), "test"); const compat = new Compatibility(undefined, [ "formdata_parser_supports_files", ]); plugin = new CorePlugin({ log, compat, rootPath }); CompatRequest = (await plugin.setup()).globals?.Request; req = new CompatRequest("http://localhost", { method: "POST", body: formData, }); reqFormData = await req.formData(); t.true(reqFormData.get("file") instanceof File); }); test("CorePlugin: setup: Response parses files in FormData as File objects only if compatibility flag enabled", async (t) => { const formData = new FormData(); formData.append("file", new File(["test"], "test.txt")); let plugin = new CorePlugin(ctx); let CompatResponse: typeof Response = (await plugin.setup()).globals ?.Response; let res = new CompatResponse(formData); let resFormData = await res.formData(); t.is(resFormData.get("file"), "test"); const compat = new Compatibility(undefined, [ "formdata_parser_supports_files", ]); plugin = new CorePlugin({ log, compat, rootPath }); CompatResponse = (await plugin.setup()).globals?.Response; res = new CompatResponse(formData); resFormData = await res.formData(); t.true(resFormData.get("file") instanceof File); }); test("CorePlugin: setup: structuredClone: creates deep-copy of value", async (t) => { const plugin = new CorePlugin(ctx); const { globals } = await plugin.setup(); assert(globals); const thing = { a: 1, b: new Date(), c: new Set([1, 2, 3]), }; const copy = globals.structuredClone(thing); t.not(thing, copy); t.deepEqual(thing, copy); }); test("CorePlugin: processedModuleRules: processes rules includes default module rules", (t) => { const plugin = new CorePlugin(ctx, { modules: true, modulesRules: [ { type: "Text", include: ["**/*.txt"], fallthrough: true }, { type: "Text", include: ["**/*.text"], fallthrough: true }, ], }); const rules = plugin.processedModuleRules; t.is(rules.length, 4); t.is(rules[0].type, "Text"); t.true(rules[0].include.test("test.txt")); t.is(rules[1].type, "Text"); t.true(rules[1].include.test("test.text")); t.is(rules[2].type, "ESModule"); t.true(rules[2].include.test("test.mjs")); t.is(rules[3].type, "CommonJS"); t.true(rules[3].include.test("test.js")); t.true(rules[3].include.test("test.cjs")); }); test("CorePlugin: processedModuleRules: ignores rules with same type if no fallthrough", (t) => { const plugin = new CorePlugin(ctx, { modules: true, modulesRules: [{ type: "CommonJS", include: ["**/*.js"] }], }); const rules = plugin.processedModuleRules; t.is(rules.length, 2); t.is(rules[0].type, "CommonJS"); t.true(rules[0].include.test("test.js")); t.is(rules[1].type, "ESModule"); t.true(rules[1].include.test("test.mjs")); }); test("CorePlugin: processedModuleRules: defaults to default module rules", (t) => { const plugin = new CorePlugin(ctx, { modules: true }); const rules = plugin.processedModuleRules; t.is(rules.length, 2); t.is(rules[0].type, "ESModule"); t.true(rules[0].include.test("test.mjs")); t.is(rules[1].type, "CommonJS"); t.true(rules[1].include.test("test.js")); t.true(rules[1].include.test("test.cjs")); }); test("CorePlugin: processedModuleRules: empty if modules disabled", (t) => { const plugin = new CorePlugin(ctx); const rules = plugin.processedModuleRules; t.is(rules.length, 0); }); test("CorePlugin: setup: loads no script if none defined", async (t) => { const plugin = new CorePlugin(ctx); const result = await plugin.setup(); t.deepEqual(result.watch, []); t.is(result.script, undefined); }); test("CorePlugin: setup: loads script from string", async (t) => { const plugin = new CorePlugin(ctx, { script: "console.log('Hello!')", }); const result = await plugin.setup(); t.deepEqual(result.watch, undefined); t.deepEqual(result.script, { filePath: STRING_SCRIPT_PATH, code: "console.log('Hello!')", }); }); test("CorePlugin: setup: loads script from package.json in default location", async (t) => { const tmp = await useTmp(t); const defaultPackagePath = path.join(tmp, "package.json"); const scriptPath = path.join(tmp, "script.js"); await fs.writeFile(scriptPath, "console.log(42)"); const plugin = new CorePlugin( { log, compat, rootPath: tmp }, { packagePath: true } ); // Shouldn't throw if package.json doesn't exist... let result = await plugin.setup(); // ...but should still watch package.json t.deepEqual(result.watch, [defaultPackagePath]); t.is(result.script, undefined); // Should still watch package.json if missing main field await fs.writeFile(defaultPackagePath, "{}"); result = await plugin.setup(); t.deepEqual(result.watch, [defaultPackagePath]); t.is(result.script, undefined); // Add main field and try setup again await fs.writeFile(defaultPackagePath, `{"main": "script.js"}`); result = await plugin.setup(); t.deepEqual(result.watch, [defaultPackagePath, scriptPath]); t.deepEqual(result.script, { filePath: scriptPath, code: "console.log(42)" }); }); test("CorePlugin: setup: loads script from package.json in custom location", async (t) => { const tmp = await useTmp(t); const customPackagePath = path.join(tmp, "package.custom.json"); const scriptPath = path.join(tmp, "script.js"); await fs.writeFile(scriptPath, "console.log('custom')"); const plugin = new CorePlugin( { log, compat, rootPath: tmp }, // Should resolve packagePath relative to rootPath { packagePath: "package.custom.json" } ); // Should throw if package.json doesn't exist await t.throwsAsync(plugin.setup(), { code: "ENOENT", message: /package\.custom\.json/, }); // Create file and try again await fs.writeFile(customPackagePath, `{"main": "script.js"}`); const result = await plugin.setup(); t.deepEqual(result.watch, [customPackagePath, scriptPath]); t.deepEqual(result.script, { filePath: scriptPath, code: "console.log('custom')", }); }); test("CorePlugin: setup: loads module from package.json", async (t) => { const tmp = await useTmp(t); const packagePath = path.join(tmp, "package.json"); await fs.writeFile(packagePath, `{"module": "script.mjs"}`); const scriptPath = path.join(tmp, "script.mjs"); await fs.writeFile(scriptPath, "export default 42"); const plugin = new CorePlugin(ctx, { modules: true, packagePath, }); const result = await plugin.setup(); t.deepEqual(result.watch, [packagePath, scriptPath]); t.deepEqual(result.script, { filePath: scriptPath, code: "export default 42", }); }); test("CorePlugin: setup: loads script from explicit path", async (t) => { const tmp = await useTmp(t); const packagePath = path.join(tmp, "package.json"); await fs.writeFile(packagePath, `{"main": "bad.js"}`); const scriptPath = path.join(tmp, "script.js"); await fs.writeFile(scriptPath, "console.log(42)"); const plugin = new CorePlugin( { log, compat, rootPath: tmp }, { // Should resolve scriptPath relative to rootPath scriptPath: "script.js", packagePath, } ); // packagePath should be ignored if an explicit scriptPath is set const result = await plugin.setup(); t.deepEqual(result.watch, [scriptPath]); // No packagePath t.deepEqual(result.script, { filePath: scriptPath, code: "console.log(42)" }); });
the_stack
import * as sdk from "../microsoft.cognitiveservices.speech.sdk"; import { ConsoleLoggingListener } from "../src/common.browser/Exports"; import { ConnectionErrorEvent, Events, EventType, IDetachable, PlatformEvent } from "../src/common/Exports"; import { Settings } from "./Settings"; import { closeAsyncObjects, WaitForCondition } from "./Utilities"; import { WaveFileAudioInput } from "./WaveFileAudioInputStream"; import * as fs from "fs"; let objsToClose: any[]; beforeAll(() => { // override inputs, if necessary Settings.LoadSettings(); Events.instance.attachListener(new ConsoleLoggingListener(EventType.Debug)); }); beforeEach(() => { objsToClose = []; // tslint:disable-next-line:no-console console.info("------------------Starting test case: " + expect.getState().currentTestName + "-------------------------"); // tslint:disable-next-line:no-console console.info("Start Time: " + new Date(Date.now()).toLocaleString()); }); afterEach(async (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("End Time: " + new Date(Date.now()).toLocaleString()); await closeAsyncObjects(objsToClose); done(); }); export const BuildRecognizerFromWaveFile: (speechConfig?: sdk.SpeechConfig, fileName?: string) => sdk.SpeechRecognizer = (speechConfig?: sdk.SpeechConfig, fileName?: string): sdk.SpeechRecognizer => { let s: sdk.SpeechConfig = speechConfig; if (s === undefined) { s = BuildSpeechConfig(); // Since we're not going to return it, mark it for closure. objsToClose.push(s); } const config: sdk.AudioConfig = WaveFileAudioInput.getAudioConfigFromFile(fileName === undefined ? Settings.WaveFile : fileName); const language: string = Settings.WaveFileLanguage; if (s.speechRecognitionLanguage === undefined) { s.speechRecognitionLanguage = language; } const r: sdk.SpeechRecognizer = new sdk.SpeechRecognizer(s, config); expect(r).not.toBeUndefined(); return r; }; const BuildSpeechConfig: () => sdk.SpeechConfig = (): sdk.SpeechConfig => { let s: sdk.SpeechConfig; if (undefined === Settings.SpeechEndpoint) { s = sdk.SpeechConfig.fromSubscription(Settings.SpeechSubscriptionKey, Settings.SpeechRegion); } else { s = sdk.SpeechConfig.fromEndpoint(new URL(Settings.SpeechEndpoint), Settings.SpeechSubscriptionKey); } if (undefined !== Settings.proxyServer) { s.setProxy(Settings.proxyServer, Settings.proxyPort); } expect(s).not.toBeUndefined(); return s; }; test("Connect / Disconnect", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Connect / Disconnect"); const s: sdk.SpeechConfig = BuildSpeechConfig(); objsToClose.push(s); const r: sdk.SpeechRecognizer = new sdk.SpeechRecognizer(s); objsToClose.push(r); let connected: boolean = false; const connection: sdk.Connection = sdk.Connection.fromRecognizer(r); connection.connected = (args: sdk.ConnectionEventArgs) => { connected = true; }; connection.disconnected = (args: sdk.ConnectionEventArgs) => { done(); }; connection.openConnection(); WaitForCondition(() => { return connected; }, () => { connection.closeConnection(); }); }); test("Disconnect during reco cancels.", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Disconnect during reco cancels."); const s: sdk.SpeechConfig = BuildSpeechConfig(); objsToClose.push(s); const fileBuffer: ArrayBuffer = WaveFileAudioInput.LoadArrayFromFile(Settings.WaveFile); let bytesSent: number = 0x0; let sendSilence: boolean = false; let p: sdk.PullAudioInputStream; p = sdk.AudioInputStream.createPullStream( { close: () => { return; }, read: (buffer: ArrayBuffer): number => { if (!!sendSilence) { return buffer.byteLength; } const copyArray: Uint8Array = new Uint8Array(buffer); const start: number = bytesSent; const end: number = buffer.byteLength > (fileBuffer.byteLength - bytesSent) ? (fileBuffer.byteLength - 1) : (bytesSent + buffer.byteLength - 1); copyArray.set(new Uint8Array(fileBuffer.slice(start, end))); bytesSent += (end - start) + 1; if (((end - start) + 1) < buffer.byteLength) { // Start sending silence, and setup to re-transmit the file when the boolean flips next. bytesSent = 0; sendSilence = true; } return (end - start) + 1; }, }); const config: sdk.AudioConfig = sdk.AudioConfig.fromStreamInput(p); const r: sdk.SpeechRecognizer = new sdk.SpeechRecognizer(s, config); objsToClose.push(r); expect(r).not.toBeUndefined(); expect(r instanceof sdk.Recognizer); let disconnected: boolean = false; let recoCount: number = 0; const connection: sdk.Connection = sdk.Connection.fromRecognizer(r); connection.disconnected = (e: sdk.ConnectionEventArgs): void => { disconnected = true; }; r.recognized = (r: sdk.Recognizer, e: sdk.SpeechRecognitionEventArgs): void => { try { const res: sdk.SpeechRecognitionResult = e.result; expect(res).not.toBeUndefined(); expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.RecognizedSpeech]); expect(res.text).toEqual("What's the weather like?"); expect(disconnected).toEqual(false); recoCount++; } catch (error) { done.fail(error); } }; r.canceled = (r: sdk.Recognizer, e: sdk.SpeechRecognitionCanceledEventArgs) => { try { expect(sdk.CancellationReason[e.reason]).toEqual(sdk.CancellationReason[sdk.CancellationReason.Error]); expect(e.errorDetails).toContain("Disconnect"); done(); } catch (error) { done.fail(error); } }; r.startContinuousRecognitionAsync( undefined, (error: string) => { done.fail(error); }); WaitForCondition(() => { return recoCount === 1; }, () => { connection.closeConnection(); }); }, 10000); test("Open during reco has no effect.", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Open during reco has no effect."); const s: sdk.SpeechConfig = BuildSpeechConfig(); objsToClose.push(s); const fileBuffer: ArrayBuffer = WaveFileAudioInput.LoadArrayFromFile(Settings.WaveFile); let bytesSent: number = 0; let sendSilence: boolean = false; let p: sdk.PullAudioInputStream; p = sdk.AudioInputStream.createPullStream( { close: () => { return; }, read: (buffer: ArrayBuffer): number => { if (!!sendSilence) { return buffer.byteLength; } const copyArray: Uint8Array = new Uint8Array(buffer); const start: number = bytesSent; const end: number = buffer.byteLength > (fileBuffer.byteLength - bytesSent) ? (fileBuffer.byteLength - 1) : (bytesSent + buffer.byteLength - 1); copyArray.set(new Uint8Array(fileBuffer.slice(start, end))); bytesSent += (end - start) + 1; if (((end - start) + 1) < buffer.byteLength) { // Start sending silence, and setup to re-transmit the file when the boolean flips next. bytesSent = 0; sendSilence = true; } return (end - start) + 1; }, }); const config: sdk.AudioConfig = sdk.AudioConfig.fromStreamInput(p); const r: sdk.SpeechRecognizer = new sdk.SpeechRecognizer(s, config); objsToClose.push(r); expect(r).not.toBeUndefined(); expect(r instanceof sdk.Recognizer); let connectionCount: number = 0; let recoCount: number = 0; const connection: sdk.Connection = sdk.Connection.fromRecognizer(r); connection.connected = (e: sdk.ConnectionEventArgs): void => { connectionCount++; }; r.recognized = (r: sdk.Recognizer, e: sdk.SpeechRecognitionEventArgs): void => { try { const res: sdk.SpeechRecognitionResult = e.result; expect(res).not.toBeUndefined(); expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.RecognizedSpeech]); expect(res.text).toEqual("What's the weather like?"); expect(connectionCount).toEqual(1); recoCount++; } catch (error) { done.fail(error); } }; r.canceled = (r: sdk.Recognizer, e: sdk.SpeechRecognitionCanceledEventArgs) => { try { expect(e.errorDetails).toBeUndefined(); expect(sdk.CancellationReason[e.reason]).toEqual(sdk.CancellationReason[sdk.CancellationReason.EndOfStream]); done(); } catch (error) { done.fail(error); } }; r.startContinuousRecognitionAsync( undefined, (error: string) => { done.fail(error); }); WaitForCondition(() => { return recoCount === 1; }, () => { connection.openConnection(); sendSilence = false; }); WaitForCondition(() => { return recoCount === 2; }, () => { p.close(); }); }, 10000); test("Connecting before reco works for cont", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Connecting before reco works for cont"); const s: sdk.SpeechConfig = BuildSpeechConfig(); objsToClose.push(s); const fileBuffer: ArrayBuffer = WaveFileAudioInput.LoadArrayFromFile(Settings.WaveFile); let bytesSent: number = 0; let sendSilence: boolean = false; let p: sdk.PullAudioInputStream; p = sdk.AudioInputStream.createPullStream( { close: () => { return; }, read: (buffer: ArrayBuffer): number => { if (!!sendSilence) { return buffer.byteLength; } const copyArray: Uint8Array = new Uint8Array(buffer); const start: number = bytesSent; const end: number = buffer.byteLength > (fileBuffer.byteLength - bytesSent) ? (fileBuffer.byteLength - 1) : (bytesSent + buffer.byteLength - 1); copyArray.set(new Uint8Array(fileBuffer.slice(start, end))); bytesSent += (end - start) + 1; if (((end - start) + 1) < buffer.byteLength) { // Start sending silence, and setup to re-transmit the file when the boolean flips next. bytesSent = 0; sendSilence = true; } return (end - start) + 1; }, }); const config: sdk.AudioConfig = sdk.AudioConfig.fromStreamInput(p); const r: sdk.SpeechRecognizer = new sdk.SpeechRecognizer(s, config); objsToClose.push(r); expect(r).not.toBeUndefined(); expect(r instanceof sdk.Recognizer); let disconnected: boolean = false; let connected: number = 0; let recoCount: number = 0; const connection: sdk.Connection = sdk.Connection.fromRecognizer(r); connection.connected = (e: sdk.ConnectionEventArgs): void => { connected++; }; connection.disconnected = (e: sdk.ConnectionEventArgs): void => { disconnected = true; }; r.recognized = (r: sdk.Recognizer, e: sdk.SpeechRecognitionEventArgs): void => { try { const res: sdk.SpeechRecognitionResult = e.result; expect(res).not.toBeUndefined(); if (0 === recoCount) { expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.RecognizedSpeech]); expect(res.text).toEqual("What's the weather like?"); } else { expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.NoMatch]); } expect(disconnected).toEqual(false); recoCount++; } catch (error) { done.fail(error); } }; r.canceled = (r: sdk.Recognizer, e: sdk.SpeechRecognitionCanceledEventArgs): void => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; connection.openConnection(); WaitForCondition(() => { return connected === 1; }, () => { r.startContinuousRecognitionAsync( undefined, (error: string) => { done.fail(error); }); }); WaitForCondition(() => { return recoCount === 1; }, () => { r.stopContinuousRecognitionAsync(() => { try { expect(connected).toEqual(1); done(); } catch (error) { done.fail(error); } }); }); }, 10000); test.skip("Switch RecoModes during a connection (cont->single)", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Switch RecoModes during a connection (cont->single)"); const s: sdk.SpeechConfig = BuildSpeechConfig(); objsToClose.push(s); const fileBuffer: ArrayBuffer = WaveFileAudioInput.LoadArrayFromFile(Settings.WaveFile); let bytesSent: number = 0; let sendSilence: boolean = false; let p: sdk.PullAudioInputStream; p = sdk.AudioInputStream.createPullStream( { close: () => { return; }, read: (buffer: ArrayBuffer): number => { if (!!sendSilence) { return buffer.byteLength; } const copyArray: Uint8Array = new Uint8Array(buffer); const start: number = bytesSent; const end: number = buffer.byteLength > (fileBuffer.byteLength - bytesSent) ? (fileBuffer.byteLength - 1) : (bytesSent + buffer.byteLength - 1); copyArray.set(new Uint8Array(fileBuffer.slice(start, end))); bytesSent += (end - start) + 1; if (((end - start) + 1) < buffer.byteLength) { // Start sending silence, and setup to re-transmit the file when the boolean flips next. bytesSent = 0; sendSilence = true; } return (end - start) + 1; }, }); const config: sdk.AudioConfig = sdk.AudioConfig.fromStreamInput(p); const r: sdk.SpeechRecognizer = new sdk.SpeechRecognizer(s, config); objsToClose.push(r); expect(r).not.toBeUndefined(); expect(r instanceof sdk.Recognizer); let disconnected: boolean = false; let recoCount: number = 0; const connection: sdk.Connection = sdk.Connection.fromRecognizer(r); connection.disconnected = (e: sdk.ConnectionEventArgs): void => { disconnected = true; }; r.recognized = (r: sdk.Recognizer, e: sdk.SpeechRecognitionEventArgs): void => { try { const res: sdk.SpeechRecognitionResult = e.result; expect(res).not.toBeUndefined(); if (0 === recoCount) { expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.RecognizedSpeech]); expect(res.text).toEqual("What's the weather like?"); } else { expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.NoMatch]); } expect(disconnected).toEqual(false); recoCount++; } catch (error) { done.fail(error); } }; r.canceled = (r: sdk.Recognizer, e: sdk.SpeechRecognitionCanceledEventArgs): void => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; r.startContinuousRecognitionAsync( undefined, (error: string) => { done.fail(error); }); WaitForCondition(() => { return recoCount === 1; }, () => { r.stopContinuousRecognitionAsync(() => { sendSilence = false; r.recognizeOnceAsync( undefined, (error: string) => { done.fail(error); }); }); }); WaitForCondition(() => { return recoCount === 2; }, () => { done(); }); }, 20000); test.skip("Switch RecoModes during a connection (single->cont)", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Switch RecoModes during a connection (single->cont)"); const s: sdk.SpeechConfig = BuildSpeechConfig(); objsToClose.push(s); const fileBuffer: ArrayBuffer = WaveFileAudioInput.LoadArrayFromFile(Settings.WaveFile); let bytesSent: number = 0; let sendSilence: boolean = false; let p: sdk.PullAudioInputStream; p = sdk.AudioInputStream.createPullStream( { close: () => { return; }, read: (buffer: ArrayBuffer): number => { if (!!sendSilence) { return buffer.byteLength; } const copyArray: Uint8Array = new Uint8Array(buffer); const start: number = bytesSent; const end: number = buffer.byteLength > (fileBuffer.byteLength - bytesSent) ? (fileBuffer.byteLength - 1) : (bytesSent + buffer.byteLength - 1); copyArray.set(new Uint8Array(fileBuffer.slice(start, end))); bytesSent += (end - start) + 1; if (((end - start) + 1) < buffer.byteLength) { // Start sending silence, and setup to re-transmit the file when the boolean flips next. bytesSent = 0; sendSilence = true; } return (end - start) + 1; }, }); const config: sdk.AudioConfig = sdk.AudioConfig.fromStreamInput(p); const r: sdk.SpeechRecognizer = new sdk.SpeechRecognizer(s, config); objsToClose.push(r); expect(r).not.toBeUndefined(); expect(r instanceof sdk.Recognizer); r.canceled = (r: sdk.Recognizer, e: sdk.SpeechRecognitionCanceledEventArgs): void => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; let disconnected: boolean = false; let recoCount: number = 0; const connection: sdk.Connection = sdk.Connection.fromRecognizer(r); connection.disconnected = (e: sdk.ConnectionEventArgs): void => { disconnected = true; }; r.recognized = (r: sdk.Recognizer, e: sdk.SpeechRecognitionEventArgs): void => { try { const res: sdk.SpeechRecognitionResult = e.result; expect(res).not.toBeUndefined(); expect(sdk.ResultReason[res.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.RecognizedSpeech]); expect(res.text).toContain("the weather like?"); expect(disconnected).toEqual(false); recoCount++; } catch (error) { done.fail(error); } }; r.recognizeOnceAsync( undefined, (error: string) => { done.fail(error); }); WaitForCondition(() => { return recoCount === 1; }, () => { sendSilence = false; r.startContinuousRecognitionAsync( undefined, (error: string) => { done.fail(error); }); }); WaitForCondition(() => { return recoCount === 2; }, () => { sendSilence = false; }); WaitForCondition(() => { return recoCount === 3; }, () => { done(); }); }, 20000); test("testAudioMessagesSent", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: testAudioMessagesSent"); const s: sdk.SpeechConfig = BuildSpeechConfig(); objsToClose.push(s); s.outputFormat = sdk.OutputFormat.Detailed; const r: sdk.SpeechRecognizer = BuildRecognizerFromWaveFile(s); objsToClose.push(r); expect(r.outputFormat === sdk.OutputFormat.Detailed); const sourceAudio: ArrayBuffer = fs.readFileSync(Settings.WaveFile); const con: sdk.Connection = sdk.Connection.fromRecognizer(r); let wavFragmentCount: number = 0; const wavFragments: { [id: number]: ArrayBuffer; } = {}; con.messageSent = (args: sdk.ConnectionMessageEventArgs): void => { if (args.message.path === "audio" && args.message.isBinaryMessage && args.message.binaryMessage !== null) { wavFragments[wavFragmentCount++] = args.message.binaryMessage; } }; r.canceled = (o: sdk.Recognizer, e: sdk.SpeechRecognitionCanceledEventArgs): void => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; r.recognizeOnceAsync((result: sdk.SpeechRecognitionResult) => { try { expect(result).not.toBeUndefined(); expect(result.text).toEqual(Settings.WaveFileText); expect(result.properties).not.toBeUndefined(); expect(result.properties.getProperty(sdk.PropertyId.SpeechServiceResponse_JsonResult)).not.toBeUndefined(); // Validate the entire wave file was sent. let byteCount: number = 0; for (let i: number = 0; i < wavFragmentCount; i++) { byteCount += wavFragments[i].byteLength; } const sentAudio: Uint8Array = new Uint8Array(byteCount); byteCount = 0; for (let i: number = 0; i < wavFragmentCount; i++) { sentAudio.set(new Uint8Array(wavFragments[i]), byteCount); byteCount += wavFragments[i].byteLength; } const sourceArray: Uint8Array = new Uint8Array(sourceAudio); expect(sourceArray.length).toEqual(sentAudio.length); // Skip the wave header. for (let i: number = 44; i < sourceArray.length; i++) { expect(sourceArray[i]).toEqual(sentAudio[i]); } done(); } catch (error) { done.fail(error); } }, (error: string) => { done.fail(error); }); }, 10000); test("testModifySpeechContext", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: testModifySpeechContext"); const s: sdk.SpeechConfig = BuildSpeechConfig(); objsToClose.push(s); s.outputFormat = sdk.OutputFormat.Detailed; const r: sdk.SpeechRecognizer = BuildRecognizerFromWaveFile(s); objsToClose.push(r); const con: sdk.Connection = sdk.Connection.fromRecognizer(r); con.setMessageProperty("speech.context", "RandomName", "RandomValue"); con.messageSent = (args: sdk.ConnectionMessageEventArgs): void => { if (args.message.path === "speech.context" && args.message.isTextMessage) { const message = JSON.parse(args.message.TextMessage); try { expect(message.RandomName).toEqual("RandomValue"); expect(args.message.TextMessage).toContain("Some phrase"); // make sure it's not overwritten... done(); } catch (error) { done.fail(error); } } }; const pg = sdk.PhraseListGrammar.fromRecognizer(r); pg.addPhrase("Some phrase"); r.canceled = (o: sdk.Recognizer, e: sdk.SpeechRecognitionCanceledEventArgs): void => { try { expect(e.errorDetails).toBeUndefined(); } catch (error) { done.fail(error); } }; r.recognizeOnceAsync((result: sdk.SpeechRecognitionResult) => { try { expect(result).not.toBeUndefined(); expect(result.text).toEqual(Settings.WaveFileText); expect(result.properties).not.toBeUndefined(); expect(result.properties.getProperty(sdk.PropertyId.SpeechServiceResponse_JsonResult)).not.toBeUndefined(); } catch (error) { done.fail(error); } }, (error: string) => { done.fail(error); }); }, 10000); test("testModifySynthesisContext", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: testModifySynthesisContext"); const speechConfig: sdk.SpeechConfig = BuildSpeechConfig(); objsToClose.push(speechConfig); const s: sdk.SpeechSynthesizer = new sdk.SpeechSynthesizer(speechConfig, undefined); objsToClose.push(s); expect(s).not.toBeUndefined(); const con: sdk.Connection = sdk.Connection.fromSynthesizer(s); con.setMessageProperty("synthesis.context", "RandomName", "RandomValue"); let doneCount: number = 0; con.messageSent = (args: sdk.ConnectionMessageEventArgs): void => { if (args.message.path === "synthesis.context" && args.message.isTextMessage) { const message = JSON.parse(args.message.TextMessage); try { expect(message.RandomName).toEqual("RandomValue"); expect(args.message.TextMessage).toContain("wordBoundaryEnabled"); // make sure it's not overwritten... doneCount++; } catch (error) { done.fail(error); } } }; s.speakTextAsync("hello world.", (result: sdk.SpeechSynthesisResult): void => { try { expect(result).not.toBeUndefined(); expect(sdk.ResultReason[result.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.SynthesizingAudioCompleted]); expect(result.audioData).not.toBeUndefined(); expect(result.audioData.byteLength).toBeGreaterThan(0); doneCount++; } catch (error) { done.fail(error); } }, (e: string): void => { done.fail(e); }); WaitForCondition(() => doneCount === 2, done); }, 10000); test("Test SendMessage Basic", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Test SendMessage Basic"); const r = BuildRecognizerFromWaveFile(); objsToClose.push(r); const con: sdk.Connection = sdk.Connection.fromRecognizer(r); con.messageSent = (message: sdk.ConnectionMessageEventArgs): void => { if (message.message.path === "speech.testmessage") { try { expect(message.message.isTextMessage).toBeTruthy(); expect(message.message.isBinaryMessage).toBeFalsy(); expect(message.message.TextMessage).toEqual("{}"); done(); } catch (err) { done.fail(err); } } }; con.sendMessageAsync("speech.testmessage", "{}", undefined, done.fail); }); test("Test SendMessage Binary", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Test SendMessage Binary"); const r = BuildRecognizerFromWaveFile(); objsToClose.push(r); const con: sdk.Connection = sdk.Connection.fromRecognizer(r); con.messageSent = (message: sdk.ConnectionMessageEventArgs): void => { if (message.message.path === "speech.testmessage") { try { expect(message.message.isTextMessage).toBeFalsy(); expect(message.message.isBinaryMessage).toBeTruthy(); done(); } catch (err) { done.fail(err); } } }; con.sendMessageAsync("speech.testmessage", new ArrayBuffer(50), undefined, done.fail); }); test("Test InjectMessage", (done: jest.DoneCallback) => { // tslint:disable-next-line:no-console console.info("Name: Test InjectMessage"); const s: sdk.SpeechConfig = BuildSpeechConfig(); objsToClose.push(s); const ps: sdk.PushAudioInputStream = sdk.AudioInputStream.createPushStream(); const r: sdk.SpeechRecognizer = BuildRecognizerFromWaveFile(); objsToClose.push(r); const con: sdk.Connection = sdk.Connection.fromRecognizer(r); let audioSeen: number = 0; let messageSeen: boolean = false; let turnStarted: boolean = false; con.messageSent = (message: sdk.ConnectionMessageEventArgs): void => { if (message.message.path === "speech.testmessage") { try { expect(audioSeen).toEqual(1); expect(message.message.isTextMessage).toBeFalsy(); expect(message.message.isBinaryMessage).toBeTruthy(); messageSeen = true; } catch (err) { done.fail(err); } } else if (message.message.path === "audio") { try { expect(messageSeen || audioSeen === 0).toBeTruthy(); audioSeen++; } catch (err) { done.fail(err); } } }; con.messageReceived = (message: sdk.ConnectionMessageEventArgs): void => { if (message.message.path === "turn.start") { turnStarted = true; } }; r.canceled = (s: sdk.SpeechRecognizer, e: sdk.SpeechRecognitionCanceledEventArgs) => { done(); }; r.startContinuousRecognitionAsync(() => { con.sendMessageAsync("speech.testmessage", new ArrayBuffer(50), () => { WaitForCondition(() => turnStarted, () => { const data: ArrayBuffer = WaveFileAudioInput.LoadArrayFromFile(Settings.WaveFile); ps.write(data); ps.close(); }); }, done.fail); }, done.fail); }); describe("Connection errors are retried", () => { let errorCount: number; let detachObject: IDetachable; beforeEach(() => { errorCount = 0; detachObject = Events.instance.attachListener({ onEvent: (event: PlatformEvent) => { if (event instanceof ConnectionErrorEvent) { const connectionEvent: ConnectionErrorEvent = event as ConnectionErrorEvent; errorCount++; } }, }); }); afterEach(() => { if (undefined !== detachObject) { detachObject.detach().catch((error: string) => { throw new Error(error); }); detachObject = undefined; } }); test.only("Bad Auth", (done: jest.DoneCallback) => { const s: sdk.SpeechConfig = sdk.SpeechConfig.fromSubscription("badKey", Settings.SpeechRegion); const ps: sdk.PushAudioInputStream = sdk.AudioInputStream.createPushStream(); const r: sdk.SpeechRecognizer = new sdk.SpeechRecognizer(s, sdk.AudioConfig.fromStreamInput(ps)); objsToClose.push(r); r.recognizeOnceAsync((result: sdk.SpeechRecognitionResult) => { try { expect(sdk.ResultReason[result.reason]).toEqual(sdk.ResultReason[sdk.ResultReason.Canceled]); const canceledDetails: sdk.CancellationDetails = sdk.CancellationDetails.fromResult(result); expect(sdk.CancellationReason[canceledDetails.reason]).toEqual(sdk.CancellationReason[sdk.CancellationReason.Error]); expect(sdk.CancellationErrorCode[sdk.CancellationErrorCode.ConnectionFailure]).toEqual(sdk.CancellationErrorCode[canceledDetails.ErrorCode]); expect(errorCount).toEqual(5); done(); } catch (e) { done.fail(e); } }, (e: string) => { done.fail(e); }); }, 15000); });
the_stack
import type { TextDocument } from 'vscode'; import { Event, BasicEvent, URI, IExtensionInfo } from '@opensumi/ide-core-common'; import type { CancellationToken } from '@opensumi/ide-core-common'; import { Uri, UriComponents } from './ext-types'; import type { WebviewPanel, IWebviewPanelOptions } from './webview'; /** * Provider for text based custom editors. * * Text based custom editors use a [`TextDocument`](#TextDocument) as their data model. This considerably simplifies * implementing a custom editor as it allows VS Code to handle many common operations such as * undo and backup. The provider is responsible for synchronizing text changes between the webview and the `TextDocument`. */ export interface CustomTextEditorProvider { /** * Resolve a custom editor for a given text resource. * * This is called when a user first opens a resource for a `CustomTextEditorProvider`, or if they reopen an * existing editor using this `CustomTextEditorProvider`. * * * @param document Document for the resource to resolve. * * @param webviewPanel The webview panel used to display the editor UI for this resource. * * During resolve, the provider must fill in the initial html for the content webview panel and hook up all * the event listeners on it that it is interested in. The provider can also hold onto the `WebviewPanel` to * use later for example in a command. See [`WebviewPanel`](#WebviewPanel) for additional details. * * @param token A cancellation token that indicates the result is no longer needed. * * @return Thenable indicating that the custom editor has been resolved. */ resolveCustomTextEditor( document: TextDocument, webviewPanel: WebviewPanel, token: CancellationToken, ): Thenable<void> | void; } /** * Represents a custom document used by a [`CustomEditorProvider`](#CustomEditorProvider). * * Custom documents are only used within a given `CustomEditorProvider`. The lifecycle of a `CustomDocument` is * managed by VS Code. When no more references remain to a `CustomDocument`, it is disposed of. */ export interface CustomDocument { /** * The associated uri for this document. */ readonly uri: Uri; /** * Dispose of the custom document. * * This is invoked by VS Code when there are no more references to a given `CustomDocument` (for example when * all editors associated with the document have been closed.) */ dispose(): void; } /** * Event triggered by extensions to signal to VS Code that an edit has occurred on an [`CustomDocument`](#CustomDocument). * * @see [`CustomDocumentProvider.onDidChangeCustomDocument`](#CustomDocumentProvider.onDidChangeCustomDocument). */ export interface CustomDocumentEditEvent<T extends CustomDocument = CustomDocument> { /** * The document that the edit is for. */ readonly document: T; /** * Undo the edit operation. * * This is invoked by VS Code when the user undoes this edit. To implement `undo`, your * extension should restore the document and editor to the state they were in just before this * edit was added to VS Code's internal edit stack by `onDidChangeCustomDocument`. */ undo(): Thenable<void> | void; /** * Redo the edit operation. * * This is invoked by VS Code when the user redoes this edit. To implement `redo`, your * extension should restore the document and editor to the state they were in just after this * edit was added to VS Code's internal edit stack by `onDidChangeCustomDocument`. */ redo(): Thenable<void> | void; /** * Display name describing the edit. * * This will be shown to users in the UI for undo/redo operations. */ readonly label?: string; } /** * Event triggered by extensions to signal to VS Code that the content of a [`CustomDocument`](#CustomDocument) * has changed. * * @see [`CustomDocumentProvider.onDidChangeCustomDocument`](#CustomDocumentProvider.onDidChangeCustomDocument). */ export interface CustomDocumentContentChangeEvent<T extends CustomDocument = CustomDocument> { /** * The document that the change is for. */ readonly document: T; } /** * A backup for an [`CustomDocument`](#CustomDocument). */ export interface CustomDocumentBackup { /** * Unique identifier for the backup. * * This id is passed back to your extension in `openCustomDocument` when opening a custom editor from a backup. */ readonly id: string; /** * Delete the current backup. * * This is called by VS Code when it is clear the current backup is no longer needed, such as when a new backup * is made or when the file is saved. */ delete(): void; } /** * Additional information used to implement [`CustomEditableDocument.backup`](#CustomEditableDocument.backup). */ export interface CustomDocumentBackupContext { /** * Suggested file location to write the new backup. * * Note that your extension is free to ignore this and use its own strategy for backup. * * If the editor is for a resource from the current workspace, `destination` will point to a file inside * `ExtensionContext.storagePath`. The parent folder of `destination` may not exist, so make sure to created it * before writing the backup to this location. */ readonly destination: Uri; } /** * Additional information about the opening custom document. */ export interface CustomDocumentOpenContext { /** * The id of the backup to restore the document from or `undefined` if there is no backup. * * If this is provided, your extension should restore the editor from the backup instead of reading the file * from the user's workspace. */ readonly backupId?: string; } /** * Provider for readonly custom editors that use a custom document model. * * Custom editors use [`CustomDocument`](#CustomDocument) as their document model instead of a [`TextDocument`](#TextDocument). * * You should use this type of custom editor when dealing with binary files or more complex scenarios. For simple * text based documents, use [`CustomTextEditorProvider`](#CustomTextEditorProvider) instead. * * @param T Type of the custom document returned by this provider. */ export interface CustomReadonlyEditorProvider<T extends CustomDocument = CustomDocument> { /** * Create a new document for a given resource. * * `openCustomDocument` is called when the first time an editor for a given resource is opened. The opened * document is then passed to `resolveCustomEditor` so that the editor can be shown to the user. * * Already opened `CustomDocument` are re-used if the user opened additional editors. When all editors for a * given resource are closed, the `CustomDocument` is disposed of. Opening an editor at this point will * trigger another call to `openCustomDocument`. * * @param uri Uri of the document to open. * @param openContext Additional information about the opening custom document. * @param token A cancellation token that indicates the result is no longer needed. * * @return The custom document. */ openCustomDocument(uri: Uri, openContext: CustomDocumentOpenContext, token: CancellationToken): Thenable<T> | T; /** * Resolve a custom editor for a given resource. * * This is called whenever the user opens a new editor for this `CustomEditorProvider`. * * @param document Document for the resource being resolved. * * @param webviewPanel The webview panel used to display the editor UI for this resource. * * During resolve, the provider must fill in the initial html for the content webview panel and hook up all * the event listeners on it that it is interested in. The provider can also hold onto the `WebviewPanel` to * use later for example in a command. See [`WebviewPanel`](#WebviewPanel) for additional details. * * @param token A cancellation token that indicates the result is no longer needed. * * @return Optional thenable indicating that the custom editor has been resolved. */ resolveCustomEditor(document: T, webviewPanel: WebviewPanel, token: CancellationToken): Thenable<void> | void; } /** * Provider for editable custom editors that use a custom document model. * * Custom editors use [`CustomDocument`](#CustomDocument) as their document model instead of a [`TextDocument`](#TextDocument). * This gives extensions full control over actions such as edit, save, and backup. * * You should use this type of custom editor when dealing with binary files or more complex scenarios. For simple * text based documents, use [`CustomTextEditorProvider`](#CustomTextEditorProvider) instead. * * @param T Type of the custom document returned by this provider. */ export interface CustomEditorProvider<T extends CustomDocument = CustomDocument> extends CustomReadonlyEditorProvider<T> { /** * Signal that an edit has occurred inside a custom editor. * * This event must be fired by your extension whenever an edit happens in a custom editor. An edit can be * anything from changing some text, to cropping an image, to reordering a list. Your extension is free to * define what an edit is and what data is stored on each edit. * * Firing `onDidChange` causes VS Code to mark the editors as being dirty. This is cleared when the user either * saves or reverts the file. * * Editors that support undo/redo must fire a `CustomDocumentEditEvent` whenever an edit happens. This allows * users to undo and redo the edit using VS Code's standard VS Code keyboard shortcuts. VS Code will also mark * the editor as no longer being dirty if the user undoes all edits to the last saved state. * * Editors that support editing but cannot use VS Code's standard undo/redo mechanism must fire a `CustomDocumentContentChangeEvent`. * The only way for a user to clear the dirty state of an editor that does not support undo/redo is to either * `save` or `revert` the file. * * An editor should only ever fire `CustomDocumentEditEvent` events, or only ever fire `CustomDocumentContentChangeEvent` events. */ readonly onDidChangeCustomDocument: Event<CustomDocumentEditEvent<T> | CustomDocumentContentChangeEvent<T>>; /** * Save a custom document. * * This method is invoked by VS Code when the user saves a custom editor. This can happen when the user * triggers save while the custom editor is active, by commands such as `save all`, or by auto save if enabled. * * To implement `save`, the implementer must persist the custom editor. This usually means writing the * file data for the custom document to disk. After `save` completes, any associated editor instances will * no longer be marked as dirty. * * @param document Document to save. * @param cancellation Token that signals the save is no longer required (for example, if another save was triggered). * * @return Thenable signaling that saving has completed. */ saveCustomDocument(document: T, cancellation: CancellationToken): Thenable<void>; /** * Revert a custom document to its last saved state. * * This method is invoked by VS Code when the user triggers `File: Revert File` in a custom editor. (Note that * this is only used using VS Code's `File: Revert File` command and not on a `git revert` of the file). * * To implement `revert`, the implementer must make sure all editor instances (webviews) for `document` * are displaying the document in the same state is saved in. This usually means reloading the file from the * workspace. * * @param document Document to revert. * @param cancellation Token that signals the revert is no longer required. * * @return Thenable signaling that the change has completed. */ revertCustomDocument(document: T, cancellation: CancellationToken): Thenable<void>; /** * Back up a dirty custom document. * * Backups are used for hot exit and to prevent data loss. Your `backup` method should persist the resource in * its current state, i.e. with the edits applied. Most commonly this means saving the resource to disk in * the `ExtensionContext.storagePath`. When VS Code reloads and your custom editor is opened for a resource, * your extension should first check to see if any backups exist for the resource. If there is a backup, your * extension should load the file contents from there instead of from the resource in the workspace. * * `backup` is triggered approximately one second after the the user stops editing the document. If the user * rapidly edits the document, `backup` will not be invoked until the editing stops. * * `backup` is not invoked when `auto save` is enabled (since auto save already persists the resource). * * @param document Document to backup. * @param context Information that can be used to backup the document. * @param cancellation Token that signals the current backup since a new backup is coming in. It is up to your * extension to decided how to respond to cancellation. If for example your extension is backing up a large file * in an operation that takes time to complete, your extension may decide to finish the ongoing backup rather * than cancelling it to ensure that VS Code has some valid backup. */ } export interface ICustomEditorSelector { filenamePattern: string; } export interface CustomEditorScheme { viewType: string; displayName: string; selector: ICustomEditorSelector[]; priority?: 'default' | 'option'; } export class CustomEditorShouldDisplayEvent extends BasicEvent<{ uri: URI; viewType: string; openTypeId: string; webviewPanelId: string; cancellationToken: CancellationToken; }> {} export class CustomEditorShouldHideEvent extends BasicEvent<{ uri: URI; viewType: string; }> {} export class CustomEditorShouldSaveEvent extends BasicEvent<{ uri: URI; viewType: string; cancellationToken: CancellationToken; }> {} export class CustomEditorShouldRevertEvent extends BasicEvent<{ uri: URI; viewType: string; cancellationToken: CancellationToken; }> {} export class CustomEditorShouldEditEvent extends BasicEvent<{ type: 'redo' | 'undo'; uri: URI; viewType: string; }> {} export class CustomEditorOptionChangeEvent extends BasicEvent<{ viewType: string; options: ICustomEditorOptions; }> {} export interface IExtHostCustomEditor { $resolveCustomTextEditor(viewType: string, uri: UriComponents, webviewPanelId: string, token: CancellationToken); $saveCustomDocument(viewType: string, uri: UriComponents, token: CancellationToken); $revertCustomDocument(viewType: string, uri: UriComponents, token: CancellationToken); $undo(viewType: string, uri: UriComponents); $redo(viewType: string, uri: UriComponents); } export enum CustomEditorType { TextEditor = 1, ReadonlyEditor = 2, FullEditor = 3, } export interface ICustomEditorOptions { supportsMultipleEditorsPerDocument?: boolean; webviewOptions?: IWebviewPanelOptions; } export interface IMainThreadCustomEditor { $registerCustomEditor( viewType: string, editorType: CustomEditorType, options: ICustomEditorOptions, extensionInfo: IExtensionInfo, ); $acceptCustomDocumentDirty(uri: UriComponents, dirty: boolean); // $unregisterCustomEditor(viewType: string); } export type TCustomEditorProvider = | { type: CustomEditorType.FullEditor; provider: CustomEditorProvider; } | { type: CustomEditorType.ReadonlyEditor; provider: CustomReadonlyEditorProvider; } | { type: CustomEditorType.TextEditor; provider: CustomTextEditorProvider; };
the_stack
import { ChangeDetectorRef, Component, ElementRef, Inject, OnInit, QueryList, ViewChildren, } from '@angular/core'; import { FormControl } from '@angular/forms'; import { EventManager } from '@angular/platform-browser'; import { SandboxMenuItem, SelectedSandboxAndScenarioKeys } from '../lib/app-state'; import { StateService } from './shared/state.service'; import { UrlService } from './shared/url.service'; import { fuzzySearch } from './shared/fuzzy-search.function'; import { LevenshteinDistance } from './shared/levenshtein-distance'; import { Middleware, MIDDLEWARE } from '../lib/middlewares'; import { Observable } from 'rxjs'; import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { Sandboxes } from "./shared/sandboxes"; @Component({ selector: 'playground-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { @ViewChildren('scenarioElement') scenarioLinkElements: QueryList<ElementRef>; commandBarActive = false; commandBarPreview = false; totalSandboxes: number; filteredSandboxMenuItems: SandboxMenuItem[]; selectedSandboxAndScenarioKeys: SelectedSandboxAndScenarioKeys = {sandboxKey: null, scenarioKey: null}; filter = new FormControl(); shortcuts = this.getShortcuts(); activeMiddleware: Middleware; embed = false; constructor( private stateService: StateService, private urlService: UrlService, private eventManager: EventManager, private levenshteinDistance: LevenshteinDistance, private changeDetectorRef: ChangeDetectorRef, @Inject(MIDDLEWARE) private middleware: Observable<Middleware>, private sandboxes: Sandboxes ) { } ngOnInit() { const sandboxMenuItems = this.sandboxes.getSandboxMenuItems(); this.middleware .subscribe(middleware => this.activeMiddleware = middleware); this.embed = this.urlService.embed; if (this.embed) { this.selectedSandboxAndScenarioKeys = { sandboxKey: this.urlService.select.sandboxKey, scenarioKey: this.urlService.select.scenarioKey, }; } else { if (this.urlService.select) { this.selectedSandboxAndScenarioKeys = { sandboxKey: this.urlService.select.sandboxKey, scenarioKey: this.urlService.select.scenarioKey, }; } this.eventManager.addGlobalEventListener('window', 'keydown.control.p', this.blockEvent); this.eventManager.addGlobalEventListener('window', 'keydown.F2', this.blockEvent); this.eventManager.addGlobalEventListener('window', 'keyup.control.p', (event: KeyboardEvent) => { this.blockEvent(event); this.toggleCommandBar(); }); this.eventManager.addGlobalEventListener('window', 'keyup.F2', (event: KeyboardEvent) => { this.blockEvent(event); this.toggleCommandBar(); }); let filterValue = this.stateService.getFilter(); this.totalSandboxes = sandboxMenuItems.length; this.filteredSandboxMenuItems = this.filterSandboxes(sandboxMenuItems, filterValue); this.filter.setValue(filterValue); this.filter.valueChanges.pipe ( debounceTime(300), distinctUntilChanged(), ) .subscribe(value => { this.stateService.setFilter(value); this.filteredSandboxMenuItems = this.filterSandboxes(sandboxMenuItems, value); if (!value) { this.selectScenario(null, null); } }); } // expose select scenario functionality for visual regression test (window as any).loadScenario = (sandboxKey: string, scenarioKey: number) => { this.selectScenario(sandboxKey, scenarioKey); this.changeDetectorRef.detectChanges(); }; // set flag to check when component is loaded (window as any).isPlaygroundComponentLoaded = () => false; (window as any).isPlaygroundComponentLoadedWithErrors = () => false; } onFilterBoxArrowDown(event: any, switchToScenario = false) { event.preventDefault(); let elementRef; const currentIndex = this.findCurrentScenarioIndex(); if (currentIndex) { elementRef = this.focusScenarioLinkElement(currentIndex + 1); } else { elementRef = this.focusScenarioLinkElement(0); } if (switchToScenario) { this.showScenario(elementRef); } } onFilterBoxArrowUp(event: any, switchToScenario = false) { event.preventDefault(); let elementRef; const currentIndex = this.findCurrentScenarioIndex(); if (currentIndex) { elementRef = this.focusScenarioLinkElement(currentIndex - 1); } else if (this.scenarioLinkElements.length > 0) { elementRef = this.focusScenarioLinkElement(this.scenarioLinkElements.length - 1); } if (switchToScenario) { this.showScenario(elementRef); } } onScenarioLinkKeyDown(scenarioElement: any, filterElement: any, event: any) { event.preventDefault(); switch (event.key) { case 'Up': case 'ArrowUp': this.goUp(scenarioElement); break; case 'Down': case 'ArrowDown': this.goDown(scenarioElement); break; default: if (event.key !== 'Escape' && event.key !== 'Enter') { if (event.key.length === 1) { this.filter.setValue(`${this.filter.value}${event.key}`); } filterElement.focus(); } break; } } onScenarioLinkKeyUp(scenarioElement: any, event: any) { event.preventDefault(); switch (event.key) { case 'Escape': this.commandBarActive = false; break; case 'Enter': scenarioElement.click(); break; } } onScenarioLinkControlDown(scenarioElement: any, event: any) { if (!this.commandBarActive) return; event.preventDefault(); let elementRef = this.goDown(scenarioElement); this.showScenario(elementRef); } onScenarioLinkControlUp(scenarioElement: any, event: any) { if (!this.commandBarActive) return; event.preventDefault(); let elementRef = this.goUp(scenarioElement); this.showScenario(elementRef); } onCommandBarStartPreview(event: any) { event.preventDefault(); this.commandBarPreview = true; } onCommandBarStopPreview() { this.commandBarPreview = false; } onScenarioClick(sandboxKey: string, scenarioKey: number, event: any) { event.preventDefault(); this.selectScenario(sandboxKey, scenarioKey); } isSelected(sandbox: any, scenario: any) { return this.selectedSandboxAndScenarioKeys.scenarioKey === scenario.key && this.selectedSandboxAndScenarioKeys.sandboxKey.toLowerCase() === sandbox.key.toLowerCase(); } toggleCommandBar() { this.commandBarActive = !this.commandBarActive; } private blockEvent(e: KeyboardEvent) { e.preventDefault(); e.stopPropagation(); } private showScenario(selectedScenarioElementRef: ElementRef) { if (selectedScenarioElementRef) { this.selectScenario( selectedScenarioElementRef.nativeElement.getAttribute('sandboxMenuItemKey'), parseInt(selectedScenarioElementRef.nativeElement.getAttribute('scenarioMenuItemkey'), 10)); } } private findCurrentScenarioIndex(): number | undefined { let currentIndex; if (this.scenarioLinkElements.length > 0) { this.scenarioLinkElements.map((element: ElementRef, i: number) => { if (element.nativeElement.className.includes('selected')) { currentIndex = i; } }); } return currentIndex; } private goUp(scenarioElement: any) { let currentIndex = -1; this.scenarioLinkElements.forEach((scenarioElementRef: ElementRef, index: number) => { if (scenarioElementRef.nativeElement === scenarioElement) { currentIndex = index; } }); if (currentIndex === 0) { return this.focusScenarioLinkElement(this.scenarioLinkElements.length - 1); } else { return this.focusScenarioLinkElement(currentIndex - 1); } } private goDown(scenarioElement: any) { let currentIndex = -1; this.scenarioLinkElements.forEach((scenarioElementRef: ElementRef, index: number) => { if (scenarioElementRef.nativeElement === scenarioElement) { currentIndex = index; } }); if (currentIndex === this.scenarioLinkElements.length - 1) { return this.focusScenarioLinkElement(0); } else { return this.focusScenarioLinkElement(currentIndex + 1); } } private focusScenarioLinkElement(index: number) { if (this.scenarioLinkElements.toArray()[index]) { let elementRef = this.scenarioLinkElements.toArray()[index]; elementRef.nativeElement.focus(); return elementRef; } } private filterSandboxes(sandboxMenuItems: SandboxMenuItem[], filter: string) { if (!filter) { return sandboxMenuItems.map((item, i) => Object.assign({}, item, {tabIndex: i})); } let tabIndex = 0; let filterNormalized = filter.toLowerCase(); return sandboxMenuItems .reduce((accum, curr) => { let searchKeyNormalized = curr.searchKey.toLowerCase(); let indexMatches = fuzzySearch(filterNormalized, searchKeyNormalized); if (indexMatches) { let weight = this.levenshteinDistance.getDistance(filterNormalized, searchKeyNormalized); return [...accum, Object.assign({}, curr, {weight, indexMatches})]; } else { return accum; } }, []) .sort((a, b) => { return a.weight - b.weight; }) .map(sandboxMenuItem => Object.assign({}, sandboxMenuItem, {tabIndex: tabIndex++})); } private selectScenario(sandboxKey: string, scenarioKey: number) { // set flag to check when component is loaded (window as any).isPlaygroundComponentLoaded = () => false; (window as any).isPlaygroundComponentLoadedWithErrors = () => false; this.selectedSandboxAndScenarioKeys = {sandboxKey, scenarioKey}; this.urlService.setSelected(sandboxKey, scenarioKey); } private getShortcuts() { return [ { keys: ['ctrl + p', 'f2'], description: 'Toggle command bar open/closed', }, { keys: ['esc'], description: 'Close command bar', }, { keys: ['\u2191', '\u2193'], description: 'Navigate up or down in command bar list', }, { keys: ['ctrl + \u2191', 'ctrl + \u2193'], description: 'Switch scenarios while navigating up or down in command bar list', }, ]; } }
the_stack
import SDKDriver from '../../../lib/sdkdriver/src'; import LocalDataTrackDriver from './localdatatrack'; import LocalMediaTrackDriver from './localmediatrack'; import LocalTrackPublicationDriver from './localtrackpublication'; import ParticipantDriver from './participant'; import TrackDriver, { TrackSID } from './track'; const { difference } = require('../../../../lib/util'); type LocalTrackDriver = LocalDataTrackDriver | LocalMediaTrackDriver; /** * {@link LocalParticipant} driver. * @classdesc A {@link LocalParticipantDriver} manages the execution of * the corresponding {@link LocalParticipant}'s methods in the browser * and re-emits its events. * @extends ParticipantDriver * @property {Map<TrackSID, LocalTrackPublicationDriver>} audioTrackPublications * @property {Map<TrackSID, LocalTrackPublicationDriver>} dataTrackPublications * @property {Map<TrackSID, LocalTrackPublicationDriver>} trackPublications * @property {Map<TrackSID, LocalTrackPublicationDriver>} videoTrackPublications * @fires LocalParticipantDriver#trackPublicationFailed * @fires LocalParticipantDriver#trackPublished */ export default class LocalParticipantDriver extends ParticipantDriver { private _removedTrackPublications: Map<TrackSID, LocalTrackPublicationDriver>; audioTrackPublications: Map<TrackSID, LocalTrackPublicationDriver>; dataTrackPublications: Map<TrackSID, LocalTrackPublicationDriver>; trackPublications: Map<TrackSID, LocalTrackPublicationDriver>; videoTrackPublications: Map<TrackSID, LocalTrackPublicationDriver>; /** * Constructor. * @param {SDKDriver} sdkDriver * @param {object} serializedLocalParticipant */ constructor(sdkDriver: SDKDriver, serializedLocalParticipant: any) { super(sdkDriver, serializedLocalParticipant, LocalDataTrackDriver, LocalMediaTrackDriver); } /** * Get or create a {@link LocalTrackPublicationDriver}. * @private * @param {object} serializedLocalTrackPublication * @returns {LocalTrackPublicationDriver} */ private _getOrCreateLocalTrackPublication(serializedLocalTrackPublication: any): LocalTrackPublicationDriver { const { track, trackSid } = serializedLocalTrackPublication; const localTrack: LocalTrackDriver = this.tracks.get(track.id) as LocalTrackDriver; let localTrackPublication: LocalTrackPublicationDriver | undefined = this.trackPublications.get(trackSid); if (!localTrackPublication) { localTrackPublication = new LocalTrackPublicationDriver(this._sdkDriver, serializedLocalTrackPublication, localTrack); this.trackPublications.set(trackSid, localTrackPublication); this[`${track.kind}TrackPublications`].set(trackSid, localTrackPublication); } return localTrackPublication; } /** * Re-emit the "trackPublicationFailed" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitTrackPublicationFailed(source: any, args: any): void { this._update(source); const [ serializedError, serializedLocalTrack ] = args; const localTrack: TrackDriver = this._removeOrGetRemovedTrack(serializedLocalTrack.id); const error: any = new Error(serializedError.message); error.code = serializedError.code; this.emit('trackPublicationFailed', error, localTrack); } /** * Re-emit the "trackPublished" event from the browser. * @private * @param {object} source * @param {Array<*>} args * @returns {void} */ private _reemitTrackPublished(source: any, args: any): void { this._update(source); const serializedLocalTrackPublication: any = args[0]; this.emit('trackPublished', this._getOrCreateLocalTrackPublication(serializedLocalTrackPublication)); } /** * Re-emit {@link LocalParticipant}'s events from the browser. * @private * @param {object} data * @returns {void} */ protected _reemitEvents(data: any): void { const { type, source, args } = data; if (source._resourceId !== this._resourceId) { return; } super._reemitEvents(data); switch (type) { case 'trackPublicationFailed': this._reemitTrackPublicationFailed(source, args); break; case 'trackPublished': this._reemitTrackPublished(source, args); break; } } /** * Remove or get an already removed {@link LocalTrackPublicationDriver}. * @private * @param {TrackSID} trackSid * @returns {LocalTrackPublicationDriver} */ private _removeOrGetRemovedLocalTrackPublication(trackSid: TrackSID): LocalTrackPublicationDriver { let localTrackPublication: LocalTrackPublicationDriver | undefined = this._removedTrackPublications.get(trackSid); if (localTrackPublication) { return localTrackPublication; } localTrackPublication = this.trackPublications.get(trackSid); if (localTrackPublication) { this.trackPublications.delete(trackSid); this[`${localTrackPublication.track.kind}TrackPublications`].delete(trackSid); this._removedTrackPublications.set(trackSid, localTrackPublication); } return localTrackPublication as LocalTrackPublicationDriver; } /** * Update the {@link LocalParticipantDriver}'s properties. * @protected * @param {object} serializedLocalParticipant * @returns {void} */ protected _update(serializedLocalParticipant: any): void { super._update(serializedLocalParticipant); this.audioTrackPublications = this.audioTrackPublications || new Map(); this.dataTrackPublications = this.dataTrackPublications || new Map(); this.trackPublications = this.trackPublications || new Map(); this.videoTrackPublications = this.videoTrackPublications || new Map(); this._removedTrackPublications = this._removedTrackPublications || new Map(); const { trackPublications } = serializedLocalParticipant; const localTrackPublications: Map<TrackSID, any> = new Map(trackPublications.map((serializedLocalTrackPublication: any) => [ serializedLocalTrackPublication.trackSid, serializedLocalTrackPublication ])); const localTrackPublicationsToAdd: Set<TrackSID> = difference( Array.from(localTrackPublications.keys()), Array.from(this.trackPublications.keys())); const localTrackPublicationsToRemove: Set<TrackSID> = difference( Array.from(this.trackPublications.keys()), Array.from(localTrackPublications.keys())); localTrackPublicationsToAdd.forEach((trackSid: TrackSID) => { const serializedLocalTrackPublication: any = localTrackPublications.get(trackSid); this._getOrCreateLocalTrackPublication(serializedLocalTrackPublication); }); localTrackPublicationsToRemove.forEach((trackSid: TrackSID) => { this._removeOrGetRemovedLocalTrackPublication(trackSid); }); } /** * Publish a {@link LocalTrack} to the {@link Room} in the browser. * @param {LocalTrackDriver} localTrack * @returns {Promise<LocalTrackPublicationDriver>} */ async publishTrack(localTrack: LocalTrackDriver): Promise<LocalTrackPublicationDriver> { this._pendingTracks.set(localTrack.id, localTrack); const { error, result } = await this._sdkDriver.sendRequest({ api: 'publishTrack', args: [localTrack.resourceId], target: this._resourceId }); if (error) { this._pendingTracks.delete(localTrack.id); const err: any = new Error(error.message); err.code = error.code; throw err; } return this._getOrCreateLocalTrackPublication(result); } /** * Publish {@link LocalTrack}s to the {@link Room} in the browser. * @param {Array<LocalTrackDriver>} localTrack * @returns {Promise<Array<LocalTrackPublicationDriver>>} */ async publishTracks(localTracks: Array<LocalTrackDriver>): Promise<Array<LocalTrackPublicationDriver>> { localTracks.forEach((localTrack: LocalTrackDriver) => { this._pendingTracks.set(localTrack.id, localTrack); }); const { error, result } = await this._sdkDriver.sendRequest({ api: 'publishTracks', args: [localTracks.map((localTrack: LocalTrackDriver) => localTrack.resourceId)], target: this._resourceId }); if (error) { const err: any = new Error(error.message); err.code = error.code; throw err; } return result.map((serializedLocalTrackPublication: any) => { return this._getOrCreateLocalTrackPublication(serializedLocalTrackPublication); }); } /** * Set {@link EncodingParameters} to the {@link LocalParticipant} * in the browser. * @param {?EncodingParameters} encodingParameters * @returns {Promise<void>} */ async setParameters(encodingParameters: any): Promise<void> { const { error, result } = await this._sdkDriver.sendRequest({ api: 'setParameters', args: [encodingParameters], target: this._resourceId }); if (error) { throw new Error(error.message); } return result; } /** * Unpublish a {@link LocalTrack} from the {@link Room} in the browser. * @param {LocalTrackDriver} localTrack * @returns {Promise<LocalTrackPublicationDriver>} */ async unpublishTrack(localTrack: LocalTrackDriver): Promise<LocalTrackPublicationDriver> { const { error, result } = await this._sdkDriver.sendRequest({ api: 'unpublishTrack', args: [localTrack.resourceId], target: this._resourceId }); if (error) { throw new Error(error.message); } return this._removeOrGetRemovedLocalTrackPublication(result.trackSid); } /** * Unpublish {@link LocalTrack}s from the {@link Room} in the browser. * @param {Array<LocalTrackDriver>} localTracks * @returns {Promise<Array<LocalTrackPublicationDriver>>} */ async unpublishTracks(localTracks: Array<LocalTrackDriver>): Promise<Array<LocalTrackPublicationDriver>> { const { error, result } = await this._sdkDriver.sendRequest({ api: 'unpublishTracks', args: [localTracks.map((track: any) => track.resourceId)], target: this._resourceId }); if (error) { throw new Error(error.message); } return result.map((serializedLocalTrackPublication: any) => { return this._removeOrGetRemovedLocalTrackPublication(serializedLocalTrackPublication.trackSid); }); } } /** * @param {TwilioError} error * @param {LocalTrackDriver} localTrack * @event LocalParticipantDriver#trackPublicationFailed */ /** * @param {LocalTrackPublicationDriver} publication * @event LocalParticipantDriver#trackPublished */
the_stack
* For all Polymer component testing, be sure to call Polymer's flush() after * any code that will cause shadow dom redistribution, such as observed array * mutation, wich is used by the dom-repeater in this case. */ window.addEventListener('WebComponentsReady', () => { describe('<item-list>', () => { let testFixture: ItemListElement; /** * Returns true iff the item at the specified index is checked * @param i index of item to check */ function isSelected(i: number): boolean { const row = getRow(i); const box = getCheckbox(i); // Check three things: the index is in the selectedIndices array, the row // has the selected attribute, and its checkbox is checked. If any of these // is missing then all of them should be false, otherwise we're in an // inconsistent state. if (testFixture.selectedIndices.indexOf(i) > -1 && row.hasAttribute('selected') && box.checked) { return true; } else if (testFixture.selectedIndices.indexOf(i) === -1 && !row.hasAttribute('selected') && !box.checked) { return false; } else { throw new Error('inconsistent state for row ' + i); } } /** * Returns the row element at the specified index * @param i index of row whose element to return */ function getRow(i: number): HTMLElement { return testFixture.$.listContainer.querySelectorAll('paper-item')[i]; } /** * Returns the row element at the specified index * @param i index of row whose element to return */ function getRowDetailsContainer(i: number): HTMLElement { return testFixture.$.listContainer.querySelectorAll('div.row-details')[i]; } /** * Returns the checkbox element at the specified index * @param i index of row whose checkbox element to return */ function getCheckbox(i: number): any { const row = getRow(i); return row.querySelector('paper-checkbox'); } /** * Rows must be recreated on each test with the fixture, to avoid state leakage. */ beforeEach(() => { testFixture = fixture('item-list-fixture'); const createDetailsElement: () => HTMLElement = () => { const span = document.createElement('span'); span.innerHTML = 'Mock details'; return span; }; testFixture.columns = [{ name: 'col1', type: ColumnTypeName.STRING, }, { name: 'col2', type: ColumnTypeName.STRING, }]; const rows = [ new ItemListRow({ columns: ['first column 1', 'second column 1'], }), new ItemListRow({ columns: ['first column 2', 'second column 2'], }), new ItemListRow({ columns: ['first column 3', 'second column 3'], }), new ItemListRow({ columns: ['first column 4', 'second column 4'], createDetailsElement, }), new ItemListRow({ columns: ['first column 5', 'second column 5'], createDetailsElement, }), ]; testFixture.rows = rows; Polymer.dom.flush(); }); it('displays a row per item in list', () => { const children = testFixture.$.listContainer.querySelectorAll('paper-item'); assert(children.length === 5, 'five rows should appear'); }); it('starts out with all items unselected', () => { assert(JSON.stringify(testFixture.selectedIndices) === '[]', 'all items should be unselected'); }); it('displays column names in the header row', () => { // Column 0 is for the checkbox assert(testFixture.$.header.children[1].innerText.trim() === 'col1', 'header should have first column name'); assert(testFixture.$.header.children[2].innerText.trim() === 'col2', 'header should have second column name'); }); it('displays column names in the item rows', () => { for (let i = 0; i < 5; ++i) { const row = getRow(i); const firstCol = row.children[1] as HTMLElement; const secondCol = row.children[2] as HTMLElement; const firstColText = 'first column ' + (i + 1); const secondColText = 'second column ' + (i + 1); assert(firstCol.innerText.trim() === firstColText, 'first column should show on item'); assert(secondCol.innerText.trim() === secondColText, 'second column should show on item'); } }); it('displays icons correctly', () => { testFixture.rows = [ new ItemListRow({columns: [''], icon: 'folder'}), new ItemListRow({columns: [''], icon: 'search'}), ]; const row0 = getRow(0); const row1 = getRow(1); const icon0 = row0.children[0].children[1] as any; const icon1 = row1.children[0].children[1] as any; assert(icon0.icon === 'folder'); assert(icon1.icon === 'search'); }); it('selects items', () => { testFixture._selectItemByDisplayIndex(1); assert(!isSelected(0), 'first item should not be selected'); assert(isSelected(1), 'second item should be selected'); assert(!isSelected(2), 'third item should not be selected'); assert(!isSelected(3), 'fourth item should not be selected'); assert(!isSelected(4), 'fifth item should not be selected'); }); it('returns selected items', () => { testFixture._selectItemByDisplayIndex(0); testFixture._selectItemByDisplayIndex(2); assert(JSON.stringify(testFixture.selectedIndices) === '[0,2]', 'first and third items should be selected'); }); it('can select/unselect all', () => { const c = testFixture.$.header.querySelector('#selectAllCheckbox') as HTMLElement; c.click(); assert(JSON.stringify(testFixture.selectedIndices) === '[0,1,2,3,4]', 'all items should be in the selected indices array'); assert(isSelected(0) && isSelected(1) && isSelected(2) && isSelected(3) && isSelected(4), 'all items should be selected'); c.click(); assert(JSON.stringify(testFixture.selectedIndices) === '[]', 'no items should be in the selected indices array'); assert(!isSelected(0) && !isSelected(1) && !isSelected(2) && !isSelected(3) && !isSelected(4), 'all items should be unselected'); }); it('selects all items if the Select All checkbox is clicked with one item selected', () => { testFixture._selectItemByDisplayIndex(1); const c = testFixture.$.header.querySelector('#selectAllCheckbox') as HTMLElement; c.click(); assert(JSON.stringify(testFixture.selectedIndices) === '[0,1,2,3,4]', 'all items should be selected'); }); it('checks the Select All checkbox if all items are selected individually', () => { const c = testFixture.$.header.querySelector('#selectAllCheckbox') as any; assert(!c.checked, 'Select All checkbox should start out unchecked'); testFixture._selectItemByDisplayIndex(0); testFixture._selectItemByDisplayIndex(1); testFixture._selectItemByDisplayIndex(2); testFixture._selectItemByDisplayIndex(3); testFixture._selectItemByDisplayIndex(4); assert(c.checked, 'Select All checkbox should become checked'); }); it('unchecks the Select All checkbox if one item becomes unchecked', () => { const c = testFixture.$.header.querySelector('#selectAllCheckbox') as any; testFixture._selectAll(); assert(c.checked, 'Select All checkbox should be checked'); testFixture._unselectItemByDisplayIndex(1); assert(!c.checked, 'Select All checkbox should become unchecked after unselecting an item'); }); it('selects the clicked item', () => { const firstRow = getRow(0); firstRow.click(); assert(isSelected(0), 'first item should be selected'); firstRow.click(); assert(isSelected(0), 'first item should still be selected'); }); it('selects only the clicked item if the checkbox was not clicked', () => { const firstRow = getRow(0); const secondRow = getRow(1); firstRow.click(); secondRow.click(); assert(!isSelected(0) && isSelected(1), 'only the second item should still be selected'); }); it('can do multi-selection using the checkboxes', () => { const firstCheckbox = getCheckbox(0); const thirdCheckbox = getCheckbox(2); firstCheckbox.click(); assert(isSelected(0), 'first item should be selected'); thirdCheckbox.click(); assert(isSelected(0) && isSelected(2), 'both first and third items should be selected'); assert(!isSelected(1) && !isSelected(3) && !isSelected(4), 'the rest should not be selected'); firstCheckbox.click(); assert(!isSelected(0) && !isSelected(1) && isSelected(2) && !isSelected(3) && !isSelected(4), 'first item should be unselected after the second click'); }); it('can do multi-selection using the ctrl key', () => { const firstRow = getRow(0); const thirdRow = getRow(2); firstRow.click(); thirdRow.dispatchEvent(new MouseEvent('click', { ctrlKey: true, })); assert(isSelected(0) && isSelected(2), 'both first and third items should be selected'); assert(!isSelected(1) && !isSelected(3) && !isSelected(4), 'the rest should not be selected'); firstRow.dispatchEvent(new MouseEvent('click', { ctrlKey: true, })); assert(!isSelected(0), 'first row should be unselected on ctrl click'); assert(isSelected(2), 'third item should still be selected'); }); it('can do multi-selection using the shift key', () => { const firstRow = getRow(0); const thirdRow = getRow(2); thirdRow.click(); firstRow.dispatchEvent(new MouseEvent('click', { shiftKey: true, })); assert(isSelected(0) && isSelected(1) && isSelected(2), 'items 1 to 3 should be selected'); assert(!isSelected(3) && !isSelected(4), 'the rest should be unselected'); }); it('can do multi-selection with ctrl and shift key combinations', () => { const firstRow = getRow(0); const thirdRow = getRow(2); const fifthRow = getRow(4); thirdRow.click(); firstRow.dispatchEvent(new MouseEvent('click', { ctrlKey: true, })); fifthRow.dispatchEvent(new MouseEvent('click', { shiftKey: true, })); assert(JSON.stringify(testFixture.selectedIndices) === '[0,1,2,3,4]', 'all rows 1 to 5 should be selected'); }); it('hides the header when no-header property is used', () => { assert(testFixture.$.header.offsetHeight !== 0, 'the header row should be visible'); testFixture.hideHeader = true; assert(testFixture.$.header.offsetHeight === 0, 'the header row should be hidden'); }); it('prevents item selection when disable-selection property is used', () => { testFixture.disableSelection = true; const firstRow = getRow(0); firstRow.click(); assert(!isSelected(0), 'first item should not be selected when selection is disabled'); }); describe('inline details', () => { it('should not create a details element for an item without details', () => { testFixture.inlineDetailsMode = InlineDetailsDisplayMode.SINGLE_SELECT; const firstRow = getRow(0); const firstRowDetailsContainer = getRowDetailsContainer(0); firstRow.click(); Polymer.dom.flush(); assert(!firstRowDetailsContainer.firstChild, 'first item should not show details when clicked'); }); it('should create a details element for an item with details', () => { testFixture.inlineDetailsMode = InlineDetailsDisplayMode.SINGLE_SELECT; const fourthRow = getRow(3); const fourthRowDetailsContainer = getRowDetailsContainer(3); fourthRow.click(); Polymer.dom.flush(); const detailsElement: HTMLElement = fourthRowDetailsContainer.firstChild as HTMLElement; assert(!!detailsElement, 'fourth item should create details element when clicked'); assert(fourthRowDetailsContainer.getAttribute('hidden') == null, 'fourth details container should be visible'); }); it('should not create a details element in NONE display mode', () => { testFixture.inlineDetailsMode = InlineDetailsDisplayMode.NONE; const fourthRow = getRow(3); const fourthRowDetailsContainer = getRowDetailsContainer(0); fourthRow.click(); Polymer.dom.flush(); assert(!fourthRowDetailsContainer.firstChild, 'fourth item should not create details element when clicked'); assert(fourthRowDetailsContainer.getAttribute('hidden') != null, 'fourth details container should not be visible'); }); it('should show details even when not clicked in ALL mode', () => { testFixture.inlineDetailsMode = InlineDetailsDisplayMode.ALL; // TODO: the current behavior of ALL does not show all of the details when // the page first renders, but only displays the details when the // selection state for an item changes. We might want to change this // behavior so that it figures out in advance that it should show // all the details. testFixture._selectAll(); // Force state change for all items testFixture._unselectAll(); // Recalculate details display for all items Polymer.dom.flush(); const fourthRowDetailsContainer = getRowDetailsContainer(3); const fifthRowDetailsContainer = getRowDetailsContainer(3); const fourthDetailsElement: HTMLElement = fourthRowDetailsContainer.firstChild as HTMLElement; assert(!!fourthDetailsElement, 'fourth item should have details element'); assert(fourthRowDetailsContainer.getAttribute('hidden') == null, 'fourth details container should be visible'); const fifthDetailsElement: HTMLElement = fifthRowDetailsContainer.firstChild as HTMLElement; assert(!!fifthDetailsElement, 'fifth item should have details element'); assert(fifthRowDetailsContainer.getAttribute('hidden') == null, 'fitth details container should be visible'); }); it('should not show details for previously selected item ' + 'in single-select mode', () => { testFixture.inlineDetailsMode = InlineDetailsDisplayMode.SINGLE_SELECT; const fourthRow = getRow(3); const fifthRow = getRow(4); const fourthDetailsContainer = getRowDetailsContainer(3); const fifthDetailsContainer = getRowDetailsContainer(4); fourthRow.click(); fifthRow.click(); Polymer.dom.flush(); assert(fourthDetailsContainer.getAttribute('hidden') != null, 'fourth details container should be hidden'); assert(fifthDetailsContainer.getAttribute('hidden') == null, 'fifth details container should be visible'); }); it('should not show any details when multiple items selected ' + 'in single-select mode', () => { testFixture.inlineDetailsMode = InlineDetailsDisplayMode.SINGLE_SELECT; const fourthRow = getRow(3); const fifthCheckbox = getCheckbox(4); const fourthDetailsContainer = getRowDetailsContainer(3); const fifthDetailsContainer = getRowDetailsContainer(4); fourthRow.click(); fifthCheckbox.click(); Polymer.dom.flush(); assert(fourthDetailsContainer.getAttribute('hidden') != null, 'fourth details container should be hidden'); assert(fifthDetailsContainer.getAttribute('hidden') != null, 'fifth details container should be hidden'); }); it('should show details for multiple selected items ' + 'in multi-select mode', () => { testFixture.inlineDetailsMode = InlineDetailsDisplayMode.MULTIPLE_SELECT; const fourthRow = getRow(3); const fifthCheckbox = getCheckbox(4); const fourthDetailsContainer = getRowDetailsContainer(3); const fifthDetailsContainer = getRowDetailsContainer(4); fourthRow.click(); fifthCheckbox.click(); Polymer.dom.flush(); assert(fourthDetailsContainer.getAttribute('hidden') == null, 'fourth details container should be visible'); assert(fifthDetailsContainer.getAttribute('hidden') == null, 'fifth details container should be visible'); fifthCheckbox.click(); Polymer.dom.flush(); assert(fourthDetailsContainer.getAttribute('hidden') == null, 'fourth details container should be visible'); assert(fifthDetailsContainer.getAttribute('hidden') != null, 'fifth details container should be hidden'); }); }); describe('filtering', () => { it('hides the filter box by default', () => { assert(testFixture.$.filterBox.offsetHeight === 0, 'filter box should not show by default'); }); it('shows/hides filter box when toggle is clicked', () => { testFixture.$.filterToggle.click(); assert(testFixture.$.filterBox.offsetHeight > 0, 'filter box should show when toggle is clicked'); testFixture.$.filterToggle.click(); assert(testFixture.$.filterBox.offsetHeight === 0, 'filter box should hide when toggle is clicked again'); }); it('filters items when typing characters in the filter box', () => { testFixture.$.filterToggle.click(); testFixture._filterString = '3'; Polymer.dom.flush(); const rows = testFixture.$.listContainer.querySelectorAll('.row'); assert(rows.length === 1, 'only one item has "3" in its name'); assert(rows[0].children[1].innerText === 'first column 3', 'filter should only return the third item'); }); it('shows all items when filter string is deleted', () => { testFixture.$.filterToggle.click(); testFixture._filterString = '3'; Polymer.dom.flush(); testFixture._filterString = ''; Polymer.dom.flush(); const rows = testFixture.$.listContainer.querySelectorAll('.row'); assert(rows.length === 5, 'should show all rows after filter string is deleted'); }); it('filters items based on first column only', () => { testFixture.$.filterToggle.click(); testFixture._filterString = 'second'; Polymer.dom.flush(); const rows = testFixture.$.listContainer.querySelectorAll('.row'); assert(rows.length === 0, 'should not show any rows, since no row has "second" in its first column'); }); it('ignores case when filtering', () => { testFixture.$.filterToggle.click(); testFixture._filterString = 'COLUMN 4'; Polymer.dom.flush(); const rows = testFixture.$.listContainer.querySelectorAll('.row'); assert(rows.length === 1, 'should show one row containing "column 4", since filtering is case insensitive'); assert(rows[0].children[1].innerText === 'first column 4', 'filter should return the fourth item'); }); it('resets filter when filter box is closed', () => { testFixture.$.filterToggle.click(); testFixture._filterString = '3'; Polymer.dom.flush(); testFixture.$.filterToggle.click(); Polymer.dom.flush(); assert(testFixture.$.listContainer.querySelectorAll('.row').length === 5, 'all rows should show after closing filter box'); }); it('selects only visible items when Select All checkbox is clicked', () => { testFixture.$.filterToggle.click(); testFixture._filterString = '3'; Polymer.dom.flush(); testFixture.$.selectAllCheckbox.click(); testFixture._filterString = ''; Polymer.dom.flush(); assert(!isSelected(0), 'only third item should be selected'); assert(!isSelected(1), 'only third item should be selected'); assert(isSelected(2), 'only third item should be selected'); assert(!isSelected(3), 'only third item should be selected'); assert(!isSelected(4), 'only third item should be selected'); }); it('returns the correct selectedIndices result matching clicked items when filtering', () => { testFixture.$.filterToggle.click(); testFixture._filterString = '2'; Polymer.dom.flush(); const firstRow = getRow(0); firstRow.click(); const selectedIndices = testFixture.selectedIndices; assert(selectedIndices.length === 1, 'only one item should be selected'); assert(selectedIndices[0] === 1, 'the second index (only one shown) should be selected'); }); }); describe('sorting', () => { const rows = [ new ItemListRow({columns: ['item c*', new Date('Sat Nov 11 2017 18:58:42 GMT+0200 (EET)')]}), new ItemListRow({columns: ['item a*', new Date('Sat Nov 11 2017 18:59:42 GMT+0200 (EET)')]}), new ItemListRow({columns: ['item b', new Date('Fri Nov 10 2017 18:57:42 GMT+0200 (EET)')]}) ]; const col0SortedOrder = [1, 2, 0]; const col1SortedOrder = [2, 0, 1]; const col0ReverseOrder = col0SortedOrder.slice().reverse(); beforeEach(async () => { testFixture = fixture('item-list-fixture'); testFixture.rows = rows; testFixture.columns = [{ name: 'col1', type: ColumnTypeName.STRING, }, { name: 'col2', type: ColumnTypeName.DATE, }]; testFixture.$.list.render(); }); it('sorts on first column by default', () => { const renderedRows = testFixture.$.listContainer.querySelectorAll('.row'); for (let i = 0; i < testFixture.rows.length; ++i) { const columns = renderedRows[i].querySelectorAll('.column'); const sortedColumns = testFixture.rows[col0SortedOrder[i]].columns; assert(columns[0].innerText === sortedColumns[0]); assert(columns[1].innerText === new Date(sortedColumns[1].toString()).toLocaleString()); } }); it('switches sort to descending order if first column is sorted on again', () => { const renderedRows = testFixture.$.listContainer.querySelectorAll('.row'); testFixture._sortBy(0); testFixture.$.list.render(); for (let i = 0; i < testFixture.rows.length; ++i) { const columns = renderedRows[i].querySelectorAll('.column'); const sortedColumns = testFixture.rows[col0ReverseOrder[i]].columns; assert(columns[0].innerText === sortedColumns[0]); assert(columns[1].innerText === new Date(sortedColumns[1].toString()).toLocaleString()); } }); it('when switching to sorting on second column, uses ascending order', () => { testFixture._sortBy(1); testFixture.$.list.render(); const renderedRows = testFixture.$.listContainer.querySelectorAll('.row'); for (let i = 0; i < testFixture.rows.length; ++i) { const columns = renderedRows[i].querySelectorAll('.column'); const sortedColumns = testFixture.rows[col1SortedOrder[i]].columns; assert(columns[0].innerText === sortedColumns[0]); assert(columns[1].innerText === new Date(sortedColumns[1].toString()).toLocaleString()); } }); it('shows arrow icon on the sorted column', () => { const headerIcons = testFixture.$.header.querySelectorAll('.sort-icon'); assert(!headerIcons[0].hidden, 'first column should show sort icon'); assert(headerIcons[0].icon === 'arrow-upward', 'first column should show ascending sort icon'); assert(headerIcons[1].hidden, 'second column icon should be hidden'); testFixture._sortBy(1); testFixture.$.list.render(); assert(headerIcons[0].hidden, 'first column icon should be hidden'); assert(!headerIcons[1].hidden, 'second column should show sort icon'); assert(headerIcons[1].icon === 'arrow-upward', 'second column should show ascending sort icon'); testFixture._sortBy(1); testFixture.$.list.render(); assert(headerIcons[0].hidden, 'first column icon should be hidden'); assert(!headerIcons[1].hidden, 'second column should show sort icon'); assert(headerIcons[1].icon === 'arrow-downward', 'second column should show descending sort icon'); }); it('sorts the clicked column', () => { const headerButtons = testFixture.$.header.querySelectorAll('.column-button'); const headerIcons = testFixture.$.header.querySelectorAll('.sort-icon'); headerButtons[0].click(); testFixture.$.list.render(); assert(headerIcons[0].icon === 'arrow-downward', 'first column should show descending sort icon'); headerButtons[1].click(); testFixture.$.list.render(); assert(headerIcons[1].icon === 'arrow-upward', 'second column should show ascending sort icon'); }); it('sorts while filtering is active', () => { testFixture.$.filterToggle.click(); testFixture._filterString = '*'; testFixture.$.list.render(); let renderedRows = testFixture.$.listContainer.querySelectorAll('.row'); // row 0 let columns0 = renderedRows[0].querySelectorAll('.column'); assert(columns0[0].innerText === testFixture.rows[1].columns[0]); assert(columns0[1].innerText === new Date(testFixture.rows[1].columns[1].toString()).toLocaleString()); // row 1 let columns1 = renderedRows[1].querySelectorAll('.column'); assert(columns1[0].innerText === testFixture.rows[0].columns[0]); assert(columns1[1].innerText === new Date(testFixture.rows[0].columns[1].toString()).toLocaleString()); testFixture._sortBy(0); testFixture.$.list.render(); renderedRows = testFixture.$.listContainer.querySelectorAll('.row'); // row 0 columns0 = renderedRows[0].querySelectorAll('.column'); assert(columns0[0].innerText === testFixture.rows[0].columns[0]); assert(columns0[1].innerText === new Date(testFixture.rows[0].columns[1].toString()).toLocaleString()); // row 1 columns1 = renderedRows[1].querySelectorAll('.column'); assert(columns1[0].innerText === testFixture.rows[1].columns[0]); assert(columns1[1].innerText === new Date(testFixture.rows[1].columns[1].toString()).toLocaleString()); }); it('sorts numbers correctly', () => { testFixture.columns = [{ name: 'col1', type: ColumnTypeName.NUMBER, }]; testFixture.rows = [ new ItemListRow({columns: [11]}), new ItemListRow({columns: [1]}), new ItemListRow({columns: [2]}), ]; const sortedOrder = [1, 2, 0]; const renderedRows = testFixture.$.listContainer.querySelectorAll('.row'); for (let i = 0; i < testFixture.rows.length; ++i) { const columns = renderedRows[i].querySelectorAll('.column'); assert(columns[0].innerText === testFixture.rows[sortedOrder[i]].columns[0].toString()); } }); it('sorts correctly when there are equal values', () => { testFixture.columns = [{ name: 'col1', type: ColumnTypeName.NUMBER, }]; testFixture.rows = [ new ItemListRow({columns: [2]}), new ItemListRow({columns: [1]}), new ItemListRow({columns: [2]}), new ItemListRow({columns: [1]}), new ItemListRow({columns: [11]}), new ItemListRow({columns: [2]}), ]; const sortedOrder = [1, 3, 0, 2, 5, 4]; const renderedRows = testFixture.$.listContainer.querySelectorAll('.row'); for (let i = 0; i < testFixture.rows.length; ++i) { const columns = renderedRows[i].querySelectorAll('.column'); assert(columns[0].innerText === testFixture.rows[sortedOrder[i]].columns[0].toString()); } }); it('returns the correct selectedIndices result matching clicked items when sorted', () => { testFixture.columns = [{ name: 'col1', type: ColumnTypeName.NUMBER, }]; testFixture.rows = [ new ItemListRow({columns: [1]}), new ItemListRow({columns: [2]}), new ItemListRow({columns: [3]}), ]; // Reverse the sorting testFixture._sortBy(0); const firstRow = getRow(0); firstRow.click(); const selectedIndices = testFixture.selectedIndices; assert(selectedIndices.length === 1, 'only one item should be selected'); assert(selectedIndices[0] === 2, 'the third index (shown first) should be selected'); }); }); }); });
the_stack
import { GeoCoordinates, GeoCoordinatesLike, GeoPolygonCoordinates, mercatorTilingScheme, Projection, sphereProjection, TileKey } from "@here/harp-geoutils"; import * as TestUtils from "@here/harp-test-utils/lib/WebGLStub"; import { assert } from "chai"; import * as sinon from "sinon"; import * as THREE from "three"; import { BoundsGenerator } from "../lib/BoundsGenerator"; import { projectTilePlaneCorners } from "../lib/geometry/ProjectTilePlaneCorners"; import { LookAtParams, MapView, MapViewOptions } from "../lib/MapView"; import { Tile } from "../lib/Tile"; import { MapViewUtils } from "../lib/Utils"; // Mocha discourages using arrow functions, see https://mochajs.org/#arrow-functions declare const global: any; describe("BoundsGenerator", function () { const inNodeContext = typeof window === "undefined"; let sandbox: sinon.SinonSandbox; let clearColorStub: sinon.SinonStub; let addEventListenerSpy: sinon.SinonStub; let removeEventListenerSpy: sinon.SinonStub; let canvas: HTMLCanvasElement; let mapView: MapView | undefined; let boundsGenerator: BoundsGenerator; let lookAtParams: Partial<LookAtParams>; let mapViewOptions: MapViewOptions; beforeEach(function () { //Setup a stubbed mapview to emulate the camera behaviour sandbox = sinon.createSandbox(); clearColorStub = sandbox.stub(); sandbox .stub(THREE, "WebGLRenderer") .returns(TestUtils.getWebGLRendererStub(sandbox, clearColorStub)); sandbox .stub(THREE, "WebGL1Renderer") .returns(TestUtils.getWebGLRendererStub(sandbox, clearColorStub)); if (inNodeContext) { const theGlobal: any = global; theGlobal.window = { window: { devicePixelRatio: 10 } }; theGlobal.navigator = {}; theGlobal.requestAnimationFrame = (callback: (time: DOMHighResTimeStamp) => void) => { setTimeout(callback, 0); }; theGlobal.performance = { now: Date.now }; } addEventListenerSpy = sinon.stub(); removeEventListenerSpy = sinon.stub(); canvas = ({ clientWidth: 1200, clientHeight: 800, addEventListener: addEventListenerSpy, removeEventListener: removeEventListenerSpy } as unknown) as HTMLCanvasElement; mapViewOptions = { canvas, // Both options cause the `addDataSource` method to be called, which we can't `await` on // because it is called in the constructor, but we can disable them being added. addBackgroundDatasource: false, enablePolarDataSource: false }; lookAtParams = { target: new GeoCoordinates(0, 0), zoomLevel: 5, tilt: 0, heading: 0 }; mapView = new MapView({ ...mapViewOptions, tileWrappingEnabled: false }); mapView.lookAt(lookAtParams); boundsGenerator = new BoundsGenerator(mapView); }); afterEach(async function () { if (mapView !== undefined) { await mapView.getTheme(); // Needed otherwise the dispose will cause log messages mapView.dispose(); mapView = undefined; } sandbox.restore(); if (inNodeContext) { delete global.window; delete global.requestAnimationFrame; delete global.cancelAnimationFrame; delete global.navigator; } }); enum CanvasSides { Bottom, Right, Top, Left, None, All } function countVerticesOnCanvasSide( coordinates: GeoPolygonCoordinates, side: CanvasSides ): number { const eps = 1e-5; let expectedNdcX: number | undefined; let expectedNdcY: number | undefined; switch (side) { case CanvasSides.Bottom: expectedNdcY = -1; break; case CanvasSides.Right: expectedNdcX = 1; break; case CanvasSides.Top: expectedNdcY = 1; break; case CanvasSides.Left: expectedNdcX = -1; break; default: assert.fail("Canvas side option not supported"); } return coordinates.filter(vertex => { const ndcPoint = mapView!.projection .projectPoint(GeoCoordinates.fromObject(vertex), new THREE.Vector3()) .project(mapView!.camera); if (expectedNdcX !== undefined) { return Math.abs(ndcPoint.x - expectedNdcX) < eps; } else if (expectedNdcY !== undefined) { return Math.abs(ndcPoint.y - expectedNdcY) < eps; } else { assert.fail("Canvas side option not supported"); } }).length; } function checkCanvasCorners(coordinates: GeoPolygonCoordinates, included = CanvasSides.All) { const bottomCorners = [ [-1, -1], [1, -1] ]; const topCorners = [ [-1, 1], [1, 1] ]; const includedCorners: number[][] = []; const excludedCorners: number[][] = []; switch (included) { case CanvasSides.None: excludedCorners.concat(bottomCorners, topCorners); break; case CanvasSides.Bottom: includedCorners.push(...bottomCorners); excludedCorners.push(...topCorners); break; case CanvasSides.All: includedCorners.concat(bottomCorners, topCorners); break; default: assert(false); } for (const cornerNdc of includedCorners) { const corner = MapViewUtils.rayCastGeoCoordinates(mapView!, cornerNdc[0], cornerNdc[1]); assert.deepInclude(coordinates, corner as GeoCoordinates); } for (const cornerNdc of excludedCorners) { const corner = MapViewUtils.rayCastGeoCoordinates(mapView!, cornerNdc[0], cornerNdc[1]); assert.notDeepInclude(coordinates, corner as GeoCoordinates); } } describe("Sphere Projection", function () { beforeEach(function () { mapView = new MapView({ ...mapViewOptions, projection: sphereProjection }); mapView.lookAt({ target: new GeoCoordinates(0, 0), zoomLevel: 12, tilt: 0, heading: 0 }); mapView.renderSync(); // render once to update camera parameter boundsGenerator = new BoundsGenerator(mapView); }); it("generates polygon of canvas corners for canvas filled with map", function () { const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal(coordinates?.length, 4); checkCanvasCorners(coordinates!); }); it("generates polygon with wrapped around coords if it crosses antimeridian", function () { mapView!.lookAt({ target: new GeoCoordinates(0, 180) }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal(coordinates?.length, 4); checkCanvasCorners(coordinates!); assert.isAbove(coordinates![1].longitude, 180); assert.isAbove(coordinates![2].longitude, 180); }); it("generates polygon with subdivided top/bottom for large longitude spans", function () { mapView!.lookAt({ target: new GeoCoordinates(75, 0), zoomLevel: 10, tilt: 0, heading: 0 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isDefined(coordinates); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 6); checkCanvasCorners(coordinates!); coordinates!.findIndex((val: GeoCoordinatesLike) => { val.latitude; }); }); it("generates polygon with subdivided lateral sides for large latitude spans", function () { mapView!.resize(100, 1000); mapView!.lookAt({ target: new GeoCoordinates(0, 0), zoomLevel: 7, tilt: 0, heading: 0 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isDefined(coordinates); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 6); checkCanvasCorners(coordinates!); }); // Horizon cases it("horizon cuts once each lateral canvas side", function () { mapView!.lookAt({ tilt: 80 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isDefined(coordinates); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 5); checkCanvasCorners(coordinates!, CanvasSides.Bottom); // 2 vertices on right side (including bottom right corner) assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Right), 2); // 2 vertices on left side (including bottom left corner) assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Left), 2); }); it("horizon cuts once each lateral canvas side and twice at the top", function () { mapView!.lookAt({ tilt: 30, zoomLevel: 6 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isDefined(coordinates); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 6); checkCanvasCorners(coordinates!, CanvasSides.Bottom); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Right), 2); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Top), 2); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Left), 2); }); it("horizon cuts twice each canvas side", function () { mapView!.lookAt({ zoomLevel: 5.5 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isDefined(coordinates); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 8); checkCanvasCorners(coordinates!, CanvasSides.None); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Bottom), 2); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Right), 2); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Top), 2); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Left), 2); }); it("horizon cuts twice each lateral canvas side", function () { mapView!.resize(800, 1200); mapView!.lookAt({ zoomLevel: 4 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isDefined(coordinates); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 4); checkCanvasCorners(coordinates!, CanvasSides.None); assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Bottom), 0); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Right), 2); assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Top), 0); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Left), 2); }); it("horizon cuts twice top and bottom canvas sides", function () { mapView!.lookAt({ zoomLevel: 4 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isDefined(coordinates); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 6); checkCanvasCorners(coordinates!, CanvasSides.None); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Bottom), 2); assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Right), 0); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Top), 2); assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Left), 0); }); it("horizon cuts twice the bottom canvas side", function () { mapView!.lookAt({ tilt: 45, zoomLevel: 4 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isDefined(coordinates); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 3); checkCanvasCorners(coordinates!, CanvasSides.None); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Bottom), 2); assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Right), 0); assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Top), 0); assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Left), 0); }); it("horizon is fully visible (no cuts on canvas sides)", function () { mapView!.lookAt({ zoomLevel: 3 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isDefined(coordinates); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 4); checkCanvasCorners(coordinates!, CanvasSides.None); assert.isAtLeast(countVerticesOnCanvasSide(coordinates!, CanvasSides.Bottom), 0); assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Right), 0); assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Top), 0); assert.equal(countVerticesOnCanvasSide(coordinates!, CanvasSides.Left), 0); // check every polygon vertex is a point in the horizon. for (const vertex of coordinates!) { const worldPoint = mapView!.projection.projectPoint( GeoCoordinates.fromObject(vertex), new THREE.Vector3() ); const cameraRay = new THREE.Vector3().subVectors( mapView!.camera.position, worldPoint ); assert.closeTo(Math.abs(cameraRay.angleTo(worldPoint)), Math.PI / 2, 1e-5); } }); // Pole wrapping it("bounds wrap around the north pole", function () { mapView!.lookAt({ zoomLevel: 6, target: new GeoCoordinates(90, 0) }); mapView!.renderSync(); // render once to update camera parameter const polygon = (boundsGenerator as BoundsGenerator).generate(); const coordinates = polygon?.coordinates; assert.isDefined(polygon); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 4); checkCanvasCorners(coordinates!, CanvasSides.All); // centroid should be above all polygon vertices (except those added at lat 90 to wrap // the polygon around the pole) const centroid = polygon!.getCentroid(); assert.isDefined(centroid); for (const coords of coordinates!.filter(value => { return value.latitude !== 90; })) { assert.isBelow(coords.latitude, centroid!.latitude); } }); it("bounds wrap around the south pole", function () { mapView!.lookAt({ zoomLevel: 6, target: new GeoCoordinates(-90, 0) }); mapView!.renderSync(); // render once to update camera parameter const polygon = (boundsGenerator as BoundsGenerator).generate(); const coordinates = polygon?.coordinates; assert.isDefined(polygon); assert.isNotEmpty(coordinates); assert.isAtLeast(coordinates!.length, 4); checkCanvasCorners(coordinates!, CanvasSides.All); // centroid should be above all polygon vertices (except those added at lat -90 to wrap // the polygon around the pole) const centroid = polygon!.getCentroid(); assert.isDefined(centroid); for (const coords of coordinates!.filter(value => { return value.latitude !== -90; })) { assert.isAbove(coords.latitude, centroid!.latitude); } }); }); describe("Mercator Projection", function () { beforeEach(function () { mapView = new MapView({ ...mapViewOptions, tileWrappingEnabled: false }); mapView.lookAt(lookAtParams); boundsGenerator = new BoundsGenerator(mapView); }); it("generates polygon of canvas corners for canvas filled with map", function () { mapView!.lookAt(lookAtParams); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal(coordinates?.length, 4); checkCanvasCorners(coordinates!); }); it("generates polygon for canvas filled with map, w/ tileWrapping", function () { //Setup mapView with tileWrapping Enabled mapView = new MapView({ ...mapViewOptions, tileWrappingEnabled: true }); //create new instance of boundsGenerator with the new mapView instance parameters boundsGenerator = new BoundsGenerator(mapView); mapView.lookAt({ zoomLevel: 10, target: { latitude: 0, longitude: 180, altitude: 0 } }); mapView.renderSync(); // render once to update camera parameter const coordinates = boundsGenerator.generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal(coordinates?.length, 4); if (coordinates === undefined) { return; } checkCanvasCorners(coordinates); }); it("generates polygon of world Corners, if whole world plane is visible", function () { mapView!.lookAt({ zoomLevel: 0 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal(coordinates?.length, 4); const geoBox = mercatorTilingScheme.getGeoBox(TileKey.fromRowColumnLevel(0, 0, 0)); const worldCorners = projectTilePlaneCorners( { geoBox } as Tile, mapView!.projection as Projection ); if (coordinates === undefined) { return; } assert.deepInclude(coordinates, mapView!.projection.unprojectPoint(worldCorners.se)); assert.deepInclude(coordinates, mapView!.projection.unprojectPoint(worldCorners.sw)); assert.deepInclude(coordinates, mapView!.projection.unprojectPoint(worldCorners.ne)); assert.deepInclude(coordinates, mapView!.projection.unprojectPoint(worldCorners.nw)); }); it("generates polygon of world vertically clipped by frustum , w/ tileWrapping", function () { //Setup mapView with tileWrapping Enabled mapView = new MapView({ ...mapViewOptions, tileWrappingEnabled: true }); //create new instance of boundsGenerator with the new mapView instance parameters boundsGenerator = new BoundsGenerator(mapView); mapView.lookAt({ zoomLevel: 1, tilt: 70, target: { latitude: 0, longitude: 180, altitude: 0 } }); mapView.renderSync(); // render once to update camera parameter const coordinates = boundsGenerator.generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal(coordinates?.length, 4); const delta = 0.0000001; coordinates?.forEach(point => { const worldPoint = mapView!.projection.projectPoint( GeoCoordinates.fromObject(point) ); if (worldPoint) { const ndcPoint = new THREE.Vector3() .copy(worldPoint as THREE.Vector3) .project(mapView!.camera as THREE.Camera); //point should be on right or left edge of the screen assert.closeTo( 1, Math.abs(ndcPoint.x), delta, "point on right or left edge of screen" ); } }); }); it("generates polygon of world horizontally clipped by frustum , w/ tileWrapping", function () { //Setup mapView with tileWrapping Enabled mapView = new MapView({ ...mapViewOptions, tileWrappingEnabled: true }); //create new instance of boundsGenerator with the new mapView instance parameters boundsGenerator = new BoundsGenerator(mapView); mapView.lookAt({ zoomLevel: 1, tilt: 0, heading: 90, target: { latitude: 0, longitude: 180, altitude: 0 } }); mapView.renderSync(); // render once to update camera parameter const coordinates = boundsGenerator.generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal(coordinates?.length, 4); const delta = 0.0000001; coordinates?.forEach(point => { const worldPoint = mapView!.projection.projectPoint( GeoCoordinates.fromObject(point) ); if (worldPoint) { const ndcPoint = new THREE.Vector3() .copy(worldPoint as THREE.Vector3) .project(mapView!.camera as THREE.Camera); //point should be on right or left edge of the screen assert.closeTo( 1, Math.abs(ndcPoint.y), delta, "point on upper or lower edge of screen" ); } }); }); it("generates polygon for tilted map, cut by horizon", function () { mapView!.lookAt({ tilt: 80 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal(coordinates?.length, 4); checkCanvasCorners(coordinates!, CanvasSides.Bottom); }); it("generates polygon for tilted map, cut by horizon, w/ tileWrapping", function () { //Setup mapView with tileWrapping Enabled mapView = new MapView({ ...mapViewOptions, tileWrappingEnabled: true }); //create new instance of boundsGenerator with the new mapView instance parameters boundsGenerator = new BoundsGenerator(mapView); mapView.lookAt({ tilt: 88, heading: 90, zoomLevel: 6 }); mapView.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal(coordinates?.length, 4); if (coordinates === undefined) { return; } checkCanvasCorners(coordinates, CanvasSides.Bottom); }); it("generates polygon for tilted and heading rotated map, one worldCorner in view", function () { //mapView.setCameraGeolocationAndZoom(new GeoCoordinates(0, 0), 2, 0, 0); mapView!.lookAt({ target: { latitude: 50.08345695126102, longitude: 4.077785404634487, altitude: 0 }, tilt: 80, heading: 45, zoomLevel: 3 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal( coordinates?.length, 5, "polygon contains 5 points and one worldcorner is in view" ); if (coordinates === undefined) { return; } checkCanvasCorners(coordinates, CanvasSides.Bottom); }); it("generates polygon for tilted and heading rotated map, plane cut 2 times", function () { //mapView.setCameraGeolocationAndZoom(new GeoCoordinates(0, 0), 2, 0, 0); mapView!.lookAt({ target: { latitude: 0, longitude: 0, altitude: 0 }, tilt: 45, heading: 45, zoomLevel: 3 }); mapView!.renderSync(); // render once to update camera parameter const coordinates = (boundsGenerator as BoundsGenerator).generate()?.coordinates; assert.isNotEmpty(coordinates); assert.equal( coordinates?.length, 6, "polygon contains 6 points and two worldcorners are in view, and 2 corners are clipped" ); }); }); });
the_stack
import * as moment from 'moment'; import * as nestedProperty from 'nested-property'; import autobind from 'autobind-decorator'; import Logger from '../logger'; import { Schema, bool, types } from '../../misc/schema'; import { EntitySchema, getRepository, Repository, LessThan, MoreThanOrEqual } from 'typeorm'; import { isDuplicateKeyValueError } from '../../misc/is-duplicate-key-value-error'; const logger = new Logger('chart', 'white', process.env.NODE_ENV !== 'test'); const utc = moment.utc; export type Obj = { [key: string]: any }; export type DeepPartial<T> = { [P in keyof T]?: DeepPartial<T[P]>; }; type ArrayValue<T> = { [P in keyof T]: T[P] extends number ? T[P][] : ArrayValue<T[P]>; }; type Span = 'day' | 'hour'; type Log = { id: number; /** * 集計のグループ */ group: string | null; /** * 集計日時のUnixタイムスタンプ(秒) */ date: number; /** * 集計期間 */ span: Span; /** * ユニークインクリメント用 */ unique?: Record<string, any>; }; const camelToSnake = (str: string) => { return str.replace(/([A-Z])/g, s => '_' + s.charAt(0).toLowerCase()); }; /** * 様々なチャートの管理を司るクラス */ export default abstract class Chart<T extends Record<string, any>> { private static readonly columnPrefix = '___'; private static readonly columnDot = '_'; private name: string; public schema: Schema; protected repository: Repository<Log>; protected abstract genNewLog(latest: T): DeepPartial<T>; protected abstract async fetchActual(group?: string): Promise<DeepPartial<T>>; @autobind private static convertSchemaToFlatColumnDefinitions(schema: Schema) { const columns = {} as any; const flatColumns = (x: Obj, path?: string) => { for (const [k, v] of Object.entries(x)) { const p = path ? `${path}${this.columnDot}${k}` : k; if (v.type === 'object') { flatColumns(v.properties, p); } else { columns[this.columnPrefix + p] = { type: 'bigint', }; } } }; flatColumns(schema.properties!); return columns; } @autobind private static convertFlattenColumnsToObject(x: Record<string, number>) { const obj = {} as any; for (const k of Object.keys(x).filter(k => k.startsWith(Chart.columnPrefix))) { // now k is ___x_y_z const path = k.substr(Chart.columnPrefix.length).split(Chart.columnDot).join('.'); nestedProperty.set(obj, path, x[k]); } return obj; } @autobind private static convertObjectToFlattenColumns(x: Record<string, any>) { const columns = {} as Record<string, number>; const flatten = (x: Obj, path?: string) => { for (const [k, v] of Object.entries(x)) { const p = path ? `${path}${this.columnDot}${k}` : k; if (typeof v === 'object') { flatten(v, p); } else { columns[this.columnPrefix + p] = v; } } }; flatten(x); return columns; } @autobind private static convertQuery(x: Record<string, any>) { const query: Record<string, Function> = {}; const columns = Chart.convertObjectToFlattenColumns(x); for (const [k, v] of Object.entries(columns)) { if (v > 0) query[k] = () => `"${k}" + ${v}`; if (v < 0) query[k] = () => `"${k}" - ${v}`; } return query; } @autobind private static momentToTimestamp(x: moment.Moment): Log['date'] { return x.unix(); } @autobind public static schemaToEntity(name: string, schema: Schema): EntitySchema { return new EntitySchema({ name: `__chart__${camelToSnake(name)}`, columns: { id: { type: 'integer', primary: true, generated: true }, date: { type: 'integer', }, group: { type: 'varchar', length: 128, nullable: true }, span: { type: 'enum', enum: ['hour', 'day'] }, unique: { type: 'jsonb', default: {} }, ...Chart.convertSchemaToFlatColumnDefinitions(schema) }, }); } constructor(name: string, schema: Schema, grouped = false) { this.name = name; this.schema = schema; const entity = Chart.schemaToEntity(name, schema); const keys = ['span', 'date']; if (grouped) keys.push('group'); entity.options.uniques = [{ columns: keys }]; this.repository = getRepository<Log>(entity); } @autobind private getNewLog(latest: T | null): T { const log = latest ? this.genNewLog(latest) : {}; const flatColumns = (x: Obj, path?: string) => { for (const [k, v] of Object.entries(x)) { const p = path ? `${path}.${k}` : k; if (v.type === 'object') { flatColumns(v.properties, p); } else { if (nestedProperty.get(log, p) == null) { nestedProperty.set(log, p, 0); } } } }; flatColumns(this.schema.properties!); return log as T; } @autobind private getCurrentDate(): [number, number, number, number] { const now = moment().utc(); const y = now.year(); const m = now.month(); const d = now.date(); const h = now.hour(); return [y, m, d, h]; } @autobind private getLatestLog(span: Span, group: string | null = null): Promise<Log | null> { return this.repository.findOne({ group: group, span: span }, { order: { date: -1 } }).then(x => x || null); } @autobind private async getCurrentLog(span: Span, group: string | null = null): Promise<Log> { const [y, m, d, h] = this.getCurrentDate(); const current = span == 'day' ? utc([y, m, d]) : span == 'hour' ? utc([y, m, d, h]) : null as never; // 現在(今日または今のHour)のログ const currentLog = await this.repository.findOne({ span: span, date: Chart.momentToTimestamp(current), ...(group ? { group: group } : {}) }); // ログがあればそれを返して終了 if (currentLog != null) { return currentLog; } let log: Log; let data: T; // 集計期間が変わってから、初めてのチャート更新なら // 最も最近のログを持ってくる // * 例えば集計期間が「日」である場合で考えると、 // * 昨日何もチャートを更新するような出来事がなかった場合は、 // * ログがそもそも作られずドキュメントが存在しないということがあり得るため、 // * 「昨日の」と決め打ちせずに「もっとも最近の」とします const latest = await this.getLatestLog(span, group); if (latest != null) { const obj = Chart.convertFlattenColumnsToObject( latest as Record<string, any>); // 空ログデータを作成 data = await this.getNewLog(obj); } else { // ログが存在しなかったら // 初期ログデータを作成 data = await this.getNewLog(null); logger.info(`${this.name}: Initial commit created`); } try { // 新規ログ挿入 log = await this.repository.save({ group: group, span: span, date: Chart.momentToTimestamp(current), ...Chart.convertObjectToFlattenColumns(data) }); } catch (e) { // duplicate key error // 並列動作している他のチャートエンジンプロセスと処理が重なる場合がある // その場合は再度最も新しいログを持ってくる if (isDuplicateKeyValueError(e)) { log = await this.getLatestLog(span, group) as Log; } else { logger.error(e); throw e; } } return log; } @autobind protected commit(query: Record<string, Function>, group: string | null = null, uniqueKey?: string, uniqueValue?: string): Promise<any> { const update = async (log: Log) => { // ユニークインクリメントの場合、指定のキーに指定の値が既に存在していたら弾く if ( uniqueKey && log.unique && log.unique[uniqueKey] && log.unique[uniqueKey].includes(uniqueValue) ) return; // ユニークインクリメントの指定のキーに値を追加 if (uniqueKey && log.unique) { if (log.unique[uniqueKey]) { const sql = `jsonb_set("unique", '{${uniqueKey}}', ("unique"->>'${uniqueKey}')::jsonb || '["${uniqueValue}"]'::jsonb)`; query['unique'] = () => sql; } else { const sql = `jsonb_set("unique", '{${uniqueKey}}', '["${uniqueValue}"]')`; query['unique'] = () => sql; } } // ログ更新 await this.repository.createQueryBuilder() .update() .set(query) .where('id = :id', { id: log.id }) .execute(); }; return Promise.all([ this.getCurrentLog('day', group).then(log => update(log)), this.getCurrentLog('hour', group).then(log => update(log)), ]); } @autobind protected async inc(inc: DeepPartial<T>, group: string | null = null): Promise<void> { await this.commit(Chart.convertQuery(inc as any), group); } @autobind protected async incIfUnique(inc: DeepPartial<T>, key: string, value: string, group: string | null = null): Promise<void> { await this.commit(Chart.convertQuery(inc as any), group, key, value); } @autobind public async getChart(span: Span, range: number, group: string | null = null): Promise<ArrayValue<T>> { const [y, m, d, h] = this.getCurrentDate(); const gt = span == 'day' ? utc([y, m, d]).subtract(range, 'days') : span == 'hour' ? utc([y, m, d, h]).subtract(range, 'hours') : null as never; // ログ取得 let logs = await this.repository.find({ where: { group: group, span: span, date: MoreThanOrEqual(Chart.momentToTimestamp(gt)) }, order: { date: -1 }, }); // 要求された範囲にログがひとつもなかったら if (logs.length === 0) { // もっとも新しいログを持ってくる // (すくなくともひとつログが無いと隙間埋めできないため) const recentLog = await this.repository.findOne({ group: group, span: span }, { order: { date: -1 }, }); if (recentLog) { logs = [recentLog]; } // 要求された範囲の最も古い箇所に位置するログが存在しなかったら } else if (!utc(logs[logs.length - 1].date * 1000).isSame(gt)) { // 要求された範囲の最も古い箇所時点での最も新しいログを持ってきて末尾に追加する // (隙間埋めできないため) const outdatedLog = await this.repository.findOne({ group: group, span: span, date: LessThan(Chart.momentToTimestamp(gt)) }, { order: { date: -1 }, }); if (outdatedLog) { logs.push(outdatedLog); } } const chart: T[] = []; // 整形 for (let i = (range - 1); i >= 0; i--) { const current = span == 'day' ? utc([y, m, d]).subtract(i, 'days') : span == 'hour' ? utc([y, m, d, h]).subtract(i, 'hours') : null as never; const log = logs.find(l => utc(l.date * 1000).isSame(current)); if (log) { const data = Chart.convertFlattenColumnsToObject(log as Record<string, any>); chart.unshift(data); } else { // 隙間埋め const latest = logs.find(l => utc(l.date * 1000).isBefore(current)); const data = latest ? Chart.convertFlattenColumnsToObject(latest as Record<string, any>) : null; chart.unshift(this.getNewLog(data)); } } const res: ArrayValue<T> = {} as any; /** * [{ foo: 1, bar: 5 }, { foo: 2, bar: 6 }, { foo: 3, bar: 7 }] * を * { foo: [1, 2, 3], bar: [5, 6, 7] } * にする */ const dive = (x: Obj, path?: string) => { for (const [k, v] of Object.entries(x)) { const p = path ? `${path}.${k}` : k; if (typeof v == 'object') { dive(v, p); } else { nestedProperty.set(res, p, chart.map(s => nestedProperty.get(s, p))); } } }; dive(chart[0]); return res; } } export function convertLog(logSchema: Schema): Schema { const v: Schema = JSON.parse(JSON.stringify(logSchema)); // copy if (v.type === 'number') { v.type = 'array'; v.items = { type: types.number, optional: bool.false, nullable: bool.false, }; } else if (v.type === 'object') { for (const k of Object.keys(v.properties!)) { v.properties![k] = convertLog(v.properties![k]); } } return v; }
the_stack
import { Class, Filter } from '@nestjs-query/core'; import { plainToClass } from 'class-transformer'; import { ObjectType, Int, Resolver, Query, Args, Float, GraphQLTimestamp, Field, InputType, registerEnumType, } from '@nestjs/graphql'; import { FilterableField, FilterType, Relation, UpdateFilterType, DeleteFilterType, SubscriptionFilterType, FilterableRelation, OffsetConnection, CursorConnection, FilterableCursorConnection, FilterableOffsetConnection, UnPagedRelation, FilterableUnPagedRelation, QueryOptions, } from '../../../src'; import { generateSchema } from '../../__fixtures__'; describe('filter types', (): void => { enum NumberEnum { ONE, TWO, THREE, FOUR, } enum StringEnum { ONE_STR = 'one', TWO_STR = 'two', THREE_STR = 'three', FOUR_STR = 'four', } registerEnumType(StringEnum, { name: 'StringEnum', }); registerEnumType(NumberEnum, { name: 'NumberEnum', }); @ObjectType({ isAbstract: true }) class BaseType { @FilterableField() id!: number; } @ObjectType('TestRelationDto') class TestRelation extends BaseType { @FilterableField() relationName!: string; @FilterableField() relationAge!: number; } @ObjectType('TestFilterDto') @Relation('unFilterableRelation', () => TestRelation) @FilterableRelation('filterableRelation', () => TestRelation) @UnPagedRelation('unPagedRelations', () => TestRelation) @FilterableUnPagedRelation('filterableUnPagedRelations', () => TestRelation) @OffsetConnection('unFilterableOffsetConnection', () => TestRelation) @FilterableOffsetConnection('filterableOffsetConnection', () => TestRelation) @CursorConnection('unFilterableCursorConnection', () => TestRelation) @FilterableCursorConnection('filterableCursorConnection', () => TestRelation) class TestDto extends BaseType { @FilterableField() boolField!: boolean; @FilterableField() dateField!: Date; @FilterableField(() => Float) floatField!: number; @FilterableField(() => Int) intField!: number; @FilterableField() numberField!: number; @FilterableField() stringField!: string; @FilterableField(() => StringEnum) stringEnumField!: StringEnum; @FilterableField(() => NumberEnum) numberEnumField!: NumberEnum; @FilterableField(() => GraphQLTimestamp) timestampField!: Date; @Field() nonFilterField!: number; } describe('FilterType', () => { const TestGraphQLFilter: Class<Filter<TestDto>> = FilterType(TestDto); @InputType() class TestDtoFilter extends TestGraphQLFilter {} it('should throw an error if the class is not annotated with @ObjectType', () => { class TestInvalidFilter {} expect(() => FilterType(TestInvalidFilter)).toThrow( 'No fields found to create FilterType. Ensure TestInvalidFilter is annotated with @nestjs/graphql @ObjectType', ); }); it('should create the correct filter graphql schema', async () => { @Resolver() class FilterTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args('input') input: TestDtoFilter): number { return 1; } } const schema = await generateSchema([FilterTypeSpec]); expect(schema).toMatchSnapshot(); }); it('should throw an error if no fields are found', () => { @ObjectType('TestNoFields') class TestInvalidFilter {} expect(() => FilterType(TestInvalidFilter)).toThrow( 'No fields found to create GraphQLFilter for TestInvalidFilter', ); }); it('should throw an error when the field type is unknown', () => { enum EnumField { ONE = 'one', } @ObjectType('TestBadField') class TestInvalidFilter { @FilterableField(() => EnumField) fakeType!: EnumField; } expect(() => FilterType(TestInvalidFilter)).toThrow('Unable to create filter comparison for {"ONE":"one"}.'); }); it('should convert and filters to filter class', () => { const filterObject: Filter<TestDto> = { and: [{ stringField: { eq: 'foo' } }], }; const filterInstance = plainToClass(TestDtoFilter, filterObject); expect(filterInstance.and![0]).toBeInstanceOf(TestGraphQLFilter); }); it('should convert or filters to filter class', () => { const filterObject: Filter<TestDto> = { or: [{ stringField: { eq: 'foo' } }], }; const filterInstance = plainToClass(TestDtoFilter, filterObject); expect(filterInstance.or![0]).toBeInstanceOf(TestGraphQLFilter); }); describe('allowedComparisons option', () => { @ObjectType('TestAllowedComparison') class TestAllowedComparisonsDto extends BaseType { @FilterableField({ allowedComparisons: ['is'] }) boolField!: boolean; @FilterableField({ allowedComparisons: ['eq', 'neq'] }) dateField!: Date; @FilterableField(() => Float, { allowedComparisons: ['gt', 'gte'] }) floatField!: number; @FilterableField(() => Int, { allowedComparisons: ['lt', 'lte'] }) intField!: number; @FilterableField({ allowedComparisons: ['eq', 'neq', 'gt', 'gte', 'lt', 'lte'] }) numberField!: number; @FilterableField({ allowedComparisons: ['like', 'notLike'] }) stringField!: string; } const TestGraphQLComparisonFilter: Class<Filter<TestDto>> = FilterType(TestAllowedComparisonsDto); @InputType() class TestComparisonDtoFilter extends TestGraphQLComparisonFilter {} it('should only expose allowed comparisons', async () => { @Resolver() class FilterTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args('input') input: TestComparisonDtoFilter): number { return 1; } } const schema = await generateSchema([FilterTypeSpec]); expect(schema).toMatchSnapshot(); }); }); describe('allowedBooleanExpressions option', () => { describe('only and boolean expressions', () => { @ObjectType('TestAllowedComparisons') @QueryOptions({ allowedBooleanExpressions: ['and'] }) class TestOnlyAndBooleanExpressionsDto extends BaseType { @FilterableField() numberField!: number; } const TestGraphQLComparisonFilter: Class<Filter<TestDto>> = FilterType(TestOnlyAndBooleanExpressionsDto); @InputType() class TestComparisonDtoFilter extends TestGraphQLComparisonFilter {} it('should only expose allowed comparisons', async () => { @Resolver() class FilterTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args('input') input: TestComparisonDtoFilter): number { return 1; } } const schema = await generateSchema([FilterTypeSpec]); expect(schema).toMatchSnapshot(); }); }); describe('only or boolean expressions', () => { @ObjectType('TestAllowedComparisons') @QueryOptions({ allowedBooleanExpressions: ['or'] }) class TestOnlyOrBooleanExpressionsDto extends BaseType { @FilterableField() numberField!: number; } const TestGraphQLComparisonFilter: Class<Filter<TestDto>> = FilterType(TestOnlyOrBooleanExpressionsDto); @InputType() class TestComparisonDtoFilter extends TestGraphQLComparisonFilter {} it('should only expose allowed comparisons', async () => { @Resolver() class FilterTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args('input') input: TestComparisonDtoFilter): number { return 1; } } const schema = await generateSchema([FilterTypeSpec]); expect(schema).toMatchSnapshot(); }); }); describe('no boolean expressions', () => { @ObjectType('TestAllowedComparisons') @QueryOptions({ allowedBooleanExpressions: [] }) class TestNoBooleanExpressionsDto extends BaseType { @FilterableField() numberField!: number; } const TestGraphQLComparisonFilter: Class<Filter<TestDto>> = FilterType(TestNoBooleanExpressionsDto); @InputType() class TestComparisonDtoFilter extends TestGraphQLComparisonFilter {} it('should only expose allowed comparisons', async () => { @Resolver() class FilterTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args('input') input: TestComparisonDtoFilter): number { return 1; } } const schema = await generateSchema([FilterTypeSpec]); expect(schema).toMatchSnapshot(); }); }); }); describe('filterRequired option', () => { @ObjectType('TestFilterRequiredComparison') class TestFilterRequiredDto extends BaseType { @FilterableField({ filterRequired: true }) requiredField!: boolean; @FilterableField({ filterRequired: false }) nonRequiredField!: Date; @FilterableField() notSpecifiedField!: number; } const TestGraphQLComparisonFilter: Class<Filter<TestDto>> = FilterType(TestFilterRequiredDto); @InputType() class TestComparisonDtoFilter extends TestGraphQLComparisonFilter {} it('should only expose allowed comparisons', async () => { @Resolver() class FilterTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args('input') input: TestComparisonDtoFilter): number { return 1; } } const schema = await generateSchema([FilterTypeSpec]); expect(schema).toMatchSnapshot(); }); }); }); describe('UpdateFilterType', () => { const TestGraphQLFilter: Class<Filter<TestDto>> = UpdateFilterType(TestDto); @InputType() class TestDtoFilter extends TestGraphQLFilter {} it('should throw an error if the class is not annotated with @ObjectType', () => { class TestInvalidFilter {} expect(() => UpdateFilterType(TestInvalidFilter)).toThrow( 'No fields found to create FilterType. Ensure TestInvalidFilter is annotated with @nestjs/graphql @ObjectType', ); }); it('should create the correct filter graphql schema', async () => { @Resolver() class FilterTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args('input') input: TestDtoFilter): number { return 1; } } const schema = await generateSchema([FilterTypeSpec]); expect(schema).toMatchSnapshot(); }); it('should throw an error if no fields are found', () => { @ObjectType('TestNoFields') class TestInvalidFilter {} expect(() => UpdateFilterType(TestInvalidFilter)).toThrow( 'No fields found to create GraphQLFilter for TestInvalidFilter', ); }); it('should throw an error when the field type is unknown', () => { enum EnumField { ONE = 'one', } @ObjectType('TestBadField') class TestInvalidFilter { @FilterableField(() => EnumField) fakeType!: EnumField; } expect(() => UpdateFilterType(TestInvalidFilter)).toThrow( 'Unable to create filter comparison for {"ONE":"one"}.', ); }); it('should convert and filters to filter class', () => { const filterObject: Filter<TestDto> = { and: [{ stringField: { eq: 'foo' } }], }; const filterInstance = plainToClass(TestDtoFilter, filterObject); expect(filterInstance.and![0]).toBeInstanceOf(TestGraphQLFilter); }); it('should convert or filters to filter class', () => { const filterObject: Filter<TestDto> = { or: [{ stringField: { eq: 'foo' } }], }; const filterInstance = plainToClass(TestDtoFilter, filterObject); expect(filterInstance.or![0]).toBeInstanceOf(TestGraphQLFilter); }); }); describe('DeleteFilterType', () => { const TestGraphQLFilter: Class<Filter<TestDto>> = DeleteFilterType(TestDto); @InputType() class TestDtoFilter extends TestGraphQLFilter {} it('should throw an error if the class is not annotated with @ObjectType', () => { class TestInvalidFilter {} expect(() => DeleteFilterType(TestInvalidFilter)).toThrow( 'No fields found to create FilterType. Ensure TestInvalidFilter is annotated with @nestjs/graphql @ObjectType', ); }); it('should create the correct filter graphql schema', async () => { @Resolver() class FilterTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args('input') input: TestDtoFilter): number { return 1; } } const schema = await generateSchema([FilterTypeSpec]); expect(schema).toMatchSnapshot(); }); it('should throw an error if no fields are found', () => { @ObjectType('TestNoFields') class TestInvalidFilter {} expect(() => DeleteFilterType(TestInvalidFilter)).toThrow( 'No fields found to create GraphQLFilter for TestInvalidFilter', ); }); it('should throw an error when the field type is unknown', () => { enum EnumField { ONE = 'one', } @ObjectType('TestBadField') class TestInvalidFilter { @FilterableField(() => EnumField) fakeType!: EnumField; } expect(() => DeleteFilterType(TestInvalidFilter)).toThrow( 'Unable to create filter comparison for {"ONE":"one"}.', ); }); it('should convert and filters to filter class', () => { const filterObject: Filter<TestDto> = { and: [{ stringField: { eq: 'foo' } }], }; const filterInstance = plainToClass(TestDtoFilter, filterObject); expect(filterInstance.and![0]).toBeInstanceOf(TestGraphQLFilter); }); it('should convert or filters to filter class', () => { const filterObject: Filter<TestDto> = { or: [{ stringField: { eq: 'foo' } }], }; const filterInstance = plainToClass(TestDtoFilter, filterObject); expect(filterInstance.or![0]).toBeInstanceOf(TestGraphQLFilter); }); }); describe('SubscriptionFilterType', () => { const TestGraphQLFilter: Class<Filter<TestDto>> = SubscriptionFilterType(TestDto); @InputType() class TestDtoFilter extends TestGraphQLFilter {} it('should throw an error if the class is not annotated with @ObjectType', () => { class TestInvalidFilter {} expect(() => SubscriptionFilterType(TestInvalidFilter)).toThrow( 'No fields found to create FilterType. Ensure TestInvalidFilter is annotated with @nestjs/graphql @ObjectType', ); }); it('should create the correct filter graphql schema', async () => { @Resolver() class FilterTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args('input') input: TestDtoFilter): number { return 1; } } const schema = await generateSchema([FilterTypeSpec]); expect(schema).toMatchSnapshot(); }); it('should throw an error if no fields are found', () => { @ObjectType('TestNoFields') class TestInvalidFilter {} expect(() => SubscriptionFilterType(TestInvalidFilter)).toThrow( 'No fields found to create GraphQLFilter for TestInvalidFilter', ); }); it('should throw an error when the field type is unknown', () => { enum EnumField { ONE = 'one', } @ObjectType('TestBadField') class TestInvalidFilter { @FilterableField(() => EnumField) fakeType!: EnumField; } expect(() => SubscriptionFilterType(TestInvalidFilter)).toThrow( 'Unable to create filter comparison for {"ONE":"one"}.', ); }); it('should convert and filters to filter class', () => { const filterObject: Filter<TestDto> = { and: [{ stringField: { eq: 'foo' } }], }; const filterInstance = plainToClass(TestDtoFilter, filterObject); expect(filterInstance.and![0]).toBeInstanceOf(TestGraphQLFilter); }); it('should convert or filters to filter class', () => { const filterObject: Filter<TestDto> = { or: [{ stringField: { eq: 'foo' } }], }; const filterInstance = plainToClass(TestDtoFilter, filterObject); expect(filterInstance.or![0]).toBeInstanceOf(TestGraphQLFilter); }); }); });
the_stack
import { OperationParameter, OperationURLParameter, OperationQueryParameter } from "@azure/core-client"; import { Workflow as WorkflowMapper, GenerateUpgradedDefinitionParameters as GenerateUpgradedDefinitionParametersMapper, GetCallbackUrlParameters as GetCallbackUrlParametersMapper, WorkflowReference as WorkflowReferenceMapper, RegenerateActionParameter as RegenerateActionParameterMapper, SetTriggerStateActionDefinition as SetTriggerStateActionDefinitionMapper, IntegrationAccount as IntegrationAccountMapper, ListKeyVaultKeysDefinition as ListKeyVaultKeysDefinitionMapper, TrackingEventsDefinition as TrackingEventsDefinitionMapper, AssemblyDefinition as AssemblyDefinitionMapper, BatchConfiguration as BatchConfigurationMapper, IntegrationAccountSchema as IntegrationAccountSchemaMapper, IntegrationAccountMap as IntegrationAccountMapMapper, IntegrationAccountPartner as IntegrationAccountPartnerMapper, IntegrationAccountAgreement as IntegrationAccountAgreementMapper, IntegrationAccountCertificate as IntegrationAccountCertificateMapper, IntegrationAccountSession as IntegrationAccountSessionMapper, IntegrationServiceEnvironment as IntegrationServiceEnvironmentMapper, IntegrationServiceEnvironmentManagedApi as IntegrationServiceEnvironmentManagedApiMapper } from "../models/mappers"; export const accept: OperationParameter = { parameterPath: "accept", mapper: { defaultValue: "application/json", isConstant: true, serializedName: "Accept", type: { name: "String" } } }; export const $host: OperationURLParameter = { parameterPath: "$host", mapper: { serializedName: "$host", required: true, type: { name: "String" } }, skipEncoding: true }; export const subscriptionId: OperationURLParameter = { parameterPath: "subscriptionId", mapper: { serializedName: "subscriptionId", required: true, type: { name: "String" } } }; export const apiVersion: OperationQueryParameter = { parameterPath: "apiVersion", mapper: { defaultValue: "2019-05-01", isConstant: true, serializedName: "api-version", type: { name: "String" } } }; export const top: OperationQueryParameter = { parameterPath: ["options", "top"], mapper: { serializedName: "$top", type: { name: "Number" } } }; export const filter: OperationQueryParameter = { parameterPath: ["options", "filter"], mapper: { serializedName: "$filter", type: { name: "String" } } }; export const resourceGroupName: OperationURLParameter = { parameterPath: "resourceGroupName", mapper: { serializedName: "resourceGroupName", required: true, type: { name: "String" } } }; export const workflowName: OperationURLParameter = { parameterPath: "workflowName", mapper: { serializedName: "workflowName", required: true, type: { name: "String" } } }; export const contentType: OperationParameter = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/json", isConstant: true, serializedName: "Content-Type", type: { name: "String" } } }; export const workflow: OperationParameter = { parameterPath: "workflow", mapper: WorkflowMapper }; export const parameters: OperationParameter = { parameterPath: "parameters", mapper: GenerateUpgradedDefinitionParametersMapper }; export const listCallbackUrl: OperationParameter = { parameterPath: "listCallbackUrl", mapper: GetCallbackUrlParametersMapper }; export const move: OperationParameter = { parameterPath: "move", mapper: WorkflowReferenceMapper }; export const keyType: OperationParameter = { parameterPath: "keyType", mapper: RegenerateActionParameterMapper }; export const validate: OperationParameter = { parameterPath: "validate", mapper: WorkflowMapper }; export const location: OperationURLParameter = { parameterPath: "location", mapper: { serializedName: "location", required: true, type: { name: "String" } } }; export const nextLink: OperationURLParameter = { parameterPath: "nextLink", mapper: { serializedName: "nextLink", required: true, type: { name: "String" } }, skipEncoding: true }; export const versionId: OperationURLParameter = { parameterPath: "versionId", mapper: { serializedName: "versionId", required: true, type: { name: "String" } } }; export const triggerName: OperationURLParameter = { parameterPath: "triggerName", mapper: { serializedName: "triggerName", required: true, type: { name: "String" } } }; export const setState: OperationParameter = { parameterPath: "setState", mapper: SetTriggerStateActionDefinitionMapper }; export const parameters1: OperationParameter = { parameterPath: ["options", "parameters"], mapper: GetCallbackUrlParametersMapper }; export const historyName: OperationURLParameter = { parameterPath: "historyName", mapper: { serializedName: "historyName", required: true, type: { name: "String" } } }; export const runName: OperationURLParameter = { parameterPath: "runName", mapper: { serializedName: "runName", required: true, type: { name: "String" } } }; export const actionName: OperationURLParameter = { parameterPath: "actionName", mapper: { serializedName: "actionName", required: true, type: { name: "String" } } }; export const repetitionName: OperationURLParameter = { parameterPath: "repetitionName", mapper: { serializedName: "repetitionName", required: true, type: { name: "String" } } }; export const requestHistoryName: OperationURLParameter = { parameterPath: "requestHistoryName", mapper: { serializedName: "requestHistoryName", required: true, type: { name: "String" } } }; export const operationId: OperationURLParameter = { parameterPath: "operationId", mapper: { serializedName: "operationId", required: true, type: { name: "String" } } }; export const integrationAccountName: OperationURLParameter = { parameterPath: "integrationAccountName", mapper: { serializedName: "integrationAccountName", required: true, type: { name: "String" } } }; export const integrationAccount: OperationParameter = { parameterPath: "integrationAccount", mapper: IntegrationAccountMapper }; export const parameters2: OperationParameter = { parameterPath: "parameters", mapper: GetCallbackUrlParametersMapper }; export const listKeyVaultKeys: OperationParameter = { parameterPath: "listKeyVaultKeys", mapper: ListKeyVaultKeysDefinitionMapper }; export const logTrackingEvents: OperationParameter = { parameterPath: "logTrackingEvents", mapper: TrackingEventsDefinitionMapper }; export const regenerateAccessKey: OperationParameter = { parameterPath: "regenerateAccessKey", mapper: RegenerateActionParameterMapper }; export const assemblyArtifactName: OperationURLParameter = { parameterPath: "assemblyArtifactName", mapper: { serializedName: "assemblyArtifactName", required: true, type: { name: "String" } } }; export const assemblyArtifact: OperationParameter = { parameterPath: "assemblyArtifact", mapper: AssemblyDefinitionMapper }; export const batchConfigurationName: OperationURLParameter = { parameterPath: "batchConfigurationName", mapper: { serializedName: "batchConfigurationName", required: true, type: { name: "String" } } }; export const batchConfiguration: OperationParameter = { parameterPath: "batchConfiguration", mapper: BatchConfigurationMapper }; export const schemaName: OperationURLParameter = { parameterPath: "schemaName", mapper: { serializedName: "schemaName", required: true, type: { name: "String" } } }; export const schema: OperationParameter = { parameterPath: "schema", mapper: IntegrationAccountSchemaMapper }; export const listContentCallbackUrl: OperationParameter = { parameterPath: "listContentCallbackUrl", mapper: GetCallbackUrlParametersMapper }; export const mapName: OperationURLParameter = { parameterPath: "mapName", mapper: { serializedName: "mapName", required: true, type: { name: "String" } } }; export const map: OperationParameter = { parameterPath: "map", mapper: IntegrationAccountMapMapper }; export const partnerName: OperationURLParameter = { parameterPath: "partnerName", mapper: { serializedName: "partnerName", required: true, type: { name: "String" } } }; export const partner: OperationParameter = { parameterPath: "partner", mapper: IntegrationAccountPartnerMapper }; export const agreementName: OperationURLParameter = { parameterPath: "agreementName", mapper: { serializedName: "agreementName", required: true, type: { name: "String" } } }; export const agreement: OperationParameter = { parameterPath: "agreement", mapper: IntegrationAccountAgreementMapper }; export const certificateName: OperationURLParameter = { parameterPath: "certificateName", mapper: { serializedName: "certificateName", required: true, type: { name: "String" } } }; export const certificate: OperationParameter = { parameterPath: "certificate", mapper: IntegrationAccountCertificateMapper }; export const sessionName: OperationURLParameter = { parameterPath: "sessionName", mapper: { serializedName: "sessionName", required: true, type: { name: "String" } } }; export const session: OperationParameter = { parameterPath: "session", mapper: IntegrationAccountSessionMapper }; export const resourceGroup: OperationURLParameter = { parameterPath: "resourceGroup", mapper: { serializedName: "resourceGroup", required: true, type: { name: "String" } } }; export const integrationServiceEnvironmentName: OperationURLParameter = { parameterPath: "integrationServiceEnvironmentName", mapper: { serializedName: "integrationServiceEnvironmentName", required: true, type: { name: "String" } } }; export const integrationServiceEnvironment: OperationParameter = { parameterPath: "integrationServiceEnvironment", mapper: IntegrationServiceEnvironmentMapper }; export const apiName: OperationURLParameter = { parameterPath: "apiName", mapper: { serializedName: "apiName", required: true, type: { name: "String" } } }; export const integrationServiceEnvironmentManagedApi: OperationParameter = { parameterPath: "integrationServiceEnvironmentManagedApi", mapper: IntegrationServiceEnvironmentManagedApiMapper };
the_stack
import { toQueryString } from "../../utils"; import { SdkClient } from "../common/sdk-client"; import { AssetManagementModels } from "./asset-models"; /** * Service for configuring, reading and managing assets, asset ~ and aspect types. * * @export * @class AssetManagementClient * @extends {SdkClient} */ export class AssetManagementClient extends SdkClient { private _baseUrl: string = "/api/assetmanagement/v3"; /** * * AspectTypes * * Managing static and dynamic aspect types. * * List all aspect types * * @param {{ * page?: number; * size?: number; * sort?: string; * filter?: string; * ifNoneMatch?: number; * includeShared?: boolean; * }} [params] * @param [params.page] Specifies the requested page index * @param [params.size] Specifies the number of elements in a page * @param [params.sort] Specifies the ordering of returned elements * @param [params.filter] Specifies the additional filtering criteria * @param [params.ifnonematch] ETag hash of previous request to allow caching * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @example await assetManagement.GetAspectTypes(); * @example await assetManagement.GetAspectTypes({filter: "id eq mdsp.wing"}); * @returns {Promise<AssetManagementModels.AspectTypeListResource>} * * @memberOf AssetManagementClient */ public async GetAspectTypes(params?: { page?: number; size?: number; sort?: string; filter?: string; ifNoneMatch?: number; includeShared?: boolean; }): Promise<AssetManagementModels.AspectTypeListResource> { const parameters = params || {}; const { page, size, sort, filter, ifNoneMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/aspecttypes?${toQueryString({ page, size, sort, filter, includeShared })}`, additionalHeaders: { "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.AspectTypeListResource; } /** * * AspectTypes * * Create or Update an aspect type. * Only adding variables supported. * User can increase the length of a static STRING variable. * The length cannot be decreased. * The length of a dynamic STRING variable cannot be changed. * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9","_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {AssetManagementModels.AspectType} aspectType aspect type * @param {{ ifMatch?: string; ifNoneMatch?: string, includeShared?:boolean }} [params] * @param {{number}} [params.ifMatch] Last known version to facilitate optimistic locking. Required for modification. * @param {{number}} [params.ifNoneMatch] Set ifNoneMatch header to"*" for ensuring create request * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * * @returns {Promise<AssetManagementModels.AspectTypeResource>} * * @example await am.PutAspectType ("mdsp.EnvironmentAspects", myAspectType, {ifNoneMatch:"*"}) * @memberOf AssetManagementClient */ public async PutAspectType( id: string, aspectType: AssetManagementModels.AspectType, params?: { ifMatch?: string; ifNoneMatch?: string; includeShared?: boolean } ): Promise<AssetManagementModels.AspectTypeResource> { const parameters = params || {}; const { ifMatch, ifNoneMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/aspecttypes/${id}?${toQueryString({ includeShared })}`, body: aspectType, additionalHeaders: { "If-Match": ifMatch, "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.AspectTypeResource; } /** * * AspectTypes * * Patch an aspect type. Only adding variables supported. * Patching requires the inclusion of already existing variables. * Other fields may be omitted. Conforms to RFC 7396 - JSON merge Patch. * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9","_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {AssetManagementModels.AspectType} aspectType aspect type * @param {{ ifMatch: string, includeShared?: boolean}} params * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @param {{number}} params.ifMatch Last known version to facilitate optimistic locking. Required for modification. * @returns {Promise<AssetManagementModels.AspectTypeResource>} * * @example await am.PatchAspectType ("mdsp.EnvironmentAspect", myAspectType, {ifMatch:"0"}) * @memberOf AssetManagementClient */ public async PatchAspectType( id: string, aspectType: AssetManagementModels.AspectType, params: { ifMatch: string; includeShared?: boolean } ): Promise<AssetManagementModels.AspectTypeResource> { const parameters = params || {}; const { ifMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "PATCH", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/aspecttypes/${id}?${toQueryString({ includeShared })}`, body: aspectType, additionalHeaders: { "If-Match": ifMatch, "Content-Type": "application/merge-patch+json" }, }); return result as AssetManagementModels.AspectTypeResource; } /** * * AspectTypes * * Delete an aspect type. Aspect type can only be deleted if there is no asset type using it. * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9","_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {{ ifMatch: string, includeShared?: boolean }} params * @param {{ ifMatch: string }} params.ifMatch Last known version to facilitate optimistic locking, required for deleting * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<Object>} - return empty object * * @example await am.DeleteAspectType("mdsp.EnvironmentAspect", {ifMatch:0}) * @memberOf AssetManagementClient * */ public async DeleteAspectType(id: string, params: { ifMatch: string; includeShared?: boolean }) { const parameters = params || {}; const { ifMatch, includeShared } = parameters; await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/aspecttypes/${id}?${toQueryString({ includeShared })}`, additionalHeaders: { "If-Match": ifMatch }, noResponse: true, }); } /** * * AspectTypes * * Read an aspect type. * * @param {string} id he type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9","_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {{ ifNoneMatch?: number, includeShared?: boolean }} [params] ETag hash of previous request to allow caching * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<AssetManagementModels.AspectTypeResource>} * * @example await am.GetAspectType("mdsp.EnvironmentAspect") * @memberOf AssetManagementClient */ public async GetAspectType( id: string, params?: { ifNoneMatch?: number; includeShared?: boolean } ): Promise<AssetManagementModels.AspectTypeResource> { const parameters = params || {}; const { ifNoneMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/aspecttypes/${id}?${toQueryString({ includeShared })}`, additionalHeaders: { "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.AspectTypeResource; } /** * * AssetTypes * ! important: the default setting for inherited properties is false * ! important: @see [params.exploded] * * List all asset types * * @param {{ * page?: number; * size?: number; * sort?: string; * filter?: string; * ifNoneMatch?: number; * exploded?: boolean; * includeShared? boolean; * }} [params] * @param [params.page] Specifies the requested page index * @param [params.size] Specifies the number of elements in a page * @param [params.sort] Specifies the ordering of returned elements * @param [params.filter] Specifies the additional filtering criteria * @param [params.ifnonematch] ETag hash of previous request to allow caching * @param [params.exploded] Specifies if the asset type should include all of it’s inherited variables and aspects. Default is false. * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * * @example await assetManagement.GetAssetTypes(); * @example await assetManagement.GetAssetTypes({filter: "id eq mdsp.spaceship"}); * @returns {Promise<AssetManagementModels.AssetTypeListResource>} * * @memberOf AssetManagementClient * */ public async GetAssetTypes(params?: { page?: number; size?: number; sort?: string; filter?: string; ifNoneMatch?: string; exploded?: boolean; includeShared?: boolean; }): Promise<AssetManagementModels.AssetTypeListResource> { const parameters = params || {}; const { page, size, sort, filter, ifNoneMatch, exploded, includeShared } = parameters; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assettypes?${toQueryString({ page, size, sort, filter, exploded, includeShared, })}`, additionalHeaders: { "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.AssetTypeListResource; } /** * * AssetTypes * * Create or Update an asset type * User can increase the length of a STRING variable. * The length cannot be decreased. * * @param {string} id * @param {AssetManagementModels.AssetType} assetType * @param {{ ifMatch?: string; ifNoneMatch?: string; exploded?: boolean }} [params] * @param {{number}} [params.ifMatch] Last known version to facilitate optimistic locking. Required for modification. * @param {{string}} [params.ifNoneMatch] Set ifNoneMatch header to "*"" for ensuring create request * @param {{boolean}} [params.exploded] Specifies if the asset type should include all of inherited variables and aspects. Default is false. * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<AssetManagementModels.AssetTypeResource>} * * @example await am.PutAssetType("mdsp.SimulationEngine", myAssetType) * @memberOf AssetManagementClient */ public async PutAssetType( id: string, assetType: AssetManagementModels.AssetType, params?: { ifMatch?: string; ifNoneMatch?: string; exploded?: boolean; includeShared?: boolean } ): Promise<AssetManagementModels.AssetTypeResource> { const parameters = params || {}; const { ifMatch, ifNoneMatch, exploded, includeShared } = parameters; const result = await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assettypes/${id}?${toQueryString({ exploded, includeShared })}`, body: assetType, additionalHeaders: { "If-Match": ifMatch, "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.AssetTypeResource; } /** * * AssetTypes * * Patch an asset type. * Patching requires the inclusion of all existing variables and aspects. * Missing file assignments will be deleted. * Other fields may be omitted. Conforms to RFC 7396 - JSON merge Patch. * * @param {string} id * @param {AssetManagementModels.AssetType} assetType * @param {{ ifMatch: string; exploded?: boolean; includeShared?:boolean }} params * @param {{number}} [params.ifMatch] Last known version to facilitate optimistic locking. Required for modification. * @param {{boolean}} [params.exploded] Specifies if the asset type should include all of inherited variables and aspects. Default is false. * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<AssetManagementModels.AssetTypeResource>} * * @example await am.PatchAssetType("mdsp.SimulationEngine", myAssetType) * @memberOf AssetManagementClient */ public async PatchAssetType( id: string, assetType: AssetManagementModels.AssetType, params: { ifMatch: string; exploded?: boolean; includeShared?: boolean } ): Promise<AssetManagementModels.AssetTypeResource> { const parameters = params || {}; const { ifMatch, exploded, includeShared } = parameters; const result = await this.HttpAction({ verb: "PATCH", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assettypes/${id}?${toQueryString({ exploded, includeShared })}`, body: assetType, additionalHeaders: { "If-Match": ifMatch, "Content-Type": "application/merge-patch+json" }, }); return result as AssetManagementModels.AssetTypeResource; } /** * * AssetTypes * * Deletes an asset type. * Deletion only possible when the type has no child-type and there is no asset that instantiate it. * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9", "_' and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {{ ifMatch: string; includeShared?:boolean; }} params * @param {{number}} params.ifMatch Last known version to facilitate optimistic locking, required for deleting * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * * @example await am.DeleteAssetType("mdsp.SimulationEnigine", {ifMatch:0}) * @memberOf AssetManagementClient * */ public async DeleteAssetType(id: string, params: { ifMatch: string; includeShared?: boolean }) { const parameters = params || {}; const { ifMatch, includeShared } = parameters; await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assettypes/${id}?${toQueryString({ includeShared })}`, additionalHeaders: { "If-Match": ifMatch }, noResponse: true, }); } /** * * AssetTypes * * Read an asset type * ! important: the default setting for inherited properties is false * ! important: @see [params.exploded] * * @param {string} id * @param {{ ifNoneMatch?: string; exploded?: boolean; includeShared?: boolean }} [params] * @returns {Promise<AssetManagementModels.AssetTypeResource>} * * @example await am.GetAssetType("mdsp.SimulationEngine") * @memberOf AssetManagementClient */ public async GetAssetType( id: string, params?: { ifNoneMatch?: string; exploded?: boolean; includeShared?: boolean } ): Promise<AssetManagementModels.AssetTypeResource> { const parameters = params || {}; const { ifNoneMatch, exploded, includeShared } = parameters; const ex = exploded === undefined ? false : exploded; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assettypes/${id}?${toQueryString({ exploded: ex, includeShared })}`, additionalHeaders: { "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.AssetTypeResource; } /** * * AssetTypes * * Add a new file assignment to a given asset type. All asset which extends these types will have its file by default. * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9", "_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {string} key Keyword for the file to be assigned to an asset or asset type. * @param {AssetManagementModels.KeyedFileAssignment} assignment Data for file assignment * @param {{ ifMatch: string ; includeShared?: boolean}} params * @param {{number}} params.ifMatch Last known version to facilitate optimistic locking * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<AssetManagementModels.AssetTypeResource>} * * @memberOf AssetManagementClient */ public async PutAssetTypeFileAssignment( id: string, key: string, assignment: AssetManagementModels.KeyedFileAssignment, params: { ifMatch: string; includeShared?: boolean } ): Promise<AssetManagementModels.AssetTypeResource> { const parameters = params || {}; const { ifMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assettypes/${id}/fileAssignments/${key}?${toQueryString({ includeShared })}`, body: assignment, additionalHeaders: { "If-Match": ifMatch }, }); return result as AssetManagementModels.AssetTypeResource; } /** * *AssetTypes * * Deletes a file assignment from an asset type. * If the type parent has defined a file with the same key, the key will be displayed with the inherited value. * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9","_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {string} key Keyword for the file to be assigned to an asset or asset type. * @param {AssetManagementModels.KeyedFileAssignment} assignment Data for file assignment * @param {{ ifMatch: string; includeShared?: boolean }} params * @param {{number}} params.ifMatch Last known version to facilitate optimistic locking * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * * @memberOf AssetManagementClient */ public async DeleteAssetTypeFileAssignment( id: string, key: string, params: { ifMatch: string; includeShared?: boolean } ) { const parameters = params || {}; const { ifMatch, includeShared } = parameters; await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assettypes/${id}/fileAssignments/${key}?${toQueryString({ includeShared })}`, additionalHeaders: { "If-Match": ifMatch }, noResponse: true, }); } /** * * AssetTypes * * Updates an existing variable defined on an asset type. Variables cannot be added or deleted using this operation, * for adding or deleting variables use patch/put assettype api. Any variable which is not part of the request will remain unchanged * Variable's Name, Length, Default Value and Unit can be changed. The unit changes from the api does not compute any value changes * derived after the unit changes, the values will remain as it is and only the unit will be updated. * The length can only be increased of a string variable and it cannot be decreased. * This operation will increment the asset type etag value. * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9","_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {{ ifMatch: string; includeShared?: boolean }} params * @param {{number}} params.ifMatch Last known version to facilitate optimistic locking * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @param {AssetManagementModels.VariableUpdateMap} variableMap * @returns {Promise<Headers>} * * @memberOf AssetManagementClient */ public async PatchAssetTypeVariable( id: string, variableMap: AssetManagementModels.VariableUpdateMap, params: { ifMatch: string; includeShared?: boolean } ): Promise<Headers> { const parameters = params || {}; const { ifMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "PATCH", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assettypes/${id}/variables?${toQueryString({ includeShared })}`, body: variableMap, returnHeaders: true, additionalHeaders: { "If-Match": ifMatch, "Content-Type": "application/merge-patch+json" }, }); return result as Headers; } /** * * Asset * * List all assets available for the authenticated user. * * @param {{ * page?: number; * size?: number; * sort?: string; * filter?: string; * ifNoneMatch?: string; * includeShared? boolean; * }} [params] * @param [params.page] Specifies the requested page index * @param [params.size] Specifies the number of elements in a page * @param [params.sort] Specifies the ordering of returned elements * @param [params.filter] Specifies the additional filtering criteria * @param [params.ifnonematch] ETag hash of previous request to allow caching * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * * @returns {Promise<AssetManagementModels.AssetListResource>} * * @example await assetManagement.GetAssets(); * @example await assetManagement.GetAssetTypes({filter: "typeid eq mdsp.spaceship"}); * * @memberOf AssetManagementClient */ public async GetAssets(params?: { page?: number; size?: number; sort?: string; filter?: string; ifNoneMatch?: string; includeShared?: boolean; }): Promise<AssetManagementModels.AssetListResource> { const parameters = params || {}; const { page, size, sort, filter, ifNoneMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets?${toQueryString({ page, size, sort, filter, includeShared })}`, additionalHeaders: { "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.AssetListResource; } /** * * Asset * * Creates a new asset with the provided content. Only instantiable types could be used. * @param {{ * includeShared? boolean; * }} [params] * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * * @param {AssetManagementModels.Asset} asset * @returns {Promise<AssetManagementModels.AssetResourceWithHierarchyPath>} * * @example await assetManagement.PostAsset(myasset); * @memberOf AssetManagementClient */ public async PostAsset( asset: AssetManagementModels.Asset, params?: { includeShared?: boolean } ): Promise<AssetManagementModels.AssetResourceWithHierarchyPath> { const parameters = params || {}; const { includeShared } = parameters; const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets?${toQueryString({ includeShared })} `, body: asset, }); return result as AssetManagementModels.AssetResourceWithHierarchyPath; } /** * * Asset * * Read a single asset. All static properties of asset are returned. * * @param {string} assetId Unique identifier * @param {{ ifNoneMatch?: string; includeShared?: boolean}} [params] * @param {{string}} [params.ifNoneMatch] * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<AssetManagementModels.AssetResourceWithHierarchyPath>} * * @memberOf AssetManagementClient */ public async GetAsset( assetId: string, params?: { ifNoneMatch?: string; includeShared?: boolean } ): Promise<AssetManagementModels.AssetResourceWithHierarchyPath> { const parameters = params || {}; const { ifNoneMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${assetId}?${toQueryString({ includeShared })}`, additionalHeaders: { "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.AssetResourceWithHierarchyPath; } /** * * Asset * * Updates an asset with the provided content. * Only values can be modified, asset structure have to be modified in asset type * * @param {string} assetId * @param {AssetManagementModels.AssetUpdate} asset * @param {{ ifMatch: string; includeShared?: boolean }} params * @param {{number}} [params.ifMatch] Last known version to facilitate optimistic locking. Required for modification. * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<AssetManagementModels.AssetResourceWithHierarchyPath>} * * @example await assetManagement.PutAsset (myAsset, {ifMatch: `${myAsset.etag}`}) * * @memberOf AssetManagementClient */ public async PutAsset( assetId: string, asset: AssetManagementModels.AssetUpdate, params: { ifMatch: string; includeShared?: boolean } ): Promise<AssetManagementModels.AssetResourceWithHierarchyPath> { const parameters = params || {}; const { ifMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${assetId}?${toQueryString({ includeShared })}`, body: asset, additionalHeaders: { "If-Match": ifMatch }, }); return result as AssetManagementModels.AssetResourceWithHierarchyPath; } /** * * Asset * * Patch an asset with the provided content. * Only values can be modified, asset structure have to be modified in asset type. * Conforms to RFC 7396 - JSON merge Patch. * * @param {string} assetId * @param {AssetManagementModels.AssetUpdate} asset * @param {{ ifMatch: string; includeShared?: boolean; }} params * @param {{number}} [params.ifMatch] Last known version to facilitate optimistic locking. Required for modification. * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<AssetManagementModels.AssetResourceWithHierarchyPath>} * * @example await assetManagement.Patch (myAsset, {ifMatch: `${myAsset.etag}`}) * * @memberOf AssetManagementClient */ public async PatchAsset( assetId: string, asset: AssetManagementModels.AssetUpdate, params: { ifMatch: string; includeShared?: boolean } ): Promise<AssetManagementModels.AssetResourceWithHierarchyPath> { const parameters = params || {}; const { ifMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "PATCH", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${assetId}?${toQueryString({ includeShared })}`, body: asset, additionalHeaders: { "If-Match": ifMatch, "Content-Type": "application/merge-patch+json" }, }); return result as AssetManagementModels.AssetResourceWithHierarchyPath; } /** * * Asset * * Deletes the given asset. * After deletion only users with admin role can read it, * but modification is not possible anymore. * It is not possible to delete an asset if it has children. * * @param {string} id The type id is a unique identifier. The id s length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9", "_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {{ ifMatch: string; includeShared?: booleanl }} params * @param {{number}} params.ifMatch Last known version to facilitate optimistic locking, required for deleting * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @example await assetManagement.DeleteAsset(id, {ifMatch:0}) * * @memberOf AssetManagementClient */ public async DeleteAsset(id: string, params: { ifMatch: string; includeShared?: boolean }) { const parameters = params || {}; const { ifMatch, includeShared } = parameters; await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${id}?${toQueryString({ includeShared })}`, additionalHeaders: { "If-Match": ifMatch }, noResponse: true, }); } /** * * Asset * * Moves an asset (and all asset children) in the instance hierarchy * * @param {string} assetId * @param {AssetManagementModels.AssetMove} moveParameters * @param {{ ifMatch: string; includeShared?: boolean }} params * @param {{number}} [params.ifMatch] Last known version to facilitate optimistic locking. Required for modification. * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<AssetManagementModels.AssetResourceWithHierarchyPath>} * * @example await assetManagement.PutAsset (myAsset, {ifMatch: `${myAsset.etag}`}) * * @memberOf AssetManagementClient */ public async MoveAsset( assetId: string, moveParameters: AssetManagementModels.AssetMove, params: { ifMatch: string; includeShared?: boolean } ): Promise<AssetManagementModels.AssetResourceWithHierarchyPath> { const parameters = params || {}; const { ifMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${assetId}?${toQueryString({ includeShared })}`, body: moveParameters, additionalHeaders: { "If-Match": ifMatch }, }); return result as AssetManagementModels.AssetResourceWithHierarchyPath; } /** * * Asset * * Save a file assignment to a given asset * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9", "_" and ". * beginning with the tenant prefix what has a maximum of 8 characters. (e.g. ten_pref.type_id) * @param {string} key Keyword for the file to be assigned to an asset or asset type. * @param {AssetManagementModels.KeyedFileAssignment} assignment Data for file assignment * @param {{ ifMatch: string; includeShared ?: boolean; }} params * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @param {{number}} [params.ifMatch] Last known version to facilitate optimistic locking * @returns {Promise<AssetManagementModels.AssetTypeResource>} * * @memberOf AssetManagementClient */ public async PutAssetFileAssignment( id: string, key: string, assignment: AssetManagementModels.KeyedFileAssignment, params: { ifMatch: string; includeShared?: boolean } ): Promise<AssetManagementModels.AssetTypeResource> { const parameters = params || {}; const { ifMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${id}/fileAssignments/${key}?${toQueryString({ includeShared })}`, body: assignment, additionalHeaders: { "If-Match": ifMatch }, }); return result as AssetManagementModels.AssetTypeResource; } /** * * Asset * * Deletes a file assignment from an asset. * If the asset parent type has defined a file with the same key, the key will be displayed with the inherited value. * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9","_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {string} key Keyword for the file to be assigned to an asset or asset type. * @param {AssetManagementModels.KeyedFileAssignment} assignment Data for file assignment * @param {{ ifMatch: string; includeShared?: boolean }} params * @param {{number}} params.ifMatch Last known version to facilitate optimistic locking * * @memberOf AssetManagementClient */ public async DeleteAssetFileAssignment( id: string, key: string, params: { ifMatch: string; includeShared?: boolean } ) { const parameters = params || {}; const { ifMatch, includeShared } = parameters; await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${id}/fileAssignments/${key}?${toQueryString({ includeShared })}`, additionalHeaders: { "If-Match": ifMatch }, noResponse: true, }); } /** * * Asset * Returns the root asset of the user. * Read the root asset of the user, from which the whole asset hierarchy can be rebuilt. * * @returns {Promise<AssetManagementModels.RootAssetResource>} * * @memberOf AssetManagementClient */ public async GetRootAsset(): Promise<AssetManagementModels.RootAssetResource> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/root`, }); return result as AssetManagementModels.RootAssetResource; } /** * * Asset Structure * Get all static and dynamic aspects of a given asset * * @param {string} assetId * @param {{ * page?: number; * size?: number; * sort?: string; * filter?: string; * ifNoneMatch?: number; * includeShared?: number; * }} [params] * @param [params.page] Specifies the requested page index * @param [params.size] Specifies the number of elements in a page * @param [params.sort] Specifies the ordering of returned elements * @param [params.filter] Specifies the additional filtering criteria * @param [params.ifnonematch] ETag hash of previous request to allow caching * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * * @returns {Promise<AssetManagementModels.AspectListResource>} * * @memberOf AssetManagementClient */ public async GetAspects( assetId: string, params?: { page?: number; size?: number; sort?: string; filter?: string; ifNoneMatch?: number; includeShared?: number; } ): Promise<AssetManagementModels.AspectListResource> { const parameters = params || {}; const { page, size, sort, filter, ifNoneMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${assetId}/aspects?${toQueryString({ page, size, sort, filter, includeShared, })}`, additionalHeaders: { "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.AspectListResource; } /** * * Asset Structure * Get all variables of a given asset including inherited ones * * @param {string} assetId * @param {{ * page?: number; * size?: number; * sort?: string; * filter?: string; * ifNoneMatch?: number; * includeShared?: boolean; * }} [params] * @param [params.page] Specifies the requested page index * @param [params.size] Specifies the number of elements in a page * @param [params.sort] Specifies the ordering of returned elements * @param [params.filter] Specifies the additional filtering criteria * @param [params.ifnonematch] ETag hash of previous request to allow caching * @param [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * * @returns {Promise<AssetManagementModels.AspectListResource>} * * @memberOf AssetManagementClient */ public async GetVariables( assetId: string, params?: { page?: number; size?: number; sort?: string; filter?: string; ifNoneMatch?: number; includeShared?: boolean; } ): Promise<AssetManagementModels.VariableListResource> { const parameters = params || {}; const { page, size, sort, filter, ifNoneMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${assetId}/variables?${toQueryString({ page, size, sort, filter, includeShared, })}`, additionalHeaders: { "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.VariableListResource; } /** * * Asset Location * * Create or Update location assigned to given asset * * * If the given asset has own location, this endpoint will update that location. * * If the given asset has no location, this endpoint will create a new location and update the given asset. * * If the given asset has inherited location, this endpoint will create a new location and update the given asset. * * If you wanted to update the inherited location you have to use the location url in AssetResource object (with PUT method). * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9","_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {AssetManagementModels.Location} location Data for location * @param {{ ifMatch: string; includeShared ?: boolean }} params * @param {{number}} params.ifMatch Last known version to facilitate optimistic locking * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<AssetManagementModels.Location>} * * ! fix: 3.11. : the swagger documentation says that the method is returning Location but it returns AssetResourceWithHierarchyPath * * @memberOf AssetManagementClient */ public async PutAssetLocation( id: string, location: AssetManagementModels.Location, params: { ifMatch: string; includeShared?: boolean } ): Promise<AssetManagementModels.AssetResourceWithHierarchyPath> { const parameters = params || {}; const { ifMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${id}/location?${toQueryString({ includeShared })}`, body: location, additionalHeaders: { "If-Match": ifMatch }, }); return result as AssetManagementModels.AssetResourceWithHierarchyPath; } /** * * Asset Location * * Delete location assigned to given asset. * * * Only those locations can be deleted here which assigned to the given asset. * * If the location inherited from an ancestor asset, you have to delete the location with the assigned assetId (using location url in AssetResource object with DELETE method). * * The response contains the updated AssetResource with the inherited Location details. * * @param {string} id The type id is a unique identifier. The id length must be between 1 and 128 characters and matches the following symbols "A-Z", "a-z", "0-9","_" and "." beginning with the tenant prefix what has a maximum of 8 characters. (e.g . ten_pref.type_id) * @param {AssetManagementModels.Location} location Data for location * @param {{ ifMatch: string; includeShared?: boolean }} params * @param {{number}} params.ifMatch Last known version to facilitate optimistic locking * @param {{boolean}} [params.includeShared] Specifies if the operation should take into account shared (received) assets, aspects and asset types. * @returns {Promise<AssetManagementModels.AssetResourceWithHierarchyPath>} * * @memberOf AssetManagementClient */ public async DeleteAssetLocation(id: string, params: { ifMatch: string; includeShared?: boolean }) { const parameters = params || {}; const { ifMatch, includeShared } = parameters; const result = await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/assets/${id}/location?${toQueryString({ includeShared })}`, additionalHeaders: { "If-Match": ifMatch }, }); return result as AssetManagementModels.AssetResourceWithHierarchyPath; } /** * * Asset Files * * Upload files to be used in Asset Management. * * @param {Buffer} file * @param {string} name * @param {{ * scope?: AssetManagementModels.FileMetadataResource.ScopeEnum; * description?: string; * mimeType?: string; * }} [params] * @returns {Promise<AssetManagementModels.FileMetadataResource>} * * @memberOf AssetManagementClient */ public async PostFile( file: Buffer, name: string, params?: { scope?: AssetManagementModels.FileMetadataResource.ScopeEnum; description?: string; mimeType?: string; } ): Promise<AssetManagementModels.FileMetadataResource> { const parameters = params || {}; const { scope, description, mimeType } = parameters; const template = `----mindsphere\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\nContent-Type: ${ mimeType || "application/octet-stream" }\r\n\r\n${file.toString( "ascii" )}\r\n----mindsphere\r\nContent-Disposition: form-data; name="name"\r\n\r\n${name}\r\n----mindsphere\r\nContent-Disposition: form-data; name="description"\r\n\r\n${ description || "uploaded file" }\r\n\----mindsphere\r\nContent-Disposition: form-data; name="scope"\r\n\r\n${ scope || "PRIVATE" }\r\n----mindsphere--`; const result = await this.HttpAction({ verb: "POST", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/files`, body: template, multiPartFormData: true, }); return result as AssetManagementModels.FileMetadataResource; } /** * * Asset files * * Get metadata of uploaded files. * Returns all visible file metadata for the tenant. Will NOT return the files. * * @param {{ * page?: number; * size?: number; * sort?: string; * filter?: string; * ifNoneMatch?: number; * }} [params] * * @param {{ * page?: number; * size?: number; * sort?: string; * filter?: string; * ifNoneMatch?: number; * }} [params] * @param [params.page] Specifies the requested page index * @param [params.size] Specifies the number of elements in a page * @param [params.sort] Specifies the ordering of returned elements * @param [params.filter] Specifies the additional filtering criteria * @param [params.ifnonematch] ETag hash of previous request to allow caching * @returns {Promise<AssetManagementModels.FileMetadataListResource>} * * @memberOf AssetManagementClient */ public async GetFiles(params?: { page?: number; size?: number; sort?: string; filter?: string; ifNoneMatch?: number; }): Promise<AssetManagementModels.FileMetadataListResource> { const parameters = params || {}; const { page, size, sort, filter, ifNoneMatch } = parameters; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/files?${toQueryString({ page, size, sort, filter })}`, additionalHeaders: { "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.FileMetadataListResource; } /** * * Asset Files * * Get metadata of uploaded files. * * @param {string} fileId * @param {{ * ifNoneMatch?: number; * }} [params] * @returns {Promise<AssetManagementModels.FileMetadataResource>} * * @memberOf AssetManagementClient */ public async GetFile( fileId: string, params?: { ifNoneMatch?: number; } ): Promise<AssetManagementModels.FileMetadataResource> { const parameters = params || {}; const { ifNoneMatch } = parameters; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/files/${fileId}`, additionalHeaders: { "If-None-Match": ifNoneMatch }, }); return result as AssetManagementModels.FileMetadataResource; } /** * Returns a file by its id * * @param {string} fileId * @param {{ * ifNoneMatch?: number; * }} [params] * @returns {Promise<Response>} Response Context Type is base64 * * @memberOf AssetManagementClient */ public async DownloadFile( fileId: string, params?: { ifNoneMatch?: number; } ): Promise<Response> { const parameters = params || {}; const { ifNoneMatch } = parameters; const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/files/${fileId}/file`, additionalHeaders: { "If-None-Match": ifNoneMatch }, rawResponse: true, }); return result as Response; } /** * * Asset Files * * Update a previously uploaded file. * Max file size is 5 MB. * * @param {string} fileid * @param {Buffer} file * @param {string} name * @param {{ * scope: AssetManagementModels.FileMetadataResource.ScopeEnum; * description?: string; * mimeType?: string; * ifMatch: string; * }} params * @returns {Promise<AssetManagementModels.FileMetadataResource>} * * @memberOf AssetManagementClient */ public async PutFile( fileid: string, file: Buffer, name: string, params: { scope: AssetManagementModels.FileMetadataResource.ScopeEnum; description?: string; mimeType?: string; ifMatch: string; } ): Promise<AssetManagementModels.FileMetadataResource> { const parameters = params || {}; const { scope, description, mimeType, ifMatch } = parameters; const template = `----mindsphere\r\nContent-Disposition: form-data; name="file"; filename="${name}"\r\nContent-Type: ${ mimeType || "application/octet-stream" }\r\n\r\n${file}\r\n----mindsphere\r\nContent-Disposition: form-data; name="name"\r\n\r\n${name}\r\n----mindsphere\r\nContent-Disposition: form-data; name="description"\r\n\r\n${ description || "uploaded file" }\r\n\----mindsphere\r\nContent-Disposition: form-data; name="scope"\r\n\r\n${ scope || "PRIVATE" }\r\n----mindsphere--`; const result = await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/files/${fileid}`, body: template, multiPartFormData: true, additionalHeaders: { "If-Match": ifMatch }, }); return result as AssetManagementModels.FileMetadataResource; } /** * * Asset Files * * Delete a file * Deletion is blocked if there are any file assignment with the given fileId. * * @param {string} fileId * @param {{ ifMatch: string }} params * * @memberOf AssetManagementClient */ public async DeleteFile(fileId: string, params: { ifMatch: string }) { const parameters = params || {}; const { ifMatch } = parameters; await this.HttpAction({ verb: "DELETE", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/files/${fileId}`, additionalHeaders: { "If-Match": ifMatch }, noResponse: true, }); } /** * * Model Lock * * Provides lock state of an asset model at tenant level. * * @returns {Promise<AssetManagementModels.AssetModelLock>} * * @memberOf AssetManagementClient */ public async GetModelLock(): Promise<AssetManagementModels.AssetModelLock> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/model/lock`, }); return result as AssetManagementModels.AssetModelLock; } /** * * * Model Lock * * Enable/disable lock state of asset model at tenant level, managing restrictions on update/delete operations on assettypes and aspecttypes. * * @param {{ enabled: boolean }} params * @returns {Promise<AssetManagementModels.AssetModelLock>} * * @memberOf AssetManagementClient */ public async PutModelLock(params: { enabled: boolean }): Promise<AssetManagementModels.AssetModelLock> { const parameters = params || {}; const result = await this.HttpAction({ verb: "PUT", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/model/lock?${toQueryString(parameters)}`, }); return result as AssetManagementModels.AssetModelLock; } /** * List all links for available resources * * @returns {Promise<AssetManagementModels.BillboardResource>} * * @memberOf AssetManagementClient */ public async GetBillboard(): Promise<AssetManagementModels.BillboardResource> { const result = await this.HttpAction({ verb: "GET", gateway: this.GetGateway(), authorization: await this.GetToken(), baseUrl: `${this._baseUrl}/`, }); return result as AssetManagementModels.BillboardResource; } }
the_stack
type uint8 = number; /* uint8 */ type uint32 = number; /* uint32 */ let maxUint32 = 4294967295 class uint64 { /* uint64 */ high: uint32; low: uint32; constructor(high: uint32, low: uint32) { this.high = high; this.low = low; } add(y: uint64): void { let low = this.low + y.low; let high = this.high + y.high + Math.trunc(low / (maxUint32 + 1)) low &= maxUint32; this.low = low; this.high = high; } lt(y: uint64): boolean { return (this.high < y.high || (this.high == y.high && this.low < y.low)); } sub(y: uint64) : void { if (this.lt(y)) { throw new Error("cannot subtract greater integer"); } let low = this.low - y.low; let high = this.high - y.high; if (low < 0) { low - 1; high += maxUint32; } this.low = low; this.high = high; } } function add64(x: uint64, y: uint64): uint64 { let res = new uint64(x.high, x.low); res.add(y); return res; } function sub64(x: uint64, y: uint64): uint64 { let res = new uint64(x.high, x.low); res.sub(y); return res; } interface ByteArrayIndex { /* 2D coordinates, MUST NOT be considered as a uint64 because not all subarrays of a byte array are full */ first: uint32; second: uint32; } function copyIndex(x: ByteArrayIndex) : ByteArrayIndex { return {first: x.first, second: x.second}; } let hexits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] class ByteArray { public bytes: uint8[][]; constructor(x: uint8[]) { this.bytes = [x]; } byteAt (index: ByteArrayIndex) : uint8 { let tindex : ByteArrayIndex = copyIndex(index); while (tindex.first < this.bytes.length && tindex.second == this.bytes[tindex.first].length) { tindex.first++; tindex.second = 0; } if (tindex.first >= this.bytes.length) { throw new Error("byteAt: high out of bounds"); } if (tindex.second >= this.bytes[tindex.first].length) { throw new Error("byteAt: low out of bounds"); } return this.bytes[tindex.first][tindex.second]; } length () : uint64 { let res : uint64 = new uint64(0, 0); let i : uint32 = 0; for (; i < this.bytes.length; ++i) { // console.log(new uint64(0, this.bytes[i].length)); res.add(new uint64(0, this.bytes[i].length)); } // console.log("!!") // console.log(res) return res; } concat (y: ByteArray) : void { if (this.bytes.length > 0 && y.bytes.length == 1 && this.bytes[this.bytes.length - 1].length + y.bytes[0].length <= maxUint32) { this.bytes[this.bytes.length - 1] = this.bytes[this.bytes.length - 1].concat(y.bytes[0]); } else { /* TODO: pack this.bytes and y.bytes first? */ this.bytes = this.bytes.concat(y.bytes); } } validIndex (x: ByteArrayIndex) : boolean { return (x.first < this.bytes.length && x.second < this.bytes[x.first].length); } dist (x: ByteArrayIndex, y: ByteArrayIndex) : uint64 { // console.log("starting slicelength") /* assume x <= y */ let temp : ByteArrayIndex = {first: x.first, second: x.second}; let res : uint64 = new uint64(0, 0); while (temp.first <= y.first) { // console.log("going from " + x.first + " " + x.second + " to " + y.first + " " + y.second) if(x.first == y.first) { let diff = y.second - x.second // console.log("adding diff 0 : " + diff) res.add(new uint64(0, diff)) } else if(temp.first == x.first) { if (temp.second <= this.bytes[temp.first].length) { let diff = this.bytes[temp.first].length - x.second // console.log("length " + this.bytes[temp.first].length) // console.log("adding diff 1 : " + diff) res.add(new uint64(0, diff)) } } else if(temp.first < y.first) { let diff = this.bytes[temp.first].length // console.log("adding diff 2: " + diff) res.add(new uint64(0, diff)) } else if(temp.first == y.first) { if (temp.second <= this.bytes[temp.first].length) { let diff = this.bytes[temp.first].length - y.second // console.log("adding diff 3: " + diff) res.add(new uint64(0, diff)) } } else { throw new Error("slice length failure, unknown case") } temp.first++; temp.second = 0; } // console.log("slice length result: " + res.low) return res; } shiftIndex (x: ByteArrayIndex, y: uint32) { let tx : ByteArrayIndex = {first: x.first, second: x.second}; let ty : uint32 = y; while (ty > 0 && tx.first < this.bytes.length) { if (tx.second <= this.bytes[tx.first].length) { if (ty > this.bytes[tx.first].length - tx.second) { tx.first++; ty -= this.bytes[tx.first].length - tx.second; tx.second = 0; } else { tx.second += ty; ty = 0; } } } return tx; } shiftIndex64 (x: ByteArrayIndex, y: uint64) { let tx : ByteArrayIndex = {first: x.first, second: x.second}; let ty : uint64 = new uint64(y.high, y.low); let tzero : uint64 = new uint64(0, 0); while (tzero.lt(ty) && tx.first < this.bytes.length) { if (tx.second <= this.bytes[tx.first].length) { let len = new uint64(0, this.bytes[tx.first].length - tx.second); if (len.lt(ty)) { tx.first++; ty.sub(len); tx.second = 0; } else { tx.second += ty.low; /* here ty.high == 0 */ ty = tzero; } } } return tx; } subarray(from: ByteArrayIndex, to: ByteArrayIndex) { let res = new ByteArray([]); let tfrom = {first: from.first, second: from.second}; let tto = {first: to.first, second: to.second}; while (tfrom.first <= tto.first) { if (tfrom.first == tto.first && tfrom.second <= tto.second && (tfrom.second !== 0 || tto.second < this.bytes[tfrom.first].length)) { // console.log("concat for res") res.concat(new ByteArray(this.bytes[tfrom.first].slice(tfrom.second, tto.second))); // console.log(res.toHexString()) } else if (tfrom.second !== 0) { if (this.bytes[tfrom.first].length < tfrom.second) { throw new Error("Bad tfrom index"); } res.concat(new ByteArray(this.bytes[tfrom.first].slice(tfrom.second))); } else { res.concat(new ByteArray(this.bytes[tfrom.first])); } tfrom.first++; tfrom.second = 0; } // console.log("subarray returning ") // console.log(res.toHexString()) return res; } endIndex() { if (this.bytes.length > 0) { return {first: this.bytes.length - 1, second: this.bytes[this.bytes.length - 1].length}; } else { return {first: 0, second: 0}; } } toHexString() { let res = ""; let i = 0; for (; i < this.bytes.length; ++i) { let b = this.bytes[i]; let j = 0; for (; j < b.length; ++j) { let v = b[j]; res = res.concat(hexits[Math.trunc(v/16)]); res = res.concat(hexits[v%16]); res = res.concat(" "); } } return res; } iterate(f: (x: Buffer) => void) { let i = 0; for (; i < this.bytes.length; ++i) { let buf = Buffer.from(this.bytes[i]) f(buf) } } } function byteArrayFromBuffer(b: Buffer) : ByteArray { // console.log("** serializing") // console.log(b) let res = new ByteArray([]) for (var byte of b.values()) { res.concat(new ByteArray([byte])) } return res } function byteArrayToBuffer(byteArray: ByteArray) : Buffer { // console.log("** byte array") // console.log(byteArray.toHexString()) let buffers : Buffer[] = [] let i = 0 for (; i < byteArray.bytes.length; ++i) { buffers.push(new Buffer(byteArray.bytes[i])) } let concatd = Buffer.concat(buffers) // console.log("** about to deserialize") // console.log(concatd) return concatd } interface slice { bytes: ByteArray; from: ByteArrayIndex; to: ByteArrayIndex; } function sliceLength(input: slice) : uint64 { return input.bytes.dist(input.from, input.to); } function checkEnd(input: slice) { if ((new uint64(0, 0)).lt(sliceLength(input))) { throw new Error("Data present, none expected, slice length: " + sliceLength(input).low); } } function sliceCrop(input: slice) : ByteArray { return input.bytes.subarray(input.from, input.to); } function wholeSlice(b: ByteArray) : slice { return { bytes: b, from: {first: 0, second: 0}, to: b.endIndex() } } function unsafeParseByte(input: slice) : uint8 { let res = input.bytes.byteAt(input.from); input.from = input.bytes.shiftIndex(input.from, 1); return res; } function parseByte(input: slice) : uint8 { if (sliceLength(input).lt(new uint64(0, 1))) { throw new Error("parseIntFixed: not enough bytes"); } return unsafeParseByte(input); } function serializeByte(x: uint8) : ByteArray { return new ByteArray([x]); } function parseByteArray(input: slice, size: uint64) : ByteArray { if (sliceLength(input).lt(size)) { throw new Error("parseByteArray: not enough bytes"); } let newFrom = input.bytes.shiftIndex64(input.from, size); let res = input.bytes.subarray(input.from, newFrom); input.from = newFrom; return res; } function serializeByteArray(array: ByteArray) : ByteArray { let res = new ByteArray([]); /* TODO: we should do a deep copy, not just a shallow copy */ res.concat(array); return res; } function parseIntFixed(input: slice) : uint32 /* intFixed */ { if (sliceLength(input).lt(new uint64(0, 4))) { throw new Error("parseIntFixed: not enough bytes"); } let b0 = unsafeParseByte(input); let b1 = unsafeParseByte(input); let b2 = unsafeParseByte(input); let b3 = unsafeParseByte(input); /* little-endian */ return (b0 + 256 * (b1 + 256 * (b2 + 256 * b3))); } function serializeIntFixed(x: uint32): ByteArray { let t = x; let b0 = t % 256; t = Math.trunc(t / 256); let b1 = t % 256; t = Math.trunc(t / 256); let b2 = t % 256; t = Math.trunc(t / 256); let b3 = t % 256; /* little-endian */ return new ByteArray([b0, b1, b2, b3]); } function parseLongFixed(input: slice) : uint64 { /* little-endian */ let low = parseIntFixed(input); let high = parseIntFixed(input); return new uint64(high, low); } function serializeLongFixed(x: uint64 /* longFixed */): ByteArray { /* little-endian */ let res : ByteArray = serializeIntFixed(x.low); res.concat(serializeIntFixed(x.high)); return res; } type zigzagInt = uint32; // uint64; // /* unsigned variable-length int, */ function zigzagIntSize(value : uint32) : uint32 { var sz : uint32 = 0; var zigZagEncoded : uint32 = maxUint32 & ((value << 1) ^ (value >> 31)); while ((zigZagEncoded & ~0x7F) !== 0) { sz++; zigZagEncoded >>= 7; } return sz + 1; } function zigzagInt64Size(value : uint64) : uint32 { // The size shall never use the high bits return serializeZigzagInt64(value).length().low; } function parseZigzagInt(input: slice) : zigzagInt { var shift : uint32 = 7; var currentByte : uint8 = parseByte(input); var read : uint8 = 1; var result : uint32 = currentByte & 0x7F; while ((currentByte & 0x80) !== 0) { currentByte = parseByte(input); read++; result |= (currentByte & 0x7F) << shift; shift += 7; if (read > 5) { throw new Error("parseZigzagInt: number is too long"); } } result = ((-(result & 1) ^ ((result >> 1) & 0x7FFFFFFF))); result &= maxUint32; return result; } function parseZigzagInt64(input: slice) : uint64 { var shift : uint32 = 7; var currentByte : uint8 = parseByte(input); var read : uint8 = 1; var hi : uint32 = 0; var lo : uint32 = currentByte & 0x7F; while ((currentByte & 0x80) !== 0) { currentByte = parseByte(input); read++; if (shift + 7 <= 32) { lo |= (currentByte & 0x7F) << shift; } else if (shift < 32) { var currentBytel = currentByte & ((1 << (32 - shift)) - 1); var currentByteh = currentByte >> (32 - shift); lo |= (currentBytel & 0x7F) << shift; hi |= (currentByteh & 0x7F) << 0; } else { hi |= (currentByte & 0x7F) << (shift - 32); } shift += 7; if (read > 9) { throw new Error("parseZigzagInt: number is too long"); } } var hilsb : uint32 = hi & 1; var lolsb : uint32 = lo & 1; lo = ((lo >> 1) | (hilsb << 31)) ^ (-lolsb); hi = (hi >> 1) ^ (-lolsb); return new uint64(hi, lo); } function serializeZigzagInt(value: zigzagInt): ByteArray { var zigZagEncoded : uint32 = maxUint32 & ((value << 1) ^ (value >> 31)); var bytes : uint8[] = []; while ((zigZagEncoded & ~0x7F) !== 0) { bytes = bytes.concat (0xFF & (zigZagEncoded | 0x80)); zigZagEncoded >>= 7; } bytes = bytes.concat(0xFF & zigZagEncoded); return new ByteArray(bytes); } function serializeZigzagInt64(value: uint64): ByteArray { var hi : uint32 = value.high; var lo : uint32 = value.low; var himsb = hi >> 31; var lomsb = lo >> 31; var nhi = (hi << 1) ^ lomsb; var nlo = (lo << 1) ^ himsb; var bytes : uint8[] = []; while (nhi !== 0 || ((nlo & ~0x7F) !== 0)) { bytes = bytes.concat (0xFF & (nlo | 0x80)); var hilsb7 = nhi & 0x7F; nhi >>= 7; nlo = (nlo >>= 7) ^ (hilsb7 << (32 - 7)); } bytes = bytes.concat(0xFF & nlo); return new ByteArray(bytes); } interface header { committerID: uint32 /* intFixed */; size: uint32 /* intFixed */; check: uint64 /* longFixed */; logRecordSequenceID: uint64 /* longFixed */; } function parseHeader(input: slice) : header { let committerID = parseIntFixed(input); let size = parseIntFixed(input); let check = parseLongFixed(input); let logRecordSequenceID = parseLongFixed(input); return { committerID: committerID, size: size, check: check, logRecordSequenceID: logRecordSequenceID }; } function serializeHeader(x: header): ByteArray { let res : ByteArray = serializeIntFixed(x.committerID); res.concat(serializeIntFixed(x.size)); res.concat(serializeLongFixed(x.check)); res.concat(serializeLongFixed(x.logRecordSequenceID)); return res; } enum MessageType { TrimTo = 14, CountReplayableRPCBatch = 13, UpgradeService = 12, TakeBecomingPrimaryCheckpoint = 11, UpgradeTakeCheckpoint = 10, InitialMessage = 9, Checkpoint = 8, RPCBatch = 5, TakeCheckpoint = 2, AttachTo = 1, RPC = 0 } function parseMessageType (input: slice) : MessageType { let v : uint8 = input.bytes.byteAt(input.from); input.from = input.bytes.shiftIndex(input.from, 1); if (MessageType[v]) { let res : MessageType = v; return res; } throw new Error("parseMessageType: invalid messageType"); } function serializeMessageType (x: MessageType) : ByteArray { return new ByteArray([x]); } class Message { typ: MessageType; protected constructor(typ: MessageType) { this.typ = typ; } serializePayload() : ByteArray { throw new Error("Unimplemented: message.serializePayload"); } } class EmptyMessage extends Message { constructor(typ: MessageType) { super(typ); } serializePayload() : ByteArray { return new ByteArray([]); } } class MsgUpgradeService extends EmptyMessage { constructor() { super(MessageType.UpgradeService); } } class MsgTakeBecomingPrimaryCheckpoint extends EmptyMessage { constructor() { super(MessageType.TakeBecomingPrimaryCheckpoint); } } class MsgUpgradeTakeCheckpoint extends EmptyMessage { constructor() { super(MessageType.UpgradeTakeCheckpoint); } } /* MsgInitialMessage depends on MsgRPC */ class MsgCheckpoint extends Message { checkpoint: ByteArray; expectedCheckpointSize: uint64; /* used only for parsing */ /* constructor: only parse the payload, i.e. fills in expectedCheckpointSize; then checkpoint must be filled in later by the caller, not the constructor */ constructor(input?: slice) { super(MessageType.Checkpoint); if (input) { let sz = parseZigzagInt64(input); this.expectedCheckpointSize = sz; this.checkpoint = new ByteArray([]); } else { this.expectedCheckpointSize = new uint64(0, 0); this.checkpoint = new ByteArray([]); } } /* serializePayload should only serialize the payload excluding the actual checkpoint contents */ serializePayload () : ByteArray { return serializeZigzagInt64(this.checkpoint.length()); } } /* RPCBatch depends on RPC */ class MsgTakeCheckpoint extends EmptyMessage { constructor() { super(MessageType.TakeCheckpoint); } } class MsgAttachTo extends Message { destinationBytes: ByteArray; constructor(input?: slice) { super(MessageType.AttachTo); if (input) { this.destinationBytes = sliceCrop(input); input.from = copyIndex(input.to); } else { this.destinationBytes = new ByteArray([]); } } serializePayload () : ByteArray { let res : ByteArray = new ByteArray([]); res.concat(this.destinationBytes); return res; } } class MsgRPC extends Message { destinationServiceName: Buffer; methodId: uint32 /* zigzagInt */ ; serializedArgs: ByteArray; isOutgoing: boolean; isSelfCall: boolean; constructor(input?: slice) { super(MessageType.RPC); // console.log("we are here in msg rpc") /* parsing ignores the destination service name */ this.destinationServiceName = new Buffer([]) if (input) { this.isOutgoing = false; this.isSelfCall = false; // Omitted in the incoming RPC. let reservedRPCOrReturn = parseByte(input); // value should be 0, but do we care at parsing? this.methodId = parseZigzagInt(input); let reservedFireAndForgetOrAsyncAwait = parseByte(input); // value should be 1, but do we care at parsing? this.serializedArgs = sliceCrop(input); input.from = copyIndex(input.to); } else { this.isOutgoing = true; this.isSelfCall = false; this.methodId = 0; this.serializedArgs = new ByteArray([]); } } serializePayload () : ByteArray { let res : ByteArray = new ByteArray([]); if (this.isOutgoing) { /* serialization needs destination service name */ if(this.isSelfCall) { res.concat(serializeZigzagInt(0)); } else { res.concat(serializeZigzagInt(this.destinationServiceName.length)); res.concat(byteArrayFromBuffer(this.destinationServiceName)); } } res.concat(serializeByte(0)); /* reserved: RPC or Return */ res.concat(serializeZigzagInt(this.methodId)); res.concat(serializeByte(2)); /* reserved: Fire and Forget (1) or Async/Await (0) or Impulse (2) */ res.concat(this.serializedArgs); return res; } } function serializeMessage (msg: Message) : ByteArray { let payload : ByteArray = msg.serializePayload (); let typ : ByteArray = serializeMessageType(msg.typ); let sz = add64(payload.length(), typ.length()); // console.log("payload: ") // console.log(payload) // console.log("typ: ") // console.log(typ) // console.log("sz: ") // console.log(sz) if (sz.high > 0) { throw new Error("message is too large, its size should fit in 32 bits"); } let res : ByteArray = serializeZigzagInt(sz.low); res.concat(typ); res.concat(payload); /* Special case: concat the checkpoint */ if (msg.typ == MessageType.Checkpoint) { res.concat((msg as MsgCheckpoint).checkpoint); } return res; } class MsgCountReplayableRPCBatch extends Message { batch: MsgRPC[]; replayable: uint32; constructor(input?: slice, parseMessage?: ((input: slice) => MsgRPC)) { super(MessageType.RPCBatch); if (input) { if (parseMessage) { let res : MsgRPC[] = []; let count = parseZigzagInt(input); this.replayable = parseZigzagInt(input); let i = 0; for (; i < count; ++i) { res = res.concat([parseMessage(input)]); } this.batch = res; } else { throw new Error("MsgRPCBatch: requires parseMessage"); } } else { this.batch = []; this.replayable = 0; } } serializePayload() : ByteArray { let res : ByteArray = serializeZigzagInt(this.batch.length); res.concat(serializeZigzagInt(this.replayable)); let i = 0; for (; i < this.batch.length; ++i) { res.concat(serializeMessage(this.batch[i])); } return res; } } class MsgInitialMessage extends Message { rpc: MsgRPC; constructor(input?: slice, parseMessage?: ((input: slice) => MsgRPC)) { super(MessageType.InitialMessage); if (input) { if (parseMessage) { this.rpc = parseMessage(input); } else { throw new Error("MsgInitialMessage: message parser required"); } } else { this.rpc = new MsgRPC(); } } serializePayload() : ByteArray { if (this.rpc.isOutgoing) { throw new Error("Initial message RPC should be an Incoming one"); } return serializeMessage(this.rpc); } } class MsgRPCBatch extends Message { batch: MsgRPC[]; constructor(input?: slice, parseMessage?: ((input: slice) => MsgRPC)) { super(MessageType.RPCBatch); if (input) { if (parseMessage) { let res : MsgRPC[] = []; let count = parseZigzagInt(input); let i = 0; for (; i < count; ++i) { res = res.concat([parseMessage(input)]); } this.batch = res; } else { throw new Error("MsgRPCBatch: requires parseMessage"); } } else { this.batch = []; } } serializePayload() : ByteArray { let res : ByteArray = serializeZigzagInt(this.batch.length); let i = 0; for (; i < this.batch.length; ++i) { res.concat(serializeMessage(this.batch[i])); } return res; } } function parseMessage (input: slice, expectedTyp?: MessageType) : Message { function parseRPCMessage (input: slice) : MsgRPC { let res = parseMessage(input, MessageType.RPC); return res as MsgRPC; } let totalSize : uint64 = new uint64(0, parseZigzagInt(input)); // console.log("totalSize: " + totalSize.low) if (sliceLength(input).lt(totalSize)) { throw new Error("parseMessage: not enough bytes for payload"); } let innerTo = input.bytes.shiftIndex64(input.from, totalSize); let inner : slice = { bytes: input.bytes, from: copyIndex(input.from), to: innerTo }; let typ : MessageType = parseMessageType(inner); // console.log("type: " + typ) if (expectedTyp) { if (typ !== expectedTyp) { throw new Error("Found a message of a different type than the one expected"); } } var res : Message; switch (typ) { case MessageType.CountReplayableRPCBatch: res = new MsgCountReplayableRPCBatch(inner, parseRPCMessage); break; case MessageType.UpgradeService: res = new MsgUpgradeService(); break; case MessageType.TakeBecomingPrimaryCheckpoint: res = new MsgTakeBecomingPrimaryCheckpoint(); break; case MessageType.UpgradeTakeCheckpoint: res = new MsgUpgradeTakeCheckpoint(); break; case MessageType.InitialMessage: res = new MsgInitialMessage(inner, parseRPCMessage); // console.log("after new initial message") break; case MessageType.Checkpoint: res = new MsgCheckpoint(inner); break; case MessageType.RPCBatch: res = new MsgRPCBatch(inner, parseRPCMessage); break; case MessageType.TakeCheckpoint: res = new MsgTakeCheckpoint(); break; case MessageType.AttachTo: res = new MsgAttachTo(inner); break; case MessageType.RPC: res = new MsgRPC(inner); // console.log("after new RPC message") break; default: throw new Error("Unsupported message type"); } /* Check that we consumed every byte of the payload */ checkEnd(inner); /* Notify the input that we consumed the payload bytes */ input.from = innerTo; return res; } interface logRecord { header: header; msgs: Message[]; } let headerSize = 24; let headerSize64 = new uint64(0, headerSize); function parseLogRecords (input: slice) : logRecord[] { console.log("LOG RECORDS input size " + input.bytes.length().low) let logRecords : logRecord[] = []; let zero = new uint64(0, 0); while (zero.lt(sliceLength(input))) { // console.log("slice length is now: " + sliceLength(input).low) /* Figure out how big the next log record is */ let tmpSlice: slice = { bytes: input.bytes, from: copyIndex(input.from), to: copyIndex(input.to) }; let header = parseHeader(tmpSlice); // console.log("slice size is " + header.size) /* Create a slice for that log record */ let logRecord = parseLogRecord(input) logRecords.push(logRecord) } return logRecords } function parseLogRecord (input: slice) : logRecord { // console.log("LOG RECORD input size " + input.bytes.length().low) let header = parseHeader(input); // console.log("headr size " + header.size) if (header.size < headerSize) { throw new Error("Size must include header size"); } let msgsSize = header.size - headerSize; let msgsSize64 = new uint64(0, msgsSize); // console.log("msgs size " + msgsSize64.low) if (sliceLength(input).lt(msgsSize64)) { throw new Error("Not enough message bytes remaining"); } let innerTo = input.bytes.shiftIndex(input.from, msgsSize); // console.log("input.from: " + input.from.second) // console.log("innerTo: " + innerTo.second) let inner: slice = { bytes: input.bytes, from: copyIndex(input.from), to: innerTo }; let mySliceLength = sliceLength(inner).low // console.log("slice length: " + mySliceLength) let msgs : Message[] = []; let zero = new uint64(0, 0); let maybeCheckpointEndPosition : ByteArrayIndex = innerTo; while (zero.lt(sliceLength(inner))) { // console.log("parsing message") let msg = parseMessage(inner) msgs = msgs.concat([msg]); if(msg instanceof MsgCheckpoint) { /* Use slice to grab the checkpoint off the stream if we just saw a checkpoint message */ let expectedCheckpointSize = (msg as MsgCheckpoint).expectedCheckpointSize let innerCheckpointTo = input.bytes.shiftIndex64(innerTo, expectedCheckpointSize) let innerCheckpoint: slice = { bytes: input.bytes, from: copyIndex(innerTo), to: innerCheckpointTo }; // console.log("checkpoint message!") /* Verify we have enough bytes to process the checkpoint, else wait */ if (sliceLength(innerCheckpoint).lt(expectedCheckpointSize)) { console.log("sliceLength: " + sliceLength(innerCheckpoint).low) throw new Error("parseMessage: not enough bytes for checkpoint yet"); } /* Take the checkpoint off of the stream */ (msg as MsgCheckpoint).checkpoint = parseByteArray(innerCheckpoint, (msg as MsgCheckpoint).expectedCheckpointSize); maybeCheckpointEndPosition = innerCheckpointTo // console.log("done capturing checkpoint") } // console.log("done parsing message") } input.from = maybeCheckpointEndPosition; return { header: header, msgs: msgs } } /* this serializer also adjusts the size field of the header */ function serializeLogRecord(header: header, msgs: Message[]) { var i: number; let n = msgs.length; let lowMsgs : ByteArray = new ByteArray([]); for (i = 0; i < n; ++i) { lowMsgs.concat(serializeMessage(msgs[i])); } let size = add64(new uint64(0, headerSize), lowMsgs.length()); if (size.high > 0) { throw new Error("log record too long"); } header.size = size.low; let res : ByteArray = serializeHeader(header); res.concat(lowMsgs); return res; } export { serializeMessage, serializeLogRecord, parseLogRecord, ByteArray, wholeSlice } export { Message, MessageType } export { MsgCountReplayableRPCBatch, MsgUpgradeService, MsgTakeBecomingPrimaryCheckpoint, MsgUpgradeTakeCheckpoint } export { MsgInitialMessage, MsgCheckpoint, MsgRPCBatch, MsgTakeCheckpoint, MsgAttachTo, MsgRPC } export { uint64, uint32 } export { byteArrayToBuffer, byteArrayFromBuffer, parseLogRecords }
the_stack
declare module "tls" { import * as crypto from "crypto"; import * as dns from "dns"; import * as net from "net"; import * as stream from "stream"; const CLIENT_RENEG_LIMIT: number; const CLIENT_RENEG_WINDOW: number; interface Certificate { /** * Country code. */ C: string; /** * Street. */ ST: string; /** * Locality. */ L: string; /** * Organization. */ O: string; /** * Organizational unit. */ OU: string; /** * Common name. */ CN: string; } interface PeerCertificate { subject: Certificate; issuer: Certificate; subjectaltname: string; infoAccess: { [index: string]: string[] | undefined }; modulus: string; exponent: string; valid_from: string; valid_to: string; fingerprint: string; ext_key_usage: string[]; serialNumber: string; raw: Buffer; } interface DetailedPeerCertificate extends PeerCertificate { issuerCertificate: DetailedPeerCertificate; } interface CipherNameAndProtocol { /** * The cipher name. */ name: string; /** * SSL/TLS protocol version. */ version: string; } class TLSSocket extends net.Socket { /** * Construct a new tls.TLSSocket object from an existing TCP socket. */ constructor(socket: net.Socket, options?: { /** * An optional TLS context object from tls.createSecureContext() */ secureContext?: SecureContext, /** * If true the TLS socket will be instantiated in server-mode. * Defaults to false. */ isServer?: boolean, /** * An optional net.Server instance. */ server?: net.Server, /** * If true the server will request a certificate from clients that * connect and attempt to verify that certificate. Defaults to * false. */ requestCert?: boolean, /** * If true the server will reject any connection which is not * authorized with the list of supplied CAs. This option only has an * effect if requestCert is true. Defaults to false. */ rejectUnauthorized?: boolean, /** * An array of strings or a Buffer naming possible NPN protocols. * (Protocols should be ordered by their priority.) */ NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, /** * An array of strings or a Buffer naming possible ALPN protocols. * (Protocols should be ordered by their priority.) When the server * receives both NPN and ALPN extensions from the client, ALPN takes * precedence over NPN and the server does not send an NPN extension * to the client. */ ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array, /** * SNICallback(servername, cb) <Function> A function that will be * called if the client supports SNI TLS extension. Two arguments * will be passed when called: servername and cb. SNICallback should * invoke cb(null, ctx), where ctx is a SecureContext instance. * (tls.createSecureContext(...) can be used to get a proper * SecureContext.) If SNICallback wasn't provided the default callback * with high-level API will be used (see below). */ SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void, /** * An optional Buffer instance containing a TLS session. */ session?: Buffer, /** * If true, specifies that the OCSP status request extension will be * added to the client hello and an 'OCSPResponse' event will be * emitted on the socket before establishing a secure communication */ requestOCSP?: boolean }); /** * A boolean that is true if the peer certificate was signed by one of the specified CAs, otherwise false. */ authorized: boolean; /** * The reason why the peer's certificate has not been verified. * This property becomes available only when tlsSocket.authorized === false. */ authorizationError: Error; /** * Static boolean value, always true. * May be used to distinguish TLS sockets from regular ones. */ encrypted: boolean; /** * String containing the selected ALPN protocol. * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. */ alpnProtocol?: string; /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. * @returns Returns an object representing the cipher name * and the SSL/TLS protocol version of the current connection. */ getCipher(): CipherNameAndProtocol; /** * Returns an object representing the peer's certificate. * The returned object has some properties corresponding to the field of the certificate. * If detailed argument is true the full chain with issuer property will be returned, * if false only the top certificate without issuer property. * If the peer does not provide a certificate, it returns null or an empty object. * @param detailed - If true; the full chain with issuer property will be returned. * @returns An object representing the peer's certificate. */ getPeerCertificate(detailed: true): DetailedPeerCertificate; getPeerCertificate(detailed?: false): PeerCertificate; getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; /** * Returns a string containing the negotiated SSL/TLS protocol version of the current connection. * The value `'unknown'` will be returned for connected sockets that have not completed the handshaking process. * The value `null` will be returned for server sockets or disconnected client sockets. * See https://www.openssl.org/docs/man1.0.2/ssl/SSL_get_version.html for more information. * @returns negotiated SSL/TLS protocol version of the current connection */ getProtocol(): string | null; /** * Could be used to speed up handshake establishment when reconnecting to the server. * @returns ASN.1 encoded TLS session or undefined if none was negotiated. */ getSession(): Buffer | undefined; /** * NOTE: Works only with client TLS sockets. * Useful only for debugging, for session reuse provide session option to tls.connect(). * @returns TLS session ticket or undefined if none was negotiated. */ getTLSTicket(): Buffer | undefined; /** * Initiate TLS renegotiation process. * * NOTE: Can be used to request peer's certificate after the secure connection has been established. * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. * @param options - The options may contain the following fields: rejectUnauthorized, * requestCert (See tls.createServer() for details). * @param callback - callback(err) will be executed with null as err, once the renegotiation * is successfully completed. * @return `undefined` when socket is destroy, `false` if negotiaion can't be initiated. */ renegotiate(options: { rejectUnauthorized?: boolean, requestCert?: boolean }, callback: (err: Error | null) => void): undefined | boolean; /** * Set maximum TLS fragment size (default and maximum value is: 16384, minimum is: 512). * Smaller fragment size decreases buffering latency on the client: large fragments are buffered by * the TLS layer until the entire fragment is received and its integrity is verified; * large fragments can span multiple roundtrips, and their processing can be delayed due to packet * loss or reordering. However, smaller fragments add extra TLS framing bytes and CPU overhead, * which may decrease overall server throughput. * @param size - TLS fragment size (default and maximum value is: 16384, minimum is: 512). * @returns Returns true on success, false otherwise. */ setMaxSendFragment(size: number): boolean; /** * events.EventEmitter * 1. OCSPResponse * 2. secureConnect */ addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; addListener(event: "secureConnect", listener: () => void): this; addListener(event: "session", listener: (session: Buffer) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "OCSPResponse", response: Buffer): boolean; emit(event: "secureConnect"): boolean; emit(event: "session", session: Buffer): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "OCSPResponse", listener: (response: Buffer) => void): this; on(event: "secureConnect", listener: () => void): this; on(event: "session", listener: (session: Buffer) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "OCSPResponse", listener: (response: Buffer) => void): this; once(event: "secureConnect", listener: () => void): this; once(event: "session", listener: (session: Buffer) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependListener(event: "secureConnect", listener: () => void): this; prependListener(event: "session", listener: (session: Buffer) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependOnceListener(event: "secureConnect", listener: () => void): this; prependOnceListener(event: "session", listener: (session: Buffer) => void): this; } interface TlsOptions extends SecureContextOptions { handshakeTimeout?: number; requestCert?: boolean; rejectUnauthorized?: boolean; NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; SNICallback?: (servername: string, cb: (err: Error | null, ctx: SecureContext) => void) => void; sessionTimeout?: number; ticketKeys?: Buffer; } interface ConnectionOptions extends SecureContextOptions { host?: string; port?: number; path?: string; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. socket?: net.Socket; // Establish secure connection on a given socket rather than creating a new socket rejectUnauthorized?: boolean; // Defaults to true NPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; ALPNProtocols?: string[] | Buffer[] | Uint8Array[] | Buffer | Uint8Array; checkServerIdentity?: typeof checkServerIdentity; servername?: string; // SNI TLS Extension session?: Buffer; minDHSize?: number; secureContext?: SecureContext; // If not provided, the entire ConnectionOptions object will be passed to tls.createSecureContext() lookup?: net.LookupFunction; timeout?: number; } class Server extends net.Server { addContext(hostName: string, credentials: SecureContextOptions): void; /** * events.EventEmitter * 1. tlsClientError * 2. newSession * 3. OCSPRequest * 4. resumeSession * 5. secureConnection */ addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; addListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; addListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; addListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void): boolean; emit(event: "OCSPRequest", certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void): boolean; emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; on(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; on(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; once(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; once(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; once(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; prependListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; prependListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; prependListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; prependOnceListener(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void): this; prependOnceListener(event: "OCSPRequest", listener: (certificate: Buffer, issuer: Buffer, callback: (err: Error | null, resp: Buffer) => void) => void): this; prependOnceListener(event: "resumeSession", listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void): this; prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; } interface SecurePair { encrypted: TLSSocket; cleartext: TLSSocket; } type SecureVersion = 'TLSv1.2' | 'TLSv1.1' | 'TLSv1'; interface SecureContextOptions { pfx?: string | Buffer | Array<string | Buffer | Object>; key?: string | Buffer | Array<Buffer | Object>; passphrase?: string; cert?: string | Buffer | Array<string | Buffer>; ca?: string | Buffer | Array<string | Buffer>; ciphers?: string; honorCipherOrder?: boolean; ecdhCurve?: string; clientCertEngine?: string; crl?: string | Buffer | Array<string | Buffer>; dhparam?: string | Buffer; secureOptions?: number; // Value is a numeric bitmask of the `SSL_OP_*` options secureProtocol?: string; // SSL Method, e.g. SSLv23_method sessionIdContext?: string; /** * Optionally set the maximum TLS version to allow. One * of `TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the * `secureProtocol` option, use one or the other. **Default:** `'TLSv1.2'`. */ maxVersion?: SecureVersion; /** * Optionally set the minimum TLS version to allow. One * of `TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the * `secureProtocol` option, use one or the other. It is not recommended to use * less than TLSv1.2, but it may be required for interoperability. * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using * `--tls-v1.0` changes the default to `'TLSv1'`. Using `--tls-v1.1` changes * the default to `'TLSv1.1'`. */ minVersion?: SecureVersion; } interface SecureContext { context: any; } /* * Verifies the certificate `cert` is issued to host `host`. * @host The hostname to verify the certificate against * @cert PeerCertificate representing the peer's certificate * * Returns Error object, populating it with the reason, host and cert on failure. On success, returns undefined. */ function checkServerIdentity(host: string, cert: PeerCertificate): Error | undefined; function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; /** * @deprecated */ function createSecurePair(credentials?: SecureContext, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; function createSecureContext(details: SecureContextOptions): SecureContext; function getCiphers(): string[]; const DEFAULT_ECDH_CURVE: string; }
the_stack
module Inknote { interface MouseMoveEvent extends MouseEvent { movementX: number; movementY: number; } interface Touch { identifier: number; target: EventTarget; screenX: number; screenY: number; clientX: number; clientY: number; pageX: number; pageY: number; }; interface TouchEvent extends UIEvent { touches: Touch[]; targetTouches: Touch[]; changedTouches: Touch[]; altKey: boolean; metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; }; declare var TouchEvent: { prototype: TouchEvent; new (): TouchEvent; } class TouchCopy { constructor(public identifier: number, public pageX: number, public pageY: number) { } } function copyTouch(touch: Touch): TouchCopy { return new TouchCopy(touch.identifier, touch.pageX, touch.pageY); } export class CanvasControl { hover(e: MouseEvent) { if (Managers.MouseManager.Instance.currentMouse == Managers.MouseType.PENCIL || Managers.MouseManager.Instance.currentMouse === Managers.MouseType.TEXT) { return; } var allItems = this.drawService.items; var hovered = false; var scoreItems: Notation[] = []; for (var i = 0; i < allItems.length; i++) { if (mouseIsOver(allItems[i], e, this.drawService.canvas)) { // log(allItems[i].y + ":" + e.clientY + ":" + ScrollService.Instance.y); if (Managers.PageManager.Current.page == Managers.Page.Score) { if (allItems[i] instanceof Notation) { scoreItems.push(<Notation>allItems[i]); } } var hoverID = allItems[i].ID; Managers.ProjectManager.Instance.hoverID = hoverID; hovered = true; this.drawService.canvas.style.cursor = "url('assets/pointer.png'), pointer"; } } var sortedScoreItems = <Notation[]>scoreItems.sort(function (a: Notation, b: Notation) { return b.order - a.order; }); if (sortedScoreItems.length > 0) { ScoringService.Instance.hoverID = sortedScoreItems[0].ID; } else { ScoringService.Instance.hoverID = null; } if (!hovered) { Managers.ProjectManager.Instance.hoverID = null; this.drawService.canvas.style.cursor = ""; } } pencilClick(e: MouseEvent | Touch) { var scoreItems = ScoringService.Instance.getItems(); var bars = getItemsWhere(scoreItems, function (item: IDrawable) { return item instanceof Drawing.Bar; }); var inBar = <Drawing.Bar>getFirstItemWhere(bars, function (item: Drawing.Bar) { return item.isOver(e.clientX, e.clientY - 50); }); if (inBar) { NoteControlService.Instance.addNoteToBar(e.clientY - 50 - inBar.y, inBar.ID); } if (!inBar) { log("the pencil can only be used to place notes within a bar"); } } textClick(e: MouseEvent | Touch) { var scoreItems = ScoringService.Instance.getItems(); var notes = getItemsWhere(scoreItems, function (item: IDrawable) { return item instanceof Drawing.Note; }); var closestNote = <Drawing.Note>getItemWithMin(notes, function (item: Drawing.Note) { return Maths.pythagoras(e.clientX - item.x, e.clientY - 50 - item.y); }); var addText = new Model.Text("add text"); var currentProject = Managers.ProjectManager.Instance.currentProject; for (var i = 0; i < currentProject.instruments.length; i++) { for (var j = 0; j < currentProject.instruments[i].bars.length; j++) { for (var k = 0; k < currentProject.instruments[i].bars[j].items.length; k++) { var tempBar = currentProject.instruments[i].bars[j]; var tempItem = tempBar.items[k]; if (tempItem.ID == closestNote.ID) { var textToAdd = prompt("text to be added:", addText.content); if (textToAdd == null) { log("adding text cancelled", MessageType.Warning); return; } addText.content = textToAdd; tempBar.items.splice(k + 1, 0, addText); ScoringService.Instance.refresh(); return; } } } } log("text click not registered", MessageType.Error); } click(e: MouseEvent | Touch) { if (Managers.MouseManager.Instance.currentMouse == Managers.MouseType.PENCIL) { this.pencilClick(e); return; } if (Managers.MouseManager.Instance.currentMouse == Managers.MouseType.TEXT) { this.textClick(e); return; } var allItems = this.drawService.items; var selected = false; var scoreItems: Notation[] = []; var sortedItems = []; for (var i = 0; i < allItems.length; i++) { sortedItems.push(allItems[i]); } sortedItems.sort(function (a: IDrawable, b: IDrawable) { return b.order - a.order; }); for (var i = 0; i < sortedItems.length; i++) { if (mouseIsOver(sortedItems[i], e, this.drawService.canvas)) { var selectedID = sortedItems[i].ID; // rightClick menu if (selectedID == RightClickMenuService.Instance.Menu.ID) { RightClickMenuService.Instance.Menu.click(e); RightClickMenuService.Instance.visible = false; return; } // note control. if (selectedID == NoteControlService.Instance.ID) { if (e.clientY - 50 > NoteControlService.Instance.piano.y) { NoteControlService.Instance.piano.click(e); } else if (e.clientY - 50 < NoteControlService.Instance.y) { NoteControlService.Instance.minimise.click(e); } else if (NoteControlService.Instance.restControl.isOver(e.clientX, e.clientY - 50)) { NoteControlService.Instance.restControl.click(e); } else if (NoteControlService.Instance.deleteNoteControl.isOver(e.clientX, e.clientY - 50)) { NoteControlService.Instance.deleteNoteControl.click(e); } else { NoteControlService.Instance.lengthControl.click(e); } return; } // if keyboard clicked, do keyboard action. if (selectedID === Drawing.Keyboard.Instance.ID) { Drawing.Keyboard.Instance.click(e); return; } // " " bottom menu if (selectedID === Drawing.BottomMenu.Instance.ID) { Drawing.BottomMenu.Instance.click(e); return; } // scroll bar if (selectedID === ScrollService.ScrollBar.ID) { ScrollService.ScrollBar.click(e); return; } // scroll thumbnail if (selectedID === ScrollService.ScrollBar.scrollThumbnail.ID) { ScrollService.ScrollBar.scrollThumbnail.click(e); return; } // licence if (selectedID === LicenceService.Instance.drawing.ID) { LicenceService.Instance.drawing.click(e); return; } if (Managers.PageManager.Current.page == Managers.Page.Score) { if (sortedItems[i] instanceof Notation) { scoreItems.push(<Notation>sortedItems[i]); } } Managers.ProjectManager.Instance.selectID = selectedID; selected = true; } } var sortedScoreItems = <Notation[]>scoreItems.sort(function (a: Notation, b: Notation) { return b.order - a.order; }); if (sortedScoreItems.length > 0) { ScoringService.Instance.selectID = sortedScoreItems[0].ID; } else { ScoringService.Instance.selectID = null; } if (!selected) { // clear ScrollService.ScrollBar.scrollThumbnail.visible = false; Managers.ProjectManager.Instance.selectID = null; RightClickMenuService.Instance.visible = false; } } dblClick(e: MouseEvent) { if (Managers.PageManager.Current.page == Managers.Page.File) { if (Managers.ProjectManager.Instance.selectID) { Managers.ProjectManager.Instance.openSelectedProject(); } } } mouseDown(e: MouseEvent, drawService: DrawService) { var onMove = function (e: MouseMoveEvent) { // ScrollService.Instance.x += e.movementX; if (e.movementY > 0 && canScroll(true) || e.movementY < 0 && canScroll(false)) { ScrollService.Instance.y -= e.movementY; } drawService.canvas.style.cursor = "url('assets/grabbing.png'), -webkit-grabbing"; }; drawService.canvas.addEventListener("mousemove", onMove, false); drawService.canvas.onmouseup = function (e: MouseEvent) { drawService.canvas.removeEventListener("mousemove", onMove, false); drawService.canvas.style.cursor = ""; }; drawService.canvas.onmouseout = function (e: MouseEvent) { drawService.canvas.removeEventListener("mousemove", onMove, false); drawService.canvas.style.cursor = ""; }; } touchCopies: TouchCopy[] = []; getTouchCopyByID(ID: number): TouchCopy { for (var i = 0; i < this.touchCopies.length; i++) { if (this.touchCopies[i].identifier == ID) { return this.touchCopies[i]; } } return null; } touchStart(e: TouchEvent, drawService: DrawService) { var touches = e.touches; this.touchCopies = []; for (var i = 0; i < touches.length; i++) { this.touchCopies.push(copyTouch(touches[i])); } var self = this; var onMove = function (e: TouchEvent) { var touches = e.changedTouches; for (var i = 0; i < touches.length; i++) { var touch = touches[i]; var lastTouch = self.getTouchCopyByID(touch.identifier); var movementX = touch.pageX - lastTouch.pageX; var movementY = touch.pageY - lastTouch.pageY; if (movementY > 0 && canScroll(true) || movementY < 0 && canScroll(false)) { ScrollService.Instance.y -= movementY; } lastTouch.pageX = touch.pageX; lastTouch.pageY = touch.pageY; } }; drawService.canvas.addEventListener("touchmove", onMove, false); drawService.canvas.addEventListener("touchend", function (e: TouchEvent) { drawService.canvas.removeEventListener("touchmove", onMove, false); }, false); drawService.canvas.addEventListener("touchleave", function (e: TouchEvent) { drawService.canvas.removeEventListener("touchmove", onMove, false); }, false); } rightClick(e: MouseEvent) { RightClickMenuService.Instance.openMenu(e.clientX, e.clientY - 50, this.drawService.canvas); e.preventDefault(); } constructor(public drawService: DrawService) { var self = this; this.drawService.canvas.onmouseover = function (e: MouseEvent) { self.drawService.canvas.onmousemove = function (me: MouseEvent) { self.hover(me); }; }; this.drawService.canvas.onmouseout = function (e: MouseEvent) { self.drawService.canvas.onmousemove = null; }; this.drawService.canvas.onclick = function (e: MouseEvent) { if (Inknote.Managers.MachineManager.Instance.machineType == Inknote.Managers.MachineType.Desktop) { try{ self.click(e); } catch(e){ if(Inknote.log){ Inknote.log(e, Inknote.MessageType.Error); } } } }; this.drawService.canvas.ondblclick = function (e: MouseEvent) { try{ self.dblClick(e); } catch(e){ if(Inknote.log){ Inknote.log(e, Inknote.MessageType.Error); } } }; this.drawService.canvas.onmousedown = function (e: MouseEvent) { try{ self.mouseDown(e, drawService); } catch(e){ if(Inknote.log){ Inknote.log(e, Inknote.MessageType.Error); } } }; // right click this.drawService.canvas.oncontextmenu = function (e: MouseEvent) { try{ self.rightClick(e); } catch(e){ if(Inknote.log){ Inknote.log(e, Inknote.MessageType.Error); } } }; this.drawService.canvas.addEventListener("touchstart", function (e: TouchEvent) { try{ self.touchStart(e, self.drawService); //var me = new MouseEvent(null); // todo: get correct touch object. var touch = e.touches[0]; self.click(touch); } catch(e){ if(Inknote.log){ Inknote.log(e, Inknote.MessageType.Error); } } }, false); } } }
the_stack
import { noop } from '@aurelia/kernel'; import { IDialogService, IDialogSettings, IDialogGlobalSettings, DialogConfiguration, DialogDefaultConfiguration, DefaultDialogGlobalSettings, customElement, DialogCancelError, DialogDeactivationStatuses, IDialogDom, IDialogController, INode, DialogController, DefaultDialogDom, CustomElement, } from '@aurelia/runtime-html'; import { createFixture, assert, createSpy, } from '@aurelia/testing'; describe('3-runtime-html/dialog/dialog-service.spec.ts', function () { describe('configuration', function () { it('throws on empty configuration', async function () { let error: unknown = void 0; try { const { startPromise } = createFixture('', class App { }, [DialogConfiguration]); await startPromise; } catch (err) { error = err; } assert.notStrictEqual(error, void 0); // assert.includes((error as Error).message, 'Invalid dialog configuration.'); assert.includes((error as Error).message, 'AUR0904'); }); it('throws when customize without any implementation', async function () { let error: unknown = void 0; try { const { startPromise } = createFixture('', class App { }, [DialogConfiguration.customize(noop, [])]); await startPromise; } catch (err) { error = err; } assert.notStrictEqual(error, void 0); // assert.includes((error as Error).message, 'Attempted to jitRegister an interface: IDialogGlobalSettings'); assert.includes((error as Error).message, 'AUR0012:IDialogGlobalSettings'); }); it('reuses previous registration', async function () { let customized = false; const { ctx, startPromise, tearDown } = createFixture( '', class App { }, [ DialogDefaultConfiguration.customize(settings => { customized = true; assert.instanceOf(settings, DefaultDialogGlobalSettings); }) ] ); await startPromise; const dialogService = ctx.container.get(IDialogService); await dialogService.open({ component: () => ({}), template: () => '<div>Hello world</div>' }); assert.strictEqual(customized, true); await tearDown(); }); }); describe('on deactivation', function () { it('throws when it fails to cleanup', async function () { const { ctx, startPromise, tearDown } = createFixture('', class App { }, [DialogDefaultConfiguration]); await startPromise; const dialogService = ctx.container.get(IDialogService); let canDeactivate = false; await dialogService.open({ component: () => ({ canDeactivate: () => canDeactivate }), template: () => '<div>Hello world</div>' }); let err: Error; await tearDown().catch(ex => { err = ex; }); assert.notStrictEqual(err, undefined); assert.includes(err.message, 'AUR0901:1'); // assert.includes(err.message, 'There are still 1 open dialog(s).'); canDeactivate = true; await dialogService.closeAll(); }); }); describe('.open()', function () { const testCases: IDialogServiceTestCase[] = [ { title: 'throws on invalid configuration', afterStarted: async (_, dialogService) => { let error: DialogCancelError<unknown>; await dialogService.open({}).catch(err => error = err); assert.strictEqual(error.message, 'AUR0903'); // assert.strictEqual(error.message, 'Invalid Dialog Settings. You must provide "component", "template" or both.'); } }, { title: 'works with @inject(IDialogController, IDialogDom, INode)', afterStarted: async (_, dialogService) => { await dialogService.open({ component: () => class { public static inject = [IDialogController, IDialogDom, INode]; public constructor( controller: DialogController, dialogDom: DefaultDialogDom, node: Element ) { assert.strictEqual(controller['dom'], dialogDom); assert.strictEqual(dialogDom.contentHost, node); } } }); } }, { title: 'throws when @inject(DialogController) instead of IDialogController', afterStarted: async (_, dialogService) => { let error: Error; await dialogService.open({ component: () => class { public static inject = [DialogController]; public constructor( controller: DialogController, dialogDom: DefaultDialogDom, node: Element ) { assert.strictEqual(controller['dom'], dialogDom); assert.strictEqual(dialogDom.contentHost, node); } } }).catch(ex => { error = ex; }); assert.notStrictEqual(error, undefined); assert.includes(error.message, 'AUR0902'); // assert.includes(error.message, 'Invalid injection of DialogController. Use IDialogController instead.'); } }, { title: 'works with promise component', afterStarted: async (_, dialogService) => { let activated = false; await dialogService.open({ component: () => new Promise(r => { setTimeout(() => r({ activate: () => activated = true }), 0); }) }); assert.strictEqual(activated, true); } }, { title: 'works with promise template', afterStarted: async ({ ctx }, dialogService) => { await dialogService.open({ template: () => new Promise(r => { setTimeout(() => r('<p>hello world 1234'), 0); }) }); assert.visibleTextEqual(ctx.doc.querySelector('p'), 'hello world 1234'); } }, { title: 'hasOpenDialog with 1 dialog', afterStarted: async (_, dialogService) => { const { dialog: controller } = await dialogService.open({ template: '' }); assert.strictEqual(dialogService.controllers.length, 1); void controller.ok(); await controller.closed; assert.strictEqual(dialogService.controllers.length, 0); } }, { title: 'hasOpenDialog with more than 1 dialog', afterStarted: async (_, dialogService) => { const { dialog: dialog1 } = await dialogService.open({ template: '' }); assert.strictEqual(dialogService.controllers.length, 1); const { dialog: dialog2 } = await dialogService.open({ template: '' }); assert.strictEqual(dialogService.controllers.length, 2); void dialog1.ok(); await dialog1.closed; assert.strictEqual(dialogService.controllers.length, 1); void dialog2.ok(); await dialog2.closed; assert.strictEqual(dialogService.controllers.length, 0); } }, { title: 'should create new settings by merging the default settings and the provided ones', afterStarted: async ({ ctx }, dialogService) => { const overrideSettings: IDialogSettings = { rejectOnCancel: true, lock: true, keyboard: ['Escape'], overlayDismiss: true, }; const { dialog: controller } = await dialogService.open({ ...overrideSettings, component: () => Object.create(null), }); const expectedSettings = { ...ctx.container.get(IDialogGlobalSettings), ...overrideSettings }; const actualSettings = { ...controller.settings }; delete actualSettings.component; assert.deepStrictEqual(actualSettings, expectedSettings); } }, { title: 'should not modify the default settings', afterStarted: async ({ ctx }, dialogService) => { const overrideSettings = { component: () => ({}), model: 'model data' }; const expectedSettings = { ...ctx.container.get(IDialogGlobalSettings) }; await dialogService.open(overrideSettings); const actualSettings = { ...ctx.container.get(IDialogGlobalSettings) }; assert.deepStrictEqual(actualSettings, expectedSettings); } }, ...[null, undefined, true].map<IDialogServiceTestCase>(canActivate => ({ title: `invokes & resolves with [canActivate: ${canActivate}]`, afterStarted: async function ({ ctx }, dialogService) { let canActivateCallCount = 0; @customElement({ name: 'test', template: 'hello dialog', }) class TestElement { public canActivate() { canActivateCallCount++; return canActivate; } } const result = await dialogService.open({ component: () => TestElement }); assert.strictEqual(result.wasCancelled, false); assert.strictEqual(canActivateCallCount, 1); assert.html.textContent(ctx.doc.querySelector('au-dialog-container'), 'hello dialog'); }, afterTornDown: ({ ctx }) => { assert.html.textContent(ctx.doc.querySelector('au-dialog-container'), null); } })), { title: 'resolves to "IOpenDialogResult" with [canActivate: false + rejectOnCancel: false]', afterStarted: async ({ ctx }, dialogService) => { let canActivateCallCount = 0; const result = await dialogService.open({ rejectOnCancel: false, template: 'hello world', component: () => class TestElement { public canActivate() { canActivateCallCount++; return false; } } }); assert.strictEqual(result.wasCancelled, true); assert.strictEqual(canActivateCallCount, 1); assert.html.textContent(ctx.doc.querySelector('au-dialog-container'), null); } }, { title: 'gets rejected with "IDialogCancelError" with [canActivate: false + rejectOnCancel: true]', afterStarted: async ({ ctx }, dialogService) => { let canActivateCallCount = 0; let error: DialogCancelError<unknown>; await dialogService.open({ rejectOnCancel: true, template: 'hello world', component: () => class TestElement { public canActivate() { canActivateCallCount++; return false; } } }).catch(err => error = err); assert.notStrictEqual(error, undefined); assert.strictEqual(error.wasCancelled, true); assert.strictEqual(error.message, 'Dialog activation rejected'); assert.strictEqual(canActivateCallCount, 1); assert.html.textContent(ctx.doc.querySelector('au-dialog-container'), null); } }, { title: 'propagates errors from canActivate', afterStarted: async (_, dialogService) => { const expectedError = new Error('Expected error.'); let canActivateCallCount = 0; let error: DialogCancelError<unknown>; await dialogService.open({ template: 'hello world', component: () => class TestElement { public canActivate() { if (canActivateCallCount === 0) { canActivateCallCount++; throw expectedError; } } } }).catch(err => error = err); assert.strictEqual(dialogService.controllers.length, 0); assert.strictEqual(error, expectedError); assert.strictEqual(canActivateCallCount, 1); } }, ...[null, undefined, true].map<IDialogServiceTestCase>(canDeactivate => ({ title: `invokes & resolves with [canDeactivate: ${canDeactivate}]`, afterStarted: async function ({ ctx }, dialogService) { let canActivateCallCount = 0; @customElement({ name: 'test', template: 'hello dialog', }) class TestElement { public canDeactivate() { canActivateCallCount++; return canDeactivate; } } const result = await dialogService.open({ component: () => TestElement }); assert.strictEqual(result.wasCancelled, false); assert.strictEqual(canActivateCallCount, 0); assert.html.textContent(ctx.doc.querySelector('au-dialog-container'), 'hello dialog'); void result.dialog.ok(); await result.dialog.closed; assert.strictEqual(canActivateCallCount, 1); assert.html.textContent(ctx.doc.querySelector('au-dialog-container'), null); } })), { title: 'resolves: "IDialogCloseResult" when: .ok()', afterStarted: async (_, dialogService) => { const { dialog } = await dialogService.open({ template: '' }); const expectedValue = 'expected ok output'; await dialog.ok(expectedValue); const result = await dialog.closed; assert.strictEqual(result.status, DialogDeactivationStatuses.Ok); assert.strictEqual(result.value, expectedValue); } }, { title: 'resolves: "IDialogCloseResult" when: .cancel() + rejectOnCancel: false', afterStarted: async (_, dialogService) => { const { dialog } = await dialogService.open({ template: '' }); const expectedOutput = 'expected cancel output'; let error: DialogCancelError<unknown>; let errorCaughtCount = 0; void dialog.cancel(expectedOutput); const result = await dialog.closed.catch(err => { errorCaughtCount++; error = err; return { status: DialogDeactivationStatuses.Error }; }); assert.strictEqual(error, undefined); assert.strictEqual(errorCaughtCount, 0); assert.strictEqual(result.status, DialogDeactivationStatuses.Cancel); } }, { title: 'rejects: "IDialogCancelError" when: .cancel() + rejectOnCancel: true', afterStarted: async (_, dialogService) => { const { dialog } = await dialogService.open({ template: '', rejectOnCancel: true }); const expectedValue = 'expected cancel error output'; let error: DialogCancelError<unknown>; let errorCaughtCount = 0; void dialog.cancel(expectedValue); await dialog.closed.catch(err => { errorCaughtCount++; error = err; return { status: DialogDeactivationStatuses.Ok }; }); assert.notStrictEqual(error, undefined); assert.strictEqual(errorCaughtCount, 1); assert.strictEqual(error.wasCancelled, true); assert.strictEqual(error.value, expectedValue); } }, { title: 'gets rejected with provided error when ".error" closed', afterStarted: async (_, dialogService) => { const { dialog } = await dialogService.open({ template: '' }); const expectedError = new Error('expected test error'); let error: DialogCancelError<unknown>; let errorCaughtCount = 0; void dialog.error(expectedError); await dialog.closed.catch(err => { errorCaughtCount++; error = err; }); assert.deepStrictEqual(error, Object.assign(new Error(), { wasCancelled: false, value: expectedError })); assert.strictEqual(errorCaughtCount, 1); } }, { title: '.closeAll() with 1 dialog', afterStarted: async (_, dialogService) => { await dialogService.open({ template: '' }); assert.strictEqual(dialogService.controllers.length, 1); const unclosedController = await dialogService.closeAll(); assert.strictEqual(dialogService.controllers.length, 0); assert.deepStrictEqual(unclosedController, []); } }, { title: '.closeAll() with more than 1 dialog', afterStarted: async (_, dialogService) => { await Promise.all([ dialogService.open({ template: '' }), dialogService.open({ template: '' }), dialogService.open({ template: '' }), ]); assert.strictEqual(dialogService.controllers.length, 3); const unclosedController = await dialogService.closeAll(); assert.strictEqual(dialogService.controllers.length, 0); assert.deepStrictEqual(unclosedController, []); } }, { title: '.closeAll() with one dialog open', afterStarted: async (_, dialogService) => { await Promise.all([ dialogService.open({ template: '' }), dialogService.open({ template: '' }), dialogService.open({ component: () => class App { private deactivateCount = 0; public canDeactivate() { // only deactivate when called 2nd time return this.deactivateCount++ > 0; } }, template: '' }), ]); assert.strictEqual(dialogService.controllers.length, 3); let unclosedController = await dialogService.closeAll(); assert.strictEqual(dialogService.controllers.length, 1); assert.strictEqual(unclosedController.length, 1); unclosedController = await dialogService.closeAll(); assert.strictEqual(dialogService.controllers.length, 0); assert.deepStrictEqual(unclosedController, []); } }, { title: 'closes dialog when clicking on overlay with lock: false', afterStarted: async ({ ctx }, dialogService) => { const { dialog } = await dialogService.open({ template: 'Hello world', lock: false }); assert.strictEqual(ctx.doc.querySelector('au-dialog-container').textContent, 'Hello world'); const overlay = ctx.doc.querySelector('au-dialog-overlay') as HTMLElement; overlay.click(); await Promise.any([ dialog.closed, new Promise(r => setTimeout(r, 50)), ]); assert.strictEqual(dialogService.controllers.length, 0); } }, { title: 'does not close dialog when clicking on overlay with lock: true', afterStarted: async ({ ctx }, dialogService) => { const { dialog } = await dialogService.open({ template: 'Hello world' }); assert.strictEqual(dialog.settings.lock, true); assert.strictEqual(ctx.doc.querySelector('au-dialog-container').textContent, 'Hello world'); const overlay = ctx.doc.querySelector('au-dialog-overlay') as HTMLElement; overlay.click(); await Promise.any([ dialog.closed, new Promise(r => setTimeout(r, 50)), ]); assert.strictEqual(dialogService.controllers.length, 1); } }, { title: 'does not close dialog when clicking inside dialog host with lock: false', afterStarted: async ({ ctx }, dialogService) => { const { dialog } = await dialogService.open({ template: 'Hello world', lock: false }); assert.strictEqual(ctx.doc.querySelector('au-dialog-container').textContent, 'Hello world'); const host = ctx.doc.querySelector('div') as HTMLElement; host.click(); await Promise.any([ dialog.closed, new Promise(r => setTimeout(r, 50)), ]); assert.strictEqual(dialogService.controllers.length, 1); } }, { title: 'closes the latest open dialog when hitting ESC key', afterStarted: async ({ ctx }, dialogService) => { const [{ dialog: dialog1 }, { dialog: dialog2 }] = await Promise.all([ dialogService.open({ template: 'Hello world', lock: false }), dialogService.open({ template: 'Hello world', lock: false }) ]); const cancelSpy1 = createSpy(dialog1, 'cancel', true); const cancelSpy2 = createSpy(dialog2, 'cancel', true); ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Escape' })); assert.strictEqual(cancelSpy1.calls.length, 0); assert.strictEqual(cancelSpy2.calls.length, 1); await dialog2.closed; ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Escape' })); assert.strictEqual(cancelSpy1.calls.length, 1); assert.strictEqual(cancelSpy2.calls.length, 1); await dialog1.closed; assert.strictEqual(dialogService.controllers.length, 0); cancelSpy1.restore(); cancelSpy2.restore(); } }, { title: 'closes with keyboard: ["Enter", "Escape"] setting', afterStarted: async ({ ctx }, dialogService) => { const [{ dialog: dialog1 }, { dialog: dialog2 }] = await Promise.all([ dialogService.open({ template: 'Hello world', lock: false, keyboard: ['Enter', 'Escape'] }), dialogService.open({ template: 'Hello world', lock: false, keyboard: ['Enter', 'Escape'] }) ]); const cancelSpy1 = createSpy(dialog1, 'ok', true); const cancelSpy2 = createSpy(dialog2, 'cancel', true); ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Escape' })); assert.strictEqual(cancelSpy1.calls.length, 0); assert.strictEqual(cancelSpy2.calls.length, 1); await dialog2.closed; ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Enter' })); assert.strictEqual(cancelSpy1.calls.length, 1); assert.strictEqual(cancelSpy2.calls.length, 1); await dialog1.closed; assert.strictEqual(dialogService.controllers.length, 0); cancelSpy1.restore(); cancelSpy2.restore(); } }, { title: 'does not close the latest open dialog when hitting ESC key when lock:true', afterStarted: async ({ ctx }, dialogService) => { const [{ dialog: dialog1 }, { dialog: dialog2 }] = await Promise.all([ dialogService.open({ template: 'Hello world', lock: false }), dialogService.open({ template: 'Hello world', lock: true }) ]); const cancelSpy1 = createSpy(dialog1, 'cancel', true); const cancelSpy2 = createSpy(dialog2, 'cancel', true); ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Escape' })); assert.strictEqual(cancelSpy1.calls.length, 0); assert.strictEqual(cancelSpy2.calls.length, 0); void dialog2.cancel(); await dialog2.closed; ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Escape' })); assert.strictEqual(cancelSpy1.calls.length, 1); await dialog1.closed; assert.strictEqual(dialogService.controllers.length, 0); cancelSpy1.restore(); cancelSpy2.restore(); } }, { title: 'closes on Enter with keyboard:Enter regardless lock:[value]', afterStarted: async ({ ctx }, dialogService) => { const { dialog: dialog1 } = await dialogService.open({ template: 'Hello world', lock: false, keyboard: ['Enter'] }); const { dialog: dialog2 } = await dialogService.open({ template: 'Hello world', lock: true, keyboard: ['Enter'] }); const okSpy1 = createSpy(dialog1, 'ok', true); const okSpy2 = createSpy(dialog2, 'ok', true); ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Escape' })); assert.strictEqual(okSpy1.calls.length, 0); assert.strictEqual(okSpy2.calls.length, 0); ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Enter' })); assert.strictEqual(okSpy1.calls.length, 0); assert.strictEqual(okSpy2.calls.length, 1); await dialog2.closed; ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Enter' })); assert.strictEqual(okSpy1.calls.length, 1); assert.strictEqual(okSpy2.calls.length, 1); await dialog1.closed; assert.strictEqual(dialogService.controllers.length, 0); okSpy1.restore(); okSpy2.restore(); } }, { title: 'does not response to keys that are not [Escape]/[Enter]', afterStarted: async ({ ctx }, dialogService) => { const { dialog: controller1 } = await dialogService.open({ template: 'Hello world', lock: false, keyboard: ['Enter', 'Escape'] }); const okSpy1 = createSpy(controller1, 'ok', true); ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Tab' })); assert.strictEqual(okSpy1.calls.length, 0); ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'A' })); assert.strictEqual(okSpy1.calls.length, 0); ctx.wnd.dispatchEvent(new ctx.wnd.KeyboardEvent('keydown', { key: 'Space' })); assert.strictEqual(okSpy1.calls.length, 0); okSpy1.restore(); } }, { title: 'invokes lifeycyles in correct order', afterStarted: async (_, dialogService) => { const lifecycles: string[] = []; function log(lifecylce: string) { lifecycles.push(lifecylce); } class MyDialog { public constructor() { log('constructor'); } } [ 'canActivate', 'activate', 'define', 'hydrating', 'hydrated', 'binding', 'bound', 'attaching', 'attached', 'canDeactivate', 'deactivate', 'detaching', 'unbinding', ].forEach(method => { MyDialog.prototype[method] = function () { log(method); }; }); const { dialog } = await dialogService.open({ component: () => MyDialog }); assert.deepStrictEqual(lifecycles, [ 'constructor', 'canActivate', 'activate', 'define', 'hydrating', 'hydrated', 'binding', 'bound', 'attaching', 'attached', ]); void dialog.ok(); await dialog.closed; assert.deepStrictEqual(lifecycles, [ 'constructor', 'canActivate', 'activate', 'define', 'hydrating', 'hydrated', 'binding', 'bound', 'attaching', 'attached', 'canDeactivate', 'deactivate', 'detaching', 'unbinding', ]); } }, { title: 'it works with .delegate listener', afterStarted: async ({ ctx }, dialogService) => { let click1CallCount = 0; let click2CallCount = 0; await Promise.all([ dialogService.open({ component: () => class MyClass1 { public onClick() { click1CallCount++; } }, template: '<button data-dialog-btn click.delegate="onClick()">' }), dialogService.open({ component: () => class MyClass2 { public onClick() { click2CallCount++; } }, template: '<button data-dialog-btn click.delegate="onClick()">' }), ]); const buttons = Array.from(ctx.doc.querySelectorAll('[data-dialog-btn]')) as HTMLElement[]; buttons[0].click(); assert.strictEqual(click1CallCount, 1); assert.strictEqual(click2CallCount, 0); buttons[1].click(); assert.strictEqual(click1CallCount, 1); assert.strictEqual(click2CallCount, 1); } }, { title: 'it passes model to the lifecycle methods', afterStarted: async (_, dialogService) => { let canActivateCalled = false; let activateCalled = false; const model = {}; await dialogService.open({ model, component: () => class { public canActivate($model: unknown) { canActivateCalled = true; assert.strictEqual(model, $model); } public activate($model: unknown) { activateCalled = true; assert.strictEqual(model, $model); } } }); assert.strictEqual(canActivateCalled, true); assert.strictEqual(activateCalled, true); } }, { title: 'works with .whenClosed() shortcut', afterStarted: async (_, dialogService) => { const openPromise = dialogService.open({ template: () => 'Hello' }); const whenClosedPromise = openPromise.whenClosed(result => result.value); const { dialog } = await openPromise; setTimeout(() => { void dialog.ok('Hello 123abc'); }, 0); const value = await whenClosedPromise; assert.strictEqual(value, 'Hello 123abc'); } }, { title: 'it renders to a specific host', afterStarted: async ({ ctx, appHost }, dialogService) => { const dialogHost = appHost.appendChild(ctx.createElement('div')); await dialogService.open({ host: dialogHost, template: '<p>Hello world</p>' }); assert.visibleTextEqual(dialogHost, 'Hello world'); } }, { title: 'registers only first deactivation value', afterStarted: async (_, dialogService) => { let resolve: (value?: unknown) => unknown; const { dialog } = await dialogService.open({ component: () => ({ deactivate: () => new Promise(r => { resolve = r; }) }) }); const dialogValue = {}; const p1 = dialog.ok(dialogValue); const p2 = dialog.ok(); resolve(); const [result1, result2] = await Promise.all([p1, p2]); assert.strictEqual(result1.value, result2.value); assert.strictEqual(result1.value, dialogValue); } }, { title: 'assigns the dialog controller to "$dialog" property for view only dialog', afterStarted: async ({ ctx }, dialogService) => { const { dialog } = await dialogService.open({ template: 'Hello world <button click.trigger="$dialog.ok(1)"></button>' }); const spy = createSpy(dialog, 'ok', true); ctx.doc.querySelector('button').click(); assert.strictEqual(spy.calls.length, 1); } }, { title: 'assigns the dialog controller to "$dialog" property for component only dialog', afterStarted: async (_, dialogService) => { let isSet = false; let $dialog: IDialogController; const { dialog } = await dialogService.open({ component: () => ({ set $dialog(dialog: IDialogController) { isSet = true; $dialog = dialog; } }) }); assert.strictEqual(isSet, true); assert.strictEqual($dialog, dialog); } }, { title: 'assigns the dialog controller to "$dialog" property for CustomElement', afterStarted: async (_, dialogService) => { let isSet = false; let $dialog: IDialogController; const { dialog } = await dialogService.open({ component: () => CustomElement.define({ name: 'hello-world', template: 'Hello 123' }, class { public set $dialog(dialog: IDialogController) { isSet = true; $dialog = dialog; } }) }); assert.strictEqual(isSet, true); assert.strictEqual($dialog, dialog); } }, { title: 'animates correctly', afterStarted: async (_, dialogService) => { const { dialog } = await dialogService.open({ template: '<div style="width: 300px; height: 300px; background: red;">Hello world', component: () => class MyDialog { public static get inject() { return [INode]; } public constructor(private readonly host: Element) {} public attaching() { const animation = this.host.animate?.( [{ transform: 'translateY(0px)' }, { transform: 'translateY(-300px)' }], { duration: 100 }, ); return animation?.finished; } public detaching() { const animation = this.host.animate?.( [{ transform: 'translateY(-300px)' }, { transform: 'translateY(0)' }], { duration: 100 }, ); return animation?.finished; } }, }); await dialog.ok(); } } ]; for (const { title, only, afterStarted, afterTornDown } of testCases) { const $it = only ? it.only : it; $it(title, async function () { const creationResult = createFixture('', class App { }, [DialogDefaultConfiguration]); const { ctx, tearDown, startPromise } = creationResult; await startPromise; const dialogService = ctx.container.get(IDialogService); try { await afterStarted(creationResult, dialogService); } catch (ex) { try { await dialogService.closeAll(); } catch (e2) {/* best effort */ } try { await tearDown(); } catch (e2) {/* best effort */ } ctx.doc.querySelectorAll('au-dialog-container').forEach(e => e.remove()); throw ex; } await tearDown(); await afterTornDown?.(creationResult, dialogService); const dialogContainerEls = ctx.doc.querySelectorAll('au-dialog-container'); dialogContainerEls.forEach(e => e.remove()); if (dialogContainerEls.length > 0) { throw new Error('Invalid test, left over <au-dialog-container/> in the document'); } }); } }); interface IDialogServiceTestCase { title: string; afterStarted: (appCreationResult: ReturnType<typeof createFixture>, dialogService: IDialogService) => void | Promise<void>; afterTornDown?: (appCreationResult: ReturnType<typeof createFixture>, dialogService: IDialogService) => void | Promise<void>; only?: boolean; } });
the_stack
import * as check from 'post-install-check'; // Used to easily debug specific tests if necessary. // Otherwise, no tests should be skipped. const SKIP = { base: false, express: false, hapi: {sixteen: false, seventeen: false}, koa: {one: false, two: false}, restify: {seven: false, eight: false}, }; const TS_CODE_ARRAY: check.CodeSample[] = [ { code: `import * as errorReporting from '@google-cloud/error-reporting'; new errorReporting.ErrorReporting();`, description: 'imports the module using * syntax', dependencies: [], devDependencies: [], skip: SKIP.base, }, { code: `import {ErrorReporting} from '@google-cloud/error-reporting'; new ErrorReporting();`, description: 'imports the module with {} syntax', dependencies: [], devDependencies: [], skip: SKIP.base, }, { code: `import {ErrorReporting} from '@google-cloud/error-reporting'; new ErrorReporting({ serviceContext: { service: 'some service' } });`, description: 'imports the module and starts with a partial `serviceContext`', dependencies: [], devDependencies: [], skip: SKIP.base, }, { code: `import {ErrorReporting} from '@google-cloud/error-reporting'; new ErrorReporting({ projectId: 'some-project', serviceContext: { service: 'Some service', version: 'Some version' } });`, description: 'imports the module and starts with a complete `serviceContext`', dependencies: [], devDependencies: [], skip: SKIP.base, }, { code: `import * as express from 'express'; import {ErrorReporting} from '@google-cloud/error-reporting'; const errors = new ErrorReporting(); const app = express(); app.get('/error', (req, res, next) => { res.send('Something broke!'); next!(new Error('Custom error message')); }); app.get('/exception', () => { JSON.parse('{"malformedJson": true'); }); app.use(errors.express); `, description: 'uses express', dependencies: ['express'], devDependencies: ['@types/express'], skip: SKIP.express, }, { code: `import * as hapi from 'hapi'; import {ErrorReporting} from '@google-cloud/error-reporting'; const errors = new ErrorReporting(); const server = new hapi.Server(); server.connection({ port: 3000 }); server.route({ method: 'GET', path: '/error', handler: (request, reply) => { reply('Something broke!'); throw new Error('Custom error message'); } }); server.register(errors.hapi); `, description: 'uses hapi16', dependencies: ['hapi@16.x.x'], devDependencies: ['@types/hapi@16.x.x'], skip: SKIP.hapi.sixteen, }, { code: `import * as hapi from 'hapi'; import {ErrorReporting} from '@google-cloud/error-reporting'; const errors = new ErrorReporting(); async function start() { const server = new hapi.Server({ host: '0.0.0.0', port: 3000 }); server.route({ method: 'GET', path: '/error', handler: async (request, h) => { throw new Error(\`You requested an error at ${new Date()}\`); } }); await server.register(errors.hapi); } start().catch(console.error); `, description: 'uses hapi17', dependencies: ['hapi@17.x.x'], devDependencies: ['@types/hapi@17.x.x'], skip: SKIP.hapi.seventeen, }, { code: `import * as Koa from 'koa'; import {ErrorReporting} from '@google-cloud/error-reporting'; const errors = new ErrorReporting(); const app = new Koa(); app.use(errors.koa); app.use(function *(this: any): IterableIterator<any> { //This will set status and message this.throw('Error Message', 500); }); // response app.use(function *(this: any): IterableIterator<any> { this.body = 'Hello World'; }); `, description: 'uses koa1', dependencies: ['koa@1.x.x'], devDependencies: ['@types/koa'], skip: SKIP.koa.one, }, { code: `import * as Koa from 'koa'; import {ErrorReporting} from '@google-cloud/error-reporting'; const errors = new ErrorReporting(); const app = new Koa(); app.use(errors.koa2); app.use(async (ctx: Koa.Context, next: {}) => { //This will set status and message ctx.throw('Error Message', 500); }); // response app.use(async (ctx: Koa.Context, next: {}): Promise<void> => { ctx.body = 'Hello World'; }); `, description: 'uses koa2', dependencies: ['koa@2.x.x'], devDependencies: ['@types/koa@2.x.x'], skip: SKIP.koa.two, }, { code: `import * as restify from 'restify'; import {ErrorReporting} from '@google-cloud/error-reporting'; const errors = new ErrorReporting(); function respond(req: {}, res: {}, next: Function) { next(new Error('this is a restify error')); } const server = restify.createServer(); server.use(errors.restify(server)); server.get('/hello/:name', respond); server.head('/hello/:name', respond); `, description: 'uses restify', dependencies: ['restify@7.x.x'], devDependencies: ['@types/restify@7.x.x'], skip: SKIP.restify.seven, }, { code: `import * as restify from 'restify'; import {ErrorReporting} from '@google-cloud/error-reporting'; const errors = new ErrorReporting(); function respond(req: {}, res: {}, next: Function) { next(new Error('this is a restify error')); } const server = restify.createServer(); server.use(errors.restify(server)); server.get('/hello/:name', respond); server.head('/hello/:name', respond); `, description: 'uses restify', dependencies: ['restify@8.x.x'], devDependencies: ['@types/restify@7.x.x'], skip: SKIP.restify.eight, }, ]; const JS_CODE_ARRAY: check.CodeSample[] = [ { code: `const ErrorReporting = require('@google-cloud/error-reporting').ErrorReporting; new ErrorReporting();`, description: 'requires the module using Node 4+ syntax', dependencies: [], devDependencies: [], skip: SKIP.base, }, { code: `const ErrorReporting = require('@google-cloud/error-reporting').ErrorReporting; new ErrorReporting({ serviceContext: { service: 'some service' } });`, description: 'requires the module and starts with a partial `serviceContext`', dependencies: [], devDependencies: [], skip: SKIP.base, }, { code: `const ErrorReporting = require('@google-cloud/error-reporting').ErrorReporting; new ErrorReporting({ projectId: 'some-project', serviceContext: { service: 'Some service', version: 'Some version' } });`, description: 'requires the module and starts with a complete `serviceContext`', dependencies: [], devDependencies: [], skip: SKIP.base, }, { code: `const express = require('express'); const ErrorReporting = require('@google-cloud/error-reporting').ErrorReporting; const errors = new ErrorReporting(); const app = express(); app.get('/error', (req, res, next) => { res.send('Something broke!'); next(new Error('Custom error message')); }); app.get('/exception', () => { JSON.parse('{"malformedJson": true'); }); // Note that express error handling middleware should be attached after all // the other routes and use() calls. See [express docs][express-error-docs]. app.use(errors.express); `, description: 'uses express', dependencies: ['express'], devDependencies: [], skip: SKIP.express, }, { code: `const hapi = require('hapi'); const ErrorReporting = require('@google-cloud/error-reporting').ErrorReporting; const errors = new ErrorReporting(); const server = new hapi.Server(); server.connection({ port: 3000 }); server.route({ method: 'GET', path: '/error', handler: (request, reply) => { reply('Something broke!'); throw new Error('Custom error message'); } }); server.register(errors.hapi); `, description: 'uses hapi16', dependencies: ['hapi@16.x.x'], devDependencies: [], skip: SKIP.hapi.sixteen, }, { code: `const hapi = require('hapi'); const ErrorReporting = require('@google-cloud/error-reporting').ErrorReporting; const errors = new ErrorReporting(); async function start() { const server = new hapi.Server({ host: '0.0.0.0', port: 3000 }); server.route({ method: 'GET', path: '/error', handler: async (request, h) => { throw new Error(\`You requested an error at ${new Date()}\`); } }); await server.register(errors.hapi); } start().catch(console.error); `, description: 'uses hapi17', dependencies: ['hapi@17.x.x'], devDependencies: [], skip: SKIP.hapi.seventeen, }, { code: `const Koa = require('koa'); const ErrorReporting = require('@google-cloud/error-reporting').ErrorReporting; const errors = new ErrorReporting(); const app = new Koa(); app.use(errors.koa); app.use(function *(next) { //This will set status and message this.throw('Error Message', 500); }); // response app.use(function *(){ this.body = 'Hello World'; }); `, description: 'uses koa1', dependencies: ['koa@1.x.x'], devDependencies: [], skip: SKIP.koa.one, }, { code: `const Koa = require('koa'); const ErrorReporting = require('@google-cloud/error-reporting').ErrorReporting; const errors = new ErrorReporting(); const app = new Koa(); app.use(errors.koa2); app.use(async (ctx, next) => { //This will set status and message ctx.throw('Error Message', 500); }); // response app.use(async (ctx, next) => { ctx.body = 'Hello World'; }); `, description: 'uses koa2', dependencies: ['koa@2.x.x'], devDependencies: [], skip: SKIP.koa.two, }, { code: `const restify = require('restify'); const ErrorReporting = require('@google-cloud/error-reporting').ErrorReporting; const errors = new ErrorReporting(); function respond(req, res, next) { next(new Error('this is a restify error')); } const server = restify.createServer(); server.use(errors.restify(server)); server.get('/hello/:name', respond); server.head('/hello/:name', respond); `, description: 'uses restify', dependencies: ['restify@7.x.x'], devDependencies: [], skip: SKIP.restify.seven, }, { code: `const restify = require('restify'); const ErrorReporting = require('@google-cloud/error-reporting').ErrorReporting; const errors = new ErrorReporting(); function respond(req, res, next) { next(new Error('this is a restify error')); } const server = restify.createServer(); server.use(errors.restify(server)); server.get('/hello/:name', respond); server.head('/hello/:name', respond); `, description: 'uses restify', dependencies: ['restify@8.x.x'], devDependencies: [], skip: SKIP.restify.eight, }, ]; check.testInstallation(TS_CODE_ARRAY, JS_CODE_ARRAY, {timeout: 2 * 60 * 1000});
the_stack
import { initTooltips } from "util.js"; import { Annotation, AnnotationType } from "code_listing/annotation"; import { MachineAnnotation, MachineAnnotationData } from "code_listing/machine_annotation"; import { UserAnnotation, UserAnnotationData, UserAnnotationFormData } from "code_listing/user_annotation"; import { createUserAnnotation, getAllUserAnnotations } from "code_listing/question_annotation"; const annotationGlobalAdd = "#add_global_annotation"; const annotationsGlobal = "#feedback-table-global-annotations"; const annotationsGlobalGroups = "#feedback-table-global-annotations-list"; const annotationHideAll = "#hide_all_annotations"; const annotationShowAll = "#show_all_annotations"; const annotationShowErrors = "#show_only_errors"; const annotationToggles = "#annotations_toggles"; const annotationFormCancel = ".annotation-cancel-button"; const annotationFormDelete = ".annotation-delete-button"; const annotationFormSubmit = ".annotation-submission-button"; const badge = "#badge_code"; type OrderGroup = "error" | "conversation" | "warning" | "info"; // Map in which annotation group the annotation should appear. const GROUP_MAPPING: Record<AnnotationType, OrderGroup> = { "error": "error", "user": "conversation", "warning": "warning", "info": "info", "question": "conversation" }; // Order the groups. We use the same order as appearance in the mapping. const GROUP_ORDER: OrderGroup[] = Array.from(new Set(Object.values(GROUP_MAPPING))); export class CodeListing { private readonly annotations: Map<number, Annotation[]>; public readonly code: string; public readonly codeLines: number; public readonly submissionId: number; private readonly markingClass: string = "marked"; private evaluationId: number; private readonly badge: HTMLSpanElement; private readonly table: HTMLTableElement; private readonly globalAnnotations: HTMLDivElement; private readonly globalAnnotationGroups: HTMLDivElement; private readonly hideAllAnnotations: HTMLButtonElement; private readonly showAllAnnotations: HTMLButtonElement; private readonly showErrorAnnotations: HTMLButtonElement; private readonly annotationToggles: HTMLDivElement; private readonly questionMode: boolean; constructor(submissionId: number, code: string, codeLines: number, questionMode = false) { this.annotations = new Map<number, Annotation[]>(); this.code = code; this.codeLines = codeLines; this.submissionId = submissionId; this.questionMode = questionMode; this.badge = document.querySelector<HTMLSpanElement>(badge); this.table = document.querySelector<HTMLTableElement>("table.code-listing"); this.hideAllAnnotations = document.querySelector<HTMLButtonElement>(annotationHideAll); this.showAllAnnotations = document.querySelector<HTMLButtonElement>(annotationShowAll); this.showErrorAnnotations = document.querySelector<HTMLButtonElement>(annotationShowErrors); this.annotationToggles = document.querySelector<HTMLDivElement>(annotationToggles); this.globalAnnotations = document.querySelector<HTMLDivElement>(annotationsGlobal); this.globalAnnotationGroups = document.querySelector<HTMLDivElement>(annotationsGlobalGroups); this.initAnnotations(); } setEvaluation(id: number): void { this.evaluationId = id; } // ///////////////////////////////////////////////////////////////////////// // Highlighting //////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// clearHighlights(): void { const markedAnnotations = this.table.querySelectorAll(`tr.lineno.${this.markingClass}`); markedAnnotations.forEach(markedAnnotation => { markedAnnotation.classList.remove(this.markingClass); }); } highlightLine(lineNr: number, scrollToLine = false): void { const toMarkAnnotationRow = this.table.querySelector(`tr.lineno#line-${lineNr}`); toMarkAnnotationRow.classList.add(this.markingClass); if (scrollToLine) { toMarkAnnotationRow.scrollIntoView({ block: "center" }); } } // ///////////////////////////////////////////////////////////////////////// // Annotation management /////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// public addAnnotation(annotation: Annotation): void { const line = annotation.global ? 0 : annotation.line; if (!this.annotations.has(line)) { this.annotations.set(line, []); } // Add the annotation in the map. this.annotations.get(line).push(annotation); // Append the HTML component of the annotation to the code table. if (annotation.global) { this.appendAnnotationToGlobal(annotation); } else { this.appendAnnotationToTable(annotation); } this.updateViewState(); } private addMachineAnnotation(data: MachineAnnotationData): void { const annotation = new MachineAnnotation(data); this.addAnnotation(annotation); } // noinspection JSUnusedGlobalSymbols used by FeedbackCodeRenderer. public addMachineAnnotations(annotations: MachineAnnotationData[]): void { annotations.forEach(ma => this.addMachineAnnotation(ma)); } // Unit-testing purposes. private addUserAnnotation(data: UserAnnotationData): void { const annotation = new UserAnnotation(data, (a, cb) => this.createUpdateAnnotationForm(a, cb)); this.addAnnotation(annotation); } // Unit-testing purposes. public addUserAnnotations(annotations: UserAnnotationData[]): void { annotations.forEach(ua => this.addUserAnnotation(ua)); } // noinspection JSUnusedGlobalSymbols used by FeedbackCodeRenderer. public async loadUserAnnotations(): Promise<void> { return getAllUserAnnotations(this.submissionId, (a, cb) => this.createUpdateAnnotationForm(a, cb)) .then(annotations => { annotations.forEach(annotation => this.addAnnotation(annotation)); initTooltips(); }); } public removeAnnotation(annotation: Annotation): void { const line = annotation.global ? 0 : annotation.line; // Remove the annotation from the map. const lineAnnotations = this.annotations.get(line).filter(a => a.__id !== annotation.__id); if (lineAnnotations.length === 0) { this.annotations.delete(line); // Remove the padding from the annotation list. if (annotation.global) { this.globalAnnotations.classList.remove("has-annotations"); } } else { this.annotations.set(line, lineAnnotations); } this.updateViewState(); } public updateAnnotation(original: Annotation, updated: Annotation): void { const origLine = original.global ? 0 : original.line; const updLine = updated.global ? 0 : updated.line; // Different line -> can simply remove and re-add. if (origLine !== updLine) { this.removeAnnotation(original); this.addAnnotation(updated); return; } // Find the annotation in the map. const lineAnnotations = this.annotations.get(origLine); lineAnnotations.forEach((annotation, idx) => { if (annotation.__id === original.__id) { lineAnnotations[idx] = updated; } }); this.annotations.set(updLine, lineAnnotations); // Replace the HTML component. document.querySelector(`#annotation-div-${original.__id}`).replaceWith(updated.html); } // ///////////////////////////////////////////////////////////////////////// // DOM operations ////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// private appendAnnotationToGlobal(annotation: Annotation): void { // Append the annotation. this.globalAnnotationGroups .querySelector<HTMLDivElement>(`.annotation-group-${GROUP_MAPPING[annotation.type]}`) .appendChild(annotation.html); // Add the padding to the global annotation list. this.globalAnnotations.classList.add("has-annotations"); } private appendAnnotationToTable(annotation: Annotation): void { const line = Math.min(annotation.line, this.codeLines); const row = this.table.querySelector<HTMLTableRowElement>(`#line-${line}`); const cell = row.querySelector<HTMLDivElement>(`#annotation-cell-${line}`); if (cell.querySelector(`.annotation-group-${GROUP_MAPPING[annotation.type]}`) === null) { // Create the dot. const dot = document.createElement("span") as HTMLSpanElement; dot.classList.add("dot", "hide"); dot.id = `dot-${line}`; row.querySelector<HTMLTableDataCellElement>(".rouge-gutter").prepend(dot); // Create annotation groups. GROUP_ORDER.forEach((type: string) => { const group = document.createElement("div") as HTMLDivElement; group.classList.add(`annotation-group-${type}`); cell.appendChild(group); }); } // Append the annotation. cell.querySelector<HTMLDivElement>(`.annotation-group-${GROUP_MAPPING[annotation.type]}`) .appendChild(annotation.html); } // ////////////////////////////////////////////////////////////////////////// // Initialisations ////////////////////////////////////////////////////////// // ////////////////////////////////////////////////////////////////////////// private initAnnotations(): void { // Create global annotation groups. GROUP_ORDER.forEach((type: string) => { const group = document.createElement("div") as HTMLDivElement; group.classList.add(`annotation-group-${type}`); this.globalAnnotationGroups.appendChild(group); }); // Create annotation cells. for (let i = 1; i <= this.codeLines; ++i) { const tableLine = this.table.querySelector<HTMLTableRowElement>(`#line-${i}`); tableLine.dataset["line"] = i.toString(); // Add an annotation container underneath the pre element. const lineCodeCell = tableLine.querySelector<HTMLTableDataCellElement>(".rouge-code"); const annotationContainer = document.createElement("div") as HTMLDivElement; annotationContainer.classList.add("annotation-cell"); annotationContainer.id = `annotation-cell-${i}`; lineCodeCell.appendChild(annotationContainer); } // Toggle buttons. this.hideAllAnnotations.addEventListener("click", () => this.hideAnnotations()); this.showAllAnnotations.addEventListener("click", () => this.showAnnotations()); this.showErrorAnnotations.addEventListener("click", () => this.hideAnnotations(true)); } // noinspection JSUnusedGlobalSymbols used by FeedbackCodeRenderer. public initAnnotateButtons(): void { // Global annotations. const globalButton = document.querySelector(annotationGlobalAdd); globalButton.addEventListener("click", () => this.handleAnnotateGlobal()); const type = this.questionMode ? "user_question" : "user_annotation"; const title = I18n.t(`js.${type}.send`); // Inline annotations. const codeLines = this.table.querySelectorAll(".lineno"); codeLines.forEach((codeLine: HTMLTableRowElement) => { const annotationButton = document.createElement("button") as HTMLButtonElement; annotationButton.classList.add("btn", "btn-primary", "annotation-button"); annotationButton.addEventListener("click", () => this.handleAnnotateLine(codeLine)); annotationButton.title = title; const annotationButtonIcon = document.createElement("i") as HTMLElement; const clazz = this.questionMode ? "mdi-comment-question-outline" : "mdi-comment-plus-outline"; annotationButtonIcon.classList.add("mdi", clazz, "mdi-18"); annotationButton.appendChild(annotationButtonIcon); codeLine.querySelector(".rouge-gutter").prepend(annotationButton); }); } // ///////////////////////////////////////////////////////////////////////// // Show and hide annotations /////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// public hideAnnotations(keepImportant = false): void { this.annotations.forEach((annotations, _line) => { // Do not hide global annotations. if (_line === 0) { return; } const line = Math.min(_line, this.codeLines); // Find the dot for this line. const dot = this.table.querySelector<HTMLSpanElement>(`#dot-${line}`); // Determine the colours of the dot for this line. const colours = annotations .filter(annotation => !annotation.important || !keepImportant) .map(annotation => `dot-${annotation.type}`); // Configure the dot. if (colours.length > 0) { // Remove previous colours. dot.classList.remove("hide", ...GROUP_ORDER.map(type => `dot-${type}`)); // Add new colours. dot.classList.add(...colours); // Help text. const count = annotations.length; if (count === 1) { dot.title = I18n.t("js.annotation.hidden.single"); } else { dot.title = I18n.t("js.annotation.hidden.plural", { count: count }); } } else { // Hide the dot. dot.classList.add("hide"); } }); this.annotations.forEach(annotations => annotations.forEach(annotation => { if (annotation.global || (keepImportant && annotation.important)) { annotation.show(); } else { annotation.hide(); } })); } public showAnnotations(): void { this.annotations.forEach(annotations => { annotations.forEach(annotation => annotation.show()); }); // Hide all dots. this.table.querySelectorAll<HTMLSpanElement>(".dot").forEach(dot => { dot.classList.add("hide"); }); } // ///////////////////////////////////////////////////////////////////////// // Creating and modifying user annotations ///////////////////////////////// // ///////////////////////////////////////////////////////////////////////// private createAnnotationForm(id: string, annotation: Annotation | null, onSubmit: (f: HTMLFormElement) => Promise<void>, onCancel: (f: HTMLFormElement) => void): HTMLFormElement { const form = document.createElement("form") as HTMLFormElement; const type = this.questionMode ? "user_question" : "user_annotation"; form.classList.add("annotation-submission"); form.id = id; // Min and max of the annotation text is defined in the annotation model. const maxLength = 10_000; form.innerHTML = ` <textarea autofocus required class="form-control annotation-submission-input" rows="3" minlength="1" maxlength="${maxLength}"></textarea> <div class="clearfix annotation-help-block"> <span class='help-block'>${I18n.t("js.user_annotation.help")}</span> <span class="help-block float-end"><span class="used-characters">0</span> / ${I18n.toNumber(maxLength, { precision: 0 })}</span> </div> <div class="annotation-submission-button-container"> ${annotation && annotation.removable ? ` <button class="btn-text annotation-control-button annotation-delete-button" type="button"> ${I18n.t("js.user_annotation.delete")} </button> ` : ""} <button class="btn-text annotation-control-button annotation-cancel-button" type="button"> ${I18n.t("js.user_annotation.cancel")} </button> <button class="btn btn-text btn-primary annotation-control-button annotation-submission-button" type="button"> ${(annotation !== null ? I18n.t(`js.${type}.update`) : I18n.t(`js.${type}.send`))} </button> </div> `; const cancelButton = form.querySelector<HTMLButtonElement>(annotationFormCancel); const deleteButton = form.querySelector<HTMLButtonElement>(annotationFormDelete); const sendButton = form.querySelector<HTMLButtonElement>(annotationFormSubmit); const inputField = form.querySelector<HTMLTextAreaElement>("textarea"); if (annotation !== null) { inputField.rows = annotation.rawText.split("\n").length + 1; inputField.textContent = annotation.rawText; } const usedCharacters = form.querySelector(".used-characters"); // Initial value. usedCharacters.innerHTML = I18n.toNumber(inputField.value.length, { precision: 0 }); // Update value while typing. inputField.addEventListener("input", () => { usedCharacters.innerHTML = I18n.toNumber(inputField.value.length, { precision: 0 }); }); // Cancellation handler. cancelButton.addEventListener("click", () => onCancel(form)); // Deletion handler. if (deleteButton !== null) { deleteButton.addEventListener("click", async () => { const type = this.questionMode ? "user_question" : "user_annotation"; const confirmText = I18n.t(`js.${type}.delete_confirm`); if (confirm(confirmText)) { annotation.remove().then(() => this.removeAnnotation(annotation)); } }); } // Submission handler. sendButton.addEventListener("click", async () => { if (sendButton.getAttribute("disabled") !== "1") { sendButton.setAttribute("disabled", "1"); await onSubmit(form); sendButton.removeAttribute("disabled"); // Ask MathJax to search for math in the annotations window.MathJax.typeset(); } }); inputField.addEventListener("keydown", e => { if (e.code === "Enter" && e.shiftKey) { // Send using Shift-Enter. e.preventDefault(); sendButton.click(); return false; } else if (e.code === "Escape") { // Cancel using ESC. e.preventDefault(); cancelButton.click(); return false; } }); return form; } private createNewAnnotationForm(line: number | null): HTMLFormElement { const onSubmit = async (form: HTMLFormElement): Promise<void> => { const inputField = form.querySelector<HTMLTextAreaElement>("textarea"); inputField.classList.remove("validation-error"); // Run client side validations. if (!inputField.reportValidity()) { return; // Something is wrong, abort. } const annotationData: UserAnnotationFormData = { "annotation_text": inputField.value, "line_nr": (line === null ? null : line - 1), "evaluation_id": this.evaluationId || undefined }; try { const mode = this.questionMode ? "question" : "annotation"; const annotation = await createUserAnnotation(annotationData, this.submissionId, (a, cb) => this.createUpdateAnnotationForm(a, cb), mode); this.addAnnotation(annotation); form.remove(); } catch (err) { inputField.classList.add("validation-error"); } }; return this.createAnnotationForm(`annotation-submission-new-${line || 0}`, null, onSubmit, form => form.remove()); } private createUpdateAnnotationForm(annotation: UserAnnotation, callback: CallableFunction): HTMLFormElement { const onSubmit = async (form: HTMLFormElement): Promise<void> => { const inputField = form.querySelector<HTMLTextAreaElement>("textarea"); // Run client side validations. if (!inputField.reportValidity()) { return; // Something is wrong, abort. } const annotationData: UserAnnotationFormData = { "annotation_text": inputField.value, "line_nr": (annotation.line === null ? null : annotation.line - 1), "evaluation_id": annotation.evaluationId || undefined }; try { const updated = await annotation.update(annotationData); this.updateAnnotation(annotation, updated); } catch (err) { inputField.classList.add("validation-error"); } }; const formId = `annotation-submission-update-${annotation.id}`; return this.createAnnotationForm(formId, annotation, onSubmit, () => callback()); } private handleAnnotateGlobal(): void { // Attempt to find an existing form and reuse that. const formId = "#annotation-submission-0"; let form = this.globalAnnotations.querySelector<HTMLFormElement>(formId); if (form === null) { form = this.createNewAnnotationForm(null); // Inject the form into the div. this.globalAnnotations.prepend(form); } // Focus the input field. We must wait till the next frame, because we can only give the // focus after the element is added to the dom. const input = form.querySelector<HTMLTextAreaElement>(".annotation-submission-input"); window.requestAnimationFrame(() => input.focus()); } private handleAnnotateLine(row: HTMLTableRowElement): void { const lineNo = parseInt(row.dataset["line"]); // Attempt to find an existing form and reuse that. let form = row.querySelector<HTMLFormElement>(`#annotation-submission-new-${lineNo}`); if (form === null) { form = this.createNewAnnotationForm(lineNo); // Inject the form into the table. const cell = row.querySelector<HTMLTableDataCellElement>(`#annotation-cell-${lineNo}`); cell.prepend(form); } // Focus the input field. We must wait till the next frame, because we can only give the // focus after the element is added to the dom. const input = form.querySelector<HTMLTextAreaElement>(".annotation-submission-input"); window.requestAnimationFrame(() => input.focus()); } // ///////////////////////////////////////////////////////////////////////// // Update view ///////////////////////////////////////////////////////////// // ///////////////////////////////////////////////////////////////////////// private get annotationCount(): number { return Array.from(this.annotations.values()) .map(ann => ann.length) .reduce((acc, nw) => acc + nw, 0); } /** * Updates the badge count and button visibility state. */ private updateViewState(): void { const amount = this.annotationCount; if (amount > 0) { // Set the badge count. this.badge.innerText = amount.toString(); // Find the important annotations. const importantAnnotationCount = Array.from(this.annotations.values()) .map(annotations => annotations.filter(an => an.important).length) .reduce((acc, nw) => acc + nw); if (importantAnnotationCount === 0 || importantAnnotationCount === amount) { this.showErrorAnnotations.classList.add("hide"); } else { this.showErrorAnnotations.classList.remove("hide"); } // Show the annotation toggles. this.annotationToggles.classList.remove("hide"); // Ask MathJax to search for math in the annotations window.MathJax.typeset(); } else { // No annotations have been added (yet). this.badge.innerText = ""; // Hide the annotation toggles. this.annotationToggles.classList.add("hide"); } } }
the_stack
import db from '../models/db.js'; import { GraphQLSchema, GraphQLObjectType, GraphQLList, GraphQLID, GraphQLString, GraphQLNonNull, } from 'graphql'; // =========================== // // ===== TYPE DEFINITIONS ==== // // =========================== // const BookType = new GraphQLObjectType({ name: 'Book', fields: () => ({ id: { type: GraphQLID }, title: { type: GraphQLString }, genre: { type: GenreType, async resolve(parent) { const queryString = ` SELECT * FROM genres WHERE id = ${parent.genre_id} `; const genre = await db.query(queryString); return genre.rows[0] as string; }, }, authors: { type: new GraphQLList(AuthorType), async resolve(parent) { const queryString = ` SELECT authors.* FROM ((authors INNER JOIN booksauthors ON booksAuthors.AuthorId = authors.id) INNER JOIN books ON books.id = booksAuthors.BookId) WHERE books.id = ${parent.id} `; const authors = await db.query(queryString); return authors.rows as string; }, }, }), }); const AuthorType = new GraphQLObjectType({ name: 'Author', fields: () => ({ id: { type: GraphQLID }, name: { type: GraphQLString }, country: { type: GraphQLString }, }), }); const GenreType = new GraphQLObjectType({ name: 'Genre', fields: () => ({ id: { type: GraphQLID }, name: { type: GraphQLString }, }), }); // ================== // // ===== QUERIES ==== // // ================== // const RootQuery = new GraphQLObjectType({ name: 'RootQueryType', fields: { //GET BOOK BY ID book: { type: BookType, args: { id: { type: GraphQLID } }, async resolve(parent, args) { const queryString = ` SELECT * FROM books WHERE id = $1 `; const book = await db.query(queryString, [args.id]); return book.rows[0] as string; }, }, //GET ALL BOOKS books: { type: new GraphQLList(BookType), async resolve() { const queryString = ` SELECT * FROM books `; const books = await db.query(queryString); return books.rows as string; }, }, //GET AUTHOR BY ID author: { type: AuthorType, args: { id: { type: GraphQLID } }, async resolve(parent, args) { const queryString = ` SELECT * FROM authors WHERE authors.id = $1 `; const author = await db.query(queryString, [args.id]); return author.rows[0] as string; }, }, //GET ALL AUTHORS authors: { type: new GraphQLList(AuthorType), async resolve() { const queryString = 'SELECT * FROM authors'; const authors = await db.query(queryString); return authors.rows as string; }, }, //GET ALL BOOKS BY AUTHOR booksByAuthor: { type: new GraphQLList(BookType), args: { name: { type: GraphQLString } }, async resolve(parent, args) { const queryString = ` SELECT books.* FROM ((books INNER JOIN booksAuthors ON books.id = booksAuthors.BookId) INNER JOIN authors ON booksAuthors.AuthorId = authors.id) WHERE authors.name = $1 `; const books = await db.query(queryString, [args.name]); return books.rows as string; }, }, //GET ALL GENRES genres: { type: new GraphQLList(GenreType), async resolve() { const queryString = 'SELECT * FROM genres'; const genres = await db.query(queryString); return genres.rows as string; }, }, //GET ALL BOOKS BY GENRE booksByGenre: { type: new GraphQLList(BookType), args: { genre: { type: GraphQLString } }, async resolve(parent, args) { const queryString = ` SELECT books.* FROM books INNER JOIN genres ON books.genre_id = genres.id WHERE genres.name = $1 `; const books = await db.query(queryString, [args.genre]); return books.rows as string; }, }, }, }); // ================== // // ===== MUTATIONS ==== // // ================== // const RootMutation = new GraphQLObjectType({ name: 'RootMutationType', fields: { //ADD BOOK addBook: { type: BookType, args: { title: { type: new GraphQLNonNull(GraphQLString) }, author: { type: new GraphQLNonNull(GraphQLString) }, genre: { type: GraphQLString }, }, async resolve(parent, args) { const author = await db.query( `SELECT id FROM authors WHERE name = '${args.author}'`, ); const genre = await db.query( `SELECT id FROM genres WHERE genres.name = '${args.genre}'`, ); //const authorId: string = author.rows[0].id; //const genreId: string = genre.rows[0].id; const authorID = author.rows[0].id; const genreID = genre.rows[0].id; const queryString = ` INSERT INTO books (title, genre_id) VALUES ($1, $2) RETURNING *`; const bookResponse = await db.query(queryString, [args.title, genreID]); const newBook = bookResponse.rows[0]; newBook.author = args.author; newBook.genre = args.genre; const bookID = newBook.id; const joinTableQueryString = ` INSERT INTO booksauthors (bookid, authorid) VALUES ($1, $2) `; await db.query(joinTableQueryString, [bookID, authorID]); return newBook as string; }, }, //UPDATE BOOK updateBook: { type: BookType, args: { id: { type: new GraphQLNonNull(GraphQLID) }, title: { type: GraphQLString }, author: { type: GraphQLString }, genre: { type: GraphQLString }, }, async resolve(parent, args) { if (args.author) { const authorQueryString = ` UPDATE booksauthors SET booksauthors.authorID = authors.id FROM booksauthors INNER JOIN authors ON booksauthors.authorID = authors.id WHERE booksauthors.bookID = ${args.id} AND authors.name = '${args.author}' `; await db.query(authorQueryString); } let bookQueryString = ` SELECT * FROM books WHERE books.id = ${args.id} `; const toUpdate = []; if (args.genre) toUpdate.push( `genre_id = (SELECT id FROM genres WHERE genres.name = '${args.genre}')`, ); if (args.title) toUpdate.push(`title = '${args.title}'`); if (toUpdate.length > 0) { bookQueryString = ` UPDATE books SET ${toUpdate.join()} WHERE id = ${args.id} RETURNING * `; } const updatedBook = await db.query(bookQueryString); return updatedBook.rows[0] as string; }, }, //DELETE BOOK deleteBook: { type: BookType, args: { id: { type: new GraphQLNonNull(GraphQLID) }, }, async resolve(parent, args) { const queryString = ` DELETE FROM books WHERE id = ${args.id} RETURNING * `; await db.query(`DELETE FROM booksauthors WHERE bookid = ${args.id}`); const deleted = await db.query(queryString); return deleted.rows[0] as string; }, }, //ADD AUTHOR addAuthor: { type: AuthorType, args: { name: { type: new GraphQLNonNull(GraphQLString) }, country: { type: new GraphQLNonNull(GraphQLString) }, }, async resolve(parent, args) { const queryString = ` INSERT INTO authors (name, country) VALUES ($1, $2) RETURNING * `; const newAuthor = await db.query(queryString, [ args.name, args.country, ]); return newAuthor.rows[0] as string; }, }, //UPDATE AUTHOR updateAuthor: { type: AuthorType, args: { id: { type: new GraphQLNonNull(GraphQLID) }, name: { type: GraphQLString }, country: { type: GraphQLString }, }, async resolve(parent, args) { const toUpdate = []; if (args.name) toUpdate.push(`name='${args.name}'`); if (args.country) toUpdate.push(`country='${args.country}'`); const queryString = ` UPDATE authors SET ${toUpdate.join()} WHERE authors.id = ${args.id} RETURNING * `; const updatedAuthor = await db.query(queryString); return updatedAuthor.rows[0] as string; }, }, //DELETE AUTHOR deleteAuthor: { type: AuthorType, args: { name: { type: GraphQLString }, }, async resolve(parent, args) { const queryString = ` DELETE FROM authors WHERE name = '${args.name}' RETURNING * `; const deletedAuthor = await db.query(queryString); return deletedAuthor.rows[0] as string; }, }, //ADD GENRE addGenre: { type: GenreType, args: { name: { type: new GraphQLNonNull(GraphQLString) }, }, async resolve(parent, args) { const queryString = ` INSERT INTO genres (name) VALUES ($1) RETURNING * `; const newGenre = await db.query(queryString, [args.name]); return newGenre.rows[0] as string; }, }, //DELETE GENRE deleteGenre: { type: GenreType, args: { name: { type: GraphQLString }, }, async resolve(parent, args) { const queryString = ` DELETE FROM genres WHERE name = '${args.name}' RETURNING * `; const deletedGenre = await db.query(queryString); return deletedGenre.rows[0] as string; }, }, }, }); export default new GraphQLSchema({ query: RootQuery, mutation: RootMutation, types: [BookType, AuthorType, GenreType], });
the_stack
import type { APIApplicationCommandAutocompleteInteraction } from "discord-api-types/payloads/v9/_interactions/autocomplete"; import type { APIApplicationCommandOptionChoice, APIAttachment, APIInteractionDataResolvedChannel, APIMessageButtonInteractionData, APIMessageSelectMenuInteractionData, APIRole, APIUser, ChannelType, } from "discord-api-types/v9"; import { ApplicationCommandOptionType } from "../api"; import { Awaitable, ValueOf } from "../helpers"; import { STATE } from "./state"; import { ComponentHandler, ModalHandler } from "./types"; export function useDescription(description: string): void { if (!STATE.commandId) { throw new Error(`Hooks must be called inside a command`); } if (STATE.recordingOptions) STATE.recordingDescription = description; } export function useDefaultPermission(permission: boolean): void { if (!STATE.commandId) { throw new Error(`Hooks must be called inside a command`); } if (STATE.recordingOptions) STATE.recordingDefaultPermission = permission; } // ======================================================================================================== // | Message Component & Modal Hooks: | // | https://discord.com/developers/docs/interactions/message-components#component-object-component-types | // ======================================================================================================== function useCustomId(): string { if (!STATE.commandId) { throw new Error(`Hooks must be called inside a command`); } return `${STATE.commandId}$${STATE.componentHandlerCount++}#`; } export function useButton<Env>( handler: ComponentHandler<Env, APIMessageButtonInteractionData> ): string { const customId = useCustomId(); STATE.componentHandlers?.set(customId, handler as any); return customId; } export function useSelectMenu<Env>( handler: ComponentHandler<Env, APIMessageSelectMenuInteractionData> ): string { const customId = useCustomId(); STATE.componentHandlers?.set(customId, handler as any); return customId; } export function useInput(): [id: string, value: string] { const customId = useCustomId(); const value = STATE.interactionComponentData?.get(customId) ?? ""; return [customId, value]; } export function useModal<Env>(handler: ModalHandler<Env>): string { const customId = useCustomId(); STATE.modalHandlers?.set(customId, handler as any); return customId; } // ==================================================================================================================================== // | Option Hooks: | // | https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-option-type | // ==================================================================================================================================== export type Choice<T> = T | { name?: string; value: T }; export type ChoiceValue<Choice> = Choice extends { value: unknown } ? Choice["value"] : Choice; function normaliseChoice<T extends string | number>( choice: Choice<T> ): APIApplicationCommandOptionChoice { if (typeof choice === "object" && "value" in choice) { return { name: choice.name ?? String(choice.value), value: choice.value }; } const name = String(choice); return { name, value: typeof choice === "number" ? choice : name }; } export function normaliseChoices<T extends string | number>( choices?: ReadonlyArray<Choice<T>> ): APIApplicationCommandOptionChoice[] | undefined { return choices?.map(normaliseChoice); } export type AutocompleteHandler<T, Env> = ( interaction: APIApplicationCommandAutocompleteInteraction, env: Env, ctx: ExecutionContext ) => Awaitable<Choice<T>[]>; export interface OptionalOption<T, Env> { required?: false; autocomplete?: AutocompleteHandler<T, Env>; } export interface RequiredOption<T, Env> { required: true; autocomplete?: AutocompleteHandler<T, Env>; } export interface OptionalChoicesOption< Choices extends ReadonlyArray<Choice<string | number>> > { required?: false; choices: Choices; } export interface RequiredChoicesOption< Choices extends ReadonlyArray<Choice<string | number>> > { required: true; choices: Choices; } export interface NumericOption { min?: number; max?: number; } export interface ChannelOption { types?: ChannelType[]; } type CombinedOption<T, Env> = { required?: boolean; autocomplete?: AutocompleteHandler<T, Env>; choices?: ReadonlyArray<Choice<T>>; } & NumericOption & ChannelOption; function useOption<T, Env>( type: ValueOf<typeof ApplicationCommandOptionType>, empty: T, name: string, description: string, options?: CombinedOption<T, Env> ): T | null { if (!STATE.commandId) { throw new Error(`Hooks must be called inside a command`); } if (STATE.autocompleteHandlers && options?.autocomplete) { STATE.autocompleteHandlers.set(name, options.autocomplete as any); } // Build a default value that satisfies the required return type, when // recording, or if the user hasn't yet provided a value for this option const def = options?.required ? options.choices?.length ? (normaliseChoice(options.choices[0] as any).value as unknown as T) : empty : null; // If not required, we can just use null :) if (STATE.interactionOptions) { return (STATE.interactionOptions.get(name)?.value as unknown as T) ?? def; } if (STATE.recordingOptions) { STATE.recordingOptions.push({ type: type as number, name, description, required: options?.required, autocomplete: options?.autocomplete && true, choices: normaliseChoices(options?.choices as any) as any, channel_types: options?.types as any, min_value: options?.min, max_value: options?.max, }); } return def; } export function useString<Env>( name: string, description: string, options?: OptionalOption<string, Env> ): string | null; export function useString<Env>( name: string, description: string, options: RequiredOption<string, Env> ): string; export function useString<Choices extends ReadonlyArray<Choice<string>>>( name: string, description: string, options: OptionalChoicesOption<Choices> ): ChoiceValue<Choices[number]> | null; export function useString<Choices extends ReadonlyArray<Choice<string>>>( name: string, description: string, options: RequiredChoicesOption<Choices> ): ChoiceValue<Choices[number]>; export function useString<Env>( name: string, description: string, options?: CombinedOption<string, Env> ): string | null { return useOption( ApplicationCommandOptionType.STRING, "", name, description, options ); } export function useInteger<Env>( name: string, description: string, options?: OptionalOption<number, Env> & NumericOption ): number | null; export function useInteger<Env>( name: string, description: string, options: RequiredOption<number, Env> & NumericOption ): number; export function useInteger<Choices extends ReadonlyArray<Choice<number>>>( name: string, description: string, options: OptionalChoicesOption<Choices> ): ChoiceValue<Choices[number]> | null; export function useInteger<Choices extends ReadonlyArray<Choice<number>>>( name: string, description: string, options: RequiredChoicesOption<Choices> ): ChoiceValue<Choices[number]>; export function useInteger<Env>( name: string, description: string, options?: CombinedOption<number, Env> ): number | null { return useOption( ApplicationCommandOptionType.INTEGER, 0, name, description, options ); } export function useBoolean<Env>( name: string, description: string, options?: OptionalOption<boolean, Env> ): boolean | null; export function useBoolean<Env>( name: string, description: string, options: RequiredOption<boolean, Env> ): boolean; export function useBoolean<Env>( name: string, description: string, options?: CombinedOption<boolean, Env> ): boolean | null { return useOption( ApplicationCommandOptionType.BOOLEAN, false, name, description, options ); } export function useUser<Env>( name: string, description: string, options?: OptionalOption<string, Env> ): APIUser | null; export function useUser<Env>( name: string, description: string, options: RequiredOption<string, Env> ): APIUser; export function useUser<Env>( name: string, description: string, options?: CombinedOption<string, Env> ): APIUser | null { const id = useOption( ApplicationCommandOptionType.USER, "", name, description, options ); // Autocomplete interactions may not include resolved, so return just the ID const fallback = id === null ? null : ({ id } as APIUser); return STATE.interactionResolved?.users?.[id!] ?? fallback; } export function useChannel<Env>( name: string, description: string, options?: OptionalOption<string, Env> & ChannelOption ): APIInteractionDataResolvedChannel | null; export function useChannel<Env>( name: string, description: string, options: RequiredOption<string, Env> & ChannelOption ): APIInteractionDataResolvedChannel; export function useChannel<Env>( name: string, description: string, options?: CombinedOption<string, Env> ): APIInteractionDataResolvedChannel | null { const id = useOption( ApplicationCommandOptionType.CHANNEL, "", name, description, options ); // Autocomplete interactions may not include resolved, so return just the ID const fallback = id === null ? null : ({ id } as APIInteractionDataResolvedChannel); return STATE.interactionResolved?.channels?.[id!] ?? fallback; } export function useRole<Env>( name: string, description: string, options?: OptionalOption<string, Env> ): APIRole | null; export function useRole<Env>( name: string, description: string, options: RequiredOption<string, Env> ): APIRole; export function useRole<Env>( name: string, description: string, options?: CombinedOption<string, Env> ): APIRole | null { const id = useOption( ApplicationCommandOptionType.ROLE, "", name, description, options ); // Autocomplete interactions may not include resolved, so return just the ID const fallback = id === null ? null : ({ id } as APIRole); return STATE.interactionResolved?.roles?.[id!] ?? fallback; } export function useMentionable<Env>( name: string, description: string, options?: OptionalOption<string, Env> ): APIUser | APIRole | null; export function useMentionable<Env>( name: string, description: string, options: RequiredOption<string, Env> ): APIUser | APIRole; export function useMentionable<Env>( name: string, description: string, options?: CombinedOption<string, Env> ): APIUser | APIRole | null { const id = useOption( ApplicationCommandOptionType.MENTIONABLE, "", name, description, options ); // Autocomplete interactions may not include resolved, so return just the ID const fallback = id === null ? null : ({ id } as APIUser | APIRole); return ( STATE.interactionResolved?.users?.[id!] ?? STATE.interactionResolved?.roles?.[id!] ?? fallback ); } export function useNumber<Env>( name: string, description: string, options?: OptionalOption<number, Env> & NumericOption ): number | null; export function useNumber<Env>( name: string, description: string, options: RequiredOption<number, Env> & NumericOption ): number; export function useNumber<Choices extends ReadonlyArray<Choice<number>>>( name: string, description: string, options: OptionalChoicesOption<Choices> ): ChoiceValue<Choices[number]> | null; export function useNumber<Choices extends ReadonlyArray<Choice<number>>>( name: string, description: string, options: RequiredChoicesOption<Choices> ): ChoiceValue<Choices[number]>; export function useNumber<Env>( name: string, description: string, options?: CombinedOption<number, Env> ): number | null { return useOption( ApplicationCommandOptionType.NUMBER, 0, name, description, options ); } export function useAttachment<Env>( name: string, description: string, options?: OptionalOption<never /* cannot be autocompleted */, Env> ): APIAttachment | null; export function useAttachment<Env>( name: string, description: string, options: RequiredOption<never /* cannot be autocompleted */, Env> ): APIAttachment; export function useAttachment<Env>( name: string, description: string, options?: CombinedOption<string, Env> ): APIAttachment | null { const id = useOption( ApplicationCommandOptionType.ATTACHMENT, "", name, description, options ); // Autocomplete interactions may not include resolved, so return just the ID const fallback = id === null ? null : ({ id } as APIAttachment); return STATE.interactionResolved?.attachments?.[id!] ?? fallback; }
the_stack
import { Component, OnDestroy, AfterViewInit, forwardRef, ChangeDetectorRef, Input, Output, EventEmitter, ContentChild, TemplateRef, ViewEncapsulation, HostBinding, ViewChild, ElementRef, ChangeDetectionStrategy, ContentChildren, QueryList, Attribute } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; import { takeUntil, startWith } from 'rxjs/operators'; import { Subject, merge } from 'rxjs'; import { PickOptionTemplateDirective, PickPaneToolbarTemplateDirective, PickPaneFooterTemplateDirective, PickOptgroupTemplateDirective, PickCustomItemTemplateDirective, PickPaneHeaderRightTemplateDirective, PickPaneHeaderLeftTemplateDirective } from './pick-templates.directive'; import { isDefined, isFunction, isObject } from '../util'; import { PickOptionComponent, PickOptionStateChange } from './pick-option.component'; import { PickPaneComponent } from './pane/pick-pane.component'; import { PicklistService } from './picklist.service'; import { SortFn, GroupValueFn, CompareWithFn, AddCustomItemFn, SearchFn, GroupByFn } from './pick.types'; /** Control for selecting multiple items from a very large set of options. `<hc-picklist>` */ @Component({ selector: 'hc-picklist', templateUrl: './picklist.component.html', styleUrls: ['./picklist.component.scss'], providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => PicklistComponent), multi: true }, PicklistService], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush }) export class PicklistComponent implements OnDestroy, AfterViewInit, ControlValueAccessor { /** If options are objects, this matches the object property to use for display in the list. * Can use nested properties. Example: `'property.nestedProperty'`. *Defaults to `'label'`.* */ @Input() bindLabel: string; /** If options are objects, this matches the object property to use for the selected model. * Can use nested properties. Example: `'property.nestedProperty'`. *By default, binds to whole object.* */ @Input() bindValue: string; /** When addCustomItem is true, this changes the default message for adding a new item. *Defaults to `"Add custom option."`* */ @Input() addCustomItemText = 'Add custom option.'; /** True if user should be able to add custom items. The button to add an option will appear when a search term is not exactly * matched. Can optionally provide a function that will generate a value for the custom option based on the given search term. * *Defaults to false.* If a function is provided, must follow this signature: `((term: string) => any | Promise<any>)`. The * function is passed the search term string and returns a value that should match the type of options in the picklist. */ @Input() addCustomItem: boolean | AddCustomItemFn = false; /** Group items by property or function expression. If a function is provided, must follow this signature: `((item: any) => any)`. The * function is passed an option and returns a value to represent the identifier for the group that option should belong to. * *Grouping is off by default.* */ @Input() groupBy: string | GroupByFn; /** Function expression to provide group value: `(key: string | object, children: any[]) => string | object`. Same as * described in ng-select component. https://ng-select.github.io/ng-select#/grouping */ @Input() groupValue: GroupValueFn; /** True if group should be clickable. Clicking the group will select all its children. *Defaults to false.* */ @Input() canSelectGroup = false; /** True if group can be closed to hide its child options. *Defaults to false.* */ @Input() canCloseGroup = false; /** True if groups should be closed to begin with. Must have `canCloseGroup` set to true to use. *Defaults to true.* */ @Input() closeGroupsByDefault = true; /** Items that cannot be grouped are placed in an orphan group. * This property sets a name for that group. *Defaults to `"Other Items"`* */ @Input() orphanItemsGroupName = 'Other Items'; /** True to enable virtual scroll for better performance when rendering a lot of data. *Defaults to false.* */ @Input() virtualScroll = false; /** When using virtual scroll, determines how many extra items on top and bottom should be rendered outside the viewport. * *Defaults to 4.* */ @Input() bufferAmount = 4; /** Provide custom trackBy function for better DOM reusage by Angular's *ngFor in the items list. */ @Input() trackByFn = null; /** Function used to sort the groups and items in the list: `(a: PickOption, b: PickOption) => number`. If the function * result is negative, a is sorted before b. If it's positive, b is sorted before a. If the result is 0, no changes are * done with the sort order of the two values. *By default, options are not sorted.* */ @Input() sortFn: SortFn; /** If true, items can be viewed but not highlighted or moved from pane to pane. Same as adding `disabled` attribute. * *Defaults to false.* */ @Input() readonly = false; /** True if search bar should be present. *Defaults to true.* */ @Input() hasSearch = true; /** Placeholder for the search input. *Defaults to 'Search'.* */ @Input() searchPlaceholder = 'Search'; /** A custom search function: `(term: string, item: any) => boolean`. *Default function does a simple scan for entire * given term within the options label.* */ @Input() searchFn: SearchFn; /** True if items should be filtered while user is still typing. *Defaults to true.* */ @Input() searchWhileComposing = true; /** Number of characters required for search to be fired. Only applies when using `externalSearchSubject`. * *Defaults to 0.* */ @Input() externalSearchTermMinLength = 0; /** A subject through which an updated search term will be sent. Use for advanced searching functionality, * like searching over http. */ @Input() externalSearchSubject: Subject<string>; /** For the left pane, force the 'Showing x of y' message to be the given number. Useful when using external search * and you want to display the total number of items available on the server rather than just those currently * available in the component. */ @Input() externalTotalOptionCount: number; /** Message shown in each pane when empty. *Defaults to 'No options to show.'* */ @Input() notFoundText = 'No options to show.'; /** Text for left pane header. Ignored if `hcPaneHeaderLeftTmp` is used. *Defaults to 'Available'.* */ @Input() leftHeaderText = 'Available'; /** Text for right pane header. Ignored if `hcPaneHeaderRightTmp` is used. *Defaults to 'Selected'.* */ @Input() rightHeaderText = 'Selected'; /** True when left pane should show as loading. *Defaults to false.* */ @Input() leftPaneLoading = false; /** True when right pane should show as loading. *Defaults to false.* */ @Input() rightPaneLoading = false; /** True if each pane should have a header. *Defaults to true.* */ @Input() hasHeader = true; /** True if each pane should have a toolbar section. *Defaults to true.* */ @Input() hasToolbar = true; /** True if each pane should have a footer section. *Defaults to true.* */ @Input() hasFooter = true; /** Set a limit to the number of selected items. * Note: This will not prevent more than limit from being added to the model outside the component. * *No limit by default.* */ @Input() maxSelectedItems: number; /** Total height of the picklist control. Should be passed as a string, including the * unit (pixels, percentage, rem, etc). *Defaults to '400px'.* */ @Input() height = '400px'; /** An array of options for the picklist. Options can be of any type, and the array can be an observable stream. * Can alternatively use `<hc-pick-option>` components to pass in options. */ @Input() get items(): unknown[] { return this._items; } set items(value: unknown[]) { this._itemsAreUsed = true; this._items = value; } /** A function to compare the option values with the selected values. `(a: any, b: any) => boolean;` * The first argument is a value from an option. The second is a value from the selection (model). * A boolean should be returned. * Same as used by https://angular.io/api/forms/SelectControlValueAccessor */ @Input() get compareWith(): CompareWithFn { return this._compareWith; } set compareWith(fn: CompareWithFn) { if (!isFunction(fn)) { throw Error('`compareWith` must be a function.'); } this._compareWith = fn; } /** Fires when model is updated. Sends an array of the currently selected values. */ @Output() change = new EventEmitter<Array<string|Record<string, unknown>|undefined>>(); /** Fires when options are added. Sends an array of the values being added. */ @Output() add = new EventEmitter<Array<string|Record<string, unknown>|undefined>>(); /** Fires when options are removed. Sends an array of the values being removed. */ @Output() remove = new EventEmitter<Array<string|Record<string, unknown>|undefined>>(); // custom templates @ContentChild(PickOptionTemplateDirective, { read: TemplateRef }) _optionTemplate: TemplateRef<unknown>; @ContentChild(PickOptgroupTemplateDirective, { read: TemplateRef }) _optgroupTemplate: TemplateRef<unknown>; @ContentChild(PickPaneToolbarTemplateDirective, { read: TemplateRef }) _toolbarTemplate: TemplateRef<unknown>; @ContentChild(PickPaneFooterTemplateDirective, { read: TemplateRef }) _footerTemplate: TemplateRef<unknown>; @ContentChild(PickCustomItemTemplateDirective, { read: TemplateRef }) _customItemTemplate: TemplateRef<unknown>; @ContentChild(PickPaneHeaderRightTemplateDirective, { read: TemplateRef }) _paneHeaderRightTemplate: TemplateRef<unknown>; @ContentChild(PickPaneHeaderLeftTemplateDirective, { read: TemplateRef }) _paneHeaderLeftTemplate: TemplateRef<unknown>; /** A template-based/declarative way to pass options available in the picklist. */ @ContentChildren(PickOptionComponent, { descendants: true }) _ngOptions: QueryList<PickOptionComponent>; @ViewChild('available', { static: true }) _availablePane: PickPaneComponent; @ViewChild('selected', { static: true }) _selectedPane: PickPaneComponent; /** Getter. Returns true if readonly property is true, or if disabled attribute is present on the control. */ @HostBinding('class.hc-picklist-disabled') get disabled(): boolean { return this.readonly || this._disabled; } /** whether or not we should escape HTML in default option templates. will be set to false if * using <hc-pick-option> instead of passing in an items array */ _escapeHTML = true; _el: HTMLElement; private _items = new Array<unknown>(); private _itemsAreUsed: boolean; private _defaultLabel = 'label'; private _disabled: boolean; private readonly _destroy$ = new Subject<void>(); private _compareWith: CompareWithFn; private _onChange = (_: unknown) => _; private _onTouched = () => null; constructor( _elementRef: ElementRef<HTMLElement>, private picklistService: PicklistService, private _cd: ChangeDetectorRef, @Attribute('autofocus') private autoFocus: any) { this._el = _elementRef.nativeElement; } ngAfterViewInit(): void { this.picklistService.reset(this._availablePane, this._selectedPane); if (!this._itemsAreUsed) { this._setItemsFromHcPickOptions(); this._escapeHTML = false; } if (isDefined(this.autoFocus)) { this._availablePane.focus(); } this._detectChanges(); } ngOnDestroy(): void { this._destroy$.next(); this._destroy$.complete(); } writeValue(value: unknown | unknown[]): void { this._selectedPane.itemsList.clearList(); this._handleWriteValue(value); this._cd.markForCheck(); } registerOnChange(fn: () => null): void { this._onChange = fn; } registerOnTouched(fn: () => null): void { this._onTouched = fn; } setDisabledState(state: boolean): void { this._disabled = state; this._cd.markForCheck(); } /** Getter. Returns true if any items are selected. */ get hasValue(): boolean { return this._selectedPane.itemsList.items.length > 0; } /** Getter. Returns true if the number of selected items matches or exceeds the maximum number. Useful if you'd like to show a custom * warning label. */ get hasMaxItemsSelected(): boolean { return Number.isFinite(this.maxSelectedItems) && this._selectedPane.itemsList.itemsTotalCount >= this.maxSelectedItems; } /** Getter. Returns true if the number of selected items exceeds the maximum number. UI won't normally allow this, but the model can * be manipulated or set outside of the component to cause this. */ get hasExceededMaxItemsSelected(): boolean { return Number.isFinite(this.maxSelectedItems) && this._selectedPane.itemsList.itemsTotalCount > this.maxSelectedItems; } /** Getter. Returns true if the "Available" pane is empty. */ get leftPaneIsEmpty(): boolean { return this._availablePane.itemsList.items.length === 0; } /** Move highlighted items from the left pane over to the right pane. */ moveLeftToRight(): void { this._move(this._availablePane, this._selectedPane, true); } /** Move highlighted items from the right pane over to the left pane. */ moveRightToLeft(): void { this._move(this._selectedPane, this._availablePane); } /** Move selected (highlighted) options from one pane to the other */ _move(source: PickPaneComponent, destination: PickPaneComponent, isAdding = false): void { let maxLimitEnforced = false; let overLimitBy = 0; if (isAdding && this.maxSelectedItems) { overLimitBy = this._selectedPane.itemsList.itemsTotalCount + source.selectedItems.length - this.maxSelectedItems; maxLimitEnforced = overLimitBy > 0; } const optionsToMove = maxLimitEnforced ? source.selectedItems.slice(0, source.selectedItems.length - overLimitBy) : source.selectedItems; optionsToMove.filter(i => !i.disabled).slice().forEach(i => { source.itemsList.removeOption(i); destination.itemsList.addOption(i); }); const eventToFire = isAdding ? this.add : this.remove; eventToFire.emit(optionsToMove.map(x => x.value)); source.itemsList.reIndex(); this._availablePane.itemsList.clearSelected(); this._selectedPane.itemsList.clearSelected(); this.refreshPanes(); this._updateNgModel(); this._onTouched(); } /** Refreshes the dimensions of the virtual scroll container and the items displayed within. Helpful when using virtual scrolling and * the window changes such that the picklist was resized. */ public refreshScrollArea(): void { this._availablePane.refreshScrollArea(); this._selectedPane.refreshScrollArea(); } /** Manually trigger change detection to update the UI. */ _detectChanges(): void { // eslint-disable-next-line @typescript-eslint/no-explicit-any if (!(<any>this._cd).destroyed) { this._cd.detectChanges(); } this._availablePane.detectChanges(); this._selectedPane.detectChanges(); } /** Convert <hc-pick-option> components into HcOptions */ private _setItemsFromHcPickOptions() { const mapNgOptions = (options: QueryList<PickOptionComponent>) => { const items = options.map(option => ({ $hcOptionValue: option.value, $hcOptionLabel: option.elementRef.nativeElement.innerHTML, disabled: option.disabled })); this._availablePane.itemsList.setItems(items); if (this.hasValue) { this.picklistService.mapIncomingOptionsToSelected(this.bindValue); } }; const handleOptionChange = () => { const changedOrDestroyed = merge(this._ngOptions.changes, this._destroy$); merge(...this._ngOptions.map(option => option._stateChange$)) .pipe(takeUntil(changedOrDestroyed)) .subscribe((option: PickOptionStateChange) => { const item = this._availablePane.itemsList.findOption(option.value); if (item) { item.disabled = option.disabled; item.label = option.label || item.label; } this._detectChanges(); }); }; this._ngOptions.changes .pipe(startWith(this._ngOptions), takeUntil(this._destroy$)) .subscribe(options => { this.bindLabel = this._defaultLabel; mapNgOptions(options); handleOptionChange(); this._detectChanges(); }); } /** Apply value passed in from ngModel as the current selection in the component */ private _handleWriteValue(ngModel: unknown[] | unknown) { if (!this._isValidWriteValue(ngModel)) { return; } const select = (val: unknown) => { const alreadySelected = this._selectedPane.itemsList.findOption(val); if (alreadySelected) { return; } const availableItem = this._availablePane.itemsList.findOption(val); if (availableItem) { this._availablePane.itemsList.removeOption(availableItem); this._selectedPane.itemsList.addOption(availableItem); this._availablePane.itemsList.reIndex(); } else { // where possible, handle cases where we're adding something to the model that's not an existing option if (this.bindValue) { throw new Error(`Attempting to set a value (${val}) in the model that does not exist in the available options. This is not allowed when the [bindValue] Input() is used. You'll need to add the option to the [items] Input().`); } this._selectedPane.itemsList.addNewOption(val); } }; (ngModel as [])?.forEach(item => select(item)); this.refreshPanes(); } /** Rerun filters and grouping logic in each pane, than force UI refresh. */ private refreshPanes() { this._availablePane.filter(); this._selectedPane.filter(); this._detectChanges(); } private _isValidWriteValue(value: unknown): boolean { if (!isDefined(value) || value === '') { return false; } if (!Array.isArray(value)) { console.warn('ngModel should be array.'); return false; } return value.every(item => this.validateBinding(item)); } private validateBinding = (item: unknown): boolean => { if (!isDefined(this.compareWith) && isObject(item) && this.bindValue) { const msg = `Setting object(${JSON.stringify(item)}) as your model with bindValue is not allowed unless [compareWith] is used.`; console.warn(msg); return false; } return true; }; private _updateNgModel() { const model = new Array<unknown>(); const selectedItems = this._selectedPane.itemsList.items.filter(i => !i.children); selectedItems.forEach(i => { const value = this.bindValue ? this._selectedPane.itemsList.resolveNested(i.value, this.bindValue) : i.value; model.push(value); }); const selected = selectedItems.map(x => x.value); this._onChange(model); this.change.emit(selected); this._cd.markForCheck(); } }
the_stack
import { getServiceNamespace, InterfaceType, ModelTypeProperty, NamespaceType, OperationType, Program, setDecoratorNamespace, Type, } from "@cadl-lang/compiler"; import { reportDiagnostic } from "./diagnostics.js"; import { getOperationVerb, getPathParamName, hasBody, HttpVerb, isPathParam } from "./http.js"; import { getResourceOperation, getSegment } from "./rest.js"; export type OperationContainer = NamespaceType | InterfaceType; export interface OperationDetails { path: string; pathFragment?: string; verb: HttpVerb; groupName: string; container: OperationContainer; parameters: ModelTypeProperty[]; operation: OperationType; } export interface RoutePath { path: string; isReset: boolean; } export function $route(program: Program, entity: Type, path: string) { setRoute(program, entity, { path, isReset: false, }); } export function $routeReset(program: Program, entity: Type, path: string) { setRoute(program, entity, { path, isReset: true, }); } const routeContainerKey = Symbol(); function addRouteContainer(program: Program, entity: Type): void { const container = entity.kind === "Operation" ? entity.interface || entity.namespace : entity; if (!container) { // Somehow the entity doesn't have a container. This should only happen // when a type was created manually and not by the checker. throw new Error(`${entity.kind} is not or does not have a container`); } if (isUninstantiatedTemplateInterface(container)) { // Don't register uninstantiated template interfaces return; } program.stateSet(routeContainerKey).add(container); } const routesKey = Symbol(); function setRoute(program: Program, entity: Type, details: RoutePath) { if (entity.kind !== "Namespace" && entity.kind !== "Interface" && entity.kind !== "Operation") { reportDiagnostic(program, { code: "decorator-wrong-type", format: { decorator: "route", entityKind: entity.kind }, target: entity, }); return; } // Register the container of the operation as one that holds routed operations addRouteContainer(program, entity); program.stateMap(routesKey).set(entity, details); } export function getRoutePath( program: Program, entity: NamespaceType | InterfaceType | OperationType ): RoutePath | undefined { return program.stateMap(routesKey).get(entity); } function buildPath(pathFragments: string[]) { // Join all fragments with leading and trailing slashes trimmed const path = pathFragments.map((r) => r.replace(/(^\/|\/$)/g, "")).join("/"); return `/${path}`; } function addSegmentFragment(program: Program, target: Type, pathFragments: string[]) { // Don't add the segment prefix if it is meant to be excluded // (empty string means exclude the segment) const segment = getSegment(program, target); if (segment && segment !== "") { pathFragments.push(`/${segment}`); } } function generatePathFromParameters( program: Program, operation: OperationType, pathFragments: string[], parameters: ModelTypeProperty[] ) { for (const [_, param] of operation.parameters.properties) { if (getPathParamName(program, param)) { addSegmentFragment(program, param, pathFragments); // Add the path variable for the parameter if (param.type.kind === "String") { pathFragments.push(`/${param.type.value}`); continue; // Skip adding to the parameter list } else { pathFragments.push(`/{${param.name}}`); } } parameters.push(param); } // Add the operation's own segment if present addSegmentFragment(program, operation, pathFragments); } function getPathForOperation( program: Program, operation: OperationType, routeFragments: string[] ): { path: string; pathFragment?: string; parameters: ModelTypeProperty[] } { const parameters: ModelTypeProperty[] = []; const pathFragments = [...routeFragments]; const routePath = getRoutePath(program, operation); if (isAutoRoute(program, operation)) { // The operation exists within an @autoRoute scope, generate the path generatePathFromParameters(program, operation, pathFragments, parameters); } else { // Prepend any explicit route path if (routePath) { pathFragments.push(routePath.path); } // Gather operation parameters parameters.push(...Array.from(operation.parameters.properties.values())); // Pull out path parameters to verify what's in the path string const paramByName = new Map( parameters.filter((p) => isPathParam(program, p)).map((p) => [p.name, p]) ); // Find path parameter names used in all route fragments const declaredPathParams = pathFragments.flatMap( (f) => f.match(/\{\w+\}/g)?.map((s) => s.slice(1, -1)) ?? [] ); // For each param in the declared path parameters (e.g. /foo/{id} has one, id), // delete it because it doesn't need to be added to the path. for (const declaredParam of declaredPathParams) { const param = paramByName.get(declaredParam); if (!param) { reportDiagnostic(program, { code: "missing-path-param", format: { param: declaredParam }, target: operation, }); continue; } paramByName.delete(declaredParam); } // Add any remaining declared path params for (const param of paramByName.keys()) { pathFragments.push(`{${param}}`); } } return { path: buildPath(pathFragments), pathFragment: routePath?.path, parameters, }; } function verbForOperationName(name: string): HttpVerb | undefined { switch (name) { case "list": return "get"; case "create": return "post"; case "read": return "get"; case "update": return "patch"; case "delete": return "delete"; case "deleteAll": return "delete"; } return undefined; } function getVerbForOperation( program: Program, operation: OperationType, parameters: ModelTypeProperty[] ): HttpVerb { const resourceOperation = getResourceOperation(program, operation); return ( (resourceOperation && resourceOperationToVerb[resourceOperation.operation]) || getOperationVerb(program, operation) || verbForOperationName(operation.name) || (hasBody(program, parameters) ? "post" : "get") ); } function buildRoutes( program: Program, container: OperationContainer, routeFragments: string[], visitedOperations: Set<OperationType> ): OperationDetails[] { // Get the route info for this container, if any const baseRoute = getRoutePath(program, container); const parentFragments = [...routeFragments, ...(baseRoute ? [baseRoute.path] : [])]; // TODO: Allow overriding the existing resource operation of the same kind const operations: OperationDetails[] = []; for (const [_, op] of container.operations) { // Skip previously-visited operations if (visitedOperations.has(op)) { continue; } const route = getPathForOperation(program, op, parentFragments); const verb = getVerbForOperation(program, op, route.parameters); operations.push({ path: route.path, pathFragment: route.pathFragment, verb, container, groupName: container.name, parameters: route.parameters, operation: op, }); } // Build all child routes and append them to the list, but don't recurse in // the global scope because that could pull in unwanted operations if (container.kind === "Namespace" && container.name !== "") { let children: OperationContainer[] = [ ...container.namespaces.values(), ...container.interfaces.values(), ]; const childRoutes = children.flatMap((child) => buildRoutes(program, child, parentFragments, visitedOperations) ); operations.push.apply(operations, childRoutes); } return operations; } export function getRoutesForContainer( program: Program, container: OperationContainer, visitedOperations: Set<OperationType> ): OperationDetails[] { return buildRoutes(program, container, [], visitedOperations); } function isUninstantiatedTemplateInterface(maybeInterface: Type): boolean { return ( maybeInterface.kind === "Interface" && maybeInterface.node.templateParameters && maybeInterface.node.templateParameters.length > 0 && (!maybeInterface.templateArguments || maybeInterface.templateArguments.length === 0) ); } export function getAllRoutes(program: Program): OperationDetails[] { let operations: OperationDetails[] = []; const serviceNamespace = getServiceNamespace(program); const containers: Type[] = [ ...(serviceNamespace ? [serviceNamespace] : []), ...Array.from(program.stateSet(routeContainerKey)), ]; const visitedOperations = new Set<OperationType>(); for (const container of containers) { // Is this container a templated interface that hasn't been instantiated? if (isUninstantiatedTemplateInterface(container)) { // Skip template interface operations continue; } const newOps = getRoutesForContainer( program, container as OperationContainer, visitedOperations ); // Make sure we don't visit the same operations again newOps.forEach((o) => visitedOperations.add(o.operation)); // Accumulate the new operations operations = [...operations, ...newOps]; } return operations; } // TODO: Make this overridable by libraries const resourceOperationToVerb: any = { read: "get", create: "post", createOrUpdate: "put", update: "patch", delete: "delete", list: "get", }; const autoRouteKey = Symbol(); export function $autoRoute(program: Program, entity: Type) { if (entity.kind !== "Namespace" && entity.kind !== "Interface" && entity.kind !== "Operation") { reportDiagnostic(program, { code: "decorator-wrong-type", format: { decorator: "route", entityKind: entity.kind }, target: entity, }); return; } // Register the container of the operation as one that holds routed operations addRouteContainer(program, entity); program.stateSet(autoRouteKey).add(entity); } export function isAutoRoute( program: Program, target: NamespaceType | InterfaceType | OperationType ): boolean { // Loop up through parent scopes (interface, namespace) to see if // @autoRoute was used anywhere let current: NamespaceType | InterfaceType | OperationType | undefined = target; while (current !== undefined) { if (program.stateSet(autoRouteKey).has(current)) { return true; } // Navigate up to the parent scope if (current.kind === "Namespace" || current.kind === "Interface") { current = current.namespace; } else if (current.kind === "Operation") { current = current.interface || current.namespace; } } return false; } setDecoratorNamespace("Cadl.Http", $route, $routeReset, $autoRoute);
the_stack
import * as debug from "debug"; import { ContinueAsNewAction, DurableOrchestrationBindingInfo, EntityId, HistoryEvent, HistoryEventType, IAction, IOrchestrationFunctionContext, LockState, OrchestratorState, TaskFilter, Utils, } from "./classes"; import { DurableOrchestrationContext } from "./durableorchestrationcontext"; import { OrchestrationFailureError } from "./orchestrationfailureerror"; import { TaskBase } from "./tasks/taskinterfaces"; /** @hidden */ const log = debug("orchestrator"); /** @hidden */ export class Orchestrator { private currentUtcDateTime: Date; constructor(public fn: (context: IOrchestrationFunctionContext) => IterableIterator<unknown>) {} public listen(): (context: IOrchestrationFunctionContext) => Promise<void> { return this.handle.bind(this); } private async handle(context: IOrchestrationFunctionContext): Promise<void> { const orchestrationBinding = Utils.getInstancesOf<DurableOrchestrationBindingInfo>( context.bindings, new DurableOrchestrationBindingInfo() )[0]; if (!orchestrationBinding) { throw new Error("Could not finding an orchestrationClient binding on context."); } const state: HistoryEvent[] = orchestrationBinding.history; const input = orchestrationBinding.input; const instanceId: string = orchestrationBinding.instanceId; // const contextLocks: EntityId[] = orchestrationBinding.contextLocks; // Initialize currentUtcDateTime let decisionStartedEvent: HistoryEvent = Utils.ensureNonNull( state.find((e) => e.EventType === HistoryEventType.OrchestratorStarted), "The orchestrator can not execute without an OrchestratorStarted event." ); this.currentUtcDateTime = new Date(decisionStartedEvent.Timestamp); // Only create durable orchestration context when `context.df` has not been defined // if it has been defined, then we must be in some unit-testing scenario if (context.df === undefined) { // Create durable orchestration context context.df = new DurableOrchestrationContext( state, instanceId, this.currentUtcDateTime, orchestrationBinding.isReplaying, orchestrationBinding.parentInstanceId, input ); } // Setup const gen = this.fn(context); const actions: IAction[][] = []; let partialResult: TaskBase; try { // First execution, we have not yet "yielded" any of the tasks. let g = gen.next(undefined); while (true) { if (!TaskFilter.isYieldable(g.value)) { if (!g.done) { // The orchestrator must have yielded a non-Task related type, // so just return execution flow with what they yielded back. g = gen.next(g.value as any); continue; } else { log("Iterator is done"); // The customer returned an absolute type. context.done( undefined, new OrchestratorState({ isDone: true, output: g.value, actions, customStatus: context.df.customStatus, }) ); return; } } partialResult = g.value as TaskBase; const newActions = partialResult.yieldNewActions(); if (newActions && newActions.length > 0) { actions.push(newActions); } // Return continue as new events as completed, as the execution itself is now completed. if ( TaskFilter.isSingleTask(partialResult) && partialResult.action instanceof ContinueAsNewAction ) { context.done( undefined, new OrchestratorState({ isDone: true, output: undefined, actions, customStatus: context.df.customStatus, }) ); return; } if (!TaskFilter.isCompletedTask(partialResult)) { context.done( undefined, new OrchestratorState({ isDone: false, output: undefined, actions, customStatus: context.df.customStatus, }) ); return; } const completionIndex = partialResult.completionIndex; // The first time a task is marked as complete, the history event that finally marked the task as completed // should not yet have been played by the Durable Task framework, resulting in isReplaying being false. // On replays, the event will have already been processed by the framework, and IsPlayed will be marked as true. if (state[completionIndex] !== undefined) { context.df.isReplaying = state[completionIndex].IsPlayed; } // Handles the case where an orchestration completes with a return value of a // completed (non-faulted) task. This shouldn't generally happen as hopefully the customer // would yield the task before returning out of the generator function. if (g.done) { log("Iterator is done"); context.done( undefined, new OrchestratorState({ isDone: true, actions, output: partialResult.result, customStatus: context.df.customStatus, }) ); return; } // We want to update the `currentUtcDateTime` to be the timestamp of the // latest (timestamp-wise) OrchestratorStarted event that occurs (position-wise) // before our current completionIndex / our current position in the History. const newDecisionStartedEvent = state .filter( (e, index) => e.EventType === HistoryEventType.OrchestratorStarted && e.Timestamp > decisionStartedEvent.Timestamp && index < completionIndex ) .pop(); decisionStartedEvent = newDecisionStartedEvent || decisionStartedEvent; context.df.currentUtcDateTime = this.currentUtcDateTime = new Date( decisionStartedEvent.Timestamp ); // The first time a task is marked as complete, the history event that finally marked the task as completed // should not yet have been played by the Durable Task framework, resulting in isReplaying being false. // On replays, the event will have already been processed by the framework, and IsPlayed will be marked as true. if (state[partialResult.completionIndex] !== undefined) { context.df.isReplaying = state[partialResult.completionIndex].IsPlayed; } if (TaskFilter.isFailedTask(partialResult)) { // We need to check if the generator has a `throw` property merely to satisfy the typechecker. // At this point, it should be guaranteed that the generator has a `throw` and a `next` property, // but we have not refined its type yet. if (!gen.throw) { throw new Error( "Cannot properly throw the exception returned by customer code" ); } g = gen.throw(partialResult.exception); continue; } g = gen.next(partialResult.result as any); } } catch (error) { // Wrap orchestration state in OutOfProcErrorWrapper to ensure data // gets embedded in error message received by C# extension. const errorState = new OrchestratorState({ isDone: false, output: undefined, actions, error: error.message, customStatus: context.df.customStatus, }); context.done(new OrchestrationFailureError(error, errorState), undefined); return; } } private isLocked(contextLocks: EntityId[]): LockState { return new LockState(contextLocks && contextLocks !== null, contextLocks); } /* private lock( state: HistoryEvent[], instanceId: string, contextLocks: EntityId[], entities: EntityId[] ): DurableLock | undefined { if (contextLocks) { throw new Error("Cannot acquire more locks when already holding some locks."); } if (!entities || entities.length === 0) { throw new Error("The list of entities to lock must not be null or empty."); } entities = this.cleanEntities(entities); context.df.newGuid(instanceId); // All the entities in entities[] need to be locked, but to avoid // deadlock, the locks have to be acquired sequentially, in order. So, // we send the lock request to the first entity; when the first lock is // granted by the first entity, the first entity will forward the lock // request to the second entity, and so on; after the last entity // grants the last lock, a response is sent back here. // send lock request to first entity in the lock set return undefined; } private cleanEntities(entities: EntityId[]): EntityId[] { // sort entities return entities.sort((a, b) => { if (a.key === b.key) { if (a.name === b.name) { return 0; } else if (a.name < b.name) { return -1; } else { return 1; } } else if (a.key < b.key) { return -1; } else { return 1; } }); // TODO: remove duplicates if necessary } */ }
the_stack
import { NotebookCell, NotebookCellExecution, NotebookCellOutput, NotebookCellOutputItem, NotebookController, NotebookDocument, notebooks } from 'vscode'; import { CellDiagnosticsProvider } from './problems'; import { Compiler } from './compiler'; import { DisplayData, TensorFlowVis } from '../server/types'; import { createDeferred, Deferred, noop } from '../coreUtils'; const taskMap = new WeakMap<NotebookCell, CellOutput>(); const tfVisContainersInACell = new WeakMap<NotebookCell, Set<string>>(); const NotebookTfVisOutputsByContainer = new WeakMap< NotebookDocument, Map<string, { cell: NotebookCell; output: NotebookCellOutput; deferred: Deferred<void> }> >(); /** * Deals with adding outputs to the cells. * Slow & inefficient implementation of appending outputs. */ export class CellOutput { private ended?: boolean; private promise = Promise.resolve(); private readonly cell: NotebookCell; public static reset(notebook: NotebookDocument) { NotebookTfVisOutputsByContainer.delete(notebook); notebook.getCells().forEach((cell) => taskMap.delete(cell)); } public static resetCell(cell: NotebookCell) { tfVisContainersInACell.delete(cell); } private get outputsByTfVisContainer() { if (!NotebookTfVisOutputsByContainer.has(this.cell.notebook)) { NotebookTfVisOutputsByContainer.set( this.cell.notebook, new Map<string, { cell: NotebookCell; output: NotebookCellOutput; deferred: Deferred<void> }>() ); } return NotebookTfVisOutputsByContainer.get(this.cell.notebook)!; } private tempTask?: NotebookCellExecution; private readonly rendererComms = notebooks.createRendererMessaging('tensorflow-vis-renderer'); private get task() { if (this.tempTask) { return this.tempTask; } try { // Once the original task has been ended, we need to create a temporary task. if (this.ended) { this.tempTask = this.controller.createNotebookCellExecution(this.cell); this.tempTask.start(this.cell.executionSummary?.timing?.startTime); this.tempTask.executionOrder = this.originalTask.executionOrder; return this.tempTask; } } catch (ex) { console.error('Failed to create a task in CellOutput', ex); } return this.originalTask; } constructor( private originalTask: NotebookCellExecution, private readonly controller: NotebookController, private readonly requestId: string ) { this.cell = originalTask.cell; this.rendererComms.onDidReceiveMessage((e) => { if (typeof e.message !== 'object' || !e.message) { return; } type Message = { containerId: string; type: 'tfvisCleared'; }; const message = e.message as Message; if (message.type === 'tfvisCleared') { this.outputsByTfVisContainer.delete(message.containerId); } }); } private setTask(task: NotebookCellExecution) { this.ended = false; this.originalTask = task; } private async waitForAllPendingPromisesToFinish() { await this.promise.catch(noop); } public async end(success?: boolean, endTime?: number) { if (this.ended) { return; } // Even with the chaining the order isn't the way we want it. // Its possible we call some API: // Thats waiting on promise // Next we end the task, that will then wait on this promise. // After the first promise is resolved, it will immediatel come here. // But even though the promise has been updated, its too late as we were merely waiting on the promise. // What we need is a stack (or just wait on all pending promises). await this.waitForAllPendingPromisesToFinish(); this.ended = true; try { this.originalTask.end(success, endTime); } catch (ex) { console.error('Failed to end task', ex); } taskMap.delete(this.cell); } public static getOrCreate(task: NotebookCellExecution, controller: NotebookController, requestId: string) { taskMap.set(task.cell, taskMap.get(task.cell) || new CellOutput(task, controller, requestId)); const output = taskMap.get(task.cell)!; output.setTask(task); return output; } private lastOutputStream?: { output: NotebookCellOutput; stream: 'stdout' | 'stderr'; id: string }; public appendStreamOutput(value: string, stream: 'stdout' | 'stderr') { if (value.length === 0) { return; } this.promise = this.promise .finally(async () => { value = Compiler.fixCellPathsInStackTrace(this.cell.notebook, value); const output: NotebookCellOutput | undefined = this.lastOutputStream && this.lastOutputStream.stream === stream ? this.cell.outputs.find((item) => item.metadata?._id === this.requestId) : undefined; if (output) { const newText = `${output.items[0].data.toString()}${value}`; const item = stream === 'stderr' ? NotebookCellOutputItem.stderr(newText) : NotebookCellOutputItem.stdout(newText); this.task .replaceOutputItems(item, output) .then(noop, (ex) => console.error('Failed to replace output items in CellOutput', ex)); } else { const item = stream === 'stderr' ? NotebookCellOutputItem.stderr(value) : NotebookCellOutputItem.stdout(value); await this.task .appendOutput(new NotebookCellOutput([item], { _id: this.requestId, stream })) .then(noop, (ex) => console.error('Failed to append output items in CellOutput', ex)); const output = this.cell.outputs.find( (item) => item.metadata?._id === this.requestId && item.metadata?.stream === stream ); if (output) { this.lastOutputStream = { output, stream, id: this.requestId }; } else { this.lastOutputStream = undefined; } } }) .finally(() => this.endTempTask()); } public appendTensorflowVisOutput(output: DisplayData) { const individualOutputItems: TensorFlowVis[] = []; if (output.type === 'multi-mime') { individualOutputItems.push(...(output.value.filter((item) => item.type === 'tensorFlowVis') as any)); } else if (output.type === 'tensorFlowVis') { individualOutputItems.push(output as any); } if (individualOutputItems.length === 0) { return; } this.promise = this.promise .finally(async () => { await Promise.all( individualOutputItems.map(async (value) => { switch (value.request) { case 'layer': case 'barchart': case 'confusionmatrix': case 'heatmap': case 'histogram': case 'modelsummary': case 'history': case 'linechart': case 'perclassaccuracy': case 'valuesdistribution': case 'table': case 'scatterplot': case 'registerfitcallback': { const containerId = JSON.stringify(value.container); const existingInfo = this.outputsByTfVisContainer.get(containerId); if (existingInfo) { // If the output exists & we're just updating that, // then send a message to that renderer (faster to update). if ( existingInfo.cell.outputs.find( (item) => item.metadata?.containerId === containerId ) ) { this.rendererComms.postMessage({ ...value }); return; } if (!existingInfo.deferred.completed) { return; } if ( existingInfo.deferred.completed && existingInfo.cell.outputs.find( (item) => item.metadata?.containerId === containerId ) ) { this.rendererComms.postMessage({ ...value }); return; } // Perhaps the user cleared the outputs. } // Create a new output item to render this information. const tfVisOutputToAppend = new NotebookCellOutput( [ NotebookCellOutputItem.json( value, `application/vnd.tfjsvis.${value.request.toLowerCase()}` ) ], { containerId, requestId: value.requestId } ); this.outputsByTfVisContainer.set(containerId, { cell: this.cell, output: tfVisOutputToAppend, deferred: createDeferred<void>() }); this.lastOutputStream = undefined; await this.task.appendOutput(tfVisOutputToAppend).then(noop, noop); // Wait for output to get created. if ( this.cell.outputs.find((item) => item.metadata?.containerId === containerId) && this.outputsByTfVisContainer.get(containerId) ) { this.outputsByTfVisContainer.get(containerId)?.deferred.resolve(); } else { this.outputsByTfVisContainer.delete(containerId); } return; } case 'fitcallback': { // Look for this output. const containerId = JSON.stringify(value.container); const existingInfo = this.outputsByTfVisContainer.get(containerId); if (existingInfo) { // Wait till the UI element is rendered by the renderer. // & Once rendered, we can send a message instead of rendering outputs. existingInfo.deferred.promise.finally(() => this.rendererComms.postMessage({ ...value }) ); } return; } case 'show': case 'setactivetab': { return; } default: break; } }) ); }) .finally(() => this.endTempTask()); } public appendOutput(output: DisplayData) { this.promise = this.promise .finally(async () => { const individualOutputItems: DisplayData[] = []; if (output.type === 'multi-mime') { individualOutputItems.push(...output.value); } else { individualOutputItems.push(output); } const items: NotebookCellOutputItem[] = []; Promise.all( individualOutputItems.map(async (value) => { switch (value.type) { case 'image': { if (value.mime === 'svg+xml') { return items.push(NotebookCellOutputItem.text(value.value, 'text/html')); } else { return items.push( new NotebookCellOutputItem(Buffer.from(value.value, 'base64'), value.mime) ); } } case 'json': case 'array': case 'tensor': { // We might end up sending strings, to avoid unnecessary issues with circular references in objects. return items.push( NotebookCellOutputItem.json( typeof value.value === 'string' ? JSON.parse(value.value) : value.value ) ); } case 'html': // Left align all html. const style = '<style> table, th, tr { text-align: left; }</style>'; return items.push( new NotebookCellOutputItem(Buffer.from(`${style}${value.value}`), 'text/html') ); case 'generatePlot': { const data = { ...value }; return items.push( NotebookCellOutputItem.json(data, 'application/vnd.ts.notebook.plotly+json') ); } case 'tensorFlowVis': { // We have a separate method for this. return; } case 'markdown': { return items.push(NotebookCellOutputItem.text(value.value, 'text/markdown')); } default: return items.push(NotebookCellOutputItem.text(value.value.toString())); } }) ); if (items.length > 0) { this.lastOutputStream = undefined; this.task.appendOutput(new NotebookCellOutput(items)).then(noop, noop); } }) .finally(() => this.endTempTask()); } public appendError(ex?: Partial<Error>) { this.promise = this.promise .finally(() => { CellDiagnosticsProvider.displayErrorsAsProblems(this.cell.notebook, ex); const newEx = new Error(ex?.message || '<unknown>'); newEx.name = ex?.name || ''; newEx.stack = ex?.stack || ''; // We dont want the same error thing display again // (its already in the stack trace & the error renderer displays it again) newEx.stack = newEx.stack.replace(`${newEx.name}: ${newEx.message}\n`, ''); newEx.stack = Compiler.fixCellPathsInStackTrace(this.cell.notebook, newEx); const output = new NotebookCellOutput([NotebookCellOutputItem.error(newEx)]); this.task.appendOutput(output); }) .then(noop, (ex) => console.error('Failed to append the Error output in cellOutput', ex)) .finally(() => this.endTempTask()); } private endTempTask() { if (this.tempTask) { this.tempTask.end(this.cell.executionSummary?.success, this.cell.executionSummary?.timing?.endTime); this.tempTask = undefined; } } } // /* eslint-disable @typescript-eslint/no-non-null-assertion */ // import { // NotebookCell, // NotebookCellExecution, // NotebookCellOutput, // NotebookCellOutputItem, // NotebookController // } from 'vscode'; // import { CellDiagnosticsProvider } from './problems'; // import { Compiler } from './compiler'; // import { DisplayData, GeneratePlot } from '../server/types'; // // eslint-disable-next-line @typescript-eslint/no-var-requires // const { isPlainObject } = require('is-plain-object'); // const taskMap = new WeakMap<NotebookCell, CellStdOutput>(); // export class CellStdOutput { // private ended?: boolean; // private lastStreamOutput?: { output: NotebookCellOutput; stream: 'stdout' | 'stderr'; value: string }; // private _tempTask?: NotebookCellExecution; // private get task() { // if (this._tempTask) { // return this._tempTask; // } // try { // if (this.ended) { // this._tempTask = this.controller.createNotebookCellExecution(this._task.cell); // this._tempTask.start(this._task.cell.executionSummary?.timing?.startTime); // this._tempTask.executionOrder = this._task.executionOrder; // return this._tempTask; // } // } catch (ex) { // console.error(ex); // } // return this._task; // } // constructor(private _task: NotebookCellExecution, private readonly controller: NotebookController) {} // private setTask(task: NotebookCellExecution) { // this.ended = false; // this._task = task; // } // public end(success?: boolean, endTimne?: number) { // if (this.ended) { // return; // } // this.ended = true; // this._task.end(success, endTimne); // } // public static getOrCreate(task: NotebookCellExecution, controller: NotebookController) { // taskMap.set(task.cell, taskMap.get(task.cell) || new CellStdOutput(task, controller)); // const output = taskMap.get(task.cell)!; // output.setTask(task); // return output; // } // /** // * This is all wrong. // */ // public appendOutput(output: DisplayData) { // this.lastStreamOutput = undefined; // const individualOutputItems: DisplayData[] = []; // if (output && typeof output === 'object' && 'type' in output && output.type === 'multi-mime') { // individualOutputItems.push(...output.data); // } else { // individualOutputItems.push(output); // } // const items = individualOutputItems.map((value) => { // if (value && typeof value === 'object' && 'type' in value && value.type === 'image') { // return new NotebookCellOutputItem(Buffer.from(value.value, 'base64'), value.mime); // } else if ( // (value && typeof value === 'object' && 'type' in value && value.type === 'json') || // (value && typeof value === 'object' && 'type' in value && value.type === 'array') || // (value && typeof value === 'object' && 'type' in value && value.type === 'tensor') // ) { // return NotebookCellOutputItem.json( // typeof value.value === 'string' ? JSON.parse(value.value) : value.value // ); // } else if (value && typeof value === 'object' && 'type' in value && value.type === 'html') { // return NotebookCellOutputItem.text(value.value, 'text/html'); // } else if (value && typeof value === 'object' && 'type' in value && value.type === 'generatePlog') { // return this.renderPlotScript(value); // } else if (isPlainObject(value)) { // return NotebookCellOutputItem.json(value); // } else { // return NotebookCellOutputItem.text(value.toString()); // } // }); // void this.task.appendOutput(new NotebookCellOutput(items)); // this.endTempTask(); // } // public appendError(ex?: Partial<Error>) { // this.lastStreamOutput = undefined; // CellDiagnosticsProvider.trackErrors(this.task.cell.notebook, ex); // const newEx = new Error(ex?.message || '<unknown>'); // newEx.name = ex?.name || ''; // newEx.stack = ex?.stack || ''; // newEx.stack = Compiler.updateCellPathsInStackTraceOrOutput(this.task.cell.notebook, newEx); // const output = new NotebookCellOutput([NotebookCellOutputItem.error(newEx)]); // void this.task.appendOutput(output); // this.endTempTask(); // } // public appendStreamOutput(value: string, stream: 'stdout' | 'stderr') { // value = Compiler.updateCellPathsInStackTraceOrOutput(this.task.cell.notebook, value); // if (this.lastStreamOutput?.stream === stream) { // this.lastStreamOutput.value += value; // const item = // stream === 'stdout' // ? NotebookCellOutputItem.stdout(this.lastStreamOutput.value) // : NotebookCellOutputItem.stderr(this.lastStreamOutput.value); // void this.task.appendOutputItems(item, this.lastStreamOutput.output); // } else { // this.lastStreamOutput = { output: new NotebookCellOutput([]), stream: 'stdout', value: '' }; // this.lastStreamOutput.value += value; // const item = // stream === 'stdout' // ? NotebookCellOutputItem.stdout(this.lastStreamOutput.value) // : NotebookCellOutputItem.stderr(this.lastStreamOutput.value); // this.lastStreamOutput.output.items.push(item); // void this.task.appendOutput(this.lastStreamOutput.output); // } // this.endTempTask(); // } // private renderPlotScript(request: GeneratePlot) { // const data = { ...request }; // return NotebookCellOutputItem.json(data, 'application/vnd.ts.notebook.plotly+json'); // } // private endTempTask() { // if (this._tempTask) { // this._tempTask.end( // this._task.cell.executionSummary?.success, // this._task.cell.executionSummary?.timing?.endTime // ); // this._tempTask = undefined; // } // } // }
the_stack
describe('Choices - text element', () => { beforeEach(() => { cy.visit('/text', { onBeforeLoad(win) { cy.stub(win.console, 'warn').as('consoleWarn'); }, }); }); describe('scenarios', () => { const textInput = 'testing'; describe('basic', () => { describe('adding items', () => { it('allows me to input items', () => { cy.get('[data-test-hook=basic]') .find('.choices__input--cloned') .type(textInput) .type('{enter}'); cy.get('[data-test-hook=basic]') .find('.choices__list--multiple .choices__item') .last() .should(($el) => { expect($el).to.contain(textInput); }); }); it('updates the value of the original input', () => { cy.get('[data-test-hook=basic]') .find('.choices__input--cloned') .type(textInput) .type('{enter}'); cy.get('[data-test-hook=basic]') .find('.choices__input[hidden]') .should('have.value', textInput); }); describe('inputting data', () => { it('shows a dropdown prompt', () => { cy.get('[data-test-hook=basic]') .find('.choices__input--cloned') .type(textInput); cy.get('[data-test-hook=basic]') .find('.choices__list--dropdown') .should('be.visible') .should(($dropdown) => { const dropdownText = $dropdown.text().trim(); expect(dropdownText).to.equal( `Press Enter to add "${textInput}"`, ); }); }); }); }); }); describe('editing items', () => { beforeEach(() => { for (let index = 0; index < 3; index++) { cy.get('[data-test-hook=edit-items]') .find('.choices__input--cloned') .type(textInput) .type('{enter}'); } }); describe('on back space', () => { it('allows me to change my entry', () => { cy.get('[data-test-hook=edit-items]') .find('.choices__input--cloned') .type('{backspace}') .type('-edited') .type('{enter}'); cy.get('[data-test-hook=edit-items]') .find('.choices__list--multiple .choices__item') .last() .should(($choice) => { expect($choice.data('value')).to.equal(`${textInput}-edited`); }); }); }); describe('on cmd+a', () => { beforeEach(() => { cy.get('[data-test-hook=edit-items]') .find('.choices__input--cloned') .type('{cmd}a'); }); it('highlights all items', () => { cy.get('[data-test-hook=edit-items]') .find('.choices__list--multiple .choices__item') .each(($choice) => { expect($choice.hasClass('is-highlighted')).to.equal(true); }); }); describe('on backspace', () => { it('clears all inputted values', () => { // two backspaces are needed as Cypress has an issue where // it will also insert an 'a' character into the text input cy.get('[data-test-hook=edit-items]') .find('.choices__input--cloned') .type('{backspace}{backspace}'); cy.get('[data-test-hook=edit-items]') .find('.choices__list--multiple .choices__item') .should('have.length', 0); }); }); }); }); describe('remove button', () => { beforeEach(() => { cy.get('[data-test-hook=remove-button]') .find('.choices__input--cloned') .type(`${textInput}`) .type('{enter}'); }); describe('on click', () => { it('removes respective choice', () => { cy.get('[data-test-hook=remove-button]') .find('.choices__list--multiple') .children() .should(($items) => { expect($items.length).to.equal(1); }); cy.get('[data-test-hook=remove-button]') .find('.choices__list--multiple .choices__item') .last() .find('.choices__button') .focus() .click(); cy.get('[data-test-hook=remove-button]') .find('.choices__list--multiple .choices__item') .should(($items) => { expect($items.length).to.equal(0); }); }); it('updates the value of the original input', () => { cy.get('[data-test-hook=remove-button]') .find('.choices__list--multiple .choices__item') .last() .find('.choices__button') .focus() .click(); cy.get('[data-test-hook=remove-button]') .find('.choices__input[hidden]') .then(($input) => { expect($input.val()).to.not.contain(textInput); }); }); }); }); describe('unique values only', () => { describe('unique values', () => { beforeEach(() => { cy.get('[data-test-hook=unique-values]') .find('.choices__input--cloned') .type(`${textInput}`) .type('{enter}') .type(`${textInput}`) .type('{enter}'); }); it('only allows me to input unique values', () => { cy.get('[data-test-hook=unique-values]') .find('.choices__list--multiple') .first() .children() .should(($items) => { expect($items.length).to.equal(1); }); }); describe('inputting a non-unique value', () => { it('displays dropdown prompt', () => { cy.get('[data-test-hook=unique-values]') .find('.choices__list--dropdown') .should('be.visible') .should(($dropdown) => { const dropdownText = $dropdown.text().trim(); expect(dropdownText).to.equal( 'Only unique values can be added', ); }); }); }); }); }); describe('input limit', () => { const inputLimit = 5; beforeEach(() => { for (let index = 0; index < inputLimit + 1; index++) { cy.get('[data-test-hook=input-limit]') .find('.choices__input--cloned') .type(`${textInput} + ${index}`) .type('{enter}'); } }); it('does not let me input more than 5 choices', () => { cy.get('[data-test-hook=input-limit]') .find('.choices__list--multiple') .first() .children() .should(($items) => { expect($items.length).to.equal(inputLimit); }); }); describe('reaching input limit', () => { it('displays dropdown prompt', () => { cy.get('[data-test-hook=input-limit]') .find('.choices__list--dropdown') .should('be.visible') .should(($dropdown) => { const dropdownText = $dropdown.text().trim(); expect(dropdownText).to.equal( `Only ${inputLimit} values can be added`, ); }); }); }); }); describe('add item filter', () => { describe('inputting a value that satisfies the filter', () => { const input = 'joe@bloggs.com'; it('allows me to add choice', () => { cy.get('[data-test-hook=add-item-filter]') .find('.choices__input--cloned') .type(input) .type('{enter}'); cy.get('[data-test-hook=add-item-filter]') .find('.choices__list--multiple .choices__item') .last() .should(($choice) => { expect($choice.text().trim()).to.equal(input); }); }); }); describe('inputting a value that does not satisfy the regex', () => { it('displays dropdown prompt', () => { cy.get('[data-test-hook=add-item-filter]') .find('.choices__input--cloned') .type(`this is not an email address`) .type('{enter}'); cy.get('[data-test-hook=add-item-filter]') .find('.choices__list--dropdown') .should('be.visible') .should(($dropdown) => { const dropdownText = $dropdown.text().trim(); expect(dropdownText).to.equal( 'Only values matching specific conditions can be added', ); }); }); }); }); describe('prepend/append', () => { beforeEach(() => { cy.get('[data-test-hook=prepend-append]') .find('.choices__input--cloned') .type(textInput) .type('{enter}'); }); it('prepends and appends value to inputted value', () => { cy.get('[data-test-hook=prepend-append]') .find('.choices__list--multiple .choices__item') .last() .should(($choice) => { expect($choice.data('value')).to.equal(`before-${textInput}-after`); }); }); it('displays just the inputted value to the user', () => { cy.get('[data-test-hook=prepend-append]') .find('.choices__list--multiple .choices__item') .last() .should(($choice) => { expect($choice.text()).to.not.contain(`before-${textInput}-after`); expect($choice.text()).to.contain(textInput); }); }); }); describe('adding items disabled', () => { it('does not allow me to input data', () => { cy.get('[data-test-hook=adding-items-disabled]') .find('.choices__input--cloned') .should('be.disabled'); }); }); describe('disabled via attribute', () => { it('does not allow me to input data', () => { cy.get('[data-test-hook=disabled-via-attr]') .find('.choices__input--cloned') .should('be.disabled'); }); }); describe('pre-populated choices', () => { it('pre-populates choices', () => { cy.get('[data-test-hook=prepopulated]') .find('.choices__list--multiple .choices__item') .should(($choices) => { expect($choices.length).to.equal(2); }); cy.get('[data-test-hook=prepopulated]') .find('.choices__list--multiple .choices__item') .first() .should(($choice) => { expect($choice.text().trim()).to.equal('Josh Johnson'); }); cy.get('[data-test-hook=prepopulated]') .find('.choices__list--multiple .choices__item') .last() .should(($choice) => { expect($choice.text().trim()).to.equal('Joe Bloggs'); }); }); }); describe('placeholder', () => { /* { placeholder: true, placeholderValue: 'I am a placeholder', } */ describe('when no value has been inputted', () => { it('displays a placeholder', () => { cy.get('[data-test-hook=placeholder]') .find('.choices__input--cloned') .should('have.attr', 'placeholder', 'I am a placeholder'); }); }); }); describe('allow html', () => { describe('is undefined', () => { it('logs a deprecation warning', () => { cy.get('@consoleWarn').should( 'be.calledOnceWithExactly', 'Deprecation warning: allowHTML will default to false in a future release. To render HTML in Choices, you will need to set it to true. Setting allowHTML will suppress this message.', ); }); it('does not show html as text', () => { cy.get('[data-test-hook=allowhtml-undefined]') .find('.choices__list--multiple .choices__item') .first() .should(($choice) => { expect($choice.text().trim()).to.equal('Mason Rogers'); }); }); }); describe('set to true', () => { it('does not show html as text', () => { cy.get('[data-test-hook=allowhtml-true]') .find('.choices__list--multiple .choices__item') .first() .should(($choice) => { expect($choice.text().trim()).to.equal('Mason Rogers'); }); }); }); describe('set to false', () => { it('shows html as text', () => { cy.get('[data-test-hook=allowhtml-false]') .find('.choices__list--multiple .choices__item') .first() .should(($choice) => { expect($choice.text().trim()).to.equal('<b>Mason Rogers</b>'); }); }); }); }); describe('within form', () => { describe('inputting item', () => { describe('on enter key', () => { it('does not submit form', () => { cy.get('[data-test-hook=within-form] form').then(($form) => { $form.submit(() => { // this will fail the test if the form submits throw new Error('Form submitted'); }); }); cy.get('[data-test-hook=within-form]') .find('.choices__input--cloned') .type(textInput) .type('{enter}'); cy.get('[data-test-hook=within-form]') .find('.choices__list--multiple .choices__item') .last() .should(($el) => { expect($el).to.contain(textInput); }); }); }); }); }); }); });
the_stack
import { createElement } from '@syncfusion/ej2-base'; import { Chart } from '../../../src/chart/chart'; import { Series, Points } from '../../../src/chart/series/chart-series'; import { Axis } from '../../../src/chart/axis/axis'; import { LineSeries } from '../../../src/chart/series/line-series'; import { DataLabel } from '../../../src/chart/series/data-label'; import { Category } from '../../../src/chart/axis/category-axis'; import { DateTime } from '../../../src/chart/axis/date-time-axis'; import { ChartSeriesType, ChartRangePadding } from '../../../src/chart/utils/enum'; import { ValueType } from '../../../src/chart/utils/enum'; import { Tooltip } from '../../../src/chart/user-interaction/tooltip'; import { ParetoSeries } from '../../../src/chart/series/pareto-series'; import { Crosshair } from '../../../src/chart/user-interaction/crosshair'; import { tooltipData1, negativeDataPoint, rotateData1, rotateData2, categoryData, categoryData1 } from '../base/data.spec'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { unbindResizeEvents } from '../base/data.spec'; import { MouseEvents } from '../base/events.spec'; import { EmitType } from '@syncfusion/ej2-base'; import { getElement } from '../../../src/index'; import {profile , inMB, getMemoryProfile} from '../../common.spec'; import { ILoadedEventArgs, IAnimationCompleteEventArgs, IPointRenderEventArgs } from '../../../src/chart/model/chart-interface'; Chart.Inject(LineSeries, ParetoSeries, DataLabel, Category, DateTime, Tooltip, Crosshair); export interface Arg { chart: Chart; } export interface series { series: Series; } describe('chart control', () => { beforeAll(() => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) return; } }); let element: HTMLElement; /** * Default Pareto Series */ describe('pareto Series', () => { let chartObj: Chart; let loaded: EmitType<ILoadedEventArgs>; let element: HTMLElement = createElement('div', { id: 'container' }); let dataLabel: HTMLElement; let point: Points; let trigger: MouseEvents = new MouseEvents(); let x: number; let y: number; let tooltip: HTMLElement; let chartArea: HTMLElement; let series: Series; let element1: Element; // let loaded: EmitType<ILoadedEventArgs>; let animationComplete: EmitType<IAnimationCompleteEventArgs>; element = createElement('div', { id: 'container' }); beforeAll(() => { document.body.appendChild(element); var data = [ { 'x': 'UC Browser', y: 37, }, { 'x': 'Chrome', y: 40, }, { 'x': 'Android', y: 3, }, { 'x': 'Mozila', y: 2, }, { 'x': 'Micromax', y: 1, }, { 'x': 'iPhone', y: 32, }, { 'x': 'Others', y: 26, }, { 'x': 'Opera', y: 8, }, ]; chartObj = new Chart( { primaryXAxis: { valueType: 'Category', title: 'Browser' }, primaryYAxis: { title: 'Values', minimum: 0, maximum: 150, interval: 30, }, series: [ { xName: 'x', yName: 'y', dataSource: data, name: 'Browser', type: 'Pareto', marker: { dataLabel: { visible: true }, visible: true, width: 10, height: 10 } }, ], legendSettings: { position: 'Top', border: { width: 1, color: 'red' } }, tooltip: { enable: true, format: '${point.x}:<b> ${point.y}<b>', enableAnimation: true }, title: 'Mobile Browser Statistics', border: { width: 2, color: 'blue' }, chartArea: { border: { width: 2, color: 'red' } } }); chartObj.appendTo('#container'); }); afterAll((): void => { chartObj.destroy(); document.getElementById('container').remove(); }); it('Checking with axis with opposed position', (done: Function) => { loaded = (args: Object): void => { let svg: HTMLElement = document.getElementById('container1_AxisLabel_0'); let svg1: HTMLElement = document.getElementById('container2_AxisLabel_0'); expect(parseFloat(svg.getAttribute('x')) < parseFloat(svg1.getAttribute('x'))).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].animation.enable = false; chartObj.axes[0].opposedPosition = true; chartObj.refresh(); }); it('Showing default data label', (done: Function) => { loaded = (args: Object): void => { let element = document.getElementById('container_Series_0_Point_3_Text_0'); expect((+element.textContent) == 26).toBe(true); expect(document.getElementById('containerShapeGroup0').childNodes.length == 0).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].marker.dataLabel.visible = true; chartObj.refresh(); }); it('Checking dataLabel positions Top', (done: Function) => { loaded = (args: Object): void => { let element1: number = +document.getElementById('container_Series_0_Point_4_Text_0').getAttribute('y'); expect((<Points>(<Series>chartObj.series[0]).points[4]).symbolLocations[0].y < element1).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].marker.dataLabel.position = 'Top'; chartObj.refresh(); }); it('Checking dataLabel positions Middle', (done: Function) => { loaded = (args: Object): void => { let element: number = +document.getElementById('container_Series_0_Point_0_Text_0').getAttribute('y'); let locationY: number = (<Points>(<Series>chartObj.series[0]).points[0]).symbolLocations[0].y; let height: number = document.getElementById('container_Series_0_Point_0_Text_0').getBoundingClientRect().height; expect(locationY != element).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].marker.dataLabel.position = 'Middle'; chartObj.refresh(); }); it('Checking dataLabel positions Outer', (done: Function) => { loaded = (args: Object): void => { let element1: number = +document.getElementById('container_Series_0_Point_2_Text_0').getAttribute('y'); expect((<Points>(<Series>chartObj.series[0]).points[2]).symbolLocations[0].y > element1).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].marker.dataLabel.position = 'Outer'; chartObj.refresh(); }); it('Checking the child Element count', (done: Function) => { loaded = (args: Object): void => { element1 = getElement('containerSeriesCollection'); expect(element1.childElementCount).toBe(6); done(); }; chartObj.loaded = loaded; chartObj.refresh(); }); it('Showing default marker', (done: Function) => { loaded = (args: Object): void => { element1 = getElement('containerSymbolGroupPareto'); expect(element1.childElementCount).toBe(9); let marker: HTMLElement = document.getElementById('container_Series_Pareto_Point_0_Symbol'); expect(marker.getAttribute('stroke') == '#000000').toBe(true); expect(marker.getAttribute('fill') == '#ffffff').toBe(true); expect(marker.getAttribute('rx') == '5').toBe(true); expect(marker.getAttribute('ry') == '5').toBe(true); done(); }; chartObj.loaded = loaded; chartObj.refresh(); }); it('Checking the last text value as 100', (done: Function) => { loaded = (args: Object): void => { expect(document.getElementById('container_Series_Pareto_Point_7_Text_0').textContent).toBe(100 + '%'); done(); } chartObj.loaded = loaded; chartObj.refresh(); }); it('Checking line series marker color', (done: Function) => { loaded = (args: Object): void => { let element1: HTMLElement = document.getElementById('container_Series_Pareto_Point_2_Symbol'); expect(element1.getAttribute('fill') == '#ffffff').toBe(true); done(); } chartObj.loaded = loaded; chartObj.refresh(); }); it('Checking column series in descending order', (done: Function) => { loaded = (args: Object): void => { let element1: HTMLElement = document.getElementById('container_Series_0_Point_3_Text_0'); let element2: HTMLElement = document.getElementById('container_Series_0_Point_4_Text_0'); expect(parseFloat(element1.getAttribute('y')) < parseFloat(element2.getAttribute('y'))).toBe(true); done(); } chartObj.loaded = loaded; chartObj.refresh(); }); it('Checking line series in ascending order', (done: Function) => { loaded = (args: Object): void => { let element1: HTMLElement = document.getElementById('container_Series_Pareto_Point_1_Text_0'); let element2: HTMLElement = document.getElementById('container_Series_Pareto_Point_2_Text_0'); expect(parseFloat(element1.getAttribute('y')) > parseFloat(element2.getAttribute('y'))).toBe(true); done(); } chartObj.loaded = loaded; chartObj.refresh(); }); it('Checking the legend', (done: Function) => { loaded = (args: Object): void => { element1 = getElement('container_chart_legend_translate_g'); expect(element1.childElementCount).toBe(2); done(); }; chartObj.loaded = loaded; chartObj.refresh(); }); it('Changing marker shape ', (done: Function) => { loaded = (args: Object): void => { let direction: string; let series1: HTMLElement; series1 = document.getElementById('container_Series_Pareto_Point_1_Symbol'); //direction = series1.getAttribute('d'); expect(series1 != null).toBe(true); done(); } chartObj.loaded = loaded; chartObj.series[0].marker.shape = 'Rectangle'; chartObj.refresh(); }); it('Checking line series rendering', (done: Function) => { loaded = (args: Object): void => { let path = document.getElementById('container_Series_Pareto'); let id: string = path.getAttribute('d'); let check: number = id.indexOf('z'); expect(check !== 0).toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].marker.shape = 'Circle'; chartObj.refresh(); }); it('Changing marker size', (done: Function) => { loaded = (args: Object): void => { let series1: HTMLElement = document.getElementById('container_Series_Pareto_Point_2_Symbol'); expect(series1.getAttribute('rx') == '5').toBe(true); expect(series1.getAttribute('ry') == '5').toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].marker.visible = true; chartObj.series[0].marker.width = 10; chartObj.series[0].marker.height = 10; chartObj.refresh(); }); it('Changing datalabel color', (done: Function) => { loaded = (args: Object): void => { let series1: HTMLElement = document.getElementById('container_Series_0_Point_1_Text_0'); expect(series1.getAttribute('fill') == 'white').toBe(true); done(); } chartObj.loaded = loaded; chartObj.series[0].marker.offset.x = 0; chartObj.series[0].marker.dataLabel.fill = "blue"; chartObj.refresh(); }); }); describe('multiple Series', () => { let chartObj: Chart; let loaded: EmitType<ILoadedEventArgs>; let element: HTMLElement = createElement('div', { id: 'container' }); let series: Series; let element1: Element; element = createElement('div', { id: 'container' }); beforeAll(() => { document.body.appendChild(element); var data = [ { x: 'Traffic', y: 56 }, { x: 'Child Care', y: 44.8 }, { x: 'Transport', y: 87.2 }, { x: 'Weather', y: 19.6 }, { x: 'Emergency', y: 6.6 } ]; var data1= [ { x: 'Traffic', y: 56 }, { x: 'Child Care', y: 44.8 }, { x: 'Transport', y: 37.2 }, { x: 'Weather', y: 19.6 }, { x: 'Emergency', y: 6.6 } ]; chartObj = new Chart( { primaryXAxis: { valueType: 'Category', title: 'Browser' }, primaryYAxis: { title: 'Values', minimum: 0, maximum: 150, interval: 30, }, axes: [{ minimum: 0, name: '', opposedPosition: true, maximum: 100, interval: 30, rowIndex: 1, lineStyle: { width: 0 }, majorTickLines: { width: 0 }, majorGridLines: { width: 1 }, minorGridLines: { width: 1 }, minorTickLines: { width: 0 } }], series: [ { xName: 'x', yName: 'y', dataSource: data, name: 'Browser', type: 'Pareto', marker: { dataLabel: { visible: true }, visible: true, width: 10, height: 10 } }, { xName: 'x', yName: 'y', dataSource: data1, name: 'Browser', type: 'Pareto', marker: { dataLabel: { visible: true }, visible: true, width: 10, height: 10, } }, ], legendSettings: { position: 'Top', border: { width: 1, color: 'red' } }, tooltip: { enable: true, format: '${point.x}:<b> ${point.y}<b>', enableAnimation: true }, title: 'Mobile Browser Statistics', border: { width: 2, color: 'blue' }, chartArea: { border: { width: 2, color: 'red' } } }); chartObj.appendTo('#container'); }); afterAll((): void => { chartObj.destroy(); document.getElementById('container').remove(); }); it('Checking with multiple series type', (done: Function) => { loaded = (args: Object): void => { let element: Element = document.getElementById('container_Series_0_Point_0'); let element1: Element = document.getElementById('container_Series_1_Point_0'); expect(element.getAttribute('d') != '').toBe(true); expect(element1.getAttribute('d') != '').toBe(true); done(); }; chartObj.loaded = loaded; chartObj.series[0].animation.enable = false; chartObj.series[1].animation.enable = false; chartObj.refresh(); }); it('Checking with axes', function (done) { loaded = function (args) { var element = document.getElementById('containerAxisLine_0'); var element1 = document.getElementById('containerAxisLine_1'); expect(element.getAttribute('y1') == '388.5'); expect(element1.getAttribute('y1') == '234.75'); done(); }; chartObj.loaded = loaded; chartObj.series[1].yAxisName='secondary'; chartObj.axes[0].name=chartObj.series[1].yAxisName; chartObj.rows = [{ height: '50%' }, { height: '50%' }]; chartObj.refresh(); }); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }) });
the_stack
import type { LiteralUnion } from '@/generalTypes' import type { JSONTextComponent, LootTableEntry } from '@arguments' import type { BASIC_COLORS, MAP_ICONS } from '@arguments/basics' import type { ATTRIBUTES, BLOCKS, ENCHANTMENTS, STRUCTURES, } from '@arguments/generated' import type { LootTableInstance } from '@resources' import type { DataInstance } from '@variables/Data' import type { NumberProvider } from './criteria/utils' import type { ObjectOrArray, PredicateCondition } from './predicate' type ItemModifierKind<TYPE extends string, VALUES extends Record<string, unknown>> = { /** * The function to apply. Must be one of the following: * - `apply_bonus`: Applies a predefined bonus formula. * - `copy_name`: For loot table type 'block', copies a block entity's `CustomName` tag into the item's `display.Name` tag. * - `copy_nbt`: Copies nbt to the item's `tag` tag. * - `copy_state`: Copies state properties from dropped block to the item's `BlockStateTag` tag. * - `enchant_randomly`: Enchants the item with one randomly-selected enchantment. The level of the enchantment, if applicable, is random. * - `enchant_with_levels`: Enchants the item, with the specified [enchantment level](https://minecraft.gamepedia.com/Enchantment_mechanics#How_Enchantments_Are_Chosen)` * (roughly equivalent to using an `enchantment table` at that level). * - `exploration_map`: Converts an empty map into an `explorer map` leading to a nearby generated structure. * - `explosion_decay`: For loot tables of type 'block', removes some items from a stack, if there was an explosion. Each item has a chance of 1/explosion radius to be lost. * - `furnace_smelt`: Smelts the item as it would be in a furnace. Used in combination with the `entity_properties` condition to cook food from animals on death. * - `fill_player_head`: Adds required item tags of a player head * - `limit_count`: Limits the count of every item stack. * - `looting_enchant`: Adjusts the stack size based on the level of the `Looting` enchantment on the `killer` entity. * - `set_attributes`: Add `attribute` modifiers to the item. * - `set_banner_patterns`: Set the banners' patterns. * - `set_contents`: For loot tables of type 'block', sets the contents of a container block item to a list of entries. * - `set_count`: Sets the stack size. * - `set_damage`: Sets the item's damage value (durability) for tools. * - `set_enchantments`: Add `enchantments` to the item. * - `set_loot_table`: Sets the loot table for a container (chest etc.). * - `set_lore`: Adds lore to the item * - `set_name`: Adds display name of the item. * - `set_nbt`: Adds NBT data to the item. * - `set_stew_effect`: Sets the status effects for `suspicious stew`. */ function: TYPE } & VALUES type ATTRIBUTE_SLOTS = 'mainhand' | 'offhand' | 'feet' | 'legs' | 'chest' | 'head' export type ItemModifierFunction = { /** Determines conditions for this function to be applied. If multiple conditions are specified, all must pass. */ conditions?: PredicateCondition[] } & ( ItemModifierKind<'apply_bonus', { /** Enchantment ID used for level calculation. */ enchantment: LiteralUnion<ENCHANTMENTS> } & ({ /** * A special function used for ore drops in the vanilla game (`Count * (max(0; random(0..Level + 2) - 1)+1)`) */ formula: 'ore_drops' } | { /** * A binomial distribution (with `n=level + extra`, `p=probability`), * - `uniform_bonus_count` for uniform distribution (from `0` to `level * bonusMultiplier`) */ formula: 'binomial_with_bonus_count' /** Values required for the formula (except ore_drops). */ parameters: { /** For formula `binomial_with_bonus_count`, the extra value. */ extra: number /** For formula `binomial_with_bonus_count`, the probability. */ probability: number } } | { /** * Can be: * - `binomial_with_bonus_count` for a binomial distribution (with `n=level + extra`, `p=probability`), * - `uniform_bonus_count` for uniform distribution (from `0` to `level * bonusMultiplier`) */ formula: 'uniform_bonus_count' /** Values required for the formula (except ore_drops). */ parameters: { /** For formula `uniform_bonus_count`, the bonus multiplier. */ bonusMultiplier: number } })> | ItemModifierKind<'copy_name', { /** * Specifies the source. Must be one of: * - `block_entity` for the block entity of the destroyed block * - `this` to use the entity that died or the player that gained the loot table * - `opened` the container or broke the block, * - `killer` for the killer, * - `killer_player` for a killer that is a player. */ source: 'block_entity' | 'this' | 'killer' | 'killer_player' }> | ItemModifierKind<'copy_nbt', { // TODO: update docs /** * Specifies the source. Must be one of: * - `block_entity` for the block entity of the destroyed block * - `this` to use the entity that died or the player that gained the loot table * - `opened` the container or broke the block, * - `killer` for the killer, * - `killer_player` for a killer that is a player. */ source: 'block_entity' | 'this' | 'killer' | 'killer_player' | { type: 'minecraft:context' target: 'block_entity' | 'this' | 'killer' | 'killer_player' } | { type: 'minecraft:storage' source: string | DataInstance<'storage'> } /** A list of operations. */ ops: { /** The nbt path to copy from. */ source: string /** The nbt path to copy to, starting from the item's tag tag. */ target: string /** Can be `replace` to replace any existing contents of the target, `append` to append to a list, or `merge` to merge into a compound tag. */ op: 'replace' | 'append' | 'merge' }[] }> | ItemModifierKind<'copy_state', { /** A block ID. Function fails if the block doesn't match. */ block?: LiteralUnion<BLOCKS> /** A list of property names to copy. */ properties: string[] }> | ItemModifierKind<'enchant_randomly', { /** List of enchantment IDs to choose from. If omitted, all enchantments applicable to the item are possible. */ enchantments: LiteralUnion<ENCHANTMENTS>[] }> | ItemModifierKind<'enchant_with_levels', { /** Determines whether treasure enchantments are allowed on this item. */ treasure?: boolean /** Specifies a random enchantment level, as an exact number or a range. */ levels: NumberProvider }> | ItemModifierKind<'exploration_map', { /** The type of generated structure to locate. Accepts any of the StructureTypes used by the `/locate` command (case insensitive). */ destination: LiteralUnion<STRUCTURES> /** * The icon used to mark the destination on the map. Accepts any of the map icon text IDs (case insensitive). * If `mansion` or `monument` is used, the color of the lines on the item texture changes to match the corresponding explorer map. */ decoration?: LiteralUnion<MAP_ICONS> /** The zoom level of the resulting map. Defaults to 2. */ zoom?: number /** * The size, in chunks, of the area to search for structures. * The area checked is square, not circular. * Radius `0` causes only the current chunk to be searched, * radius `1` causes the current chunk and eight adjacent chunks to be searched, and so on. * Defaults to `50`. */ search_radius?: number /** Don't search in chunks that have already been generated. Defaults to `true`. */ skip_existing_chunks?: boolean }> | ItemModifierKind<'explosion_decay', { // No properties }> | ItemModifierKind<'furnace_smelt', { // No properties }> | ItemModifierKind<'fill_player_head', { /** * Specifies an entity to be used for the player head. Set to: * - `this` to use the entity that died or the player that gained the advancement, * opened the container or broke the block * - `killer` for the killer * - `killer_player` for a killer that is a player. */ entity: 'this' | 'killer' | 'killer_player' }> | ItemModifierKind<'limit_count', { /** Specify the count limit of every item stack. */ limit: number | { min?: NumberProvider max?: NumberProvider } }> | ItemModifierKind<'looting_enchant', { /** * If a number is given, it specifies an exact number * of additional items per level of looting. * * If a range is given, it specifies a random number * (within a range) of additional items per level of looting. * Note the random number generated may be fractional, rounded after multiplying by the looting level. * */ count?: NumberProvider /** * Specifies the maximum amount of items in the stack after the looting calculation. * If the value is `0`, no limit is applied. */ limit?: number }> | ItemModifierKind<'set_attributes', { /** The modifiers to apply to the item. */ modifiers: { name: string attribute: LiteralUnion<ATTRIBUTES> operation: 'addition' | 'multiply_base' | 'multiply_total' amount: NumberProvider id?: string /** * Slots the item must be in for the modifier to take effect. * This value can be one of the following : `mainhand`, `offhand`, `feet`, `legs`, `chest`, or `head`. * * If a list is given, one of the listed slots will be chosen randomly. * */ slot?: ATTRIBUTE_SLOTS | ATTRIBUTE_SLOTS[] }[] }> | ItemModifierKind<'set_banner_pattern', { patterns: { pattern: string // TODO: add patterns type color: BASIC_COLORS }[] append?: boolean }> | ItemModifierKind<'set_contents', { /** For loot tables of type 'block', sets the contents of a container block item to a list of entries. */ entries: LootTableEntry[] }> | ItemModifierKind<'set_count', { /** Specifies the exact stack size to set, or a random stack size within a range. */ count: number | { /** * The distribution type. Must be: * - `uniform`: Uniform distribution. A random integer is chosen with probability of each number being equal. * - `binomial`: Binomial distribution. Roll a number of times, each having a chance of adding 1 to the stack size. */ type: 'uniform' /** Minimum stack size. */ min: number /** Maximum stack size. */ max: number } | { /** * The distribution type. Must be: * - `uniform`: Uniform distribution. A random integer is chosen with probability of each number being equal. * - `binomial`: Binomial distribution. Roll a number of times, each having a chance of adding 1 to the stack size. */ type: 'binomial' /** Number of rolls. */ n: number /** Chance of each roll. */ p: number } }> | ItemModifierKind<'set_damage', { /** * If a number is given, it specifies the damage fraction to set * (1.0 is undamaged, 0.0 is zero durability left). * * If a range is give, it specifies a random damage fraction within the given range. */ damage: NumberProvider add?: boolean }> | ItemModifierKind<'set_enchantments', { // TODO: add docs enchantments: { [K in ENCHANTMENTS]?: NumberProvider } add?: boolean }> | ItemModifierKind<'set_loot_table', { /** Specifies the resource location of the loot table to be used. */ name: string | LootTableInstance /** Optional. Specifies the loot table seed. If absent or set to 0, a random seed will be used. */ seed?: number }> | ItemModifierKind<'set_lore', { /** List of JSON text components. Each list entry represents one line of the lore. */ lore: JSONTextComponent[] /** * Specifies the entity to act as the source @s in the JSON text component. Set to: * - `this` to use the entity that died or the player that gained the advancement, opened the container or broke the block * - `killer` for the killer * - `killer_player` for a killer that is a player. */ entity?: 'this' | 'killer' | 'killer_player' | 'direct_killer' /** If true, replaces all existing lines of lore, if false appends the list. */ replace?: boolean }> | ItemModifierKind<'set_name', { /** A JSON text component name, allowing color, translations, etc. */ name: JSONTextComponent /** * Specifies the entity to act as the source @s in the JSON text component. Set to: * - `this` to use the entity that died or the player that gained the advancement, opened the container or broke the block * - `killer` for the killer * - `killer_player` for a killer that is a player. */ entity?: 'this' | 'killer' | 'killer_player' | 'direct_killer' }> | ItemModifierKind<'set_nbt', { /** * Tag string to add, similar to those used by commands. * Note that the first bracket is required, * and quotation marks need to be escaped using a backslash. */ tag: string }> | ItemModifierKind<'set_stew_effect', { /** The effects to apply. */ effects: { /** The effect ID. */ type: LiteralUnion<ENCHANTMENTS> /** The duration of the effect. */ duration: NumberProvider }[] }> ) export type ItemModifierJSON = ObjectOrArray<ItemModifierFunction>
the_stack
import NumberColumn from './NumberColumn'; import type { IEventListener } from '../internal'; import { SortByDefault, toolbar } from './annotations'; import Column, { dirty, dirtyCaches, dirtyHeader, dirtyValues, groupRendererChanged, labelChanged, metaDataChanged, rendererTypeChanged, summaryRendererChanged, visibilityChanged, widthChanged, } from './Column'; import type { addColumn, moveColumn, removeColumn } from './CompositeColumn'; import type CompositeColumn from './CompositeColumn'; import CompositeNumberColumn, { ICompositeNumberDesc } from './CompositeNumberColumn'; import type { IDataRow, ITypeFactory } from './interfaces'; import { isDummyNumberFilter, noNumberFilter, restoreNumberFilter } from './internalNumber'; import { IColorMappingFunction, IMapAbleColumn, IMapAbleDesc, IMappingFunction, INumberFilter, isNumberColumn, } from './INumberColumn'; import { restoreMapping } from './MappingFunction'; import { integrateDefaults } from './internal'; const DEFAULT_SCRIPT = `let s = 0; col.forEach((c) => s += c.v); return s / col.length`; /** * factory for creating a description creating a mean column * @param label * @returns {{type: string, label: string}} */ export function createScriptDesc(label = 'script') { return { type: 'script', label, script: DEFAULT_SCRIPT }; } function wrapWithContext(code: string) { let clean = code.trim(); if (!clean.includes('return')) { clean = `return (${clean});`; } return ` const max = function(arr) { return Math.max.apply(Math, arr); }; const min = function(arr) { return Math.min.apply(Math, arr); }; const extent = function(arr) { return [min(arr), max(arr)]; }; const clamp = function(v, minValue, maxValue) { return v < minValue ? minValue : (v > maxValue ? maxValue : v); }; const normalize = function(v, minMax, max) { if (Array.isArray(minMax)) { minMax = minMax[0]; max = minMax[1]; } return (v - minMax) / (max - minMax); }; const denormalize = function(v, minMax, max) { if (Array.isArray(minMax)) { minMax = minMax[0]; max = minMax[1]; } return v * (max - minMax) + minMax; }; const linear = function(v, source, target) { target = target || [0, 1]; return denormalize(normalize(v, source), target); }; const v = (function custom() { ${clean} })(); return typeof v === 'number' ? v : NaN`; } interface IColumnWrapper { v: any; raw: number | null; type: string; name: string; id: string; } /** * wrapper class for simpler column accessing */ class ColumnWrapper implements IColumnWrapper { constructor(private readonly c: Column, public readonly v: any, public readonly raw: number | null) {} get type() { return this.c.desc.type; } get name() { return this.c.getMetaData().label; } get id() { return this.c.id; } } class LazyColumnWrapper implements IColumnWrapper { constructor(private readonly c: Column, private readonly row: IDataRow) {} get type() { return this.c.desc.type; } get name() { return this.c.getMetaData().label; } get id() { return this.c.id; } get v() { return this.c.getValue(this.row); } get raw() { return isNumberColumn(this.c) ? this.c.getRawNumber(this.row) : null; } } /** * helper context for accessing columns within a scripted columns */ class ColumnContext { private readonly lookup = new Map<string, IColumnWrapper>(); private _all: ColumnContext | null = null; constructor(private readonly children: IColumnWrapper[], private readonly allFactory?: () => ColumnContext) { children.forEach((c) => { this.lookup.set(`ID@${c.id}`, c); this.lookup.set(`ID@${c.id.toLowerCase()}`, c); this.lookup.set(`NAME@${c.name}`, c); this.lookup.set(`NAME@${c.name.toLowerCase()}`, c); }); } /** * get a column by name * @param {string} name * @return {IColumnWrapper} */ byName(name: string) { return this.lookup.get(`NAME@${name}`); } /** * get a column by id * @param {string} id * @return {IColumnWrapper} */ byID(id: string) { return this.lookup.get(`ID@${id}`); } /** * get a column by index * @param {number} index * @return {IColumnWrapper} */ byIndex(index: number) { return this.children[index]; } forEach(callback: (c: IColumnWrapper, index: number) => void) { return this.children.forEach(callback); } /** * number of columns * @return {number} */ get length() { return this.children.length; } /** * get the all context, i.e one with all columns of this ranking * @return {ColumnContext} */ get all() { if (this._all == null) { this._all = this.allFactory ? this.allFactory() : null; } return this._all!; } } export interface IScriptDesc extends ICompositeNumberDesc, IMapAbleDesc { /** * the function to use, it has two parameters: children (current children) and values (their row values) * @default 'return Math.max.apply(Math,values)' */ script?: string; } export declare type IScriptColumnDesc = IScriptDesc; /** * emitted when the script property changes * @asMemberOf ScriptColumn * @event */ export declare function scriptChanged(previous: string, current: string): void; /** * emitted when the mapping property changes * @asMemberOf ScriptColumn * @event */ export declare function mappingChanged(previous: IMappingFunction, current: IMappingFunction): void; /** * emitted when the color mapping property changes * @asMemberOf ScriptColumn * @event */ export declare function colorMappingChanged(previous: IColorMappingFunction, current: IColorMappingFunction): void; /** * emitted when the filter property changes * @asMemberOf ScriptColumn * @event */ export declare function filterChanged(previous: INumberFilter | null, current: INumberFilter | null): void; /** * column combiner which uses a custom JavaScript function to combined the values * The script itself can be any valid JavaScript code. It will be embedded in a function. * Therefore the last statement has to return a value. * * In case of a single line statement the code piece statement <code>return</code> will be automatically prefixed. * * The function signature is: <br><code>(row: any, index: number, children: Column[], values: any[], raws: (number|null)[]) => number</code> * <dl> * <dt>param: <code>row</code></dt> * <dd>the row in the dataset to compute the value for</dd> * <dt>param: <code>index</code></dt> * <dd>the index of the row</dd> * <dt>param: <code>children</code></dt> * <dd>the list of LineUp columns that are part of this ScriptColumn</dd> * <dt>param: <code>values</code></dt> * <dd>the computed value of each column (see <code>children</code>) for the current row</dd> * <dt>param: <code>raws</code></dt> * <dd>similar to <code>values</code>. Numeric columns return by default the normalized value, this array gives access to the original "raw" values before mapping is applied</dd> * <dt>returns:</dt> * <dd>the computed number <strong>in the range [0, 1] or NaN</strong></dd> * </dl> * * In addition to the standard JavaScript functions and objects (Math, ...) a couple of utility functions are available: </p> * <dl> * <dt><code>max(arr: number[]) => number</code></dt> * <dd>computes the maximum of the given array of numbers</dd> * <dt><code>min(arr: number[]) => number</code></dt> * <dd>computes the minimum of the given array of numbers</dd> * <dt><code>extent(arr: number[]) => [number, number]</code></dt> * <dd>computes both minimum and maximum and returning an array with the first element the minimum and the second the maximum</dd> * <dt><code>clamp(v: number, min: number, max: number) => number</code></dt> * <dd>ensures that the given value is within the given min/max value</dd> * <dt><code>normalize(v: number, min: number, max: number) => number</code></dt> * <dd>normalizes the given value <code>(v - min) / (max - min)</code></dd> * <dt><code>denormalize(v: number, min: number, max: number) => number</code></dt> * <dd>inverts a normalized value <code>v * (max - min) + min</code></dd> * <dt><code>linear(v: number, input: [number, number], output: [number, number]) => number</code></dt> * <dd>performs a linear mapping from input domain to output domain both given as an array of [min, max] values. <code>denormalize(normalize(v, input[0], input[1]), output[0], output[1])</code></dd> * </dl> */ @toolbar('script', 'filterNumber', 'colorMapped', 'editMapping') @SortByDefault('descending') export default class ScriptColumn extends CompositeNumberColumn implements IMapAbleColumn { static readonly EVENT_MAPPING_CHANGED = NumberColumn.EVENT_MAPPING_CHANGED; static readonly EVENT_COLOR_MAPPING_CHANGED = NumberColumn.EVENT_COLOR_MAPPING_CHANGED; static readonly EVENT_SCRIPT_CHANGED = 'scriptChanged'; static readonly DEFAULT_SCRIPT = DEFAULT_SCRIPT; private script = ScriptColumn.DEFAULT_SCRIPT; private f: (children, values: number[], raws: any[], col: ColumnContext, row: any, index: number) => number | null = null; private mapping: IMappingFunction; private original: IMappingFunction; private colorMapping: IColorMappingFunction; /** * currently active filter * @type {{min: number, max: number}} * @private */ private currentFilter: INumberFilter = noNumberFilter(); constructor(id: string, desc: Readonly<IScriptColumnDesc>, factory: ITypeFactory) { super( id, integrateDefaults(desc, { renderer: 'number', groupRenderer: 'boxplot', summaryRenderer: 'histogram', }) ); this.script = desc.script || this.script; this.mapping = restoreMapping(desc, factory); this.original = this.mapping.clone(); this.colorMapping = factory.colorMappingFunction(desc.colorMapping || desc.color); } protected createEventList() { return super .createEventList() .concat([ ScriptColumn.EVENT_SCRIPT_CHANGED, ScriptColumn.EVENT_COLOR_MAPPING_CHANGED, ScriptColumn.EVENT_MAPPING_CHANGED, ]); } on(type: typeof ScriptColumn.EVENT_COLOR_MAPPING_CHANGED, listener: typeof colorMappingChanged | null): this; on(type: typeof ScriptColumn.EVENT_MAPPING_CHANGED, listener: typeof mappingChanged | null): this; on(type: typeof ScriptColumn.EVENT_FILTER_CHANGED, listener: typeof filterChanged | null): this; on(type: typeof ScriptColumn.EVENT_SCRIPT_CHANGED, listener: typeof scriptChanged | null): this; on(type: typeof CompositeColumn.EVENT_FILTER_CHANGED, listener: typeof filterChanged | null): this; on(type: typeof CompositeColumn.EVENT_ADD_COLUMN, listener: typeof addColumn | null): this; on(type: typeof CompositeColumn.EVENT_MOVE_COLUMN, listener: typeof moveColumn | null): this; on(type: typeof CompositeColumn.EVENT_REMOVE_COLUMN, listener: typeof removeColumn | null): this; on(type: typeof Column.EVENT_WIDTH_CHANGED, listener: typeof widthChanged | null): this; on(type: typeof Column.EVENT_LABEL_CHANGED, listener: typeof labelChanged | null): this; on(type: typeof Column.EVENT_METADATA_CHANGED, listener: typeof metaDataChanged | null): this; on(type: typeof Column.EVENT_DIRTY, listener: typeof dirty | null): this; on(type: typeof Column.EVENT_DIRTY_HEADER, listener: typeof dirtyHeader | null): this; on(type: typeof Column.EVENT_DIRTY_VALUES, listener: typeof dirtyValues | null): this; on(type: typeof Column.EVENT_DIRTY_CACHES, listener: typeof dirtyCaches | null): this; on(type: typeof Column.EVENT_RENDERER_TYPE_CHANGED, listener: typeof rendererTypeChanged | null): this; on(type: typeof Column.EVENT_GROUP_RENDERER_TYPE_CHANGED, listener: typeof groupRendererChanged | null): this; on(type: typeof Column.EVENT_SUMMARY_RENDERER_TYPE_CHANGED, listener: typeof summaryRendererChanged | null): this; on(type: typeof Column.EVENT_VISIBILITY_CHANGED, listener: typeof visibilityChanged | null): this; on(type: string | string[], listener: IEventListener | null): this; // required for correct typings in *.d.ts on(type: string | string[], listener: IEventListener | null): this { return super.on(type, listener); } setScript(script: string) { if (this.script === script) { return; } this.f = null; this.fire( [ScriptColumn.EVENT_SCRIPT_CHANGED, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_CACHES, Column.EVENT_DIRTY], this.script, (this.script = script) ); } getScript() { return this.script; } dump(toDescRef: (desc: any) => any) { const r = super.dump(toDescRef); r.script = this.script; r.filter = !isDummyNumberFilter(this.currentFilter) ? this.currentFilter : null; r.map = this.mapping.toJSON(); r.colorMapping = this.colorMapping.toJSON(); return r; } restore(dump: any, factory: ITypeFactory) { super.restore(dump, factory); this.script = dump.script || this.script; if (dump.filter) { this.currentFilter = restoreNumberFilter(dump.filter); } if (dump.map || dump.domain) { this.mapping = restoreMapping(dump.map, factory); } if (dump.colorMapping) { this.colorMapping = factory.colorMappingFunction(dump.colorMapping); } } protected compute(row: IDataRow) { if (this.f == null) { // eslint-disable-next-line no-new-func this.f = new Function('children', 'values', 'raws', 'col', 'row', 'index', wrapWithContext(this.script)) as any; } const children = this._children; const values = this._children.map((d) => d.getValue(row)); const raws = this._children.map((d) => (isNumberColumn(d) ? d.getRawNumber(row) : null)) as number[]; const col = new ColumnContext( children.map((c, i) => new ColumnWrapper(c, values[i], raws[i])), () => { const cols = this.findMyRanker()!.flatColumns; // all except myself return new ColumnContext(cols.map((c) => new LazyColumnWrapper(c, row))); } ); return this.f.call(this, children, values, raws, col, row.v, row.i); } getExportValue(row: IDataRow, format: 'text' | 'json'): any { if (format === 'json') { return { value: this.getRawNumber(row), children: this.children.map((d) => d.getExportValue(row, format)), }; } return super.getExportValue(row, format); } getRange() { return this.mapping.getRange(this.getNumberFormat()); } getOriginalMapping() { return this.original.clone(); } getMapping() { return this.mapping.clone(); } setMapping(mapping: IMappingFunction) { if (this.mapping.eq(mapping)) { return; } this.fire( [ ScriptColumn.EVENT_MAPPING_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_CACHES, Column.EVENT_DIRTY, ], this.mapping.clone(), (this.mapping = mapping) ); } getColor(row: IDataRow) { return NumberColumn.prototype.getColor.call(this, row); } getColorMapping() { return this.colorMapping.clone(); } setColorMapping(mapping: IColorMappingFunction) { if (this.colorMapping.eq(mapping)) { return; } this.fire( [ ScriptColumn.EVENT_COLOR_MAPPING_CHANGED, Column.EVENT_DIRTY_HEADER, Column.EVENT_DIRTY_VALUES, Column.EVENT_DIRTY_CACHES, Column.EVENT_DIRTY, ], this.colorMapping.clone(), (this.colorMapping = mapping) ); } isFiltered() { return NumberColumn.prototype.isFiltered.call(this); } getFilter(): INumberFilter { return NumberColumn.prototype.getFilter.call(this); } setFilter(value: INumberFilter | null) { NumberColumn.prototype.setFilter.call(this, value); } filter(row: IDataRow) { return NumberColumn.prototype.filter.call(this, row); } clearFilter() { return NumberColumn.prototype.clearFilter.call(this); } }
the_stack
import { EventEmitter } from 'eventemitter3'; import * as Sentry from '@sentry/minimal'; import { config, Hosts } from '../config'; import { FilestackError } from './../filestack_error'; import { metadata, MetadataOptions, remove, retrieve, RetrieveOptions, download } from './api/file'; import { transform, TransformOptions } from './api/transform'; import { storeURL } from './api/store'; import * as Utils from './utils'; import { Upload, InputFile, UploadOptions, StoreUploadOptions, UploadTags } from './api/upload'; import { preview, PreviewOptions } from './api/preview'; import { CloudClient } from './api/cloud'; import { Prefetch, PrefetchResponse, PrefetchOptions } from './api/prefetch'; import { FsResponse } from './request/types'; import { StoreParams } from './filelink'; import { picker, PickerInstance, PickerOptions } from './picker'; /* istanbul ignore next */ Sentry.addBreadcrumb({ category: 'sdk', message: 'filestack-js-sdk scope' }); export interface Session { apikey: string; urls: Hosts; cname?: string; policy?: string; signature?: string; prefetch?: PrefetchResponse; } export interface Security { policy: string; signature: string; } export interface ClientOptions { [option: string]: any; /** * Security object with policy and signature keys. * Can be used to limit client capabilities and protect public URLs. * It is intended to be used with server-side policy and signature generation. * Read about [security policies](https://www.filestack.com/docs/concepts/security). */ security?: Security; /** * Domain to use for all URLs. __Requires the custom CNAME addon__. * If this is enabled then you must also set up your own OAuth applications * for each cloud source you wish to use in the picker. */ cname?: string; /** * Enable/disable caching of the cloud session token. Default is false. * This ensures that users will be remembered on your domain when calling the cloud API from the browser. * Please be aware that tokens stored in localStorage are accessible by other scripts on the same domain. */ sessionCache?: boolean; /** * Enable forwarding error logs to sentry * @default false */ forwardErrors?: boolean; } /** * The Filestack client, the entry point for all public methods. Encapsulates session information. * * ### Example * ```js * // ES module * import * as filestack from 'filestack-js'; * const client = filestack.init('apikey'); * ``` * * ```js * // UMD module in browser * <script src="https://static.filestackapi.com/filestack-js/3.x.x/filestack.min.js"></script> * const client = filestack.init('apikey'); * ``` */ export class Client extends EventEmitter { public session: Session; private cloud: CloudClient; private prefetchInstance: Prefetch; private forwardErrors: boolean = true; /** * Returns filestack utils * * @readonly * @memberof Client */ get utils() { return Utils; } constructor(apikey: string, private options?: ClientOptions) { super(); /* istanbul ignore if */ if (options && options.forwardErrors) { this.forwardErrors = options.forwardErrors; } if (!apikey || typeof apikey !== 'string' || apikey.length === 0) { throw new Error('An apikey is required to initialize the Filestack client'); } const { urls } = config; this.session = { apikey, urls }; if (options) { const { cname, security } = options; this.setSecurity(security); this.setCname(cname); } this.prefetchInstance = new Prefetch(this.session); this.cloud = new CloudClient(this.session, options); } /** * Make basic prefetch request to check permissions * * @param params */ prefetch(params: PrefetchOptions) { return this.prefetchInstance.getConfig(params); } /** * Set security object * * @param {Security} security * @memberof Client */ setSecurity(security: Security) { if (security && !(security.policy && security.signature)) { throw new FilestackError('Both policy and signature are required for client security'); } if (security && security.policy && security.signature) { this.session.policy = security.policy; this.session.signature = security.signature; } } /** * Set custom cname * * @param {string} cname * @returns * @memberof Client */ setCname(cname: string) { if (!cname || cname.length === 0) { return; } this.session.cname = cname; this.session.urls = Utils.resolveHost(this.session.urls, cname); } /** * Clear all current cloud sessions in the picker. * Optionally pass a cloud source name to only log out of that cloud source. * This essentially clears the OAuth authorization codes from the Filestack session. * @param name Optional cloud source name. */ logout(name?: string) { return this.cloud.logout(name); } /** * Retrieve detailed data of stored files. * * ### Example * * ```js * client * .metadata('DCL5K46FS3OIxb5iuKby') * .then((res) => { * console.log(res); * }) * .catch((err) => { * console.log(err); * })); * ``` * @see [File API - Metadata](https://www.filestack.com/docs/api/file#metadata). * @param handle Valid Filestack handle. * @param options Metadata fields to enable on response. * @param security Optional security override. */ metadata(handle: string, options?: MetadataOptions, security?: Security) { /* istanbul ignore next */ return metadata(this.session, handle, options, security); } /** * Construct a new picker instance. */ picker(options?: PickerOptions): PickerInstance { /* istanbul ignore next */ return picker(this, options); } /** * Used for viewing files via Filestack handles or storage aliases, __requires Document Viewer addon to your Filestack application__. * Opens document viewer in new window if id option is not provided. * * ### Example * * ```js * // <div id="preview"></div> * * client.preview('DCL5K46FS3OIxb5iuKby', { id: 'preview' }); * ``` * @param handle Valid Filestack handle. * @param options Preview options */ preview(handle: string, options?: PreviewOptions) { /* istanbul ignore next */ return preview(this.session, handle, options); } /** * Remove a file from storage and the Filestack system. * * __Requires a valid security policy and signature__. The policy and signature will be pulled from the client session, or it can be overridden with the security parameter. * * ### Example * * ```js * client * .remove('DCL5K46FS3OIxb5iuKby') * .then((res) => { * console.log(res); * }) * .catch((err) => { * console.log(err); * })); * ``` * @see [File API - Delete](https://www.filestack.com/docs/api/file#delete) * @param handle Valid Filestack handle. * @param security Optional security override. */ remove(handle: string, security?: Security): Promise<any> { /* istanbul ignore next */ return remove(this.session, handle, false, security); } /** * Remove a file **only** from the Filestack system. The file remains in storage. * * __Requires a valid security policy and signature__. The policy and signature will be pulled from the client session, or it can be overridden with the security parameter. * * ### Example * * ```js * client * .removeMetadata('DCL5K46FS3OIxb5iuKby') * .then((res) => { * console.log(res); * }) * .catch((err) => { * console.log(err); * })); * ``` * @see [File API - Delete](https://www.filestack.com/docs/api/file#delete) * @param handle Valid Filestack handle. * @param security Optional security override. */ removeMetadata(handle: string, security?: Security): Promise<any> { /* istanbul ignore next */ return remove(this.session, handle, true, security); } /** * Store a file from its URL. * * ### Example * * ```js * client * .storeURL('https://d1wtqaffaaj63z.cloudfront.net/images/NY_199_E_of_Hammertown_2014.jpg') * .then(res => console.log(res)); * ``` * @see [File API - Store](https://www.filestack.com/docs/api/file#store) * @param url Valid URL to a file. * @param options Configure file storage. * @param token Optional control token to call .cancel() * @param security Optional security override. * @param uploadTags Optional tags visible in webhooks. * @param headers Optional headers to send * @param workflowIds Optional workflowIds to send */ storeURL(url: string, storeParams?: StoreParams, token?: any, security?: Security, uploadTags?: UploadTags, headers?: {[key: string]: string}, workflowIds?: string[]): Promise<Object> { return storeURL({ session: this.session, url, storeParams, token, security, uploadTags, headers, workflowIds, }); } /** * Access files via their Filestack handles. * * If head option is provided - request headers are returned in promise * If metadata option is provided - metadata object is returned in promise * Otherwise file blob is returned * Metadata and head options cannot be mixed * * ### Example * * ```js * client.retrieve('fileHandle', { * metadata: true, * }).then((response) => { * console.log(response); * }).catch((err) => { * console.error(err); * }) * ``` * * @see [File API - Download](https://www.filestack.com/docs/api/file#download) * @deprecated use metadata or download methods instead * @param handle Valid file handle * @param options RetrieveOptions * @param security Optional security override. * @throws Error */ retrieve(handle: string, options?: RetrieveOptions, security?: Security): Promise<Object | Blob> { /* istanbul ignore next */ return retrieve(this.session, handle, options, security); } /** * Download file by handle * * * ### Browser Example * * ```js * client.download('fileHandle').then((response) => { * const img = new Image(); * img.src = URL.createObjectURL(res.data) * document.body.appendChild(img); * }).catch((err) => { * console.error(err); * }) * ``` * * @see [File API - Download](https://www.filestack.com/docs/api/file#download) * @param handle Valid file handle * @throws Error */ download(handle: string, security?: Security): Promise<FsResponse> { /* istanbul ignore next */ return download(this.session, handle, security); } /** * Interface to the Filestack [Processing API](https://www.filestack.com/docs/api/processing). * Convert a URL, handle, or storage alias to another URL which links to the transformed file. * You can optionally store the returned URL with client.storeURL. * * Transform params can be provided in camelCase or snakeCase style ie: partial_pixelate or partialPixelate * * ### Example * * ```js * const transformedUrl = client.transform(url, { * crop: { * dim: [x, y, width, height], * }, * vignette: { * blurmode: 'gaussian', * amount: 50, * }, * flip: true, * partial_pixelate: { * objects: [[10, 20, 200, 250], [275, 91, 500, 557]], * }, * }; * * // optionally store the new URL * client.storeURL(transformedUrl).then(res => console.log(res)); * ``` * @see [Filestack Processing API](https://www.filestack.com/docs/api/processing) * @param url Single or multiple valid URLs (http(s)://), file handles, or storage aliases (src://) to an image. * @param options Transformations are applied in the order specified by this object. * @param b64 Use new more safe format for generating transforms url (default=false) Note: If there will be any issues with url please test it with enabled b64 support * @returns A new URL that points to the transformed resource. */ transform(url: string | string[], options: TransformOptions, b64: boolean = false) { /* istanbul ignore next */ return transform(this.session, url, options, b64); } /** * Initiates a multi-part upload flow. Use this for Filestack CIN and FII uploads. * * In Node runtimes the file argument is treated as a file path. * Uploading from a Node buffer is not yet implemented. * * ### Example * * ```js * const token = {}; * const onRetry = (obj) => { * console.log(`Retrying ${obj.location} for ${obj.filename}. Attempt ${obj.attempt} of 10.`); * }; * * client.upload(file, { onRetry }, { filename: 'foobar.jpg' }, token) * .then(res => console.log(res)); * * client.upload({file, name}, { onRetry }, { filename: 'foobar.jpg' }, token) * .then(res => console.log(res)); * * token.pause(); // Pause flow * token.resume(); // Resume flow * token.cancel(); // Cancel flow (rejects) * ``` * @param {InputFile} file Must be a valid [File | Blob | Buffer | string] * @param uploadOptions Uploader options. * @param storeOptions Storage options. * @param token A control token that can be used to call cancel(), pause(), and resume(). * @param security Optional security policy and signature override. * * @returns {Promise} */ upload(file: InputFile, options?: UploadOptions, storeOptions?: StoreUploadOptions, token?: any, security?: Security) { let upload = new Upload(options, storeOptions); upload.setSession(this.session); if (token) { upload.setToken(token); } if (security) { upload.setSecurity(security); } upload.on('start', () => this.emit('upload.start')); /* istanbul ignore next */ upload.on('error', e => { if (this.forwardErrors) { Sentry.withScope(scope => { scope.setTag('filestack-apikey', this.session.apikey); scope.setTag('filestack-version', Utils.getVersion()); scope.setExtra('filestack-options', this.options); scope.setExtras({ uploadOptions: options, storeOptions, details: e.details }); e.message = `FS-${e.message}`; Sentry.captureException(e); }); } this.emit('upload.error', e); }); return upload.upload(file); } /** * Initiates a multi-part upload flow. Use this for Filestack CIN and FII uploads. * * In Node runtimes the file argument is treated as a file path. * Uploading from a Node buffer is not yet implemented. * * ### Example * * ```js * const token = {}; * const onRetry = (obj) => { * console.log(`Retrying ${obj.location} for ${obj.filename}. Attempt ${obj.attempt} of 10.`); * }; * * client.multiupload([file], { onRetry }, token) * .then(res => console.log(res)); * * client.multiupload([{file, name}], { onRetry }, token) * .then(res => console.log(res)); * * token.pause(); // Pause flow * token.resume(); // Resume flow * token.cancel(); // Cancel flow (rejects) * ``` * @param {InputFile[]} file Must be a valid [File | Blob | Buffer | string (base64)] * @param uploadOptions Upload options. * @param storeOptions Storage options. * @param token A control token that can be used to call cancel(), pause(), and resume(). * @param security Optional security policy and signature override. * * @returns {Promise} */ multiupload(file: InputFile[], options?: UploadOptions, storeOptions?: StoreUploadOptions, token?: any, security?: Security) { let upload = new Upload(options, storeOptions); upload.setSession(this.session); if (token) { upload.setToken(token); } if (security) { upload.setSecurity(security); } upload.on('start', () => this.emit('upload.start')); /* istanbul ignore next */ upload.on('error', e => { Sentry.withScope(scope => { scope.setTag('filestack-apikey', this.session.apikey); scope.setTag('filestack-version', Utils.getVersion()); scope.setExtra('filestack-options', this.options); scope.setExtras(e.details); scope.setExtras({ uploadOptions: options, storeOptions }); Sentry.captureException(e); }); this.emit('upload.error', e); }); return upload.multiupload(file); } }
the_stack
import {ColorArea} from '../'; import {XBlueYGreen as DefaultColorArea, XSaturationYBrightness, XSaturationYLightness} from '../stories/ColorArea.stories'; import {defaultTheme} from '@adobe/react-spectrum'; import {fireEvent, render} from '@testing-library/react'; import {installMouseEvent, installPointerEvent} from '@react-spectrum/test-utils'; import {parseColor} from '@react-stately/color'; import {Provider} from '@react-spectrum/provider'; import React from 'react'; import userEvent from '@testing-library/user-event'; const SIZE = 160; const CENTER = SIZE / 2; const THUMB_RADIUS = 68; const getBoundingClientRect = () => ({ width: SIZE, height: SIZE, x: 0, y: 0, top: 0, left: 0, bottom: SIZE, right: SIZE, toJSON() { return this; } }); describe('ColorArea', () => { let onChangeSpy = jest.fn(); let onChangeEndSpy = jest.fn(); beforeAll(() => { jest.spyOn(window.HTMLElement.prototype, 'offsetWidth', 'get').mockImplementation(() => SIZE); // @ts-ignore jest.useFakeTimers('modern'); }); afterAll(() => { // @ts-ignore jest.useRealTimers(); }); afterEach(() => { // for restoreTextSelection jest.runAllTimers(); onChangeSpy.mockClear(); onChangeEndSpy.mockClear(); }); // get group corresponds to the index returned by getAllByRole('group') describe.each` Name | Component | groupIndex ${'Controlled'} | ${DefaultColorArea} | ${1} ${'Uncontrolled'} | ${ColorArea} | ${0} `('$Name', ({Component, groupIndex}) => { describe('attributes', () => { it('sets input props', () => { let {getAllByRole} = render(<Component defaultValue={'#ff00ff'} />); let [xSlider, ySlider] = getAllByRole('slider', {hidden: true}); expect(xSlider).toHaveAttribute('type', 'range'); expect(xSlider).toHaveAttribute('aria-label', 'Color picker'); expect(xSlider).toHaveAttribute('min', '0'); expect(xSlider).toHaveAttribute('max', '255'); expect(xSlider).toHaveAttribute('step', '1'); expect(xSlider).toHaveAttribute('aria-valuetext', 'Red: 255, Green: 0'); expect(xSlider).not.toHaveAttribute('tabindex', '0'); expect(ySlider).toHaveAttribute('type', 'range'); expect(ySlider).toHaveAttribute('aria-label', 'Color picker'); expect(ySlider).toHaveAttribute('min', '0'); expect(ySlider).toHaveAttribute('max', '255'); expect(ySlider).toHaveAttribute('step', '1'); expect(ySlider).toHaveAttribute('aria-valuetext', 'Green: 0, Red: 255'); expect(ySlider).toHaveAttribute('tabindex', '-1'); expect(ySlider).toHaveAttribute('aria-hidden', 'true'); }); it('disabled', () => { let {getAllByRole} = render(<div> <button>A</button> <Component defaultValue={'#ff00ff'} isDisabled /> <button>B</button> </div>); let [xSlider, ySlider] = getAllByRole('slider', {hidden: true}); let [buttonA, buttonB] = getAllByRole('button'); expect(xSlider).toHaveAttribute('disabled'); expect(ySlider).toHaveAttribute('disabled'); userEvent.tab(); expect(document.activeElement).toBe(buttonA); userEvent.tab(); expect(document.activeElement).toBe(buttonB); userEvent.tab({shift: true}); expect(document.activeElement).toBe(buttonA); }); describe('labelling', () => { it('should support a custom aria-label', () => { let {getAllByRole} = render(<Component defaultValue={'#ff00ff'} aria-label="Color hue" />); let [xSlider, ySlider] = getAllByRole('slider', {hidden: true}); expect(xSlider).toHaveAttribute('aria-label', 'Color hue, Color picker'); expect(ySlider).toHaveAttribute('aria-label', 'Color hue, Color picker'); expect(xSlider).not.toHaveAttribute('aria-labelledby'); expect(ySlider).not.toHaveAttribute('aria-labelledby'); }); it('should support a custom aria-labelledby', () => { let {getAllByRole} = render(<Component defaultValue={'#ff00ff'} aria-labelledby="label-id" />); let [xSlider, ySlider] = getAllByRole('slider', {hidden: true}); expect(xSlider).toHaveAttribute('aria-label', 'Color picker'); expect(ySlider).toHaveAttribute('aria-label', 'Color picker'); expect(xSlider).toHaveAttribute('aria-labelledby', `label-id ${xSlider.id}`); expect(ySlider).toHaveAttribute('aria-labelledby', `label-id ${ySlider.id}`); }); }); }); describe('behaviors', () => { let pressKey = (element, options) => { fireEvent.keyDown(element, options); fireEvent.keyUp(element, options); }; describe('keyboard events', () => { it.each` Name | props | actions | result ${'left/right'} | ${{defaultValue: parseColor('#ff00ff')}} | ${{forward: (elem) => pressKey(elem, {key: 'ArrowLeft'}), backward: (elem) => pressKey(elem, {key: 'ArrowRight'})}} | ${parseColor('#fe00ff')} ${'up/down'} | ${{defaultValue: parseColor('#ff00ff')}} | ${{forward: (elem) => pressKey(elem, {key: 'ArrowUp'}), backward: (elem) => pressKey(elem, {key: 'ArrowDown'})}} | ${parseColor('#ff01ff')} ${'shiftleft/shiftright'} | ${{defaultValue: parseColor('#f000f0')}} | ${{forward: (elem) => pressKey(elem, {key: 'ArrowLeft', shiftKey: true}), backward: (elem) => pressKey(elem, {key: 'ArrowRight', shiftKey: true})}} | ${parseColor('#df00f0')} ${'shiftup/shiftdown'} | ${{defaultValue: parseColor('#f000f0')}} | ${{forward: (elem) => pressKey(elem, {key: 'ArrowUp', shiftKey: true}), backward: (elem) => pressKey(elem, {key: 'ArrowDown', shiftKey: true})}} | ${parseColor('#f011f0')} ${'pageup/pagedown'} | ${{defaultValue: parseColor('#f000f0')}} | ${{forward: (elem) => pressKey(elem, {key: 'PageUp'}), backward: (elem) => pressKey(elem, {key: 'PageDown'})}} | ${parseColor('#f011f0')} ${'home/end'} | ${{defaultValue: parseColor('#f000f0')}} | ${{forward: (elem) => pressKey(elem, {key: 'Home'}), backward: (elem) => pressKey(elem, {key: 'End'})}} | ${parseColor('#df00f0')} `('$Name', ({props, actions: {forward, backward}, result}) => { let {getAllByRole} = render( <Component {...props} onChange={onChangeSpy} onChangeEnd={onChangeEndSpy} /> ); let [xSlider, ySlider] = getAllByRole('slider', {hidden: true}); expect(xSlider.getAttribute('aria-valuetext')).toBe([ `${props.defaultValue.getChannelName('red', 'en-US')}: ${props.defaultValue.formatChannelValue('red', 'en-US')}`, `${props.defaultValue.getChannelName('green', 'en-US')}: ${props.defaultValue.formatChannelValue('green', 'en-US')}` ].join(', ')); expect(ySlider.getAttribute('aria-valuetext')).toBe([ `${props.defaultValue.getChannelName('green', 'en-US')}: ${props.defaultValue.formatChannelValue('green', 'en-US')}`, `${props.defaultValue.getChannelName('red', 'en-US')}: ${props.defaultValue.formatChannelValue('red', 'en-US')}` ].join(', ')); expect(xSlider).not.toHaveAttribute('tabindex'); expect(xSlider).not.toHaveAttribute('aria-hidden', 'true'); expect(ySlider).toHaveAttribute('tabindex', '-1'); expect(ySlider).toHaveAttribute('aria-hidden', 'true'); userEvent.tab(); forward(xSlider); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeSpy.mock.calls[0][0].toString('rgba')).toBe(result.toString('rgba')); expect(onChangeEndSpy).toHaveBeenCalledTimes(1); expect(onChangeEndSpy.mock.calls[0][0].toString('rgba')).toBe(result.toString('rgba')); expect(xSlider.getAttribute('aria-valuetext')).toBe(`${result.getChannelName('red', 'en-US')}: ${result.formatChannelValue('red', 'en-US')}`); expect(document.activeElement).not.toHaveAttribute('tabindex', '0'); expect(document.activeElement).not.toHaveAttribute('aria-hidden'); expect(document.activeElement === xSlider ? ySlider : xSlider).toHaveAttribute('tabindex', '-1'); expect(document.activeElement === xSlider ? ySlider : xSlider).not.toHaveAttribute('aria-hidden', 'true'); backward(ySlider); expect(onChangeSpy).toHaveBeenCalledTimes(2); expect(onChangeSpy.mock.calls[1][0].toString('rgba')).toBe(props.defaultValue.toString('rgba')); expect(onChangeEndSpy).toHaveBeenCalledTimes(2); expect(onChangeEndSpy.mock.calls[1][0].toString('rgba')).toBe(props.defaultValue.toString('rgba')); expect(ySlider.getAttribute('aria-valuetext')).toBe(`${props.defaultValue.getChannelName('green', 'en-US')}: ${props.defaultValue.formatChannelValue('green', 'en-US')}`); expect(document.activeElement).not.toHaveAttribute('tabindex', '0'); expect(document.activeElement).not.toHaveAttribute('aria-hidden'); expect(document.activeElement === xSlider ? ySlider : xSlider).toHaveAttribute('tabindex', '-1'); expect(document.activeElement === xSlider ? ySlider : xSlider).not.toHaveAttribute('aria-hidden', 'true'); }); it.each` Name | props | actions | result ${'left/right'} | ${{defaultValue: parseColor('#ff00ff')}} | ${{forward: (elem) => pressKey(elem, {key: 'ArrowRight'}), backward: (elem) => pressKey(elem, {key: 'ArrowLeft'})}} | ${parseColor('#fe00ff')} ${'up/down'} | ${{defaultValue: parseColor('#ff00ff')}} | ${{forward: (elem) => pressKey(elem, {key: 'ArrowUp'}), backward: (elem) => pressKey(elem, {key: 'ArrowDown'})}} | ${parseColor('#ff01ff')} ${'shiftleft/shiftright'} | ${{defaultValue: parseColor('#f000f0')}} | ${{forward: (elem) => pressKey(elem, {key: 'ArrowRight', shiftKey: true}), backward: (elem) => pressKey(elem, {key: 'ArrowLeft', shiftKey: true})}} | ${parseColor('#df00f0')} ${'shiftup/shiftdown'} | ${{defaultValue: parseColor('#f000f0')}} | ${{forward: (elem) => pressKey(elem, {key: 'ArrowUp', shiftKey: true}), backward: (elem) => pressKey(elem, {key: 'ArrowDown', shiftKey: true})}} | ${parseColor('#f011f0')} ${'pageup/pagedown'} | ${{defaultValue: parseColor('#f000f0')}} | ${{forward: (elem) => pressKey(elem, {key: 'PageUp'}), backward: (elem) => pressKey(elem, {key: 'PageDown'})}} | ${parseColor('#f011f0')} ${'home/end'} | ${{defaultValue: parseColor('#f000f0')}} | ${{forward: (elem) => pressKey(elem, {key: 'End'}), backward: (elem) => pressKey(elem, {key: 'Home'})}} | ${parseColor('#df00f0')} `('$Name RTL', ({props, actions: {forward, backward}, result}) => { let {getAllByRole} = render( <Provider locale="ar-AE" theme={defaultTheme}> <Component {...props} onChange={onChangeSpy} onChangeEnd={onChangeEndSpy} /> </Provider> ); let [xSlider, ySlider] = getAllByRole('slider', {hidden: true}); expect(xSlider.getAttribute('aria-valuetext')).toBe([ `${props.defaultValue.getChannelName('red', 'ar-AE')}: ${props.defaultValue.formatChannelValue('red', 'ar-AE')}`, `${props.defaultValue.getChannelName('green', 'ar-AE')}: ${props.defaultValue.formatChannelValue('green', 'ar-AE')}` ].join(', ')); expect(ySlider.getAttribute('aria-valuetext')).toBe([ `${props.defaultValue.getChannelName('green', 'ar-AE')}: ${props.defaultValue.formatChannelValue('green', 'ar-AE')}`, `${props.defaultValue.getChannelName('red', 'ar-AE')}: ${props.defaultValue.formatChannelValue('red', 'ar-AE')}` ].join(', ')); expect(xSlider).not.toHaveAttribute('tabindex'); expect(xSlider).not.toHaveAttribute('aria-hidden', 'true'); expect(ySlider).toHaveAttribute('tabindex', '-1'); expect(ySlider).toHaveAttribute('aria-hidden', 'true'); userEvent.tab(); forward(xSlider); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeSpy.mock.calls[0][0].toString('rgba')).toBe(result.toString('rgba')); expect(onChangeEndSpy).toHaveBeenCalledTimes(1); expect(onChangeEndSpy.mock.calls[0][0].toString('rgba')).toBe(result.toString('rgba')); expect(xSlider.getAttribute('aria-valuetext')).toBe(`${result.getChannelName('red', 'ar-AE')}: ${result.formatChannelValue('red', 'ar-AE')}`); expect(document.activeElement).not.toHaveAttribute('tabindex'); expect(document.activeElement).not.toHaveAttribute('aria-hidden'); expect(document.activeElement === xSlider ? ySlider : xSlider).toHaveAttribute('tabindex', '-1'); expect(document.activeElement === xSlider ? ySlider : xSlider).not.toHaveAttribute('aria-hidden', 'true'); backward(ySlider); expect(onChangeSpy).toHaveBeenCalledTimes(2); expect(onChangeSpy.mock.calls[1][0].toString('rgba')).toBe(props.defaultValue.toString('rgba')); expect(onChangeEndSpy).toHaveBeenCalledTimes(2); expect(onChangeEndSpy.mock.calls[1][0].toString('rgba')).toBe(props.defaultValue.toString('rgba')); expect(ySlider.getAttribute('aria-valuetext')).toBe(`${props.defaultValue.getChannelName('green', 'ar-AE')}: ${props.defaultValue.formatChannelValue('green', 'ar-AE')}`); expect(document.activeElement).not.toHaveAttribute('tabindex'); expect(document.activeElement).not.toHaveAttribute('aria-hidden'); expect(document.activeElement === xSlider ? ySlider : xSlider).toHaveAttribute('tabindex', '-1'); expect(document.activeElement === xSlider ? ySlider : xSlider).not.toHaveAttribute('aria-hidden', 'true'); }); it('no events when disabled', () => { let defaultColor = parseColor('#ff00ff'); let {getAllByRole, getByRole} = render(<div> <Component isDisabled defaultValue={defaultColor} onChange={onChangeSpy} onChangeEnd={onChangeEndSpy} /> <button>B</button> </div>); let buttonA = getByRole('button'); let [xSlider] = getAllByRole('slider'); userEvent.tab(); expect(buttonA).toBe(document.activeElement); pressKey(xSlider, {key: 'LeftArrow'}); expect(onChangeSpy).not.toHaveBeenCalled(); expect(onChangeEndSpy).not.toHaveBeenCalled(); pressKey(xSlider, {key: 'RightArrow'}); expect(onChangeSpy).not.toHaveBeenCalled(); expect(onChangeEndSpy).not.toHaveBeenCalled(); }); }); describe.each` type | prepare | actions ${'Mouse Events'} | ${installMouseEvent} | ${[ (el, {pageX, pageY}) => fireEvent.mouseDown(el, {button: 0, pageX, pageY, clientX: pageX, clientY: pageY}), (el, {pageX, pageY}) => fireEvent.mouseMove(el, {button: 0, pageX, pageY, clientX: pageX, clientY: pageY}), (el, {pageX, pageY}) => fireEvent.mouseUp(el, {button: 0, pageX, pageY, clientX: pageX, clientY: pageY}) ]} ${'Pointer Events'} | ${installPointerEvent}| ${[ (el, {pageX, pageY}) => fireEvent.pointerDown(el, {button: 0, pointerId: 1, pageX, pageY, clientX: pageX, clientY: pageY}), (el, {pageX, pageY}) => fireEvent.pointerMove(el, {button: 0, pointerId: 1, pageX, pageY, clientX: pageX, clientY: pageY}), (el, {pageX, pageY}) => fireEvent.pointerUp(el, {button: 0, pointerId: 1, pageX, pageY, clientX: pageX, clientY: pageY}) ]} ${'Touch Events'} | ${() => {}} | ${[ (el, {pageX, pageY}) => fireEvent.touchStart(el, {changedTouches: [{identifier: 1, pageX, pageY, clientX: pageX, clientY: pageY}]}), (el, {pageX, pageY}) => fireEvent.touchMove(el, {changedTouches: [{identifier: 1, pageX, pageY, clientX: pageX, clientY: pageY}]}), (el, {pageX, pageY}) => fireEvent.touchEnd(el, {changedTouches: [{identifier: 1, pageX, pageY, clientX: pageX, clientY: pageY}]}) ]} `('$type', ({actions: [start, move, end], prepare}) => { prepare(); it('clicking on the area chooses the color at that point', () => { let defaultColor = parseColor('#ff00ff'); let {getAllByRole} = render( <Component defaultValue={defaultColor} onChange={onChangeSpy} onChangeEnd={onChangeEndSpy} /> ); let [xSlider] = getAllByRole('slider'); let groups = getAllByRole('group'); let container = groups[groupIndex]; container.getBoundingClientRect = getBoundingClientRect; expect(document.activeElement).not.toBe(xSlider); start(container, {pageX: CENTER + THUMB_RADIUS, pageY: CENTER}); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeEndSpy).toHaveBeenCalledTimes(0); expect(onChangeSpy.mock.calls[0][0].toString('rgba')).toBe(parseColor('#EC80FF').toString('rgba')); expect(document.activeElement).toBe(xSlider); end(container, {pageX: CENTER + THUMB_RADIUS, pageY: CENTER}); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeEndSpy).toHaveBeenCalledTimes(1); expect(onChangeEndSpy.mock.calls[0][0].toString('rgba')).toBe(parseColor('#EC80FF').toString('rgba')); expect(document.activeElement).toBe(xSlider); }); it('dragging the thumb works', () => { let defaultColor = parseColor('#ff00ff'); let {getAllByRole} = render( <Component defaultValue={defaultColor} onChange={onChangeSpy} onChangeEnd={onChangeEndSpy} /> ); let [xSlider] = getAllByRole('slider'); let groups = getAllByRole('group'); let thumb = xSlider.parentElement; let container = groups[groupIndex]; container.getBoundingClientRect = getBoundingClientRect; expect(document.activeElement).not.toBe(xSlider); start(thumb, {pageX: CENTER + THUMB_RADIUS, pageY: CENTER}); expect(onChangeSpy).toHaveBeenCalledTimes(0); expect(onChangeEndSpy).toHaveBeenCalledTimes(0); expect(document.activeElement).toBe(xSlider); move(thumb, {pageX: CENTER, pageY: CENTER + THUMB_RADIUS}); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeSpy.mock.calls[0][0].toString('rgba')).toBe(parseColor('#9300FF').toString('rgba')); expect(onChangeEndSpy).toHaveBeenCalledTimes(0); expect(document.activeElement).toBe(xSlider); end(thumb, {pageX: CENTER, pageY: CENTER + THUMB_RADIUS}); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeEndSpy).toHaveBeenCalledTimes(1); expect(onChangeEndSpy.mock.calls[0][0].toString('rgba')).toBe(parseColor('#9300FF').toString('rgba')); expect(document.activeElement).toBe(xSlider); }); it('dragging the thumb doesn\'t works when disabled', () => { let defaultColor = parseColor('#ff00ff'); let {getAllByRole} = render( <Component isDisabled defaultValue={defaultColor} onChange={onChangeSpy} onChangeEnd={onChangeEndSpy} /> ); let [xSlider] = getAllByRole('slider'); let groups = getAllByRole('group'); let thumb = xSlider.parentElement; let container = groups[groupIndex]; container.getBoundingClientRect = getBoundingClientRect; expect(document.activeElement).not.toBe(xSlider); start(thumb, {pageX: CENTER + THUMB_RADIUS, pageY: CENTER}); expect(onChangeSpy).toHaveBeenCalledTimes(0); move(thumb, {pageX: CENTER, pageY: CENTER + THUMB_RADIUS}); expect(onChangeSpy).toHaveBeenCalledTimes(0); end(thumb, {pageX: CENTER, pageY: CENTER + THUMB_RADIUS}); expect(onChangeSpy).toHaveBeenCalledTimes(0); expect(onChangeEndSpy).toHaveBeenCalledTimes(0); }); it('clicking and dragging on the track works', () => { let defaultColor = parseColor('#ff00ff'); let {getAllByRole} = render( <Component defaultValue={defaultColor} onChange={onChangeSpy} onChangeEnd={onChangeEndSpy} /> ); let [xSlider] = getAllByRole('slider'); let groups = getAllByRole('group'); let container = groups[groupIndex]; container.getBoundingClientRect = getBoundingClientRect; expect(document.activeElement).not.toBe(xSlider); start(container, {pageX: CENTER + THUMB_RADIUS, pageY: CENTER}); expect(onChangeSpy).toHaveBeenCalledTimes(1); expect(onChangeEndSpy).toHaveBeenCalledTimes(0); expect(onChangeSpy.mock.calls[0][0].toString('rgba')).toBe(parseColor('#EC80FF').toString('rgba')); expect(document.activeElement).toBe(xSlider); move(container, {pageX: CENTER, pageY: CENTER + THUMB_RADIUS}); expect(onChangeSpy).toHaveBeenCalledTimes(2); expect(onChangeSpy.mock.calls[1][0].toString('rgba')).toBe(parseColor('#8014FF').toString('rgba')); expect(document.activeElement).toBe(xSlider); end(container, {pageX: CENTER, pageY: CENTER + THUMB_RADIUS}); expect(onChangeSpy).toHaveBeenCalledTimes(2); expect(onChangeEndSpy).toHaveBeenCalledTimes(1); expect(onChangeEndSpy.mock.calls[0][0].toString('rgba')).toBe(parseColor('#8014FF').toString('rgba')); expect(document.activeElement).toBe(xSlider); }); it('clicking and dragging on the track doesn\'t work when disabled', () => { let defaultColor = parseColor('#ff00ff'); let {getAllByRole} = render( <Component isDisabled defaultValue={defaultColor} onChange={onChangeSpy} onChangeEnd={onChangeEndSpy} /> ); let [xSlider] = getAllByRole('slider'); let groups = getAllByRole('group'); let container = groups[groupIndex]; container.getBoundingClientRect = getBoundingClientRect; expect(document.activeElement).not.toBe(xSlider); start(container, {pageX: CENTER, pageY: CENTER + THUMB_RADIUS}); expect(onChangeSpy).toHaveBeenCalledTimes(0); expect(document.activeElement).not.toBe(xSlider); move(container, {pageX: CENTER - THUMB_RADIUS, pageY: CENTER}); expect(onChangeSpy).toHaveBeenCalledTimes(0); expect(document.activeElement).not.toBe(xSlider); end(container, {pageX: CENTER - THUMB_RADIUS, pageY: CENTER}); expect(onChangeSpy).toHaveBeenCalledTimes(0); expect(document.activeElement).not.toBe(xSlider); }); }); }); }); describe('defaults uncontrolled', () => { let pressKey = (element, options) => { fireEvent.keyDown(element, options); fireEvent.keyUp(element, options); }; it('sets input props', () => { let {getAllByRole} = render(<ColorArea />); let [xSlider, ySlider] = getAllByRole('slider', {hidden: true}); expect(xSlider).toHaveAttribute('type', 'range'); expect(xSlider).toHaveAttribute('aria-label', 'Color picker'); expect(xSlider).toHaveAttribute('min', '0'); expect(xSlider).toHaveAttribute('max', '255'); expect(xSlider).toHaveAttribute('step', '1'); expect(xSlider).toHaveAttribute('aria-valuetext', 'Red: 255, Green: 255'); expect(xSlider).not.toHaveAttribute('tabindex'); expect(xSlider).not.toHaveAttribute('aria-hidden'); expect(ySlider).toHaveAttribute('type', 'range'); expect(ySlider).toHaveAttribute('aria-label', 'Color picker'); expect(ySlider).toHaveAttribute('min', '0'); expect(ySlider).toHaveAttribute('max', '255'); expect(ySlider).toHaveAttribute('step', '1'); expect(ySlider).toHaveAttribute('aria-valuetext', 'Green: 255, Red: 255'); expect(ySlider).toHaveAttribute('tabindex', '-1'); expect(ySlider).toHaveAttribute('aria-hidden', 'true'); }); it('the slider is focusable', () => { let {getAllByRole} = render(<div> <button>A</button> <ColorArea defaultValue={'#ff00ff'} /> <button>B</button> </div>); let [xSlider, ySlider] = getAllByRole('slider', {hidden: true}); let [buttonA, buttonB] = getAllByRole('button'); userEvent.tab(); expect(document.activeElement).toBe(buttonA); userEvent.tab(); expect(document.activeElement).toBe(xSlider); // focusing into ColorArea, value text for each slider will include name and value for each channel expect(xSlider).toHaveAttribute('aria-valuetext', 'Red: 255, Green: 0'); expect(ySlider).toHaveAttribute('aria-valuetext', 'Green: 0, Red: 255'); pressKey(xSlider, {key: 'ArrowLeft'}); // following a keyboard event that changes a value, value text for each slider will include only the name and value for that channel. expect(xSlider).toHaveAttribute('aria-valuetext', 'Red: 254'); expect(ySlider).toHaveAttribute('aria-valuetext', 'Green: 0'); userEvent.tab(); expect(document.activeElement).toBe(buttonB); // focusing out of ColorArea, value text for each slider will include name and value for each channel expect(xSlider).toHaveAttribute('aria-valuetext', 'Red: 254, Green: 0'); expect(ySlider).toHaveAttribute('aria-valuetext', 'Green: 0, Red: 254'); userEvent.tab({shift: true}); expect(document.activeElement).toBe(xSlider); // focusing back into ColorArea, value text for each slider will include name and value for each channel expect(xSlider).toHaveAttribute('aria-valuetext', 'Red: 254, Green: 0'); expect(ySlider).toHaveAttribute('aria-valuetext', 'Green: 0, Red: 254'); }); }); describe('full implementation controlled', () => { it('sets input props rgb', () => { let {getAllByRole, getByLabelText} = render(<DefaultColorArea {...DefaultColorArea.args} />); let sliders = getAllByRole('slider'); expect(sliders.length).toBe(2); let [xSlider, ySlider, zSlider] = getAllByRole('slider', {hidden: true}); expect(xSlider).toHaveAttribute('type', 'range'); expect(xSlider).toHaveAttribute('aria-label', 'Color picker'); expect(xSlider).toHaveAttribute('min', '0'); expect(xSlider).toHaveAttribute('max', '255'); expect(xSlider).toHaveAttribute('step', '1'); expect(xSlider).toHaveAttribute('aria-valuetext', 'Blue: 255, Green: 255'); expect(xSlider).not.toHaveAttribute('tabindex'); expect(xSlider).not.toHaveAttribute('aria-hidden'); expect(ySlider).toHaveAttribute('type', 'range'); expect(ySlider).toHaveAttribute('aria-label', 'Color picker'); expect(ySlider).toHaveAttribute('min', '0'); expect(ySlider).toHaveAttribute('max', '255'); expect(ySlider).toHaveAttribute('step', '1'); expect(ySlider).toHaveAttribute('aria-valuetext', 'Green: 255, Blue: 255'); expect(ySlider).toHaveAttribute('tabindex', '-1'); expect(ySlider).toHaveAttribute('aria-hidden', 'true'); let redSlider = getByLabelText('Red', {selector: 'input'}); expect(zSlider).toHaveAttribute('type', 'range'); expect(zSlider).not.toHaveAttribute('aria-label'); expect(zSlider).toBe(redSlider); expect(zSlider).toHaveAttribute('min', '0'); expect(zSlider).toHaveAttribute('max', '255'); expect(zSlider).toHaveAttribute('step', '1'); expect(zSlider).toHaveAttribute('aria-valuetext', '0'); }); it('sets input props hsb', () => { let {getAllByRole, getByLabelText} = render(<XSaturationYBrightness {...XSaturationYBrightness.args} />); let sliders = getAllByRole('slider'); expect(sliders.length).toBe(2); let [xSlider, ySlider, zSlider] = getAllByRole('slider', {hidden: true}); expect(xSlider).toHaveAttribute('type', 'range'); expect(xSlider).toHaveAttribute('aria-label', 'Color picker'); expect(xSlider).toHaveAttribute('min', '0'); expect(xSlider).toHaveAttribute('max', '100'); expect(xSlider).toHaveAttribute('step', '1'); expect(xSlider).toHaveAttribute('aria-valuetext', 'Saturation: 100%, Brightness: 100%'); expect(xSlider).not.toHaveAttribute('tabindex'); expect(xSlider).not.toHaveAttribute('aria-hidden'); expect(ySlider).toHaveAttribute('type', 'range'); expect(ySlider).toHaveAttribute('aria-label', 'Color picker'); expect(ySlider).toHaveAttribute('min', '0'); expect(ySlider).toHaveAttribute('max', '100'); expect(ySlider).toHaveAttribute('step', '1'); expect(ySlider).toHaveAttribute('aria-valuetext', 'Brightness: 100%, Saturation: 100%'); expect(ySlider).toHaveAttribute('tabindex', '-1'); expect(ySlider).toHaveAttribute('aria-hidden', 'true'); let hueSlider = getByLabelText('Hue', {selector: 'input'}); expect(zSlider).toHaveAttribute('type', 'range'); expect(zSlider).toHaveAttribute('aria-label', 'Hue'); expect(zSlider).toBe(hueSlider); expect(zSlider).toHaveAttribute('min', '0'); expect(zSlider).toHaveAttribute('max', '360'); expect(zSlider).toHaveAttribute('step', '1'); expect(zSlider).toHaveAttribute('aria-valuetext', '0°'); }); it('sets input props hsl', () => { let {getAllByRole, getByLabelText} = render(<XSaturationYLightness {...XSaturationYLightness.args} />); let sliders = getAllByRole('slider'); expect(sliders.length).toBe(2); let [xSlider, ySlider, zSlider] = getAllByRole('slider', {hidden: true}); expect(xSlider).toHaveAttribute('type', 'range'); expect(xSlider).toHaveAttribute('aria-label', 'Color picker'); expect(xSlider).toHaveAttribute('min', '0'); expect(xSlider).toHaveAttribute('max', '100'); expect(xSlider).toHaveAttribute('step', '1'); expect(xSlider).toHaveAttribute('aria-valuetext', 'Saturation: 100%, Lightness: 50%'); expect(xSlider).not.toHaveAttribute('tabindex'); expect(xSlider).not.toHaveAttribute('aria-hidden'); expect(ySlider).toHaveAttribute('type', 'range'); expect(ySlider).toHaveAttribute('aria-label', 'Color picker'); expect(ySlider).toHaveAttribute('min', '0'); expect(ySlider).toHaveAttribute('max', '100'); expect(ySlider).toHaveAttribute('step', '1'); expect(ySlider).toHaveAttribute('aria-valuetext', 'Lightness: 50%, Saturation: 100%'); expect(ySlider).toHaveAttribute('tabIndex', '-1'); expect(ySlider).toHaveAttribute('aria-hidden', 'true'); let hueSlider = getByLabelText('Hue', {selector: 'input'}); expect(zSlider).toHaveAttribute('type', 'range'); expect(zSlider).toHaveAttribute('aria-label', 'Hue'); expect(zSlider).toBe(hueSlider); expect(zSlider).toHaveAttribute('min', '0'); expect(zSlider).toHaveAttribute('max', '360'); expect(zSlider).toHaveAttribute('step', '1'); expect(zSlider).toHaveAttribute('aria-valuetext', '0°'); }); it('the slider is focusable', () => { let {getAllByRole, getByRole} = render(<div> <button>A</button> <DefaultColorArea defaultValue={'#ff00ff'} /> <button>B</button> </div>); let [xSlider, zSlider] = getAllByRole('slider'); let colorField = getByRole('textbox'); let [buttonA, buttonB] = getAllByRole('button'); userEvent.tab(); expect(document.activeElement).toBe(buttonA); userEvent.tab(); expect(document.activeElement).toBe(xSlider); userEvent.tab(); expect(document.activeElement).toBe(zSlider); userEvent.tab(); expect(document.activeElement).toBe(colorField); userEvent.tab(); expect(document.activeElement).toBe(buttonB); userEvent.tab({shift: true}); userEvent.tab({shift: true}); expect(document.activeElement).toBe(zSlider); }); }); });
the_stack
import { ACellTableSection, GridStyleManager, IAbortAblePromise, ICellRenderContext, IExceptionContext, isAbortAble, isAsyncUpdate, isLoadingCell, ITableSection, nonUniformContext, PrefetchMixin, tableIds, uniformContext, IAsyncUpdate, } from 'lineupengine'; import type { ILineUpFlags } from '../config'; import { HOVER_DELAY_SHOW_DETAIL } from '../constants'; import { AEventDispatcher, clear, debounce, IEventContext, IEventHandler, IEventListener, suffix } from '../internal'; import { Column, IGroupData, IGroupItem, IOrderedGroup, isGroup, isMultiLevelColumn, Ranking, StackColumn, IGroupParent, defaultGroup, IGroup, } from '../model'; import type { IImposer, IRenderCallback, IRenderContext } from '../renderer'; import { CANVAS_HEIGHT, COLUMN_PADDING, cssClass, engineCssClass } from '../styles'; import { lineupAnimation } from './animation'; import type { IRankingBodyContext, IRankingHeaderContextContainer } from './interfaces'; import MultiLevelRenderColumn from './MultiLevelRenderColumn'; import RenderColumn, { IRenderers } from './RenderColumn'; import SelectionManager from './SelectionManager'; import { groupRoots } from '../model/internal'; import { isAlwaysShowingGroupStrategy, toRowMeta } from '../provider/internal'; export interface IEngineRankingContext extends IRankingHeaderContextContainer, IRenderContext { createRenderer(c: Column, imposer?: IImposer): IRenderers; } export interface IEngineRankingOptions { animation: boolean; levelOfDetail: (rowIndex: number) => 'high' | 'low'; customRowUpdate: (row: HTMLElement, rowIndex: number) => void; flags: ILineUpFlags; } /** * emitted when the width of the ranking changed * @asMemberOf EngineRanking * @event */ export declare function widthChanged(): void; /** * emitted when the data of the ranking needs to be updated * @asMemberOf EngineRanking * @event */ export declare function updateData(): void; /** * emitted when the table has be recreated * @asMemberOf EngineRanking * @event */ export declare function recreate(): void; /** * emitted when the highlight changes * @asMemberOf EngineRanking * @param dataIndex the highlighted data index or -1 for none * @event */ export declare function highlightChanged(dataIndex: number): void; /** @internal */ class RankingEvents extends AEventDispatcher { static readonly EVENT_WIDTH_CHANGED = 'widthChanged'; static readonly EVENT_UPDATE_DATA = 'updateData'; static readonly EVENT_RECREATE = 'recreate'; static readonly EVENT_HIGHLIGHT_CHANGED = 'highlightChanged'; fire(type: string | string[], ...args: any[]) { super.fire(type, ...args); } protected createEventList() { return super .createEventList() .concat([ RankingEvents.EVENT_WIDTH_CHANGED, RankingEvents.EVENT_UPDATE_DATA, RankingEvents.EVENT_RECREATE, RankingEvents.EVENT_HIGHLIGHT_CHANGED, ]); } } const PASSIVE: AddEventListenerOptions = { passive: false, }; export default class EngineRanking extends ACellTableSection<RenderColumn> implements ITableSection, IEventHandler { static readonly EVENT_WIDTH_CHANGED = RankingEvents.EVENT_WIDTH_CHANGED; static readonly EVENT_UPDATE_DATA = RankingEvents.EVENT_UPDATE_DATA; static readonly EVENT_RECREATE = RankingEvents.EVENT_RECREATE; static readonly EVENT_HIGHLIGHT_CHANGED = RankingEvents.EVENT_HIGHLIGHT_CHANGED; private _context: ICellRenderContext<RenderColumn>; private readonly loadingCanvas = new WeakMap< HTMLCanvasElement, { col: number; render: IAbortAblePromise<IRenderCallback> }[] >(); private readonly renderCtx: IRankingBodyContext; private data: (IGroupItem | IGroupData)[] = []; private readonly selection: SelectionManager; private highlight = -1; private readonly canvasPool: HTMLCanvasElement[] = []; private currentCanvasShift = 0; private currentCanvasWidth = 0; private readonly events = new RankingEvents(); private roptions: Readonly<IEngineRankingOptions> = { animation: true, levelOfDetail: () => 'high', customRowUpdate: () => undefined, flags: { disableFrozenColumns: false, advancedModelFeatures: true, advancedRankingFeatures: true, advancedUIFeatures: true, }, }; private readonly delayedUpdate: (this: { type: string }) => void; private readonly delayedUpdateAll: () => void; private readonly delayedUpdateColumnWidths: () => void; private readonly columns: RenderColumn[]; private readonly canvasMouseHandler = { timer: new Set<number>(), hoveredRows: new Set<HTMLElement>(), cleanUp: () => { const c = this.canvasMouseHandler; c.timer.forEach((timer) => { clearTimeout(timer); }); c.timer.clear(); for (const row of Array.from(c.hoveredRows)) { c.unhover(row); } }, enter: (evt: MouseEvent) => { const c = this.canvasMouseHandler; c.cleanUp(); const row = evt.currentTarget as HTMLElement; row.addEventListener('mouseleave', c.leave, PASSIVE); c.timer.add( setTimeout(() => { c.hoveredRows.add(row); this.updateHoveredRow(row, true); }, HOVER_DELAY_SHOW_DETAIL) as unknown as number ); }, leave: (evt: MouseEvent | HTMLElement) => { // on row to survive canvas removal const c = this.canvasMouseHandler; const row = ( typeof (evt as MouseEvent).currentTarget !== 'undefined' ? (evt as MouseEvent).currentTarget : evt ) as HTMLElement; c.unhover(row); c.cleanUp(); }, unhover: (row: HTMLElement) => { // remove self const c = this.canvasMouseHandler; c.hoveredRows.delete(row); row.removeEventListener('mouseleave', c.leave); if (!EngineRanking.isCanvasRenderedRow(row) && row.parentElement) { // and part of dom setTimeout(() => this.updateHoveredRow(row, false)); } }, }; private readonly highlightHandler = { enabled: false, enter: (evt: MouseEvent) => { if (this.highlight >= 0) { const old = this.body.getElementsByClassName(engineCssClass('highlighted'))[0]; if (old) { old.classList.remove(engineCssClass('highlighted')); } this.highlight = -1; } const row = evt.currentTarget as HTMLElement; const dataIndex = Number.parseInt(row.dataset.i || '-1', 10); this.events.fire(EngineRanking.EVENT_HIGHLIGHT_CHANGED, dataIndex); }, leave: () => { if (this.highlight >= 0) { const old = this.body.getElementsByClassName(engineCssClass('highlighted'))[0]; if (old) { old.classList.remove(engineCssClass('highlighted')); } this.highlight = -1; } this.events.fire(EngineRanking.EVENT_HIGHLIGHT_CHANGED, -1); }, }; constructor( public readonly ranking: Ranking, header: HTMLElement, body: HTMLElement, tableId: string, style: GridStyleManager, private readonly ctx: IEngineRankingContext, roptions: Partial<IEngineRankingOptions> = {} ) { super(header, body, tableId, style, { mixins: [PrefetchMixin], batchSize: 20 }); Object.assign(this.roptions, roptions); body.dataset.ranking = ranking.id; // eslint-disable-next-line @typescript-eslint/no-this-alias const that = this; this.delayedUpdate = debounce( function (this: { type: string; primaryType: string }) { if (this.type !== Ranking.EVENT_DIRTY_VALUES) { that.events.fire(EngineRanking.EVENT_UPDATE_DATA); return; } if ( this.primaryType !== Column.EVENT_RENDERER_TYPE_CHANGED && this.primaryType !== Column.EVENT_GROUP_RENDERER_TYPE_CHANGED && this.primaryType !== Column.EVENT_LABEL_CHANGED ) { // just the single column will be updated that.updateBody(); } }, 50, (current, next) => { const currentEvent = current.self.type; // order changed is more important return currentEvent === Ranking.EVENT_ORDER_CHANGED ? current : next; } ); this.delayedUpdateAll = debounce(() => this.updateAll(), 50); this.delayedUpdateColumnWidths = debounce(() => this.updateColumnWidths(), 50); ranking.on(`${Ranking.EVENT_ADD_COLUMN}.hist`, (col: Column, index: number) => { // index doesn't consider the hidden columns const hiddenOffset = this.ranking.children.slice(0, index).reduce((acc, c) => acc + (!c.isVisible() ? 1 : 0), 0); const shiftedIndex = index - hiddenOffset; this.columns.splice(shiftedIndex, 0, this.createCol(col, shiftedIndex)); this.reindex(); this.delayedUpdateAll(); }); ranking.on(`${Ranking.EVENT_REMOVE_COLUMN}.body`, (col: Column, index: number) => { EngineRanking.disableListener(col); // index doesn't consider the hidden columns const hiddenOffset = this.ranking.children.slice(0, index).reduce((acc, c) => acc + (!c.isVisible() ? 1 : 0), 0); const shiftedIndex = index - hiddenOffset; this.columns.splice(shiftedIndex, 1); this.reindex(); this.delayedUpdateAll(); }); ranking.on(`${Ranking.EVENT_MOVE_COLUMN}.body`, (col: Column, index: number) => { //delete first const shiftedOld = this.columns.findIndex((d) => d.c === col); const c = this.columns.splice(shiftedOld, 1)[0]; // adapt target index based on previous index, i.e shift by one const hiddenOffset = this.ranking.children.slice(0, index).reduce((acc, c) => acc + (!c.isVisible() ? 1 : 0), 0); const shiftedIndex = index - hiddenOffset; this.columns.splice(shiftedOld < shiftedIndex ? shiftedIndex - 1 : shiftedIndex, 0, c); this.reindex(); this.delayedUpdateAll(); }); ranking.on( `${Ranking.EVENT_COLUMN_VISIBILITY_CHANGED}.body`, (col: Column, _oldValue: boolean, newValue: boolean) => { if (newValue) { // become visible const index = ranking.children.indexOf(col); const hiddenOffset = this.ranking.children .slice(0, index) .reduce((acc, c) => acc + (!c.isVisible() ? 1 : 0), 0); const shiftedIndex = index - hiddenOffset; this.columns.splice(shiftedIndex, 0, this.createCol(col, shiftedIndex)); } else { // hide const index = this.columns.findIndex((d) => d.c === col); EngineRanking.disableListener(col); this.columns.splice(index, 1); } this.reindex(); this.delayedUpdateAll(); } ); ranking.on(`${Ranking.EVENT_ORDER_CHANGED}.body`, this.delayedUpdate); this.selection = new SelectionManager(this.ctx, body); this.selection.on(SelectionManager.EVENT_SELECT_RANGE, (from: number, to: number, additional: boolean) => { this.selection.selectRange(this.data.slice(from, to + 1), additional); }); this.renderCtx = Object.assign( { isGroup: (index: number) => isGroup(this.data[index]), getRow: (index: number) => this.data[index] as IGroupItem, getGroup: (index: number) => this.data[index] as IGroupData, }, ctx ); // default context this.columns = ranking.children.filter((c) => c.isVisible()).map((c, i) => this.createCol(c, i)); this._context = Object.assign( { columns: this.columns, column: nonUniformContext( this.columns.map((w) => w.width), 100, COLUMN_PADDING ), }, uniformContext(0, 20) ); this.columns.forEach((column) => { if (column instanceof MultiLevelRenderColumn) { column.updateWidthRule(this.style); } column.renderers = this.ctx.createRenderer(column.c); }); this.style.updateRule( `hoverOnly${this.tableId}`, ` #${tableIds(this.tableId).tbody}:hover > .${engineCssClass('tr')}:hover .${cssClass('hover-only')}, #${tableIds(this.tableId).tbody} > .${engineCssClass('tr')}.${cssClass('selected')} .${cssClass('hover-only')}, #${tableIds(this.tableId).tbody} > .${engineCssClass('tr')}.${engineCssClass('highlighted')} .${cssClass( 'hover-only' )}`, { visibility: 'visible', } ); this.updateCanvasRule(); } on(type: typeof EngineRanking.EVENT_WIDTH_CHANGED, listener: typeof widthChanged | null): this; on(type: typeof EngineRanking.EVENT_UPDATE_DATA, listener: typeof updateData | null): this; on(type: typeof EngineRanking.EVENT_RECREATE, listener: typeof recreate | null): this; on(type: typeof EngineRanking.EVENT_HIGHLIGHT_CHANGED, listener: typeof highlightChanged | null): this; on(type: string | string[], listener: IEventListener | null): this; // required for correct typings in *.d.ts on(type: string | string[], listener: IEventListener | null): this { this.events.on(type, listener); return this; } get id() { return this.ranking.id; } protected onVisibilityChanged(visible: boolean) { super.onVisibilityChanged(visible); if (visible) { this.delayedUpdate.call({ type: Ranking.EVENT_ORDER_CHANGED }); } } updateHeaders() { this.updateColumnSummaryFlag(); return super.updateHeaders(); } get currentData() { return this.data; } get context(): ICellRenderContext<RenderColumn> { return this._context; } protected createHeader(_document: Document, column: RenderColumn): HTMLElement | IAsyncUpdate<HTMLElement> { return column.createHeader(); } private updateColumnSummaryFlag() { // updates the header flag depending on whether there are any sublabels this.header.classList.toggle( cssClass('show-sublabel'), this.columns.some((c) => c.hasSummaryLine()) ); } protected updateHeader(node: HTMLElement, column: RenderColumn) { if (column instanceof MultiLevelRenderColumn) { column.updateWidthRule(this.style); } return column.updateHeader(node); } protected createCell(_document: Document, index: number, column: RenderColumn) { return column.createCell(index); } private createCellHandled(col: RenderColumn, index: number) { const r = col.createCell(index); let item: HTMLElement; if (isAsyncUpdate(r)) { item = this.handleCellReady(r.item, r.ready, col.index); } else { item = r; } this.initCellClasses(item, col.id); return item; } protected updateCell(node: HTMLElement, index: number, column: RenderColumn) { return column.updateCell(node, index); } private selectCanvas() { if (this.canvasPool.length > 0) { return this.canvasPool.pop()!; } const c = this.body.ownerDocument!.createElement('canvas'); c.classList.add(cssClass(`low-c${this.tableId}`)); return c; } private rowFlags(row: HTMLElement) { const rowany: any = row; const v = rowany.__lu__; if (v == null) { return (rowany.__lu__ = {}); } return v; } private visibleRenderedWidth() { let width = 0; for (const col of this.visibleColumns.frozen) { width += this.columns[col].width + COLUMN_PADDING; } for (let col = this.visibleColumns.first; col <= this.visibleColumns.last; ++col) { width += this.columns[col].width + COLUMN_PADDING; } if (width > 0) { width -= COLUMN_PADDING; // for the last one } return width; } private pushLazyRedraw( canvas: HTMLCanvasElement, x: number, column: RenderColumn, render: IAbortAblePromise<IRenderCallback> ) { render.then((r) => { const l = this.loadingCanvas.get(canvas) || []; const pos = l.findIndex((d) => d.render === render && d.col === column.index); if (pos < 0) { // not part anymore ignore return; } l.splice(pos, 1); if (typeof r === 'function') { // i.e not aborted const ctx = canvas.getContext('2d')!; ctx.clearRect(x - 1, 0, column.width + 2, canvas.height); ctx.save(); ctx.translate(x, 0); r(ctx); ctx.restore(); } if (l.length > 0) { return; } this.loadingCanvas.delete(canvas); canvas.classList.remove(cssClass('loading-c')); }); if (!this.loadingCanvas.has(canvas)) { canvas.classList.add(cssClass('loading-c')); this.loadingCanvas.set(canvas, [{ col: column.index, render }]); } else { this.loadingCanvas.get(canvas)!.push({ col: column.index, render }); } } private renderRow(canvas: HTMLCanvasElement, node: HTMLElement, index: number) { if (this.loadingCanvas.has(canvas)) { for (const a of this.loadingCanvas.get(canvas)!) { a.render.abort(); } this.loadingCanvas.delete(canvas); } canvas.classList.remove(cssClass('loading-c')); canvas.width = this.currentCanvasWidth; canvas.height = CANVAS_HEIGHT; const ctx = canvas.getContext('2d')!; ctx.imageSmoothingEnabled = false; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.save(); const domColumns: RenderColumn[] = []; let x = 0; const renderCellImpl = (col: number) => { const c = this.columns[col]; const r = c.renderCell(ctx, index); if (r === true) { domColumns.push(c); } else if (r !== false && isAbortAble(r)) { this.pushLazyRedraw(canvas, x, c, r); } const shift = c.width + COLUMN_PADDING; x += shift; ctx.translate(shift, 0); }; for (const col of this.visibleColumns.frozen) { renderCellImpl(col); } for (let col = this.visibleColumns.first; col <= this.visibleColumns.last; ++col) { renderCellImpl(col); } ctx.restore(); const visibleElements = node.childElementCount - 1; // for canvas if (domColumns.length === 0) { while (node.lastElementChild !== node.firstElementChild) { const n = node.lastElementChild! as HTMLElement; node.removeChild(n); this.recycleCell(n); } return; } if (domColumns.length === 1) { const first = domColumns[0]; if (visibleElements === 0) { const item = this.createCellHandled(first, index); item.classList.add(cssClass('low')); node.appendChild(item); return; } const firstDOM = node.lastElementChild! as HTMLElement; if (visibleElements === 1 && firstDOM.dataset.colId === first.id) { const isLoading = isLoadingCell(firstDOM); if (isLoading) { const item = this.createCellHandled(first, index); node.replaceChild(item, firstDOM); this.recycleCell(firstDOM, first.index); return; } this.updateCellImpl(first, node.lastElementChild as HTMLElement, index); return; } } const existing = new Map((Array.from(node.children) as HTMLElement[]).slice(1).map((d) => [d.dataset.id, d])); for (const col of domColumns) { const elem = existing.get(col.id); if (elem && !isLoadingCell(elem)) { existing.delete(col.id); this.updateCellImpl(col, elem, index); } else { const c = this.createCellHandled(col, index); c.classList.add(cssClass('low')); node.appendChild(c); } } existing.forEach((v) => { v.remove(); this.recycleCell(v); }); } protected updateCanvasCell( canvas: HTMLCanvasElement, node: HTMLElement, index: number, column: RenderColumn, x: number ) { // delete lazy that would render the same thing if (this.loadingCanvas.has(canvas)) { const l = this.loadingCanvas.get(canvas)!; const me = l.filter((d) => d.col === column.index); if (me.length > 0) { this.loadingCanvas.set( canvas, l.filter((d) => d.col !== column.index) ); for (const a of me) { a.render.abort(); } } } const ctx = canvas.getContext('2d')!; ctx.clearRect(x - 1, 0, column.width + 2, canvas.height); ctx.save(); ctx.translate(x, 0); const needDOM = column.renderCell(ctx, index); ctx.restore(); if (typeof needDOM !== 'boolean' && isAbortAble(needDOM)) { this.pushLazyRedraw(canvas, x, column, needDOM); } if (needDOM !== true && node.childElementCount === 1) { // just canvas return; } const elem = node.querySelector<HTMLElement>(`[data-id="${column.id}"]`); if (elem && !needDOM) { elem.remove(); this.recycleCell(elem, column.index); return; } if (elem) { return this.updateCellImpl(column, elem, index); } const c = this.createCellHandled(column, index); c.classList.add(cssClass('low')); node.appendChild(c); } private reindex() { this.columns.forEach((c, i) => { c.index = i; }); } updateAll() { this.columns.forEach((c, i) => { c.index = i; c.renderers = this.ctx.createRenderer(c.c); }); this._context = Object.assign({}, this._context, { column: nonUniformContext( this.columns.map((w) => w.width), 100, COLUMN_PADDING ), }); this.updateColumnSummaryFlag(); this.events.fire(EngineRanking.EVENT_RECREATE); super.recreate(); this.events.fire(EngineRanking.EVENT_WIDTH_CHANGED); } updateBody() { if (this.hidden) { return; } this.events.fire(EngineRanking.EVENT_WIDTH_CHANGED); super.forEachRow((row, rowIndex) => this.updateRow(row, rowIndex)); } updateHeaderOf(col: Column) { const i = this._context.columns.findIndex((d) => d.c === col); if (i < 0) { return false; } const node = this.header.children[i]! as HTMLElement; const column = this._context.columns[i]; if (node && column) { this.updateHeader(node, column); } this.updateColumnSummaryFlag(); return node && column; } protected createRow(node: HTMLElement, rowIndex: number): void { node.classList.add(this.style.cssClasses.tr); this.roptions.customRowUpdate(node, rowIndex); if (this.highlightHandler.enabled) { node.addEventListener('mouseenter', this.highlightHandler.enter, PASSIVE); this.rowFlags(node).highlight = true; } const isGroup = this.renderCtx.isGroup(rowIndex); const meta = this.toRowMeta(rowIndex); if (!meta) { delete node.dataset.meta; } else { node.dataset.meta = meta; } if (isGroup) { node.dataset.agg = 'group'; super.createRow(node, rowIndex); return; } const { dataIndex } = this.renderCtx.getRow(rowIndex); node.classList.toggle(engineCssClass('highlighted'), this.highlight === dataIndex); node.dataset.i = dataIndex.toString(); node.dataset.agg = 'detail'; //or 'group' this.selection.updateState(node, dataIndex); this.selection.add(node); const low = this.roptions.levelOfDetail(rowIndex) === 'low'; node.classList.toggle(cssClass('low'), low); if (!low || this.ctx.provider.isSelected(dataIndex)) { super.createRow(node, rowIndex); return; } const canvas = this.selectCanvas(); node.appendChild(canvas); node.addEventListener('mouseenter', this.canvasMouseHandler.enter, PASSIVE); this.renderRow(canvas, node, rowIndex); } protected updateRow(node: HTMLElement, rowIndex: number, hoverLod?: 'high' | 'low'): void { this.roptions.customRowUpdate(node, rowIndex); const computedLod = this.roptions.levelOfDetail(rowIndex); const low = (hoverLod ? hoverLod : computedLod) === 'low'; const wasLow = node.classList.contains(cssClass('low')); const isGroup = this.renderCtx.isGroup(rowIndex); const wasGroup = node.dataset.agg === 'group'; node.classList.toggle(cssClass('low'), computedLod === 'low'); if (this.highlightHandler.enabled && !this.rowFlags(node).highlight) { node.addEventListener('mouseenter', this.highlightHandler.enter, PASSIVE); this.rowFlags(node).highlight = true; } if (isGroup !== wasGroup) { // change of mode clear the children to reinitialize them clear(node); // adapt body node.dataset.agg = isGroup ? 'group' : 'detail'; if (isGroup) { node.dataset.i = ''; this.selection.remove(node); } else { this.selection.add(node); } } if (wasLow && (!computedLod || isGroup)) { node.removeEventListener('mouseenter', this.canvasMouseHandler.enter); } const meta = this.toRowMeta(rowIndex); if (!meta) { delete node.dataset.meta; } else { node.dataset.meta = meta; } if (isGroup) { node.classList.remove(engineCssClass('highlighted')); super.updateRow(node, rowIndex); return; } const { dataIndex } = this.renderCtx.getRow(rowIndex); node.classList.toggle(engineCssClass('highlighted'), this.highlight === dataIndex); node.dataset.i = dataIndex.toString(); this.selection.updateState(node, dataIndex); const canvas = wasLow && node.firstElementChild!.nodeName.toLowerCase() === 'canvas' ? (node.firstElementChild! as HTMLCanvasElement) : null; if (!low || this.ctx.provider.isSelected(dataIndex)) { if (canvas) { this.recycleCanvas(canvas); clear(node); node.removeEventListener('mouseenter', this.canvasMouseHandler.enter); } super.updateRow(node, rowIndex); return; } // use canvas if (wasLow && canvas) { this.renderRow(canvas, node, rowIndex); return; } // clear old clear(node); node.dataset.agg = 'detail'; const canvas2 = this.selectCanvas(); node.appendChild(canvas2); node.addEventListener('mouseenter', this.canvasMouseHandler.enter, PASSIVE); this.renderRow(canvas2, node, rowIndex); } private updateCanvasBody() { this.updateCanvasRule(); super.forEachRow((row, index) => { if (EngineRanking.isCanvasRenderedRow(row)) { this.renderRow(row.firstElementChild! as HTMLCanvasElement, row, index); } }); } private toRowMeta(rowIndex: number) { const provider = this.renderCtx.provider; const topNGetter = (group: IGroup) => provider.getTopNAggregated(this.ranking, group); return toRowMeta(this.renderCtx.getRow(rowIndex), provider.getAggregationStrategy(), topNGetter); } private updateCanvasRule() { this.style.updateRule(`renderCanvas${this.tableId}`, `.${cssClass(`low-c${this.tableId}`)}`, { transform: `translateX(${this.currentCanvasShift}px)`, width: `${this.currentCanvasWidth}px`, }); } protected updateShifts(top: number, left: number) { super.updateShifts(top, left); const width = this.visibleRenderedWidth(); if (left === this.currentCanvasShift && width === this.currentCanvasWidth) { return; } this.currentCanvasShift = left; this.currentCanvasWidth = width; this.updateCanvasBody(); } private recycleCanvas(canvas: HTMLCanvasElement) { if (this.loadingCanvas.has(canvas)) { for (const a of this.loadingCanvas.get(canvas)!) { a.render.abort(); } this.loadingCanvas.delete(canvas); } else if (!canvas.classList.contains(cssClass('loading-c'))) { this.canvasPool.push(canvas); } } enableHighlightListening(enable: boolean) { if (this.highlightHandler.enabled === enable) { return; } this.highlightHandler.enabled = enable; if (enable) { this.body.addEventListener('mouseleave', this.highlightHandler.leave, PASSIVE); super.forEachRow((row) => { row.addEventListener('mouseenter', this.highlightHandler.enter, PASSIVE); this.rowFlags(row).highlight = true; }); return; } this.body.removeEventListener('mouseleave', this.highlightHandler.leave); super.forEachRow((row) => { row.removeEventListener('mouseenter', this.highlightHandler.enter); this.rowFlags(row).highlight = false; }); } private updateHoveredRow(row: HTMLElement, hover: boolean) { const isCanvas = EngineRanking.isCanvasRenderedRow(row); if (isCanvas !== hover) { return; // good nothing to do } const index = Number.parseInt(row.dataset.index!, 10); this.updateRow(row, index, hover ? 'high' : 'low'); } protected forEachRow(callback: (row: HTMLElement, rowIndex: number) => void, inplace = false) { const adapter = (row: HTMLElement, rowIndex: number) => { if (EngineRanking.isCanvasRenderedRow(row)) { // skip canvas return; } callback(row, rowIndex); }; return super.forEachRow(adapter, inplace); } updateSelection(selectedDataIndices: { has(i: number): boolean }) { super.forEachRow((node: HTMLElement, rowIndex: number) => { if (this.renderCtx.isGroup(rowIndex)) { this.updateRow(node, rowIndex); } else { // fast pass for item this.selection.update(node, selectedDataIndices); } }, true); } updateColumnWidths() { // update the column context in place (this._context as any).column = nonUniformContext( this._context.columns.map((w) => w.width), 100, COLUMN_PADDING ); super.updateColumnWidths(); const { columns } = this.context; //no data update needed since just width changed columns.forEach((column) => { if (column instanceof MultiLevelRenderColumn) { column.updateWidthRule(this.style); } column.renderers = this.ctx.createRenderer(column.c); }); this.events.fire(EngineRanking.EVENT_WIDTH_CHANGED); } private updateColumn(index: number) { const columns = this.context.columns; const column = columns[index]; if (!column) { return false; } let x = 0; for (let i = this.visibleColumns.first; i < index; ++i) { x += columns[i].width + COLUMN_PADDING; } super.forEachRow((row, rowIndex) => { if (EngineRanking.isCanvasRenderedRow(row)) { this.updateCanvasCell(row.firstElementChild! as HTMLCanvasElement, row, rowIndex, column, x); return; } this.updateCellImpl(column, row.children[index] as HTMLElement, rowIndex); }); return true; } private updateCellImpl(column: RenderColumn, before: HTMLElement, rowIndex: number) { if (!before) { return; // race condition } const r = this.updateCell(before, rowIndex, column); let after: HTMLElement; if (isAsyncUpdate(r)) { after = this.handleCellReady(r.item, r.ready, column.index); } else { after = r; } if (before === after || !after) { return; } this.initCellClasses(after, column.id); before.parentElement!.replaceChild(after, before); } private initCellClasses(node: HTMLElement, id: string) { node.dataset.id = id; node.classList.add(engineCssClass('td'), this.style.cssClasses.td, engineCssClass(`td-${this.tableId}`)); } destroy() { super.destroy(); this.style.deleteRule(`hoverOnly${this.tableId}`); this.style.deleteRule(`renderCanvas${this.tableId}`); this.ranking.flatColumns.forEach((c) => EngineRanking.disableListener(c)); } groupData(): (IGroupItem | IGroupData)[] { const groups = this.ranking.getGroups(); const provider = this.ctx.provider; const strategy = provider.getAggregationStrategy(); const alwaysShowGroup = isAlwaysShowingGroupStrategy(strategy); const r: (IGroupItem | IGroupData)[] = []; if (groups.length === 0) { return r; } const pushItem = (group: IOrderedGroup, dataIndex: number, i: number) => { r.push({ group, dataIndex, relativeIndex: i, }); }; if (groups.length === 1 && groups[0].name === defaultGroup.name) { const group = groups[0]; const l = group.order.length; for (let i = 0; i < l; ++i) { pushItem(group, group.order[i], i); } return r; } const roots = groupRoots(groups); const pushGroup = (group: IOrderedGroup | Readonly<IGroupParent>) => { const n = provider.getTopNAggregated(this.ranking, group); // all are IOrderedGroup since propagated const ordered = group as IOrderedGroup; const groupParent = group as IGroupParent; if (n === 0 || alwaysShowGroup) { r.push(ordered); } if (n !== 0 && Array.isArray(groupParent.subGroups) && groupParent.subGroups.length > 0) { for (const g of groupParent.subGroups) { pushGroup(g as IOrderedGroup | Readonly<IGroupParent>); } return; } const l = n < 0 ? ordered.order.length : Math.min(n, ordered.order.length); for (let i = 0; i < l; ++i) { pushItem(ordered, ordered.order[i], i); } }; for (const root of roots) { pushGroup(root); } return r; } render(data: (IGroupItem | IGroupData)[], rowContext: IExceptionContext) { const previous = this._context; const previousData = this.data; this.data = data; this.columns.forEach((c, i) => { c.index = i; c.renderers = this.ctx.createRenderer(c.c); }); this._context = Object.assign( { columns: this.columns, column: nonUniformContext( this.columns.map((w) => w.width), 100, COLUMN_PADDING ), }, rowContext ); if (!this.bodyScroller) { // somehow not part of dom return; } this.events.fire(EngineRanking.EVENT_RECREATE); return super.recreate(this.roptions.animation ? lineupAnimation(previous, previousData, this.data) : undefined); } setHighlight(dataIndex: number) { this.highlight = dataIndex; const old = this.body.querySelector(`[data-i].${engineCssClass('highlighted')}`); if (old) { old.classList.remove(engineCssClass('highlighted')); } if (dataIndex < 0) { return false; } const item = this.body.querySelector(`[data-i="${dataIndex}"]`); if (item) { item.classList.add(engineCssClass('highlighted')); } return item != null; } findNearest(dataIndices: number[]) { // find the nearest visible data index // first check if already visible const index = dataIndices.find((d) => Boolean(this.body.querySelectorAll(`[data-i="${d}"]`))); if (index != null) { return index; // visible one } const visible = this.visible; const lookFor = new Set(dataIndices); let firstBeforePos = -1; let firstAfterPos = -1; for (let i = visible.first; i >= 0; --i) { const d = this.data[i]; if (!isGroup(d) && lookFor.has(d.dataIndex)) { firstBeforePos = i; break; } } for (let i = visible.last; i < this.data.length; ++i) { const d = this.data[i]; if (!isGroup(d) && lookFor.has(d.dataIndex)) { firstAfterPos = i; break; } } if (firstBeforePos < 0 && firstBeforePos < 0) { return -1; // not found at all } const nearestPos = firstBeforePos >= 0 && visible.first - firstBeforePos < firstAfterPos - visible.last ? firstBeforePos : firstAfterPos; return (this.data[nearestPos] as IGroupItem).dataIndex; } scrollIntoView(dataIndex: number) { const item = this.body.querySelector(`[data-i="${dataIndex}"]`); if (item) { item.scrollIntoView(true); return true; } const index = this.data.findIndex((d) => !isGroup(d) && d.dataIndex === dataIndex); if (index < 0) { return false; // part of a group? } const posOf = () => { const c = this._context; if (c.exceptions.length === 0 || index < c.exceptions[0].index) { // fast pass return index * c.defaultRowHeight; } const before = c.exceptions.reverse().find((d) => d.index <= index); if (!before) { return -1; } if (before.index === index) { return before.y; } const regular = index - before.index - 1; return before.y2 + regular * c.defaultRowHeight; }; const pos = posOf(); if (pos < 0) { return false; } const scroller = this.bodyScroller; if (!scroller) { return false; } const top = scroller.scrollTop; scroller.scrollTop = Math.min(pos, scroller.scrollHeight - scroller.clientHeight); this.onScrolledVertically(scroller.scrollTop, scroller.clientHeight, top < scroller.scrollTop); const found = this.body.querySelector(`[data-i="${dataIndex}"]`); if (found) { found.scrollIntoView(true); return true; } return false; } getHighlight() { const item = this.body.querySelector<HTMLElement>(`[data-i]:hover, [data-i].${engineCssClass('highlighted')}`); if (item) { return Number.parseInt(item.dataset.i!, 10); } return this.highlight; } private createCol(c: Column, index: number) { const col = isMultiLevelColumn(c) && !c.getCollapsed() ? new MultiLevelRenderColumn(c, index, this.renderCtx, this.roptions.flags) : new RenderColumn(c, index, this.renderCtx, this.roptions.flags); c.on(`${Column.EVENT_WIDTH_CHANGED}.body`, () => { // replace myself upon width change since we renderers are allowed to col.renderers = this.ctx.createRenderer(c); this.delayedUpdateColumnWidths(); }); const debounceUpdate = debounce(() => { const valid = this.updateColumn(col.index); if (!valid) { EngineRanking.disableListener(c); // destroy myself } }, 25); c.on([`${Column.EVENT_RENDERER_TYPE_CHANGED}.body`, `${Column.EVENT_GROUP_RENDERER_TYPE_CHANGED}.body`], () => { // replace myself upon renderer type change col.renderers = this.ctx.createRenderer(c); debounceUpdate(); }); // eslint-disable-next-line @typescript-eslint/no-this-alias const that = this; c.on(`${Column.EVENT_DIRTY_HEADER}.body`, function (this: IEventContext) { const valid = that.updateHeaderOf(col.c); if (!valid) { EngineRanking.disableListener(c); // destroy myself } }); c.on(suffix('.body', Column.EVENT_SUMMARY_RENDERER_TYPE_CHANGED, Column.EVENT_DIRTY_CACHES), () => { // replace myself upon renderer type change col.renderers = this.ctx.createRenderer(c); const valid = this.updateHeaderOf(col.c); if (!valid) { EngineRanking.disableListener(c); // destroy myself } }); c.on(`${Column.EVENT_DIRTY_VALUES}.body`, debounceUpdate); if (isMultiLevelColumn(c)) { c.on(`${StackColumn.EVENT_COLLAPSE_CHANGED}.body`, () => { // rebuild myself from scratch EngineRanking.disableListener(c); // destroy myself const index = col.index; const replacement = this.createCol(c, index); replacement.index = index; this.columns.splice(index, 1, replacement); this.delayedUpdateAll(); }); if (!c.getCollapsed()) { (col as MultiLevelRenderColumn).updateWidthRule(this.style); c.on(`${StackColumn.EVENT_MULTI_LEVEL_CHANGED}.body`, () => { (col as MultiLevelRenderColumn).updateWidthRule(this.style); }); c.on(`${StackColumn.EVENT_MULTI_LEVEL_CHANGED}.bodyUpdate`, debounceUpdate); } } return col; } private static isCanvasRenderedRow(row: HTMLElement) { return ( row.classList.contains(cssClass('low')) && row.childElementCount >= 1 && row.firstElementChild!.nodeName.toLowerCase() === 'canvas' ); } private static disableListener(c: Column) { c.on(`${Column.EVENT_WIDTH_CHANGED}.body`, null); c.on( suffix( '.body', Column.EVENT_RENDERER_TYPE_CHANGED, Column.EVENT_GROUP_RENDERER_TYPE_CHANGED, Column.EVENT_SUMMARY_RENDERER_TYPE_CHANGED, Column.EVENT_DIRTY_CACHES, Column.EVENT_LABEL_CHANGED ), null ); c.on(`${Ranking.EVENT_DIRTY_HEADER}.body`, null); c.on(`${Ranking.EVENT_DIRTY_VALUES}.body`, null); if (!isMultiLevelColumn(c)) { return; } c.on(`${StackColumn.EVENT_COLLAPSE_CHANGED}.body`, null); c.on(`${StackColumn.EVENT_MULTI_LEVEL_CHANGED}.body`, null); c.on(`${StackColumn.EVENT_MULTI_LEVEL_CHANGED}.bodyUpdate`, null); } }
the_stack
import * as c from '@aws-accelerator/common-config'; import * as cdk from '@aws-cdk/core'; import { AccountStacks } from '../../common/account-stacks'; import { getStackJsonOutput, ResolverRulesOutput, ResolversOutput, StackOutput, } from '@aws-accelerator/common-outputs/src/stack-output'; import { VpcOutputFinder } from '@aws-accelerator/common-outputs/src/vpc'; import { ResolverEndpoint } from '@aws-accelerator/cdk-constructs/src/route53'; import { JsonOutputValue } from '../../common/json-output'; import { Account, getAccountId } from '../../utils/accounts'; import * as ram from '@aws-cdk/aws-ram'; import { createName, hashPath } from '@aws-accelerator/cdk-accelerator/src/core/accelerator-name-generator'; import { CreateResolverRule, TargetIp } from '@aws-accelerator/custom-resource-create-resolver-rule'; import { IamRoleOutputFinder } from '@aws-accelerator/common-outputs/src/iam-role'; import { StaticResourcesOutput, StaticResourcesOutputFinder, } from '@aws-accelerator/common-outputs/src/static-resource'; import { CfnStaticResourcesOutput } from './outputs'; // Changing these values will lead to redeploying all Phase-3 Endpoint stacks const MAX_RESOURCES_IN_STACK = 10; const RESOURCE_TYPE = 'ResolverEndpointAndRule'; const CENTRAL_VPC_RESOURCE_TYPE = 'CentralVpcResolverEndpointAndRule'; const STACK_COMMON_SUFFIX = 'ResolverEndpoints'; const STACK_CENTRAL_VPC_COMMON_SUFFIX = 'CentralVpcResolverEndpoints'; export interface CentralEndpointsStep2Props { accountStacks: AccountStacks; config: c.AcceleratorConfig; outputs: StackOutput[]; accounts: Account[]; } /** * Creates Route53 Resolver endpoints and resolver rules * Inbound, OutBound Endoints * Resolver Rules for on-Premise ips * Resolver Rules for mad */ export async function step2(props: CentralEndpointsStep2Props) { const { accountStacks, config, outputs, accounts } = props; // Create resolvers for all VPC configs const vpcConfigs = config.getVpcConfigs(); const madConfigs = config.getMadConfigs(); const allStaticResources: StaticResourcesOutput[] = StaticResourcesOutputFinder.findAll({ outputs, }).filter(sr => sr.resourceType === RESOURCE_TYPE); const centralVpcStaticResources: StaticResourcesOutput[] = StaticResourcesOutputFinder.findAll({ outputs, }).filter(sr => sr.resourceType === CENTRAL_VPC_RESOURCE_TYPE); // Initiate previous stacks to handle deletion of previously deployed stack if there are no resources for (const sr of allStaticResources) { const localAccount = accounts.find(acc => acc.key === sr.accountKey); accountStacks.tryGetOrCreateAccountStack( sr.accountKey, sr.region, `${STACK_COMMON_SUFFIX}-${sr.suffix}`, localAccount?.inScope, ); } // Initiate previous stacks to handle deletion of previously deployed stack if there are no resources for (const sr of centralVpcStaticResources) { const localAccount = accounts.find(acc => acc.key === sr.accountKey); accountStacks.tryGetOrCreateAccountStack( sr.accountKey, sr.region, STACK_CENTRAL_VPC_COMMON_SUFFIX, localAccount?.inScope, ); } const accountStaticResourcesConfig: { [accountKey: string]: StaticResourcesOutput[] } = {}; const accountRegionExistingResources: { [accountKey: string]: { [region: string]: string[]; }; } = {}; const accountRegionMaxSuffix: { [accountKey: string]: { [region: string]: number; }; } = {}; for (const { accountKey, vpcConfig } of vpcConfigs) { const resolversConfig = vpcConfig.resolvers; if (!resolversConfig) { console.debug(`Skipping resolver creation for VPC "${vpcConfig.name}" in account "${accountKey}"`); continue; } /** * Checking if current VPC is under Regional Central VPCs (global-options/zones), * If yes then only we will share Rules from this account to another accounts */ const isRuleShareNeeded = vpcConfig['central-endpoint']; const vpcSubnet = vpcConfig.subnets?.find(s => s.name === resolversConfig.subnet); if (!vpcSubnet) { console.error( `Subnet provided in resolvers doesn't exist in Subnet = ${resolversConfig.subnet} and VPC = ${vpcConfig.name}`, ); continue; } const vpcOutput = VpcOutputFinder.tryFindOneByAccountAndRegionAndName({ outputs, accountKey, region: vpcConfig.region, vpcName: vpcConfig.name, }); if (!vpcOutput) { console.error(`Cannot find resolved VPC with name "${vpcConfig.name}"`); continue; } const roleOutput = IamRoleOutputFinder.tryFindOneByName({ outputs, accountKey, roleKey: 'CentralEndpointDeployment', }); if (!roleOutput) { continue; } const subnetIds = vpcOutput.subnets.filter(s => s.subnetName === resolversConfig.subnet).map(s => s.subnetId); if (subnetIds.length === 0) { console.error( `Cannot find subnet IDs for subnet name = ${resolversConfig.subnet} and VPC = ${vpcConfig.name} in outputs`, ); continue; } let suffix: number; let stackSuffix: string; let newResource = true; const constructName = `${STACK_COMMON_SUFFIX}-${vpcConfig.name}`; // Load all account stacks to object if (!accountStaticResourcesConfig[accountKey]) { accountStaticResourcesConfig[accountKey] = allStaticResources.filter(sr => sr.accountKey === accountKey); } if (!accountRegionMaxSuffix[accountKey]) { accountRegionMaxSuffix[accountKey] = {}; } // Load Max suffix for each region of account to object if (!accountRegionMaxSuffix[accountKey][vpcConfig.region]) { const localSuffix = accountStaticResourcesConfig[accountKey] .filter(sr => sr.region === vpcConfig.region) .flatMap(r => r.suffix); accountRegionMaxSuffix[accountKey][vpcConfig.region] = localSuffix.length === 0 ? 1 : Math.max(...localSuffix); } if (!accountRegionExistingResources[accountKey]) { const localRegionalResources = accountStaticResourcesConfig[accountKey] .filter(sr => sr.region === vpcConfig.region) .flatMap(sr => sr.resources); accountRegionExistingResources[accountKey] = {}; accountRegionExistingResources[accountKey][vpcConfig.region] = localRegionalResources; } else if (!accountRegionExistingResources[accountKey][vpcConfig.region]) { const localRegionalResources = accountStaticResourcesConfig[accountKey] .filter(sr => sr.region === vpcConfig.region) .flatMap(sr => sr.resources); accountRegionExistingResources[accountKey][vpcConfig.region] = localRegionalResources; } suffix = accountRegionMaxSuffix[accountKey][vpcConfig.region]; stackSuffix = `${STACK_COMMON_SUFFIX}-${suffix}`; const centralVpc = vpcConfig['central-endpoint']; if (centralVpc) { stackSuffix = STACK_CENTRAL_VPC_COMMON_SUFFIX; } else { if (accountRegionExistingResources[accountKey][vpcConfig.region].includes(constructName)) { newResource = false; const regionStacks = accountStaticResourcesConfig[accountKey].filter(sr => sr.region === vpcConfig.region); for (const rs of regionStacks) { if (rs.resources.includes(constructName)) { stackSuffix = `${STACK_COMMON_SUFFIX}-${rs.suffix}`; break; } } } else { const existingResources = accountStaticResourcesConfig[accountKey].find( sr => sr.region === vpcConfig.region && sr.suffix === suffix, ); if (existingResources && existingResources.resources.length >= MAX_RESOURCES_IN_STACK) { accountRegionMaxSuffix[accountKey][vpcConfig.region] = ++suffix; } stackSuffix = `${STACK_COMMON_SUFFIX}-${suffix}`; } } const localAccount = accounts.find(acc => acc.key === accountKey); const accountStack = accountStacks.tryGetOrCreateAccountStack( accountKey, vpcConfig.region, stackSuffix, localAccount?.inScope, ); if (!accountStack) { console.error(`Cannot find account stack ${accountKey}: ${vpcConfig.region}, while deploying Resolver Endpoints`); continue; } // Call r53-resolver-endpoint per Account const r53ResolverEndpoints = new ResolverEndpoint( accountStack, `${STACK_COMMON_SUFFIX}-${accountKey}-${vpcConfig.name}`, { vpcId: vpcOutput.vpcId, name: vpcConfig.name, subnetIds, }, ); const resolverOutput: ResolversOutput = { vpcName: vpcConfig.name, accountKey, region: vpcConfig.region, }; const resolverRulesOutput: ResolverRulesOutput = {}; if (resolversConfig.inbound) { r53ResolverEndpoints.enableInboundEndpoint(); resolverOutput.inBound = r53ResolverEndpoints.inboundEndpointRef; } const onPremRules: string[] = []; const madRules: string[] = []; if (resolversConfig.outbound) { r53ResolverEndpoints.enableOutboundEndpoint(); resolverOutput.outBound = r53ResolverEndpoints.outboundEndpointRef; // For each on-premise domain defined in the parameters file, create a Resolver rule which points to the specified IP's for (const onPremRuleConfig of vpcConfig['on-premise-rules'] || []) { const targetIps: TargetIp[] = onPremRuleConfig['outbound-ips'].map(ip => ({ Ip: ip, Port: 53, })); const rule = new CreateResolverRule(accountStack, `${domainToName(onPremRuleConfig.zone)}-${vpcConfig.name}`, { domainName: onPremRuleConfig.zone, resolverEndpointId: r53ResolverEndpoints.outboundEndpointRef!, roleArn: roleOutput.roleArn, targetIps, vpcId: vpcOutput.vpcId, name: createRuleName(`${vpcConfig.name}-onprem-${domainToName(onPremRuleConfig.zone)}`), }); rule.node.addDependency(r53ResolverEndpoints.outboundEndpoint!); onPremRules.push(rule.ruleId); } resolverRulesOutput.onPremRules = onPremRules; // Check for MAD configuration whose resolver is current account VPC const madConfigsWithVpc = madConfigs.filter( mc => mc.mad['central-resolver-rule-account'] === accountKey && mc.mad.region === vpcConfig.region && mc.mad['central-resolver-rule-vpc'] === vpcConfig.name, ); for (const { accountKey: madAccountKey, mad } of madConfigsWithVpc) { const madOutput = getStackJsonOutput(outputs, { accountKey: madAccountKey, outputType: 'MadOutput', }); if (madOutput.length === 0) { console.warn(`MAD is not deployed yet in account ${accountKey}`); continue; } const madIPs: string[] = madOutput[0].dnsIps.split(','); const targetIps: TargetIp[] = madIPs.map(ip => ({ Ip: ip, Port: 53, })); const madRule = new CreateResolverRule(accountStack, `${domainToName(mad['dns-domain'])}-${vpcConfig.name}`, { domainName: mad['dns-domain'], resolverEndpointId: r53ResolverEndpoints.outboundEndpointRef!, roleArn: roleOutput.roleArn, targetIps, vpcId: vpcOutput.vpcId, name: createRuleName(`${vpcConfig.name}-mad-${domainToName(mad['dns-domain'])}`), }); madRule.node.addDependency(r53ResolverEndpoints.outboundEndpoint!); madRules.push(madRule.ruleId); } resolverRulesOutput.madRules = madRules; } resolverOutput.rules = resolverRulesOutput; new JsonOutputValue(accountStack, `ResolverOutput-${resolverOutput.vpcName}`, { type: 'GlobalOptionsOutput', value: resolverOutput, }); if (isRuleShareNeeded) { const regionVpcs = config .getVpcConfigs() .filter( vc => vc.vpcConfig.region === vpcConfig.region && vc.vpcConfig['use-central-endpoints'] && vc.accountKey !== accountKey, ); const sharedToAccountKeys = regionVpcs.map(rv => rv.accountKey); const sharedToAccountIds: string[] = sharedToAccountKeys.map(accId => getAccountId(accounts, accId)!); if (sharedToAccountIds.length > 0) { const ruleArns: string[] = [ ...madRules.map( ruleId => `arn:aws:route53resolver:${vpcConfig.region}:${cdk.Aws.ACCOUNT_ID}:resolver-rule/${ruleId}`, ), ...onPremRules.map( ruleId => `arn:aws:route53resolver:${vpcConfig.region}:${cdk.Aws.ACCOUNT_ID}:resolver-rule/${ruleId}`, ), ]; // share the route53 resolver rules new ram.CfnResourceShare(accountStack, `ResolverRuleShare-${vpcConfig.name}`, { name: createName({ name: `${vpcConfig.name}-ResolverRules`, }), allowExternalPrincipals: false, principals: sharedToAccountIds, resourceArns: ruleArns, }); } } if (centralVpc) { const currentResourcesObject = { accountKey, id: `${CENTRAL_VPC_RESOURCE_TYPE}-${vpcConfig.region}-${accountKey}-${suffix}`, region: vpcConfig.region, resourceType: CENTRAL_VPC_RESOURCE_TYPE, resources: [`${STACK_CENTRAL_VPC_COMMON_SUFFIX}-${vpcConfig.name}`], // Setting sufix to -1 since will only have one Central VPC per region suffix: -1, }; new CfnStaticResourcesOutput( accountStack, `CentralVpcResolverEndpointsOutput-${vpcConfig.name}`, currentResourcesObject, ); } if (newResource && !centralVpc) { const currentSuffixIndex = allStaticResources.findIndex( sr => sr.region === vpcConfig.region && sr.suffix === suffix && sr.accountKey === accountKey, ); const currentAccountSuffixIndex = accountStaticResourcesConfig[accountKey].findIndex( sr => sr.region === vpcConfig.region && sr.suffix === suffix, ); if (currentSuffixIndex === -1) { const currentResourcesObject = { accountKey, id: `${RESOURCE_TYPE}-${vpcConfig.region}-${accountKey}-${suffix}`, region: vpcConfig.region, resourceType: RESOURCE_TYPE, resources: [constructName], suffix, }; allStaticResources.push(currentResourcesObject); accountStaticResourcesConfig[accountKey].push(currentResourcesObject); } else { const currentResourcesObject = allStaticResources[currentSuffixIndex]; const currentAccountResourcesObject = accountStaticResourcesConfig[accountKey][currentAccountSuffixIndex]; if (!currentResourcesObject.resources.includes(constructName)) { currentResourcesObject.resources.push(constructName); } if (!currentAccountResourcesObject.resources.includes(constructName)) { currentAccountResourcesObject.resources.push(constructName); } allStaticResources[currentSuffixIndex] = currentResourcesObject; accountStaticResourcesConfig[accountKey][currentAccountSuffixIndex] = currentAccountResourcesObject; } } } for (const sr of allStaticResources) { const srLocalAccount = accounts.find(acc => acc.key === sr.accountKey); const accountStack = accountStacks.tryGetOrCreateAccountStack( sr.accountKey, sr.region, `${STACK_COMMON_SUFFIX}-${sr.suffix}`, srLocalAccount?.inScope, ); if (!accountStack) { throw new Error( `Not able to get or create stack for ${sr.accountKey}: ${sr.region}: ${STACK_COMMON_SUFFIX}-${sr.suffix}`, ); } new CfnStaticResourcesOutput(accountStack, `StaticResourceOutput-${sr.suffix}`, sr); } } function domainToName(domain: string): string { return domain.replace(/\./gi, '-'); } export function createRuleName(name: string): string { const hash = hashPath([name], 8); if (name.length > 44) { name = name.substring(0, 44); } name = name + hash; return createName({ name, }); }
the_stack
import { ArrowUp16, Close20 } from '@carbon/icons-react'; import { InlineLoading } from 'carbon-components-react'; import cx from 'classnames'; import { unzipSync, strFromU8 } from 'fflate'; import { Stack } from 'office-ui-fabric-react'; import React, { useCallback, useEffect, useRef, useState } from 'react'; import Avatar from 'react-avatar'; import { useDispatch, useSelector } from 'react-redux'; import { withRouter } from 'react-router'; import { useHistory } from 'react-router-dom'; import { useManagedRenderStack } from '../../context/RenderStack'; import { addDriveLinks, setHeaders, setDriveLinks, setExternalLinks, setComments, selectComments, selectDriveLinksLookup, setFile, setNoFile, DriveLink, ExternalLink, } from '../../reduxSlices/doc'; import { selectSidebarOpen } from '../../reduxSlices/siderTree'; import { DriveFile, MimeTypes } from '../../utils'; import { fromHTML, MakeTree } from '../../utils/docHeaders'; import { gdocIdAttr, origHrefAttr, prettify, rewriteLink } from '../../utils/docMarkup'; import { escapeHtml, isModifiedEvent } from '../../utils/html'; import styles from './DocPage.module.scss'; export interface IDocPageProps { file: DriveFile; renderStackOffset?: number; match: any; location: any; history: any; } function strToUint8Array(binary_string: string): Uint8Array { var len = binary_string.length; var bytes = new Uint8Array(len); for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i); } return bytes; } type DriveFileLookup = { [fileId: string]: DriveFile }; // linkPreview performs blocking API calls async function linkPreview( baseEl: HTMLElement, driveFileLookup?: DriveFileLookup ): Promise<{ driveLinks: DriveLink[], externalLinks: ExternalLink[] }> { const files: { [fileId: string]: DriveFile } = driveFileLookup ?? {}; const driveLinks: DriveLink[] = []; const externalLinks: ExternalLink[] = []; try { const linkElems = baseEl.classList.contains(styles.gdocLink) ? [baseEl] : baseEl.querySelectorAll('.' + styles.gdocLink); for (const linkEl of linkElems) { const link = linkEl as HTMLAnchorElement; const id = link.dataset?.[gdocIdAttr]; if (id && !files[id]) { const fields = 'id,name,thumbnailLink,mimeType,iconLink'; const req = { fileId: id, supportsAllDrives: true, fields }; const rsp = await gapi.client.drive.files.get(req); files[id] = rsp.result; driveLinks.push({ file: rsp.result, wikiLink: link.href, driveLink: link.dataset?.[origHrefAttr] || link.href, linkText: link.innerText, id: id, }); const imgSrc = rsp.result.thumbnailLink; if (!imgSrc) { if (rsp.result.mimeType !== MimeTypes.GoogleFolder) { console.debug('preview no thumbnail', id); } continue; } let img = document.createElement('img'); img.src = imgSrc; img.alt = 'Doc Preview'; img.classList.add(styles.gdocThumbnail); img.setAttribute('style', 'border:solid;'); link.append(img); } } if (!baseEl.classList.contains(styles.gdocLink)) { const linkElems = baseEl.getElementsByTagName('a'); for (const linkEl of linkElems) { const link = linkEl as HTMLAnchorElement; const id = link.dataset?.[gdocIdAttr]; const href = link.getAttribute('href'); if (!id && href?.match(/https?:/)) { externalLinks.push({ linkText: link.textContent, href: link.href, }); } } } } catch (e) { if (e.result?.error) { console.error('linkPreview thumbnails', e.result.error); } else { console.error('linkPreview thumbnails', e); } } return { driveLinks, externalLinks }; } interface UpgradedComment { htmlId: string; topHref: string; comment: gapi.client.drive.Comment; } function DocPage({ match, file, renderStackOffset = 0 }: IDocPageProps) { const docContentElement = useRef(null as null | HTMLBodyElement); const [docContent, setDocContent] = useState(''); const docContentHasBeenRendered = !!docContentElement.current; const [docName] = useState(file.name ?? ''); const [isLoading, setIsLoading] = useState(true); const [viewingComment, setViewingComment] = useState(null as string | null); const dispatch = useDispatch(); const docComments = useSelector(selectComments); const sidebarOpen = useSelector(selectSidebarOpen); const driveLinksLookup = useSelector(selectDriveLinksLookup); const history = useHistory(); const [upgradedComments, setUpgradedComments] = useState([] as UpgradedComment[]); const [readyForLinkPreview, setReadyForLinkPreview] = useState(false); const [docHtmlChangesFinished, setDocHtmlChangesFinished] = useState(false); const isSpreadSheet = file.mimeType === MimeTypes.GoogleSpreadsheet; useCallback(() => { if (file.name) { dispatch(setFile(file)); } else { dispatch(setNoFile()); } }, [dispatch, file])(); useManagedRenderStack({ depth: renderStackOffset, id: 'DocPage', file, }); const setDocWithPlainText = useCallback( (content: string) => { setDocContent(content); dispatch(setHeaders([])); }, [dispatch] ); useEffect( // Support Google Chrome's built-in translation feature. // It works when clicking on a new document // However it does not work for headers // Generally it has problems with small dynamic updates. // Solution: re-generate the headers from the now translated content. function chromeTranslateHeaders() { function handleTranslated(msg: string = '') { if (document.documentElement.className.includes('translated')) { const contentNode = document.getElementById('gdoc-html-content')!; if (!contentNode) { return; } dispatch( setHeaders( MakeTree( Array.from(contentNode.querySelectorAll('h1, h2, h3, h4, h5, h6')).map(fromHTML) ) ) ); } } // Translation just enabled const htmlObserver = new MutationObserver(function () { handleTranslated('html'); }); htmlObserver.observe(document.documentElement, { attributes: true, childList: false, subtree: false, }); // Translation is already enabled and now opening the doc. // This is not entirely reliable because we don't know how long translation will take. // We could listen for inner mutations indicating a translation update. const docObserver = new MutationObserver(function (mutationList: MutationRecord[] ) { for (const mutation of mutationList) { if (mutation.type === 'childList') { for (const node of mutation.addedNodes) { if ((node as HTMLElement).id === 'gdoc-html-content') { setTimeout(() => { handleTranslated('gdoc html content'); }, 1000); } } } } }); docObserver.observe(document.getElementById('doc-page-outer')!, { attributes: false, childList: true, subtree: false, }); // Only the visible content is translated. // So update as the document is scrolled. function scrollCallback() { setTimeout(() => { handleTranslated('scroll'); }, 1000); } document.addEventListener('scroll', scrollCallback); return () => { htmlObserver.disconnect(); docObserver.disconnect(); document.removeEventListener('scroll', scrollCallback); }; }, [dispatch] ); useEffect( function doLinkPreview() { const content = docContentElement.current; if (!content) { return; } linkPreview(content).then(function (newLinks) { setDocContent(content.innerHTML); dispatch(setDriveLinks(newLinks.driveLinks)); dispatch(setExternalLinks(newLinks.externalLinks)); setDocHtmlChangesFinished(true); }); }, [readyForLinkPreview, dispatch], ); useEffect( function doAlterHtml() { async function alterHtml() { const content = docContentElement.current; if (!content) { return; } // prettify could take a noticeable amount of time for a large doc on a slow device. // So it is important to be in a separate useEffect prettify(content, styles, file); setDocContent(content.innerHTML); setReadyForLinkPreview(true); } // check file.name: optimistic rendering initially sets only the id if (!isSpreadSheet && docContentHasBeenRendered && file.name) { alterHtml(); } }, // file.name is needed in the dependencies // optimistic rendering initially sets only the id [file, file.name, isSpreadSheet, docContentHasBeenRendered, dispatch] ); const setDocWithRichContent = useCallback( (content: HTMLBodyElement, pretty: boolean) => { dispatch( setHeaders( MakeTree(Array.from(content.querySelectorAll('h1, h2, h3, h4, h5, h6')).map(fromHTML)) ) ); setDocContent(content.innerHTML); docContentElement.current = content; }, [dispatch] ); useEffect( function loadDoc() { function loadHtmlBody(body: string, pretty: boolean = true): void { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(body, 'text/html'); const bodyEl = htmlDoc.querySelector('body'); if (bodyEl) { const styleEls = htmlDoc.querySelectorAll('style'); styleEls.forEach((el) => bodyEl.appendChild(el)); setDocWithRichContent(bodyEl, pretty); } else { setDocWithPlainText('Error?'); } } async function loadHtmlView() { setIsLoading(true); // At least when in dev mode this needs to be reset docContentElement.current = null; setDocWithPlainText(''); // TODO: this gets called multiple times on page load // separate this out with only a dependency on file.id try { if (isSpreadSheet) { const resp = await gapi.client.drive.files.export({ alt: 'media', fileId: file.id!, mimeType: 'application/zip', }); const decompressed = unzipSync(strToUint8Array(resp.body), {}) console.debug('DocPage files.export zip', file.id, Object.keys(decompressed)); let html = ''; let css = ''; for (const k in decompressed) { // TODO: multiple sheets if (!html && k.endsWith('.html')) { html = strFromU8(decompressed[k]); } else if (k.endsWith('.css')) { // An iframe would probably be better // But this seems to fix visible issues css = strFromU8(decompressed[k]).replaceAll(/(a[{:])/g, '#gdoc-html-content $1'); } } loadHtmlBody(html + '<style>' + css + '</style>', false); } else { const resp = await gapi.client.drive.files.export({ fileId: file.id!, mimeType: 'text/html', }); console.debug('DocPage files.export', file.id); loadHtmlBody(resp.body, true); } } catch (e) { // To speed things up we do optimistic rendering just with the id // That would result in throwing an error here if (docName) { setDocWithPlainText('Error Loading Document'); throw e; } console.debug('ignore optimistic export error'); } finally { setIsLoading(false); } } loadHtmlView(); return function () { dispatch(setHeaders([])); dispatch(setDriveLinks([])); dispatch(setExternalLinks([])); }; }, [file.id, isSpreadSheet, dispatch, setDocWithPlainText, setDocWithRichContent, docName] ); useEffect( function showNameInUrl() { // The DocPage can be shown without a /view or /n url. // Just skip in this case. It may not be a file. if (match.params.id !== file.id || !file.name) { return; } var urlParams = new URLSearchParams(window.location.search); // Change invalid characters to '_' but don't show 2 of those next to each other // Change '_-_' to '-' let newSlugName = encodeURIComponent(file.name.replaceAll('%', '_')) .replaceAll(/%../g, '_') .replaceAll(/_+/g, '_') .replaceAll(/_-/g, '-') .replaceAll(/-_+/g, '-') .replace(/_+$/, '') .replace(/^_+/, ''); const givenParamName = urlParams.get('n'); if (givenParamName === newSlugName) { return; } const givenPathName = match.params.slug; if (!givenPathName) { urlParams.set('n', newSlugName); const urlNoParam = window.location.pathname; const newUrl = urlNoParam + '?' + urlParams.toString(); history.replace(newUrl); return; } if (newSlugName === '_' || newSlugName === '-') { newSlugName = ''; } if (givenPathName !== newSlugName) { let path = '/n/' + newSlugName + '/' + match.params.id; history.replace(path); } }, [file.id, file.name, match.params, history] ); useEffect( function doLoadComments() { // When optimistically rendering the document, only an id is available. // Avoid optimistically fetching comments as well. // This API call would actually succeed against a folder // but we wouldn't end up using the resulit. if (!file.name) { return; } async function loadComments() { try { // problem: this does not return all of the visible comments const resp = await gapi.client.drive.comments.list({ fileId: file.id!, includeDeleted: false, fields: '*', pageSize: 100, }); const respComments = resp.result.comments ?? []; dispatch(setComments(respComments)); } catch (e) { console.error('error loading comments', e); } } loadComments(); return function () { dispatch(setComments([])); }; }, [file.id, dispatch, file.name] ); // TODO: when using Google translate the comments could already be translated // We need to use the pre-inserted HTML // In this case we need to fallback to using the quoted value and position // // TODO: // We do not get the comments from the API for a re-opened comment thread. // AS per above should have a fallback, at least do not remove superscript links from text. useEffect( function doUpgradeComments(): void { async function upgradeComments() { function removeSpace(s: string): string { return s.replaceAll(/\s+/g, ''); } function replyText(reply: gapi.client.drive.Reply): string { if (reply.action === 'resolve' && !reply.content?.startsWith('_Marked as done_')) { return '_Marked as done_ ' + (reply.content ?? ''); } return reply.content ?? ''; } const body = docContentElement.current; if (!body) { return; } // We would like to filter out resolve comments // However, once a comment thread is resolved it may stay marked resolved // Even after being re-opened // We also won't see the replies after it is re-opened const apiComments = docComments; // .filter((comment) => comment.resolved !== true); if (apiComments.length === 0) { return; } let newDriveLinks: DriveLink[] = []; let fileLookup: { [fileId: string]: DriveFile } = {}; for (const id in driveLinksLookup) { const f = driveLinksLookup[id].file; if (f) { fileLookup[id] = f; } } const prettifyHtmlContent = async (htmlContent: string) => { if (!htmlContent) { return htmlContent; } const parser = new DOMParser(); const body = parser.parseFromString(htmlContent, 'text/html').body; for (const el of body.getElementsByTagName('a')) { rewriteLink(el, styles); const newLinks = await linkPreview(el, fileLookup); newDriveLinks = newDriveLinks.concat(newLinks.driveLinks); } return body.innerHTML; }; const newComments: UpgradedComment[] = []; const commentLookup: { [text: string]: gapi.client.drive.Comment[] } = {}; for (const comment of apiComments) { const text = removeSpace(comment.content ?? '') const multi = commentLookup[text]; if (multi) { multi.push(comment); } else { commentLookup[text] = [comment]; } } const replyLookup: { [text: string]: gapi.client.drive.Comment[] } = {}; let i = 0; while (true) { i += 1; const domId = '#cmnt' + i.toString(); const commentLink = body.querySelector(domId); if (!commentLink) { // console.debug(commentLookup); // console.debug(replyLookup); break; } let parent = commentLink.parentElement; while (parent && parent.nodeName !== 'DIV') { parent = parent.parentElement; } if (!parent) { console.error('no parent for comment'); continue; } let origTextPieces = [commentLink.nextElementSibling?.textContent ?? '']; for (const child of Array.from(parent.children).slice(1)) { const textContent = child.textContent || ''; if ( textContent.startsWith('_Assigned to') || textContent.startsWith('_Reassigned to') ) { continue; } origTextPieces.push(textContent); } const lookupText = removeSpace(origTextPieces.join('\n')); const comments = commentLookup[lookupText]; if (comments) { if (comments.length === 1) { delete commentLookup[lookupText]; } const topHref = commentLink.getAttribute('href') ?? '#'; // console.log(topHref); // console.log(body.querySelector(topHref)); const docTextNoSpace = removeSpace( escapeHtml((body.querySelector(topHref) as HTMLElement | null)?.innerText ?? '') ); let exactComment: null | gapi.client.drive.Comment = null; if (docTextNoSpace) { for (const comment of comments) { const quotedNoSpace = removeSpace(comment.quotedFileContent?.value ?? ''); if (quotedNoSpace === docTextNoSpace) { exactComment = comment; } } } if (!exactComment) { exactComment = comments.shift()!; if (comments.length > 0) { console.debug( 'did not find exact', docTextNoSpace, 'guessing', exactComment.quotedFileContent?.value ); } for (const comment of comments) { console.debug('alternative', removeSpace(comment.quotedFileContent?.value ?? '')); } } for (const child of parent.children) { parent.removeChild(child); } let apiComment = exactComment; if (exactComment.htmlContent) { const html = await prettifyHtmlContent(exactComment.htmlContent); apiComment = { ...exactComment, htmlContent: html }; } // Create a lookup for all the replies. // This will confirm that the replies in the DOM exist in our data. if (apiComment.replies) { const replies = [...apiComment.replies]; for (const [i, reply] of apiComment.replies.entries()) { const replyNoSpace = removeSpace(replyText(reply)); const repliesForText = replyLookup[replyNoSpace]; if (repliesForText) { repliesForText.push(reply); } else { replyLookup[replyNoSpace] = [reply]; } if (reply.htmlContent) { const html = await prettifyHtmlContent(reply.htmlContent); replies[i] = { ...reply, htmlContent: html }; } } apiComment = { ...apiComment, replies } } newComments.push({ comment: apiComment, topHref, htmlId: commentLink.id, }); parent.remove(); } else if (replyLookup[lookupText]) { const replies = replyLookup[lookupText]; // Don't bother figuring out the exact correct reply. replies.shift(); if (replies.length === 0) { delete replyLookup[lookupText]; } // note that we no longer link replies back to the text // So delete those supers as well (body.querySelector( commentLink.getAttribute('href') ?? '' ) as HTMLElement | null)?.remove(); parent.remove(); } else { console.debug('did not find comment for', lookupText); // console.debug(Object.keys(commentLookup)); // console.debug(replyLookup); } } if (newDriveLinks.length > 0) { dispatch(addDriveLinks(newDriveLinks)); } setUpgradedComments(newComments); setDocContent(body.innerHTML); } // wait for all other HTML alterations to complete if (docHtmlChangesFinished) { upgradeComments(); } }, [docComments, docHtmlChangesFinished, dispatch, driveLinksLookup] ); useEffect( function updateLastViewed() { // wait for all other HTML alterations to complete. // There are 2 potential benefits: // * ensure this network request does not delay more important ones // * If someone quickly hits the back button their view may not be recorded if (!docHtmlChangesFinished) { return; } // check another field like mimeType for the case of optimistic rendering if (!file.id || !file.mimeType) { return; } async function updateApi() { const d = new Date(); try { await gapi.client.drive.files.update( { fileId: file.id!, supportsAllDrives: true }, { viewedByMeTime: d.toISOString() } ); } catch (e) { console.log('update file error: ', e); } } updateApi(); }, [file.id, file.mimeType, docHtmlChangesFinished] ); const handleDocContentClick = useCallback( (ev: React.MouseEvent) => { if (isModifiedEvent(ev)) { return; } // Find the target href // An individual onclick handler would have been easier let target = ev.target as HTMLElement; if (target.nodeName !== 'A' && target.parentElement) { target = target.parentElement; while (['SVG', 'PATH', 'FONT'].includes(target.nodeName) && target.parentElement) { target = target.parentElement; } } const id = target.dataset?.[gdocIdAttr]; if (id) { ev.preventDefault(); if ((target as HTMLElement).nodeName === 'A') { const hrefAttr = target.getAttribute('href'); console.log('opening target', hrefAttr); if (hrefAttr?.[0] === '/' && hrefAttr?.[1] !== '/') { const u = new URL((target as HTMLAnchorElement).href); history.push(u.pathname + u.search + u.hash); } else { // For touchscreen preview/edit we open externally in gdocs app window.open((target as HTMLAnchorElement).href, '_blank'); } } else { history.push(`/view/${id}`); } return; } const commentLink = target.dataset?.['gdocwiki_comment_id']; if (commentLink) { ev.preventDefault(); console.log('setting viewing comment to', commentLink); setViewingComment(commentLink); scrollWithOffset(target); } }, [history] ); if (isLoading) { return ( <div id="doc-page-outer" style={{ maxWidth: '50rem' }}> <InlineLoading description="Loading document content..." /> </div> ); } const fixSidebar = { position: 'fixed' as 'fixed', right: 0, left: sidebarOpen ? '320px' : '0' }; return ( <div id="doc-page-outer" style={{ maxWidth: '50rem' }} onClick={handleDocContentClick}> <div key="gdoc-html-content" id="gdoc-html-content" style={{ marginTop: '1rem' }} dangerouslySetInnerHTML={{ __html: docContent }} /> <div key="upgradedComments" style={{ paddingTop: '30px' }}> <hr /> <p>{upgradedComments.length === 0 ? 'No' : 'All'} Comments</p> <hr style={{ marginBottom: '1rem' }} /> {upgradedComments.map((comment, i) => ( <div key={comment.htmlId}> {i !== 0 && <hr />} <CommentView key={comment.htmlId} fileId={file.id!} comment={comment} /> </div> ))} </div> {viewingComment && ( <div key="viewingComment" style={fixSidebar} className={cx(styles.commentsDrawer, { [styles.viewing]: !!viewingComment })} > <div key="view-comment-header" style={fixSidebar}> <hr /> <Stack horizontal> <a onClick={() => { setViewingComment(null); }} > <Close20 /> </a> <h4>Comment</h4> </Stack> <hr /> </div> <div key="vew-comment-body" style={{ marginTop: '4.0rem' }}> {upgradedComments.map((comment) => !!viewingComment && comment.htmlId !== viewingComment ? null : ( <div> <CommentView hideLinkBack={true} key={comment.htmlId} fileId={file.id!} comment={comment} /> </div> ) )} </div> </div> )} </div> ); } function scrollWithOffset(link: HTMLElement, fixedOffset = 100) { const rect = link.getBoundingClientRect(); const fractionFromBottom = (window.innerHeight - rect.top) / window.innerHeight; // The comment drawer is set to a height of 50% if (fractionFromBottom > 0.5) { return; } // Add a fixedOffset to give some room before the comments const scrollToY = window.pageYOffset + fixedOffset + (0.5 - fractionFromBottom) * window.innerHeight; console.log('scrollWithOffset', scrollToY, fixedOffset, window.pageYOffset); window.scrollTo(window.pageXOffset, scrollToY); } interface CommentViewProps { fileId: string; comment: UpgradedComment; hideLinkBack?: boolean; } function CommentView(props: CommentViewProps): JSX.Element { const { htmlId, topHref, comment } = props.comment; return ( <div style={{ paddingBottom: '20px' }}> <Stack horizontal style={{ paddingLeft: '10px' }} key={topHref} tokens={{ childrenGap: 12, padding: 0 }} > {!props.hideLinkBack && ( <a href={topHref} title="back to document"> <ArrowUp16 /> </a> )} <span> <a id={htmlId} data-__gdoc_id={props.fileId} href={`/view/${props.fileId}/edit/?disco=${comment.id}`} style={{ textDecoration: 'none' }} title="view in doc"> <em>{comment.quotedFileContent?.value}</em> </a> </span> </Stack> <hr /> <Stack horizontal key={comment.id} tokens={{ childrenGap: 8, padding: 8 }}> <Stack> <Avatar name={comment.author?.displayName} src={'https://' + comment.author?.photoLink} size="30" round /> </Stack> <Stack> <span dangerouslySetInnerHTML={{ __html: comment.htmlContent ?? '' }} /> </Stack> </Stack> {comment.replies?.map((reply) => ( <Stack horizontal key={reply.id} tokens={{ childrenGap: 8, padding: 8 }}> <Stack> <Avatar name={reply.author?.displayName} src={'https://' + reply.author?.photoLink} size="30" round /> </Stack> <Stack> <span dangerouslySetInnerHTML={{ __html: reply.htmlContent ?? '' }} /> </Stack> </Stack> ))} </div> ); } export default React.memo(withRouter(DocPage));
the_stack
import assert from 'assert'; import NodeVisitor from './ast/visitor'; import * as Ast from './ast'; import List from './utils/list'; import { isUnaryExpressionOp, flipOperator, getScalarExpressionName } from './utils'; function flattenAnd(expr : Ast.BooleanExpression) : Ast.BooleanExpression[] { const flattened = []; if (expr instanceof Ast.AndBooleanExpression) { for (const op of expr.operands) { const operands = flattenAnd(op); operands.forEach((op) => assert(op instanceof Ast.BooleanExpression)); for (const subop of operands) flattened.push(subop); } } else { flattened.push(expr); } return flattened; } function flattenOr(expr : Ast.BooleanExpression) : Ast.BooleanExpression[] { const flattened = []; if (expr instanceof Ast.OrBooleanExpression) { for (const op of expr.operands) { const operands = flattenOr(op); operands.forEach((op) => assert(op instanceof Ast.BooleanExpression)); for (const subop of operands) flattened.push(subop); } } else { flattened.push(expr); } return flattened; } function compareList<T>(one : List<T>, two : List<T>) : -1|0|1 { const oneit = one[Symbol.iterator](), twoit = two[Symbol.iterator](); for (;;) { const onev = oneit.next(), twov = twoit.next(); if (onev.done && twov.done) return 0; if (onev.done) return -1; if (twov.done) return 1; if (String(onev.value) < String(twov.value)) return -1; if (String(twov.value) < String(onev.value)) return 1; } } // compare according to the lexicographic representation function compareBooleanExpression(one : Ast.BooleanExpression, two : Ast.BooleanExpression) { return compareList(one.toSource(), two.toSource()); } function optimizeFilter(expr : Ast.BooleanExpression) : Ast.BooleanExpression { if (expr.isTrue || expr.isFalse || expr.isDontCare) return expr; if (expr instanceof Ast.AndBooleanExpression) { const operands = flattenAnd(expr).map((o) => optimizeFilter(o)).filter((o) => !o.isTrue); operands.forEach((op) => assert(op instanceof Ast.BooleanExpression)); operands.sort(compareBooleanExpression); for (const o of operands) { if (o.isFalse) return Ast.BooleanExpression.False; } if (operands.length === 0) return Ast.BooleanExpression.True; if (operands.length === 1) return operands[0]; return new Ast.BooleanExpression.And(expr.location, operands); } if (expr instanceof Ast.OrBooleanExpression) { const operands = flattenOr(expr).map((o) => optimizeFilter(o)).filter((o) => !o.isFalse); operands.forEach((op) => assert(op instanceof Ast.BooleanExpression)); operands.sort(compareBooleanExpression); for (const o of operands) { if (o.isTrue) return Ast.BooleanExpression.True; } if (operands.length === 0) return Ast.BooleanExpression.False; if (operands.length === 1) return operands[0]; // convert "x == foo || x == bar" to "x in_array [foo, bar]" // and "x =~ foo || x =~ bar" to "x in_array~ [foo, bar]" const equalityFilters : { [key : string] : Ast.Value[] } = {}; const likeFilters : { [key : string] : Ast.Value[] } = {}; const otherFilters : Ast.BooleanExpression[] = []; for (const operand of operands) { if (operand instanceof Ast.AtomBooleanExpression) { if (operand.operator === '==') { if (operand.name in equalityFilters) equalityFilters[operand.name].push(operand.value); else equalityFilters[operand.name] = [operand.value]; } else if (operand.operator === '=~') { if (operand.name in likeFilters) likeFilters[operand.name].push(operand.value); else likeFilters[operand.name] = [operand.value]; } else { otherFilters.push(operand); } } else { otherFilters.push(operand); } } for (const eqParam in equalityFilters) { if (equalityFilters[eqParam].length > 1) { otherFilters.push(new Ast.BooleanExpression.Atom(expr.location, eqParam, 'in_array', new Ast.Value.Array(equalityFilters[eqParam]))); } else { otherFilters.push(new Ast.BooleanExpression.Atom(expr.location, eqParam, '==', equalityFilters[eqParam][0])); } } for (const eqParam in likeFilters) { if (likeFilters[eqParam].length > 1) { otherFilters.push(new Ast.BooleanExpression.Atom(expr.location, eqParam, 'in_array~', new Ast.Value.Array(likeFilters[eqParam]))); } else { otherFilters.push(new Ast.BooleanExpression.Atom(expr.location, eqParam, '=~', likeFilters[eqParam][0])); } } return new Ast.BooleanExpression.Or(expr.location, otherFilters); } if (expr instanceof Ast.NotBooleanExpression) { if (expr.expr instanceof Ast.NotBooleanExpression) // double negation return optimizeFilter(expr.expr.expr); const subexpr = optimizeFilter(expr.expr); if (subexpr.isTrue) return Ast.BooleanExpression.False; if (subexpr.isFalse) return Ast.BooleanExpression.True; return new Ast.BooleanExpression.Not(expr.location, subexpr); } if (expr instanceof Ast.ExternalBooleanExpression) { const subfilter = optimizeFilter(expr.filter); if (subfilter.isFalse) return Ast.BooleanExpression.False; // NOTE: it does not hold that if subfilter is True // the whole expression is true, because the invocation // might return no results! return new Ast.BooleanExpression.External(expr.location, expr.selector, expr.channel, expr.in_params, subfilter, expr.schema); } if (expr instanceof Ast.ExistentialSubqueryBooleanExpression) { return new Ast.BooleanExpression.ExistentialSubquery( expr.location, optimizeExpression(expr.subquery) ); } if (expr instanceof Ast.ComputeBooleanExpression) { const lhs = expr.lhs; const rhs = expr.rhs; const op = expr.operator; // convert to atom filters if possible (easier to deal with as slots) if (lhs instanceof Ast.VarRefValue && !lhs.name.startsWith('__const_')) { return optimizeFilter(new Ast.BooleanExpression.Atom(expr.location, lhs.name, op, rhs)); } if (rhs instanceof Ast.VarRefValue && !rhs.name.startsWith('__const_')) { return optimizeFilter(new Ast.BooleanExpression.Atom(expr.location, rhs.name, flipOperator(op), lhs)); } // check for common equality cases if (lhs.equals(rhs) && (op === '==' || op === '=~' || op === '>=' || op === '<=')) return Ast.BooleanExpression.True; if (lhs.isConstant() && rhs.isConstant() && !lhs.equals(rhs) && op === '==') return Ast.BooleanExpression.False; // put constants on the right side if (lhs.isConstant() && !rhs.isConstant()) { return new Ast.BooleanExpression.Compute(expr.location, rhs, flipOperator(op), lhs); } return expr; } if (expr instanceof Ast.ComparisonSubqueryBooleanExpression) return new Ast.BooleanExpression.ComparisonSubquery(null, expr.lhs, expr.operator, optimizeExpression(expr.rhs)); assert(expr instanceof Ast.AtomBooleanExpression); const lhs = expr.name; const rhs = expr.value; const op = expr.operator; if (rhs instanceof Ast.VarRefValue && rhs.name === lhs) { // x = x , x =~ x , x >= x, x <= x if (op === '==' || op === '=~' || op === '>=' || op === '<=') return Ast.BooleanExpression.True; } return expr; } function compareInputParam(one : Ast.InputParam, two : Ast.InputParam) : -1|0|1 { if (one.name < two.name) return -1; if (two.name < one.name) return 1; return 0; } class UsesParamVisitor extends NodeVisitor { pname : string; used = false; constructor(pname : string) { super(); this.pname = pname; } visitVarRefValue(value : Ast.VarRefValue) { this.used = this.used || value.name === this.pname; return true; } visitAtomBooleanExpressionValue(atom : Ast.AtomBooleanExpression) { this.used = this.used || atom.name === this.pname; return true; } // FIXME this is a bit sloppy in that it doesn't track shadowing // by nested boolean expressions correctly // we cannot do that because we run this code before typechecking } function valueUsesParam(expr : Ast.Value, pname : string) { const visitor = new UsesParamVisitor(pname); expr.visit(visitor); return visitor.used; } function compareProjArg(one : string, two : string) { if (one === two) return 0; if (one === '*') return -1; if (two === '*') return 1; if (one < two) return -1; else return 1; } function optimizeExpression(expression : Ast.Expression, allow_projection=true) : Ast.Expression { if (expression instanceof Ast.FunctionCallExpression) { expression.in_params.sort(compareInputParam); return expression; } if (expression instanceof Ast.InvocationExpression) { expression.invocation.in_params.sort(compareInputParam); return expression; } if (expression instanceof Ast.ProjectionExpression) { let optimized = optimizeExpression(expression.expression, allow_projection); expression.args.sort(compareProjArg); // convert projection-of-chain to chain-of-projection (push the projection // down to the last element) if (optimized instanceof Ast.ChainExpression) { const last = optimized.last; const newProjection = optimizeExpression(new Ast.ProjectionExpression(expression.location, last, expression.args, expression.computations, expression.aliases, expression.schema), allow_projection); optimized.expressions[optimized.expressions.length-1] = newProjection; return optimized; } if (expression.computations.length === 0) { if (expression.args[0] === '*') return optimized; if (!allow_projection) return optimized; if (optimized instanceof Ast.AggregationExpression) return optimized; } // collapse projection of projection // this is quite tricky because of computations if (optimized instanceof Ast.ProjectionExpression) { const ourNames = []; for (let i = 0; i < expression.computations.length; i++) ourNames.push(expression.aliases[i] || getScalarExpressionName(expression.computations[i])); // remove shadowed computations and computations that are not exposed const innerComputations : Ast.Value[] = []; const innerAliases : Array<string|null> = []; const innerNames : string[] = []; const innerArgs = optimized.args; const reusedNames : string[] = []; const reusedComputations : Ast.Value[] = []; const reusedAliases : Array<string|null> = []; for (let i = 0; i < optimized.computations.length; i++) { const name = optimized.aliases[i] || getScalarExpressionName(optimized.computations[i]); // not used in our computations if (expression.computations.some((comp) => valueUsesParam(comp, name))) { reusedNames.push(name); reusedComputations.push(optimized.computations[i]); reusedAliases.push(optimized.aliases[i]); continue; } // not used in another computation and also projected away if (!expression.args.includes(name)) continue; // shadowed if (ourNames.includes(name)) continue; innerNames.push(name); innerComputations.push(optimized.computations[i]); innerAliases.push(optimized.aliases[i]); } // if we're using some of the computations in our computations, // we need to leave the existing computation if (reusedComputations.length > 0) { optimized = new Ast.ProjectionExpression(optimized.location, optimized.expression, ['*'], reusedComputations, reusedAliases, optimized.schema); } else { // else cut the middle man optimized = optimized.expression; } // combine our computations and the inner unrelated computations // remove all of our args that were just picking up the computations expression.args = expression.args.filter((a) => !innerNames.includes(a)); if (expression.args[0] === '*') expression.args = innerArgs.concat(reusedNames); expression.args.sort(compareProjArg); // append the computations expression.computations.push(...innerComputations); expression.aliases.push(...innerAliases); expression.expression = optimized; return expression; } // nope, no optimization here expression.expression = optimized; return expression; } if (expression instanceof Ast.SortExpression) { const optimized = optimizeExpression(expression.expression, allow_projection); // flip sort of a projection to projection of a sort // this takes care of legacy compute tables as well if (optimized instanceof Ast.ProjectionExpression) { const computeNames = []; for (let i = 0; i < optimized.computations.length; i++) computeNames.push(optimized.aliases[i] || getScalarExpressionName(optimized.computations[i])); if (expression.value instanceof Ast.VarRefValue && computeNames.length === 1 && computeNames[0] === expression.value.name) { // yep, we're sorting on the result of this computation expression.value = optimized.computations[0]; } if (computeNames.every((name) => !valueUsesParam(expression.value, name))) { // we're not using the computation, good to flip! return new Ast.ProjectionExpression(optimized.location, new Ast.SortExpression(expression.location, optimized.expression, expression.value, expression.direction, optimized.expression.schema), optimized.args, optimized.computations, optimized.aliases, optimized.schema); } } // nope, no optimization here expression.expression = optimized; return expression; } if (expression instanceof Ast.MonitorExpression) { // always allow projection inside a monitor, because the projection affects which parameters we monitor const optimized = optimizeExpression(expression.expression, true); expression.args?.sort(compareProjArg); // convert monitor of a projection to a projection of a monitor if (optimized instanceof Ast.ProjectionExpression && optimized.computations.length === 0) { const newMonitor = new Ast.MonitorExpression(expression.location, optimized.expression, expression.args || optimized.args, expression.schema); if (allow_projection) return new Ast.ProjectionExpression(expression.location, newMonitor, optimized.args, optimized.computations, optimized.aliases, expression.schema); else return newMonitor; } expression.expression = optimized; return expression; } if (expression instanceof Ast.FilterExpression) { expression.filter = optimizeFilter(expression.filter); // handle constant filters if (expression.filter.isTrue) return optimizeExpression(expression.expression, allow_projection); const inner = optimizeExpression(expression.expression, allow_projection); expression.expression = inner; // compress filter of filter if (inner instanceof Ast.FilterExpression) { expression.filter = optimizeFilter(new Ast.BooleanExpression.And(expression.filter.location, [expression.filter, inner.filter])); expression.expression = inner.expression; return optimizeExpression(expression, allow_projection); } // switch filter of project to project of filter if (inner instanceof Ast.ProjectionExpression && inner.computations.length === 0) { if (allow_projection) { const optimized = optimizeExpression(new Ast.FilterExpression( inner.location, inner.expression, expression.filter, inner.expression.schema), allow_projection); return new Ast.ProjectionExpression( expression.location, optimized, inner.args, [], [], inner.schema ); } else { return optimizeExpression(new Ast.FilterExpression( expression.location, inner.expression, expression.filter, inner.expression.schema ), allow_projection); } } } if (expression instanceof Ast.IndexExpression && expression.indices.length === 1) { const index = expression.indices[0]; if (index instanceof Ast.ArrayValue) expression.indices = index.value; } // turn a slice with a constant limit of 1 to an index if (expression instanceof Ast.SliceExpression && expression.limit instanceof Ast.NumberValue && expression.limit.value === 1) return optimizeExpression(new Ast.IndexExpression(expression.location, expression.expression, [expression.base], expression.expression.schema), allow_projection); // flip index of projection to projection of index if (expression instanceof Ast.IndexExpression) { const optimized = optimizeExpression(expression.expression); if (optimized instanceof Ast.ProjectionExpression) { const inner = optimized.expression; return new Ast.ProjectionExpression(optimized.location, new Ast.IndexExpression(expression.location, inner, expression.indices, inner.schema), optimized.args, optimized.computations, optimized.aliases, optimized.schema); } expression.expression = optimized; return expression; } // same thing but for slice if (expression instanceof Ast.SliceExpression) { const optimized = optimizeExpression(expression.expression); if (optimized instanceof Ast.ProjectionExpression) { const inner = optimized.expression; return new Ast.ProjectionExpression(optimized.location, new Ast.SliceExpression(expression.location, inner, expression.base, expression.limit, inner.schema), optimized.args, optimized.computations, optimized.aliases, optimized.schema); } expression.expression = optimized; return expression; } if (expression instanceof Ast.JoinExpression) { const lhs = optimizeExpression(expression.lhs); const rhs = optimizeExpression(expression.rhs); return new Ast.JoinExpression(expression.location, lhs, rhs, expression.schema); } if (isUnaryExpressionOp(expression)) { const inner = optimizeExpression(expression.expression, allow_projection); expression.expression = inner; return expression; } if (expression instanceof Ast.ChainExpression) { if (expression.expressions.length === 1) return optimizeExpression(expression.expressions[0], allow_projection); // flatten ChainExpressions const newExpressions : Ast.Expression[] = []; for (let i = 0; i < expression.expressions.length; i++) { const optimized = optimizeExpression(expression.expressions[i], allow_projection && i === expression.expressions.length - 1); if (optimized instanceof Ast.ChainExpression) newExpressions.push(...optimized.expressions); else newExpressions.push(optimized); } expression.expressions = newExpressions; } return expression; } function optimizeRule(rule : Ast.ExpressionStatement) : Ast.ExpressionStatement { // in old thingtalk, projection was only allowed when there is no action // but we don't know that at this stage, because we're running before // typechecking, so we don't know if something is an action or not const allow_projection = true; const newExpression = optimizeExpression(rule.expression, allow_projection); if (!(newExpression instanceof Ast.ChainExpression)) rule.expression = new Ast.ChainExpression(newExpression.location, [newExpression], newExpression.schema); else rule.expression = newExpression; return rule; } function optimizeProgram<T extends Ast.Program|Ast.FunctionDeclaration>(program : T) : T { const newDeclarations = []; for (const decl of program.declarations) newDeclarations.push(optimizeProgram(decl)); program.declarations = newDeclarations; const statements : Ast.ExecutableStatement[] = []; program.statements.forEach((stmt) => { if (stmt instanceof Ast.Assignment) { const optimized = optimizeExpression(stmt.value); stmt.value = optimized; statements.push(stmt); } else if (stmt instanceof Ast.ReturnStatement) { const optimized = optimizeExpression(stmt.expression); stmt.expression = optimized; statements.push(stmt); } else { const newrule = optimizeRule(stmt); statements.push(newrule); } }); program.statements = statements; return program; } function optimizeDataset(dataset : Ast.Dataset) : Ast.Dataset { const newExamples = []; for (const ex of dataset.examples) { const optimized = optimizeExpression(ex.value, true); if (!optimized) continue; ex.value = optimized; newExamples.push(ex); } dataset.examples = newExamples; return dataset; } export { optimizeRule, optimizeProgram, optimizeDataset, optimizeFilter };
the_stack
import React, {useCallback} from 'react'; import {fromLonLat} from 'ol/proj'; import IGC from 'ol/format/IGC'; import {getVectorContext} from 'ol/render'; import {Geometry, LineString, Point} from 'ol/geom'; import { RMap, RLayerTile, RLayerVector, RFeature, RenderEvent, MapBrowserEvent, VectorSourceEvent } from 'rlayers'; import {RStyle, RStroke, RFill, RCircle, useRStyle} from 'rlayers/style'; import 'ol/ol.css'; import ClementLatour from '!!file-loader!./data/igc/Clement-Latour.igc'; import DamienDeBaenst from '!!file-loader!./data/igc/Damien-de-Baenst.igc'; import SylvainDhonneur from '!!file-loader!./data/igc/Sylvain-Dhonneur.igc'; import TomPayne from '!!file-loader!./data/igc/Tom-Payne.igc'; import UlrichPrinz from '!!file-loader!./data/igc/Ulrich-Prinz.igc'; type InputFormEventType = React.FormEvent<HTMLInputElement>; const igcsDesc = [ {c: 'rgba(0, 0, 250, 0.7)', i: ClementLatour}, {c: 'rgba(0, 50, 200, 0.7)', i: DamienDeBaenst}, {c: 'rgba(0, 100, 150, 0.7)', i: SylvainDhonneur}, {c: 'rgba(0, 150, 200, 0.7)', i: TomPayne}, {c: 'rgba(0, 200, 50, 0.7)', i: UlrichPrinz} ]; // A constant avoids re-rendering of the component // a property initialized with an anonymous object is not constant // it will recreate a new instance at every evaluation const origin = fromLonLat([6, 45.7]); // This part is re-rendered on every pointermove export default function IGCComp(): JSX.Element { const [time, setTime] = React.useState(''); const [point, setPoint] = React.useState(null as Point); const [line, setLine] = React.useState(null as LineString); const [slider, setSlider] = React.useState(0); const [highlights, setHighlights] = React.useState([]); const [flight, setFlight] = React.useState({ start: Infinity, stop: -Infinity, duration: 0 }); const [igcs, setIgcs] = React.useState(() => { Promise.all(igcsDesc.map((i) => fetch(i.i).then((r) => r.text()))).then((r) => setIgcs(r)); return []; }); const styles = { redCircle: useRStyle(), blueCircle: useRStyle(), // This is a technique for an array of React.RefObjects // It is ugly but it works flightPath: React.useRef([]) as React.RefObject<RStyle[]> }; // createRef instead of useRef here will severely impact performance const igcVectorLayer = React.useRef() as React.RefObject<RLayerVector>; const highlightVectorLayer = React.useRef() as React.RefObject<RLayerVector>; return ( <React.Fragment> {React.useMemo( // This is not a dynamic RStyle, these are 5 static RStyle's // Thus the useMemo () => igcsDesc.map((igc, idx) => ( <RStyle key={idx} ref={(el) => (styles.flightPath.current[idx] = el)}> <RStroke color={igc.c} width={3} /> </RStyle> )), [styles.flightPath] )} <RStyle ref={styles.redCircle}> <RStroke color='red' width={1} /> <RCircle radius={6}> <RFill color='red' /> </RCircle> </RStyle> <RStyle ref={styles.blueCircle}> <RCircle radius={6}> <RFill color='blue' /> </RCircle> </RStyle> <RMap className='example-map' initial={{center: origin, zoom: 9}} onPointerMove={useCallback( (e: MapBrowserEvent<UIEvent>) => { // This useCallback is very important -> without it // onPointerMove will be a new anonymous function on every render const source = igcVectorLayer.current.source; const feature = source.getClosestFeatureToCoordinate(e.coordinate); // Did the user move the mouse before the flight paths were loaded? if (feature === null) return; const point = feature.getGeometry().getClosestPoint(e.coordinate); const date = new Date(point[2] * 1000); setPoint(new Point(point)); setLine(new LineString([e.coordinate, [point[0], point[1]]])); setTime( '<strong>' + feature.get('PLT') + '</strong><br><em>' + date.toUTCString() + '</em>' ); e.map.render(); }, [igcVectorLayer] )} > <RLayerTile zIndex={5} url='https://{a-c}.tile.opentopomap.org/{z}/{x}/{y}.png' attributions='Kartendaten: © OpenStreetMap-Mitwirkende, SRTM | Kartendarstellung: © OpenTopoMap (CC-BY-SA)' /> { // This layer contains the flight paths, we install an `onAddFeature` handler // to receive all features as their loaded to do additional processing } <RLayerVector zIndex={10} ref={igcVectorLayer} onAddFeature={useCallback( // This useCallback transforms this function to a constant value // None of its dependencies change after initialization (e: VectorSourceEvent<Geometry>) => { const geometry = e.feature.getGeometry() as LineString; flight.start = Math.min(flight.start, geometry.getFirstCoordinate()[2]); flight.stop = Math.max(flight.stop, geometry.getLastCoordinate()[2]); flight.duration = flight.stop - flight.start; setFlight({...flight}); }, [flight] )} onPostRender={useCallback( // This useCallback is less efficient than the previous one // as it depends on the state // LayerVector is re-rendered every time point/line change (e: RenderEvent) => { const vectorContext = getVectorContext(e); vectorContext.setStyle(RStyle.getStyleStatic(styles.redCircle)); if (point && line) { vectorContext.drawGeometry(point); vectorContext.drawGeometry(line); } }, [point, line, styles.redCircle] )} > {React.useMemo( () => ( // This component appears dynamic to React because of the map but it is in fact constant // useMemo will render it truly constant <React.Fragment> {igcs.map((igc, idx) => ( <RFeature key={idx} feature={ new IGC().readFeatures(igc, { featureProjection: 'EPSG:3857' })[0] } style={styles.flightPath.current[idx]} /> ))} </React.Fragment> ), // The array trick renders it impossible for React to track the useMemo dependencies // -> we do it manually // eslint-disable-next-line react-hooks/exhaustive-deps [igcs, styles.flightPath, styles.flightPath.current[0]] )} </RLayerVector> { // This layer contains the blue circle (the highlighted section) } <RLayerVector zIndex={10} ref={highlightVectorLayer} style={styles.blueCircle}> {React.useMemo( () => ( // This component appears dynamic to React because of the map but it is in fact constant // useMemo will render it truly constant <React.Fragment> {highlights.map((coords, i) => ( <RFeature key={i} geometry={new Point(coords)} /> ))} </React.Fragment> ), [highlights] )} </RLayerVector> </RMap> <div className='d-flex flex-row mb-3 align-items-center'> <div className='jumbotron py-1 px-3 m-0 me-3 w-50' dangerouslySetInnerHTML={{__html: time}} /> <div className='w-50'> <input type='range' className='range-slider range-slider--primary w-100' min='0' max='100' value={slider} onChange={useCallback( // This useCallback transforms this function to a constant value // None of its dependencies change after initialization // A normal function instead of an arrow lambda allows to access // the context in this function (e: InputFormEventType) { const value = parseInt(e.currentTarget.value); setSlider(value); const source = igcVectorLayer.current.source; const m = flight.start + (flight.duration * value) / 100; const newHighlights = []; source.forEachFeature((feature) => { if (!feature.get('PLT')) return; const geometry = feature.getGeometry() as LineString; const coords = geometry.getCoordinateAtM(m, true); newHighlights.push(coords); }); setHighlights(newHighlights); }, [igcVectorLayer, flight] )} /> </div> </div> </React.Fragment> ); }
the_stack
import { Injectable } from '@angular/core'; import { ConfigurationProvider } from '../config/provider/config.provider'; import { CallbackContext } from '../flows/callback-context'; import { LoggerService } from '../logging/logger.service'; import { StoragePersistenceService } from '../storage/storage-persistence.service'; import { EqualityService } from '../utils/equality/equality.service'; import { FlowHelper } from '../utils/flowHelper/flow-helper.service'; import { TokenHelperService } from '../utils/tokenHelper/token-helper.service'; import { StateValidationResult } from './state-validation-result'; import { TokenValidationService } from './token-validation.service'; import { ValidationResult } from './validation-result'; @Injectable() export class StateValidationService { constructor( private storagePersistenceService: StoragePersistenceService, private tokenValidationService: TokenValidationService, private tokenHelperService: TokenHelperService, private loggerService: LoggerService, private configurationProvider: ConfigurationProvider, private equalityService: EqualityService, private flowHelper: FlowHelper ) {} getValidatedStateResult(callbackContext: CallbackContext, configId: string): StateValidationResult { if (!callbackContext) { return new StateValidationResult('', '', false, {}); } if (callbackContext.authResult.error) { return new StateValidationResult('', '', false, {}); } return this.validateState(callbackContext, configId); } validateState(callbackContext: any, configId: string): StateValidationResult { const toReturn = new StateValidationResult(); const authStateControl = this.storagePersistenceService.read('authStateControl', configId); if (!this.tokenValidationService.validateStateFromHashCallback(callbackContext.authResult.state, authStateControl, configId)) { this.loggerService.logWarning(configId, 'authCallback incorrect state'); toReturn.state = ValidationResult.StatesDoNotMatch; this.handleUnsuccessfulValidation(configId); return toReturn; } const isCurrentFlowImplicitFlowWithAccessToken = this.flowHelper.isCurrentFlowImplicitFlowWithAccessToken(configId); const isCurrentFlowCodeFlow = this.flowHelper.isCurrentFlowCodeFlow(configId); if (isCurrentFlowImplicitFlowWithAccessToken || isCurrentFlowCodeFlow) { toReturn.accessToken = callbackContext.authResult.access_token; } if (callbackContext.authResult.id_token) { const { clientId, issValidationOff, maxIdTokenIatOffsetAllowedInSeconds, disableIatOffsetValidation, ignoreNonceAfterRefresh } = this.configurationProvider.getOpenIDConfiguration(configId); toReturn.idToken = callbackContext.authResult.id_token; toReturn.decodedIdToken = this.tokenHelperService.getPayloadFromToken(toReturn.idToken, false, configId); if (!this.tokenValidationService.validateSignatureIdToken(toReturn.idToken, callbackContext.jwtKeys, configId)) { this.loggerService.logDebug(configId, 'authCallback Signature validation failed id_token'); toReturn.state = ValidationResult.SignatureFailed; this.handleUnsuccessfulValidation(configId); return toReturn; } const authNonce = this.storagePersistenceService.read('authNonce', configId); if (!this.tokenValidationService.validateIdTokenNonce(toReturn.decodedIdToken, authNonce, ignoreNonceAfterRefresh, configId)) { this.loggerService.logWarning(configId, 'authCallback incorrect nonce'); toReturn.state = ValidationResult.IncorrectNonce; this.handleUnsuccessfulValidation(configId); return toReturn; } if (!this.tokenValidationService.validateRequiredIdToken(toReturn.decodedIdToken, configId)) { this.loggerService.logDebug(configId, 'authCallback Validation, one of the REQUIRED properties missing from id_token'); toReturn.state = ValidationResult.RequiredPropertyMissing; this.handleUnsuccessfulValidation(configId); return toReturn; } if ( !this.tokenValidationService.validateIdTokenIatMaxOffset( toReturn.decodedIdToken, maxIdTokenIatOffsetAllowedInSeconds, disableIatOffsetValidation, configId ) ) { this.loggerService.logWarning( configId, 'authCallback Validation, iat rejected id_token was issued too far away from the current time' ); toReturn.state = ValidationResult.MaxOffsetExpired; this.handleUnsuccessfulValidation(configId); return toReturn; } const authWellKnownEndPoints = this.storagePersistenceService.read('authWellKnownEndPoints', configId); if (authWellKnownEndPoints) { if (issValidationOff) { this.loggerService.logDebug(configId, 'iss validation is turned off, this is not recommended!'); } else if ( !issValidationOff && !this.tokenValidationService.validateIdTokenIss(toReturn.decodedIdToken, authWellKnownEndPoints.issuer, configId) ) { this.loggerService.logWarning(configId, 'authCallback incorrect iss does not match authWellKnownEndpoints issuer'); toReturn.state = ValidationResult.IssDoesNotMatchIssuer; this.handleUnsuccessfulValidation(configId); return toReturn; } } else { this.loggerService.logWarning(configId, 'authWellKnownEndpoints is undefined'); toReturn.state = ValidationResult.NoAuthWellKnownEndPoints; this.handleUnsuccessfulValidation(configId); return toReturn; } if (!this.tokenValidationService.validateIdTokenAud(toReturn.decodedIdToken, clientId, configId)) { this.loggerService.logWarning(configId, 'authCallback incorrect aud'); toReturn.state = ValidationResult.IncorrectAud; this.handleUnsuccessfulValidation(configId); return toReturn; } if (!this.tokenValidationService.validateIdTokenAzpExistsIfMoreThanOneAud(toReturn.decodedIdToken)) { this.loggerService.logWarning(configId, 'authCallback missing azp'); toReturn.state = ValidationResult.IncorrectAzp; this.handleUnsuccessfulValidation(configId); return toReturn; } if (!this.tokenValidationService.validateIdTokenAzpValid(toReturn.decodedIdToken, clientId)) { this.loggerService.logWarning(configId, 'authCallback incorrect azp'); toReturn.state = ValidationResult.IncorrectAzp; this.handleUnsuccessfulValidation(configId); return toReturn; } if (!this.isIdTokenAfterRefreshTokenRequestValid(callbackContext, toReturn.decodedIdToken, configId)) { this.loggerService.logWarning(configId, 'authCallback pre, post id_token claims do not match in refresh'); toReturn.state = ValidationResult.IncorrectIdTokenClaimsAfterRefresh; this.handleUnsuccessfulValidation(configId); return toReturn; } if (!this.tokenValidationService.validateIdTokenExpNotExpired(toReturn.decodedIdToken, configId)) { this.loggerService.logWarning(configId, 'authCallback id token expired'); toReturn.state = ValidationResult.TokenExpired; this.handleUnsuccessfulValidation(configId); return toReturn; } } else { this.loggerService.logDebug(configId, 'No id_token found, skipping id_token validation'); } // flow id_token if (!isCurrentFlowImplicitFlowWithAccessToken && !isCurrentFlowCodeFlow) { toReturn.authResponseIsValid = true; toReturn.state = ValidationResult.Ok; this.handleSuccessfulValidation(configId); this.handleUnsuccessfulValidation(configId); return toReturn; } // only do check if id_token returned, no always the case when using refresh tokens if (callbackContext.authResult.id_token) { const idTokenHeader = this.tokenHelperService.getHeaderFromToken(toReturn.idToken, false, configId); // The at_hash is optional for the code flow if (isCurrentFlowCodeFlow && !(toReturn.decodedIdToken.at_hash as string)) { this.loggerService.logDebug(configId, 'Code Flow active, and no at_hash in the id_token, skipping check!'); } else if ( !this.tokenValidationService.validateIdTokenAtHash( toReturn.accessToken, toReturn.decodedIdToken.at_hash, idTokenHeader.alg, // 'RSA256' configId ) || !toReturn.accessToken ) { this.loggerService.logWarning(configId, 'authCallback incorrect at_hash'); toReturn.state = ValidationResult.IncorrectAtHash; this.handleUnsuccessfulValidation(configId); return toReturn; } } toReturn.authResponseIsValid = true; toReturn.state = ValidationResult.Ok; this.handleSuccessfulValidation(configId); return toReturn; } private isIdTokenAfterRefreshTokenRequestValid(callbackContext: CallbackContext, newIdToken: any, configId: string): boolean { const { useRefreshToken, disableRefreshIdTokenAuthTimeValidation } = this.configurationProvider.getOpenIDConfiguration(configId); if (!useRefreshToken) { return true; } if (!callbackContext.existingIdToken) { return true; } const decodedIdToken = this.tokenHelperService.getPayloadFromToken(callbackContext.existingIdToken, false, configId); // Upon successful validation of the Refresh Token, the response body is the Token Response of Section 3.1.3.3 // except that it might not contain an id_token. // If an ID Token is returned as a result of a token refresh request, the following requirements apply: // its iss Claim Value MUST be the same as in the ID Token issued when the original authentication occurred, if (decodedIdToken.iss !== newIdToken.iss) { this.loggerService.logDebug(configId, `iss do not match: ${decodedIdToken.iss} ${newIdToken.iss}`); return false; } // its azp Claim Value MUST be the same as in the ID Token issued when the original authentication occurred; // if no azp Claim was present in the original ID Token, one MUST NOT be present in the new ID Token, and // otherwise, the same rules apply as apply when issuing an ID Token at the time of the original authentication. if (decodedIdToken.azp !== newIdToken.azp) { this.loggerService.logDebug(configId, `azp do not match: ${decodedIdToken.azp} ${newIdToken.azp}`); return false; } // its sub Claim Value MUST be the same as in the ID Token issued when the original authentication occurred, if (decodedIdToken.sub !== newIdToken.sub) { this.loggerService.logDebug(configId, `sub do not match: ${decodedIdToken.sub} ${newIdToken.sub}`); return false; } // its aud Claim Value MUST be the same as in the ID Token issued when the original authentication occurred, if (!this.equalityService.isStringEqualOrNonOrderedArrayEqual(decodedIdToken?.aud, newIdToken?.aud)) { this.loggerService.logDebug(configId, `aud in new id_token is not valid: '${decodedIdToken?.aud}' '${newIdToken.aud}'`); return false; } if (disableRefreshIdTokenAuthTimeValidation) { return true; } // its iat Claim MUST represent the time that the new ID Token is issued, // if the ID Token contains an auth_time Claim, its value MUST represent the time of the original authentication // - not the time that the new ID token is issued, if (decodedIdToken.auth_time !== newIdToken.auth_time) { this.loggerService.logDebug(configId, `auth_time do not match: ${decodedIdToken.auth_time} ${newIdToken.auth_time}`); return false; } return true; } private handleSuccessfulValidation(configId: string): void { const { autoCleanStateAfterAuthentication } = this.configurationProvider.getOpenIDConfiguration(configId); this.storagePersistenceService.write('authNonce', null, configId); if (autoCleanStateAfterAuthentication) { this.storagePersistenceService.write('authStateControl', '', configId); } this.loggerService.logDebug(configId, 'authCallback token(s) validated, continue'); } private handleUnsuccessfulValidation(configId: string): void { const { autoCleanStateAfterAuthentication } = this.configurationProvider.getOpenIDConfiguration(configId); this.storagePersistenceService.write('authNonce', null, configId); if (autoCleanStateAfterAuthentication) { this.storagePersistenceService.write('authStateControl', '', configId); } this.loggerService.logDebug(configId, 'authCallback token(s) invalid'); } }
the_stack
import { LatLng, LatLngBounds, LeafletMouseEvent, Map, Point } from "leaflet"; import { Feature, FeatureCollection, LineString } from "geojson"; import { MapMatrix } from "./map-matrix"; import { ICanvasOverlayDrawEvent } from "./canvas-overlay"; import { ILinesSettings, Lines, WeightCallback } from "./lines"; jest.mock("./canvas-overlay"); jest.mock("./utils", () => { return { inBounds: () => true, latLngDistance: () => 2, }; }); const mockFeatureCollection: FeatureCollection<LineString> = { type: "FeatureCollection", features: [ { type: "Feature", properties: {}, geometry: { type: "LineString", coordinates: [ [1, 2], [3, 4], [5, 6], ], }, }, ], }; function getSettings( settings?: Partial<ILinesSettings> ): Partial<ILinesSettings> { const element = document.createElement("div"); const map = new Map(element); return { map, data: mockFeatureCollection, vertexShaderSource: " ", fragmentShaderSource: " ", latitudeKey: 0, longitudeKey: 1, color: { r: 3, g: 4, b: 5, a: 6 }, ...settings, }; } describe("Lines", () => { describe("weight", () => { describe("when settings.weight is falsey", () => { it("throws", () => { const settings = getSettings({ weight: 0 }); let weight: WeightCallback | number | null = null; expect(() => { weight = new Lines(settings).weight; }).toThrow(); expect(weight).toBeNull(); }); }); describe("when settings.weight is truthy", () => { expect(new Lines(getSettings()).weight).toBe(Lines.defaults.weight); }); }); describe("constructor", () => { let element: HTMLElement; let map: Map; let data: FeatureCollection<LineString>; let settings: Partial<ILinesSettings>; let setupSpy: jest.SpyInstance; let renderSpy: jest.SpyInstance; beforeEach(() => { element = document.createElement("div"); map = new Map(element); data = { type: "FeatureCollection", features: [], }; settings = { className: "lines-class", map, data, vertexShaderSource: " ", fragmentShaderSource: " ", latitudeKey: 0, longitudeKey: 1, }; setupSpy = jest.spyOn(Lines.prototype, "setup"); renderSpy = jest.spyOn(Lines.prototype, "render"); }); afterEach(() => { setupSpy.mockRestore(); renderSpy.mockRestore(); }); it("sets this.settings", () => { const lines = new Lines(settings); expect(lines.settings).toEqual({ ...Lines.defaults, ...settings }); }); describe("when missing settings.data", () => { it("throws", () => { delete settings.data; let lines: Lines | null = null; expect(() => { lines = new Lines(settings); }).toThrow('"data" is missing'); expect(lines).toBeNull(); }); }); it("sets this.active to true", () => { const lines = new Lines(settings); expect(lines.active).toBe(true); }); it("calls this.setup and this.render", () => { const lines = new Lines(settings); expect(lines).toBeInstanceOf(Lines); expect(setupSpy).toHaveBeenCalled(); expect(renderSpy).toHaveBeenCalled(); }); }); describe("render", () => { let element: HTMLElement; let map: Map; let data: FeatureCollection<LineString>; let settings: Partial<ILinesSettings>; let resetVerticesSpy: jest.SpyInstance; let getBufferSpy: jest.SpyInstance; let getAttributeLocationSpy: jest.SpyInstance; beforeEach(() => { element = document.createElement("div"); map = new Map(element); data = { type: "FeatureCollection", features: [], }; settings = { className: "lines-class", color: { r: 3, g: 4, b: 5, a: 6 }, // these should be between 0 and 1, but for the same of the test map, data, vertexShaderSource: " ", fragmentShaderSource: " ", latitudeKey: 0, longitudeKey: 1, }; resetVerticesSpy = jest.spyOn(Lines.prototype, "resetVertices"); getBufferSpy = jest.spyOn(Lines.prototype, "getBuffer"); getAttributeLocationSpy = jest.spyOn( Lines.prototype, "getAttributeLocation" ); }); afterEach(() => { resetVerticesSpy.mockRestore(); getBufferSpy.mockRestore(); getAttributeLocationSpy.mockRestore(); }); it("calls this.resetVertices()", () => { const lines = new Lines(settings); resetVerticesSpy.mockReset(); lines.render(); expect(resetVerticesSpy).toHaveBeenCalled(); }); it("calls gl.bindBuffer correctly", () => { const lines = new Lines(settings); const vertexBuffer = new WebGLBuffer(); getBufferSpy.mockReturnValue(vertexBuffer); const bindBufferSpy = jest.spyOn(lines.gl, "bindBuffer"); lines.render(); expect(bindBufferSpy).toHaveBeenCalledWith( lines.gl.ARRAY_BUFFER, vertexBuffer ); }); it("calls gl.bufferData correctly", () => { const lines = new Lines({ ...settings, data: mockFeatureCollection, }); const { gl } = lines; const bufferDataSpy = jest.spyOn(gl, "bufferData"); lines.render(); expect(bufferDataSpy).toHaveBeenCalledWith( gl.ARRAY_BUFFER, lines.allVerticesTyped, gl.STATIC_DRAW ); }); it("calls gl.vertexAttribPointer correctly", () => { const lines = new Lines(settings); const { gl } = lines; jest.spyOn(lines, "getAttributeLocation").mockReturnValue(42); const vertexAttribPointerSpy = jest.spyOn(gl, "vertexAttribPointer"); lines.render(); expect(vertexAttribPointerSpy).toHaveBeenCalledWith( 42, 2, gl.FLOAT, false, 24, 0 ); }); it("calls gl.enableVertexAttribArray correctly", () => { const lines = new Lines(settings); getAttributeLocationSpy.mockReturnValue(42); const enableVertexAttribArraySpy = jest.spyOn( lines.gl, "enableVertexAttribArray" ); lines.render(); expect(enableVertexAttribArraySpy).toHaveBeenCalledWith(42); }); it("calls mapMatrix.setSize() correctly", () => { const lines = new Lines(settings); const mapMatrix = (lines.mapMatrix = new MapMatrix()); const setSizeSpy = jest.spyOn(mapMatrix, "setSize"); lines.render(); expect(setSizeSpy).toHaveBeenCalledWith( lines.canvas.width, lines.canvas.height ); }); it("calls gl.viewport() correctly", () => { const lines = new Lines(settings); const { gl } = lines; const viewportSpy = jest.spyOn(gl, "viewport"); lines.render(); expect(viewportSpy).toHaveBeenCalledWith( 0, 0, lines.canvas.width, lines.canvas.height ); }); it("calls gl.uniformMatrix4fv() correctly", () => { const lines = new Lines(settings); const { gl } = lines; const uniformMatrix4fvSpy = jest.spyOn(gl, "uniformMatrix4fv"); lines.render(); expect(uniformMatrix4fvSpy).toHaveBeenCalledWith( lines.matrix, false, lines.mapMatrix.array ); }); it("calls this.attachShaderVariables() correctly", () => { const lines = new Lines(settings); const attachShaderVariablesSpy = jest.spyOn( lines, "attachShaderVariables" ); lines.render(); expect(attachShaderVariablesSpy).toHaveBeenCalledWith(4); }); it("calls layer.redraw()", () => { const lines = new Lines(settings); const redrawSpy = jest.spyOn(lines.layer, "redraw"); lines.render(); expect(redrawSpy).toHaveBeenCalled(); }); }); describe("resetVertices", () => { describe("when settings.color is a function", () => { it("is called with index and feature", () => { const lines = new Lines( getSettings({ color: jest.fn(() => { return { r: 1, g: 1, b: 1, a: 1 }; }), }) ); lines.resetVertices(); expect(lines.color).toHaveBeenCalledWith(0, lines.data.features[0]); }); }); it("accumulates this.vertices, this.allVertices and this.allVerticesTyped correctly", () => { const lines = new Lines(getSettings()); jest.spyOn(lines.map, "project").mockReturnValue(new Point(1, 2)); lines.resetVertices(); const expected = [ 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, ]; const expectedVerticesArray = [ 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, ]; expect(lines.vertices.length).toBe(1); expect(lines.vertices[0].array).toEqual(expectedVerticesArray); expect(lines.vertices[0].settings.longitudeKey).toEqual( lines.longitudeKey ); expect(lines.vertices[0].settings.latitudeKey).toEqual(lines.latitudeKey); expect(lines.vertices[0].settings.color).toEqual(lines.settings.color); expect(lines.vertices[0].settings.opacity).toEqual( lines.settings.opacity ); expect(lines.allVertices).toEqual(expected); expect(lines.allVerticesTyped).toEqual(new Float32Array(expected)); }); }); describe("drawOnCanvas", () => { function callDrawOnCanvas( lines: Lines, event?: Partial<ICanvasOverlayDrawEvent> ): void { lines.drawOnCanvas({ canvas: lines.canvas, bounds: new LatLngBounds(new LatLng(1, 1), new LatLng(2, 2)), offset: new Point(1, 1), scale: 1, size: new Point(10, 10), zoomScale: 1, zoom: 1, ...event, }); } it("calls gl.clear() correctly", () => { const lines = new Lines(getSettings()); const { gl } = lines; const clearSpy = jest.spyOn(gl, "clear"); callDrawOnCanvas(lines); expect(clearSpy).toHaveBeenCalledWith(gl.COLOR_BUFFER_BIT); }); it("calls gl.viewport() correctly", () => { const lines = new Lines(getSettings()); const { gl } = lines; const viewportSpy = jest.spyOn(gl, "viewport"); callDrawOnCanvas(lines); expect(viewportSpy).toHaveBeenCalledWith( 0, 0, lines.canvas.width, lines.canvas.height ); }); it("calls gl.vertexAttrib1f() correctly", () => { const lines = new Lines(getSettings()); const { gl } = lines; const vertexAttrib1fSpy = jest.spyOn(gl, "vertexAttrib1f"); callDrawOnCanvas(lines); expect(vertexAttrib1fSpy).toHaveBeenCalledWith(lines.aPointSize, 4); }); it("calls mapMatrix.setSize and mapMatrix.scaleMatrix correctly", () => { const lines = new Lines(getSettings()); const setSizeSpy = jest.spyOn(lines.mapMatrix, "setSize"); const scaleMatrixSpy = jest.spyOn(lines.mapMatrix, "scaleTo"); callDrawOnCanvas(lines); expect(setSizeSpy).toHaveBeenCalledWith( lines.canvas.width, lines.canvas.height ); expect(scaleMatrixSpy).toHaveBeenCalledWith(1); }); describe("when zoom is greater than 18", () => { it("draws arrays once", () => { const lines = new Lines(getSettings()); const uniformMatrix4fvSpy = jest.spyOn(lines.gl, "uniformMatrix4fv"); const drawArraysSpy = jest.spyOn(lines.gl, "drawArrays"); const setSizeSpy = jest.spyOn(lines.mapMatrix, "setSize"); const scaleToSpy = jest.spyOn(lines.mapMatrix, "scaleTo"); const translateToSpy = jest.spyOn(lines.mapMatrix, "translateTo"); const offset = new Point(5, 5); const zoom = 19; callDrawOnCanvas(lines, { zoom, offset }); expect(setSizeSpy).toHaveBeenCalledTimes(1); expect(setSizeSpy).toHaveBeenCalledWith( lines.canvas.width, lines.canvas.height ); expect(scaleToSpy).toHaveBeenCalledTimes(1); expect(scaleToSpy).toHaveBeenCalledWith(1); expect(translateToSpy).toHaveBeenCalledTimes(1); expect(translateToSpy).toHaveBeenCalledWith(-offset.x, -offset.y); expect(uniformMatrix4fvSpy).toHaveBeenCalledWith( lines.matrix, false, lines.mapMatrix.array ); expect(drawArraysSpy).toHaveBeenCalledWith(lines.gl.LINES, 0, 4); }); }); describe("when zoom is less than 19", () => { describe("when weight is a number", () => { it("draws arrays using weight", () => { const lines = new Lines({ ...getSettings(), weight: 1 }); const uniformMatrix4fvSpy = jest.spyOn(lines.gl, "uniformMatrix4fv"); const drawArraysSpy = jest.spyOn(lines.gl, "drawArrays"); const setSizeSpy = jest.spyOn(lines.mapMatrix, "setSize"); const scaleToSpy = jest.spyOn(lines.mapMatrix, "scaleTo"); const translateToSpy = jest.spyOn(lines.mapMatrix, "translateTo"); const offset = new Point(5, 5); const zoom = 18; callDrawOnCanvas(lines, { zoom, offset }); expect(setSizeSpy).toHaveBeenCalledTimes(1); expect(setSizeSpy).toHaveBeenCalledWith( lines.canvas.width, lines.canvas.height ); expect(scaleToSpy).toHaveBeenCalledTimes(1); expect(scaleToSpy).toHaveBeenCalledWith(1); expect(translateToSpy).toHaveBeenCalledTimes(25); expect(translateToSpy).toHaveBeenCalledWith(-offset.x, -offset.y); expect(uniformMatrix4fvSpy).toHaveBeenCalledWith( lines.matrix, false, lines.mapMatrix.array ); expect(drawArraysSpy).toHaveBeenCalledWith(lines.gl.LINES, 0, 4); }); }); describe("when weight is a function", () => { it("draws arrays using weight function", () => { const lines = new Lines({ ...getSettings(), weight: (i: number, feature: LineString): number => { return 2; }, }); const uniformMatrix4fvSpy = jest.spyOn(lines.gl, "uniformMatrix4fv"); const drawArraysSpy = jest.spyOn(lines.gl, "drawArrays"); const setSizeSpy = jest.spyOn(lines.mapMatrix, "setSize"); const scaleToSpy = jest.spyOn(lines.mapMatrix, "scaleTo"); const translateToSpy = jest.spyOn(lines.mapMatrix, "translateTo"); const offset = new Point(5, 5); const zoom = 18; callDrawOnCanvas(lines, { zoom, offset }); expect(setSizeSpy).toHaveBeenCalledTimes(1); expect(setSizeSpy).toHaveBeenCalledWith( lines.canvas.width, lines.canvas.height ); expect(scaleToSpy).toHaveBeenCalledTimes(1); expect(scaleToSpy).toHaveBeenCalledWith(1); expect(translateToSpy).toHaveBeenCalledTimes(81); expect(translateToSpy).toHaveBeenCalledWith(-offset.x, -offset.y); expect(uniformMatrix4fvSpy).toHaveBeenCalledWith( lines.matrix, false, lines.mapMatrix.array ); expect(drawArraysSpy).toHaveBeenCalledWith(lines.gl.LINES, 0, 4); }); }); }); }); describe("tryClick", () => { let lines: Lines; let settings: Partial<ILinesSettings>; let map: Map; let mockClick: LeafletMouseEvent; let forEachSpy: jest.SpyInstance; beforeEach(() => { settings = getSettings({ click: jest.fn(() => { return true; }), }); lines = new Lines(settings); lines.scale = 1; map = lines.map; forEachSpy = jest.spyOn(lines.data.features, "forEach"); const latlngArray = mockFeatureCollection.features[0].geometry.coordinates[0]; const latlng = new LatLng(latlngArray[0], latlngArray[1]); mockClick = { type: "click", target: map, sourceTarget: map, propagatedFrom: "mock", layer: lines, latlng, layerPoint: new Point(1, 1), containerPoint: new Point(1, 1), originalEvent: new MouseEvent("click"), }; }); afterEach(() => { forEachSpy.mockRestore(); }); describe("when layer has been removed", () => { it("is not checked for click", () => { lines.remove(); Lines.tryClick(mockClick, map, [lines]); expect(forEachSpy).not.toHaveBeenCalled(); }); }); describe("when map is not same as instance.map", () => { it("is not checked for click", () => { Lines.tryClick(mockClick, new Map(document.createElement("div")), [ lines, ]); expect(forEachSpy).not.toHaveBeenCalled(); }); }); describe("when map is same", () => { it("is checked for click", () => { Lines.tryClick(mockClick, lines.map, [lines]); expect(forEachSpy).toHaveBeenCalled(); }); describe("when a feature is near point", () => { it("calls settings.click", () => { Lines.tryClick(mockClick, lines.map, [lines]); expect(lines.settings.click).toHaveBeenCalledWith( mockClick, lines.data.features[0] ); }); it("returns the response from settings.click", () => { const result = Lines.tryClick(mockClick, lines.map, [lines]); expect(result).toBe(true); }); }); describe("when a feature is not near point", () => { // distance = 2 // sensitivity = 0.1 // weight = 2 // distance < sensitivity + weight / scale // 2 < 0.01 + 2 / 1 // 2 < 0.01 + 2 / 1 (2.01) it("does not call settings.click", () => { lines.settings.sensitivity = -0.01; Lines.tryClick(mockClick, lines.map, [lines]); expect(lines.settings.click).not.toHaveBeenCalled(); }); }); }); }); describe("tryHover", () => { let lines: Lines; let settings: Partial<ILinesSettings>; let map: Map; let mockHover: LeafletMouseEvent; let forEachSpy: jest.SpyInstance; let hoverMock: jest.Mock; beforeEach(() => { hoverMock = jest.fn(() => { return true; }); settings = getSettings({ hover: hoverMock, }); lines = new Lines(settings); lines.scale = 1; map = lines.map; forEachSpy = jest.spyOn(lines.data.features, "forEach"); const latlngArray = mockFeatureCollection.features[0].geometry.coordinates[0]; const latlng = new LatLng(latlngArray[0], latlngArray[1]); mockHover = { type: "mousemove", target: map, sourceTarget: map, propagatedFrom: "mock", layer: lines, latlng, layerPoint: new Point(1, 1), containerPoint: new Point(1, 1), originalEvent: new MouseEvent("mousemove"), }; }); afterEach(() => { forEachSpy.mockRestore(); }); describe("when layer has been removed", () => { it("is not checked for hover", () => { lines.remove(); Lines.tryHover(mockHover, map, [lines]); expect(forEachSpy).not.toHaveBeenCalled(); }); }); describe("when map is not same as instance.map", () => { it("is not checked for hover", () => { Lines.tryHover(mockHover, new Map(document.createElement("div")), [ lines, ]); expect(forEachSpy).not.toHaveBeenCalled(); }); }); describe("when map is same", () => { it("is checked for hover", () => { Lines.tryHover(mockHover, lines.map, [lines]); expect(forEachSpy).toHaveBeenCalled(); }); describe("when a feature is near point", () => { describe("when lines.hoverFeatures does not contain the feature being hovered", () => { it("it is added a new array in lines.hoveringFeatures", () => { const oldHoveringFeatures = lines.hoveringFeatures; expect(oldHoveringFeatures).toEqual([]); Lines.tryHover(mockHover, lines.map, [lines]); const newHoveringFeatures = lines.hoveringFeatures; expect(oldHoveringFeatures).not.toBe(newHoveringFeatures); expect(newHoveringFeatures).toEqual([lines.data.features[0]]); }); it("calls settings.hover", () => { Lines.tryHover(mockHover, lines.map, [lines]); expect(hoverMock).toHaveBeenCalledWith( mockHover, lines.data.features[0] ); }); }); describe("when a feature is not near point", () => { // distance = 2 // sensitivityHover = 0.1 // weight = 2 // distance < sensitivityHover + weight / scale // 2 < 0.01 + 2 / 1 // 2 < 0.01 + 2 / 1 (2.01) it("does not call settings.hover", () => { lines.settings.sensitivityHover = -0.01; Lines.tryHover(mockHover, lines.map, [lines]); expect(lines.settings.hover).not.toHaveBeenCalled(); }); }); describe("when lines.hoverFeatures does contain the feature being hovered", () => { it("it is added a new array in lines.hoveringFeatures", () => { Lines.tryHover(mockHover, lines.map, [lines]); const oldHoveringFeatures = lines.hoveringFeatures; expect(oldHoveringFeatures).toEqual([lines.data.features[0]]); Lines.tryHover(mockHover, lines.map, [lines]); const newHoveringFeatures = lines.hoveringFeatures; expect(oldHoveringFeatures).not.toBe(newHoveringFeatures); expect(newHoveringFeatures).toEqual([lines.data.features[0]]); }); it("does not calls settings.hover", () => { Lines.tryHover(mockHover, lines.map, [lines]); hoverMock.mockReset(); Lines.tryHover(mockHover, lines.map, [lines]); expect(hoverMock).not.toHaveBeenCalled(); }); }); it("returns the responses from settings.hover", () => { const result = Lines.tryHover(mockHover, lines.map, [lines]); expect(result).toEqual([true]); }); }); describe("when a feature is no longer hovered", () => { it("the instance.hoverOff is called with event and feature", () => { const fakeFeature: Feature<LineString> = { type: "Feature", properties: {}, geometry: { type: "LineString", coordinates: [[5, 6]], }, }; lines.hoveringFeatures.push(fakeFeature); const hoverOff = (lines.settings.hoverOff = jest.fn(() => {})); Lines.tryHover(mockHover, lines.map, [lines]); expect(hoverOff).toHaveBeenCalledWith(mockHover, fakeFeature); }); }); }); }); });
the_stack
* @category pipeline */ import { ccclass, displayOrder, type, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { builtinResMgr } from '../../builtin/builtin-res-mgr'; import { Texture2D } from '../../assets/texture-2d'; import { RenderPipeline, IRenderPipelineInfo, PipelineRenderData, PipelineInputAssemblerData } from '../render-pipeline'; import { MainFlow } from './main-flow'; import { RenderTextureConfig } from '../pipeline-serialization'; import { ShadowFlow } from '../shadow/shadow-flow'; import { Format, StoreOp, ColorAttachment, DepthStencilAttachment, RenderPass, LoadOp, RenderPassInfo, Texture, AccessType, Framebuffer, TextureInfo, TextureType, TextureUsageBit, FramebufferInfo, Swapchain } from '../../gfx'; import { UBOGlobal, UBOCamera, UBOShadow, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING } from '../define'; import { Camera } from '../../renderer/scene'; import { errorID } from '../../platform/debug'; import { DeferredPipelineSceneData } from './deferred-pipeline-scene-data'; import { PipelineEventType } from '../pipeline-event'; const PIPELINE_TYPE = 1; export class DeferredRenderData extends PipelineRenderData { gbufferFrameBuffer: Framebuffer = null!; gbufferRenderTargets: Texture[] = []; } /** * @en The deferred render pipeline * @zh 延迟渲染管线。 */ @ccclass('DeferredPipeline') export class DeferredPipeline extends RenderPipeline { private _gbufferRenderPass: RenderPass | null = null; private _lightingRenderPass: RenderPass | null = null; @type([RenderTextureConfig]) @serializable @displayOrder(2) protected renderTextures: RenderTextureConfig[] = []; public initialize (info: IRenderPipelineInfo): boolean { super.initialize(info); if (this._flows.length === 0) { const shadowFlow = new ShadowFlow(); shadowFlow.initialize(ShadowFlow.initInfo); this._flows.push(shadowFlow); const mainFlow = new MainFlow(); mainFlow.initialize(MainFlow.initInfo); this._flows.push(mainFlow); } return true; } public activate (swapchain: Swapchain): boolean { if (EDITOR) { console.info('Deferred render pipeline initialized. ' + 'Note that non-transparent materials with no lighting will not be rendered, such as builtin-unlit.'); } this._macros = { CC_PIPELINE_TYPE: PIPELINE_TYPE }; this._pipelineSceneData = new DeferredPipelineSceneData(); if (!super.activate(swapchain)) { return false; } if (!this._activeRenderer(swapchain)) { errorID(2402); return false; } return true; } public destroy () { this._destroyUBOs(); this._destroyQuadInputAssembler(); this._destroyDeferredData(); const rpIter = this._renderPasses.values(); let rpRes = rpIter.next(); while (!rpRes.done) { rpRes.value.destroy(); rpRes = rpIter.next(); } this._commandBuffers.length = 0; return super.destroy(); } public getPipelineRenderData (): DeferredRenderData { if (!this._pipelineRenderData) { this._generateDeferredRenderData(); } return this._pipelineRenderData as DeferredRenderData; } private _activeRenderer (swapchain: Swapchain) { const device = this.device; this._commandBuffers.push(device.commandBuffer); const sampler = this.globalDSManager.pointSampler; this._descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, sampler); this._descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get<Texture2D>('default-texture').getGFXTexture()!); this._descriptorSet.bindSampler(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, sampler); this._descriptorSet.bindTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, builtinResMgr.get<Texture2D>('default-texture').getGFXTexture()!); this._descriptorSet.update(); let inputAssemblerDataOffscreen = new PipelineInputAssemblerData(); inputAssemblerDataOffscreen = this._createQuadInputAssembler(); if (!inputAssemblerDataOffscreen.quadIB || !inputAssemblerDataOffscreen.quadVB || !inputAssemblerDataOffscreen.quadIA) { return false; } this._quadIB = inputAssemblerDataOffscreen.quadIB; this._quadVBOffscreen = inputAssemblerDataOffscreen.quadVB; this._quadIAOffscreen = inputAssemblerDataOffscreen.quadIA; const inputAssemblerDataOnscreen = this._createQuadInputAssembler(); if (!inputAssemblerDataOnscreen.quadIB || !inputAssemblerDataOnscreen.quadVB || !inputAssemblerDataOnscreen.quadIA) { return false; } this._quadVBOnscreen = inputAssemblerDataOnscreen.quadVB; this._quadIAOnscreen = inputAssemblerDataOnscreen.quadIA; if (!this._gbufferRenderPass) { const colorAttachment0 = new ColorAttachment(); colorAttachment0.format = Format.RGBA16F; colorAttachment0.loadOp = LoadOp.CLEAR; // should clear color attachment colorAttachment0.storeOp = StoreOp.STORE; const colorAttachment1 = new ColorAttachment(); colorAttachment1.format = Format.RGBA16F; colorAttachment1.loadOp = LoadOp.CLEAR; // should clear color attachment colorAttachment1.storeOp = StoreOp.STORE; const colorAttachment2 = new ColorAttachment(); colorAttachment2.format = Format.RGBA16F; colorAttachment2.loadOp = LoadOp.CLEAR; // should clear color attachment colorAttachment2.storeOp = StoreOp.STORE; const colorAttachment3 = new ColorAttachment(); colorAttachment3.format = Format.RGBA16F; colorAttachment3.loadOp = LoadOp.CLEAR; // should clear color attachment colorAttachment3.storeOp = StoreOp.STORE; const depthStencilAttachment = new DepthStencilAttachment(); depthStencilAttachment.format = Format.DEPTH_STENCIL; depthStencilAttachment.depthLoadOp = LoadOp.CLEAR; depthStencilAttachment.depthStoreOp = StoreOp.STORE; depthStencilAttachment.stencilLoadOp = LoadOp.CLEAR; depthStencilAttachment.stencilStoreOp = StoreOp.STORE; const renderPassInfo = new RenderPassInfo( [colorAttachment0, colorAttachment1, colorAttachment2, colorAttachment3], depthStencilAttachment, ); this._gbufferRenderPass = device.createRenderPass(renderPassInfo); } if (!this._lightingRenderPass) { const colorAttachment = new ColorAttachment(); colorAttachment.format = Format.RGBA8; colorAttachment.loadOp = LoadOp.CLEAR; // should clear color attachment colorAttachment.storeOp = StoreOp.STORE; colorAttachment.endAccesses = [AccessType.COLOR_ATTACHMENT_WRITE]; const depthStencilAttachment = new DepthStencilAttachment(); depthStencilAttachment.format = Format.DEPTH_STENCIL; depthStencilAttachment.depthLoadOp = LoadOp.LOAD; depthStencilAttachment.depthStoreOp = StoreOp.DISCARD; depthStencilAttachment.stencilLoadOp = LoadOp.LOAD; depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD; depthStencilAttachment.beginAccesses = [AccessType.DEPTH_STENCIL_ATTACHMENT_WRITE]; depthStencilAttachment.endAccesses = [AccessType.DEPTH_STENCIL_ATTACHMENT_WRITE]; const renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment); this._lightingRenderPass = device.createRenderPass(renderPassInfo); } this._width = swapchain.width; this._height = swapchain.height; this._generateDeferredRenderData(); return true; } private _destroyUBOs () { if (this._descriptorSet) { this._descriptorSet.getBuffer(UBOGlobal.BINDING).destroy(); this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy(); this._descriptorSet.getBuffer(UBOCamera.BINDING).destroy(); this._descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy(); this._descriptorSet.getTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING).destroy(); } } private _destroyDeferredData () { const deferredData = this._pipelineRenderData as DeferredRenderData; if (deferredData) { if (deferredData.gbufferFrameBuffer) deferredData.gbufferFrameBuffer.destroy(); if (deferredData.outputFrameBuffer) deferredData.outputFrameBuffer.destroy(); if (deferredData.outputDepth) deferredData.outputDepth.destroy(); for (let i = 0; i < deferredData.gbufferRenderTargets.length; i++) { deferredData.gbufferRenderTargets[i].destroy(); } deferredData.gbufferRenderTargets.length = 0; for (let i = 0; i < deferredData.outputRenderTargets.length; i++) { deferredData.outputRenderTargets[i].destroy(); } deferredData.outputRenderTargets.length = 0; this._destroyBloomData(); } this._pipelineRenderData = null; } protected _ensureEnoughSize (cameras: Camera[]) { let newWidth = this._width; let newHeight = this._height; for (let i = 0; i < cameras.length; ++i) { const window = cameras[i].window!; newWidth = Math.max(window.width, newWidth); newHeight = Math.max(window.height, newHeight); } if (newWidth !== this._width || newHeight !== this._height) { this._width = newWidth; this._height = newHeight; this._destroyDeferredData(); this._generateDeferredRenderData(); } } private _generateDeferredRenderData () { const device = this.device; const data: DeferredRenderData = this._pipelineRenderData = new DeferredRenderData(); for (let i = 0; i < 4; ++i) { data.gbufferRenderTargets.push(device.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, // positions & normals need more precision this._width, this._height, ))); } data.outputDepth = device.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.DEPTH_STENCIL_ATTACHMENT, Format.DEPTH_STENCIL, this._width, this._height, )); data.gbufferFrameBuffer = device.createFramebuffer(new FramebufferInfo( this._gbufferRenderPass!, data.gbufferRenderTargets, data.outputDepth, )); data.outputRenderTargets.push(device.createTexture(new TextureInfo( TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, this._width, this._height, ))); data.outputFrameBuffer = device.createFramebuffer(new FramebufferInfo( this._lightingRenderPass!, data.outputRenderTargets, data.outputDepth, )); // Listens when the attachment texture is scaled this.on(PipelineEventType.ATTACHMENT_SCALE_CAHNGED, (val: number) => { data.sampler = val < 1 ? this.globalDSManager.pointSampler : this.globalDSManager.linearSampler; this.applyFramebufferRatio(data.gbufferFrameBuffer); this.applyFramebufferRatio(data.outputFrameBuffer); }); data.sampler = this.globalDSManager.linearSampler; this._generateBloomRenderData(); } }
the_stack
import * as ts from 'typescript'; import { ParseArrayLiteral, ParseArrayType, ParseClassDeclaration, ParseDecorator, ParseDefinition, ParseDependency, ParseEmpty, ParseExpression, ParseIndexSignature, ParseInterfaceDeclaration, ParseIntersectionType, ParseLocation, ParseMethod, ParseNode, ParseObjectLiteral, ParseParenthesizedType, ParsePrimitiveType, ParseProperty, ParseReferenceType, ParseResult, ParseSimpleType, ParseType, ParseTypeAliasDeclaration, ParseTypeLiteral, ParseTypeParameter, ParseUnionType, ParseValueType, ParseVariableDeclaration, Primitives, ParsePartialType, } from './parsed-nodes'; import { getSymbolName, parseAbsoluteModulePath, getNodeTags, NodeTags } from './utils'; import { Logger } from '@sketchmine/node-helpers'; import { flatten } from 'lodash'; import { dirname } from 'path'; import chalk from 'chalk'; const log = new Logger(); /** * @description * Signature types are members of interfaces */ type signatureTypes = | ts.CallSignatureDeclaration | ts.ConstructSignatureDeclaration | ts.IndexSignatureDeclaration | ts.MethodSignature | ts.PropertySignature; /** * @description * All possible members of a class */ type classMembers = | ts.ConstructorDeclaration | ts.GetAccessorDeclaration | ts.MethodDeclaration | ts.PropertyDeclaration | ts.SetAccessorDeclaration; /** * @description * All types that can be converted to a ParseMethod */ type methodTypes = | ts.ConstructorTypeNode | ts.FunctionDeclaration | ts.MethodDeclaration | ts.SetAccessorDeclaration | ts.MethodSignature ; /** * @description * A node that can have a typeParameters property */ export type hasTypeParameterNode = | ts.ClassDeclaration | ts.InterfaceDeclaration | ts.TypeAliasDeclaration | methodTypes; /** * @description * Types that can be a parse property */ type propertyTypes = | ts.ParameterDeclaration | ts.PropertyAssignment | ts.GetAccessorDeclaration | ts.PropertyDeclaration | ts.PropertySignature; /** * @description * interface for a helper function that collects the following information * out of a ts.Node */ interface BaseProperties { location: ParseLocation; name: string; tags?: NodeTags[]; } /** * @classdesc * The Visitor is responsible to traverse a typescript source file and build up * an abstract syntax tree from the parsed nodes. * The main entry point is the `visitSourceFile(sourceFile: ts.SourceFile): ParseResult` * function that starts traversing a source file. * When the traverser finds an import or export statement this file urls are collected and * can be parsed later on. */ export class Visitor { /** * @description * Array of dependencies that is used to visit all necessary files */ dependencyPaths: ParseDependency[] = []; /** * @param paths used to parse the absolute module paths in import or export declarations * @param nodeModulesPath path to node_modules */ constructor( public paths: Map<string, string>, public nodeModulesPath: string, ) {} /** * @description * Visits a source file and generates the parsed abstract syntax tree out * of all the definitions. Every import and export statement is used to explore * new files in the tree that have to be parsed as well. Creates a dependency tree * out of every import or export. * @param sourceFile The sourceFile that should be visited * @returns A parsedResult that holds all dependencies and declarations */ visitSourceFile(sourceFile: ts.SourceFile): ParseResult { const location = this.getLocation(sourceFile); const definitions: ParseDefinition[] = sourceFile.statements .map((node: ts.Node) => this.visit(node)) .filter((node: ParseNode) => node !== undefined); return new ParseResult(location, flatten(definitions), this.dependencyPaths); } /** * @description * Visits a typescript Node according to the kind of the node * @returns a parsed Node that represents a class in the parsed abstract syntax tree */ visit(node: ts.Node): any { // Early exit if there is no node passed if (!node) { return new ParseEmpty(); } switch (node.kind) { case ts.SyntaxKind.ArrayLiteralExpression: return this.visitArrayLiteral(node as ts.ArrayLiteralExpression); case ts.SyntaxKind.ClassDeclaration: return this.visitClassDeclaration(node as ts.ClassDeclaration); case ts.SyntaxKind.InterfaceDeclaration: return this.visitInterfaceDeclaration(node as ts.InterfaceDeclaration); case ts.SyntaxKind.ExportDeclaration: case ts.SyntaxKind.ImportDeclaration: this.visitExportOrImportDeclaration(node as ts.ImportDeclaration | ts.ExportDeclaration); break; case ts.SyntaxKind.HeritageClause: return this.visitHeritageClause(node as ts.HeritageClause); case ts.SyntaxKind.VariableStatement: return this.visitVariableStatement(node as ts.VariableStatement); case ts.SyntaxKind.VariableDeclaration: return this.visitVariableDeclaration(node as ts.VariableDeclaration); case ts.SyntaxKind.TypeParameter: return this.visitTypeParameter(node as ts.TypeParameterDeclaration); case ts.SyntaxKind.TypeAliasDeclaration: return this.visitTypeAliasDeclaration(node as ts.TypeAliasDeclaration); case ts.SyntaxKind.PropertyDeclaration: case ts.SyntaxKind.PropertyAssignment: case ts.SyntaxKind.Parameter: case ts.SyntaxKind.GetAccessor: return this.visitPropertyOrParameter(node as propertyTypes); case ts.SyntaxKind.MethodDeclaration: case ts.SyntaxKind.FunctionDeclaration: case ts.SyntaxKind.SetAccessor: return this.visitMethod(node as methodTypes); case ts.SyntaxKind.ObjectLiteralExpression: return this.visitObjectLiteral(node as ts.ObjectLiteralExpression); case ts.SyntaxKind.StringLiteral: case ts.SyntaxKind.FirstLiteralToken: case ts.SyntaxKind.FirstTemplateToken: case ts.SyntaxKind.FalseKeyword: case ts.SyntaxKind.TrueKeyword: case ts.SyntaxKind.Identifier: return this.visitType(node as ts.TypeNode); case ts.SyntaxKind.Decorator: return this.visitDecorator(node as ts.Decorator); case ts.SyntaxKind.Constructor: return this.visitConstructor(node as ts.ConstructorDeclaration); case ts.SyntaxKind.CallExpression: return this.visitCallExpression(node as ts.CallExpression); case ts.SyntaxKind.EmptyStatement: // this would be an empty statement: doSomething(() => {}); case ts.SyntaxKind.PropertyAccessExpression: case ts.SyntaxKind.ExpressionStatement: // We do not need property accesses or expressionStatements (does not provide any value or type information) // in case that we do not execute // the code only gets analyzed. return new ParseEmpty(); default: log.warning(`Unsupported SyntaxKind to visit: <${ts.SyntaxKind[node.kind]}>`); return; } } /** * @description * Visit property and value types of a nodes type child * @returns a parsed Type or the ParseEmpty if it could not resolve the type */ visitType(node: ts.TypeNode): any { // Early exit if there is no node passed if (!node) { return new ParseEmpty(); } const location = this.getLocation(node); switch (node.kind) { case ts.SyntaxKind.ObjectKeyword: return new ParseEmpty(); case ts.SyntaxKind.VoidKeyword: return new ParseValueType(location, 'void'); case ts.SyntaxKind.AnyKeyword: return new ParseValueType(location, 'any'); case ts.SyntaxKind.NumberKeyword: return new ParsePrimitiveType(location, Primitives.Number); case ts.SyntaxKind.StringKeyword: return new ParsePrimitiveType(location, Primitives.String); case ts.SyntaxKind.BooleanKeyword: return new ParsePrimitiveType(location, Primitives.Boolean); case ts.SyntaxKind.SymbolKeyword: return new ParsePrimitiveType(location, Primitives.Symbol); case ts.SyntaxKind.NullKeyword: return new ParsePrimitiveType(location, Primitives.Null); case ts.SyntaxKind.UndefinedKeyword: return new ParsePrimitiveType(location, Primitives.Undefined); case ts.SyntaxKind.FalseKeyword: return new ParseValueType(location, false); case ts.SyntaxKind.TrueKeyword: return new ParseValueType(location, true); case ts.SyntaxKind.Identifier: case ts.SyntaxKind.TypeReference: const typeReferenceName = getSymbolName(node); let typeArguments: ParseType[] = []; if ((<ts.TypeReferenceNode>node).typeArguments) { typeArguments = (<ts.TypeReferenceNode>node).typeArguments .map((argument: ts.TypeNode) => this.visitType(argument)); } if (typeReferenceName === 'Partial') { return new ParsePartialType(location, typeArguments as ParseSimpleType[]); } return new ParseReferenceType(location, typeReferenceName, typeArguments); case ts.SyntaxKind.ArrayType: const arrayType = this.visitType((<ts.ArrayTypeNode>node).elementType); return new ParseArrayType(location, arrayType); case ts.SyntaxKind.FirstLiteralToken: // First LiteralToken is a number as value // occurs by variable declarations as value `const x = 1` return new ParseValueType(location, parseInt(node.getText(), 10)); case ts.SyntaxKind.FirstTemplateToken: case ts.SyntaxKind.StringLiteral: return new ParseValueType(location, `\"${node.getText().replace(/\'/gm, '')}\"`); case ts.SyntaxKind.TypeLiteral: const typeLiteralMembers: ParseProperty[] = (<ts.TypeLiteralNode>node).members .map((member: ts.PropertySignature) => this.visitSignature(member)); return new ParseTypeLiteral(location, typeLiteralMembers); case ts.SyntaxKind.UnionType: return this.visitUnionType(node as ts.UnionTypeNode); case ts.SyntaxKind.ParenthesizedType: return this.visitParenthesizedType(node as ts.ParenthesizedTypeNode); case ts.SyntaxKind.LiteralType: return this.visitType((<any>node).literal); case ts.SyntaxKind.FunctionType: case ts.SyntaxKind.ConstructorType: return this.visitMethod(node as any); case ts.SyntaxKind.IntersectionType: return this.visitIntersectionType(node as ts.IntersectionTypeNode); } log.warning( chalk`Node Type {bgBlue {magenta <ts.${ts.SyntaxKind[node.kind]}> }} ` + chalk`not handled yet! {grey – visitType(node: ts.TypeNode)}\n ` + chalk`{grey ${location.path}}`, ); return new ParseEmpty(); } /** * @description * @todo UX-9177, UX-9175 * the visitSignature function visits the members of an typescript interface * can return * - ParseIndexSignature * - ParseProperty * - ParseMethodSignature * - (call signature) not implemented yet * - (construct signature) not implemented yet */ visitSignature(node: signatureTypes): any { if (!node) { return; } const { location, tags } = this.getBaseProperties(node); const type = this.visitType(node.type); switch (node.kind) { case ts.SyntaxKind.PropertySignature: return this.visitPropertyOrParameter(node); case ts.SyntaxKind.MethodSignature: return this.visitMethod(node); case ts.SyntaxKind.IndexSignature: const parameter = (<ts.IndexSignatureDeclaration>node).parameters[0]; const parameterName = getSymbolName(parameter); const parameterType = this.visitType(parameter.type); return new ParseIndexSignature(location, parameterName, tags, parameterType, type); case ts.SyntaxKind.CallSignature: // TODO: UX-9175 implement call signature // interface I2 { // (source: string, subString: string): boolean; // } break; case ts.SyntaxKind.ConstructSignature: // TODO: UX-9177 implement construct signature // interface ClockConstructor { // new (hour: number, minute: number): ClockInterface; // } break; default: log.warning( chalk`Signature Type {bgBlue {magenta <ts.${ts.SyntaxKind[(<ts.Node>node).kind]}> }} ` + chalk`not handled yet! {grey – visitSignature(node) @${location.path}}`, ); } } /** * @description * Visits a typescript call Expression we need to check the return type * in case that it can be used to assign data to a variable statement. */ private visitCallExpression(node: ts.CallExpression): ParseExpression { const { location, name } = this.getBaseProperties(node); let typeArguments: ParseType[] = []; let args: ParseNode[] = []; // A call expression can have besides the normal arguments type arguments // that are passed to the function. if (node.typeArguments) { typeArguments = node.typeArguments .map((argument: ts.TypeNode) => this.visitType(argument)); } // the parameters that are passed to the call expression if (node.arguments) { args = node.arguments.map((argument: ts.Node) => this.visit(argument)); } return new ParseExpression(location, name, typeArguments, args); } /** * @description * We need to visit a class constructor declaration in case that there can be * some public or private properties defined in the parameters. * In this case we need to return an array an ParseProperties */ private visitConstructor(node: ts.ConstructorDeclaration): ParseProperty[] { const keywords: Partial<NodeTags>[] = ['private', 'public', 'protected']; // get all parameters and filter the private and public ones const parameters = node.parameters .map((parameter: ts.ParameterDeclaration) => this.visit(parameter)) .filter((parameter: ParseProperty) => parameter.tags.some((tag: NodeTags) => keywords.includes(tag))); return parameters; } /** * @description * Visits a typescript decorator. */ private visitDecorator(node: ts.Decorator) { const expression = node.expression as ts.CallExpression; const { location, name } = this.getBaseProperties(expression.expression); const args = expression.arguments .map((argument: ts.Expression) => this.visit(argument)); return new ParseDecorator(location, name, args); } /** * @description * Visits a typescript type parameter. Type parameters can be any type or a generic. * They are provided like T in this example `type myType<T> …` */ private visitTypeParameter(node: ts.TypeParameterDeclaration): any { const { location, name } = this.getBaseProperties(node); const constraint = node.constraint ? this.visitType(node.constraint) : undefined; return new ParseTypeParameter(location, name, constraint); } /** * @description * Visits a typescript type declaration that can be resolved later on for reference types. * A type alias declaration can look for example like that `type myType<T> = () => T;` */ private visitTypeAliasDeclaration(node: ts.TypeAliasDeclaration): any { const { location, name, tags } = this.getBaseProperties(node); const type = this.visitType(node.type); const typeParameters = this.getTypeParametersOfNode(node); return new ParseTypeAliasDeclaration(location, name, tags, type, typeParameters); } /** * @description * Visits a typescript class with the heritage clauses and implements */ private visitClassDeclaration(node: ts.ClassDeclaration): any { const { location, name, tags } = this.getBaseProperties(node); const typeParameters = this.getTypeParametersOfNode(node); const extending = this.getHeritageClauses(node, ts.SyntaxKind.ExtendsKeyword); const implementing = this.getHeritageClauses(node, ts.SyntaxKind.ImplementsKeyword); let decorators: ParseDecorator[]; const members = node.members ? node.members.map((member: classMembers) => this.visit(member)) : []; if (node.hasOwnProperty('decorators') && node.decorators) { decorators = node.decorators .map((decorator: ts.Decorator) => this.visit(decorator)); } return new ParseClassDeclaration( location, name, tags, // flatten in case there can be an array from all the constructor parameters // that get parsed as members when they are public, private or protected flatten(members), typeParameters, // there can only be one extends in typescript extending[0], implementing, decorators, ); } /** * @description * Visits a typescript heritage clause (implements or extends expression) * of a class or interface */ private visitHeritageClause(node: ts.HeritageClause) { return node.types.map((expression: ts.ExpressionWithTypeArguments) => { const location = this.getLocation(expression); return new ParseReferenceType(location, getSymbolName(expression.expression)); }); } /** * @description * A property can be a member of a typescript class or interface, * a property can also be a function parameter, or a get accessor */ private visitPropertyOrParameter(node: propertyTypes): ParseProperty { const { location, name, tags } = this.getBaseProperties(node); let decorators: ParseDecorator[]; let type: ParseType = new ParseEmpty(); let value; // A Property Assignment has no type so we need to check for the type // property on the node if (node.hasOwnProperty('type') && (<any>node).type) { type = this.visitType((<any>node).type); } // If the node has an initializer (a value) then visit it. // A variable declaration without assigning a value has no initializer // A Get Accessor has no initializer, in case it is a function, so we need to check it if (node.hasOwnProperty('initializer') && (<any>node).initializer) { value = this.visit((<any>node).initializer); } // A get accessor can have a decorator as well or class members, so // we need to check the properties here if (node.hasOwnProperty('decorators') && node.decorators) { decorators = node.decorators .map((decorator: ts.Decorator) => this.visit(decorator)); } // the isOptional marks a parameter as optional is used by function arguments like fn(a?: boolean) const isOptional = node.hasOwnProperty('questionToken') && node.questionToken ? true : undefined; return new ParseProperty(location, name, tags, type, value, decorators, isOptional); } /** * @description * Visits a method inside a typescript class or interface, or a plain function. * A method signature or declaration can look like: `method<T>(a: boolean, b: string): T;` */ private visitMethod(node: methodTypes): ParseMethod { const { location, tags } = this.getBaseProperties(node); const methodName = getSymbolName(node); const returnType = this.visitType(node.type); const parameters = this.getMethodParameters(node); const typeParameters = this.getTypeParametersOfNode(node); let decorators: ParseDecorator[]; if (node.hasOwnProperty('decorators') && node.decorators) { decorators = node.decorators .map((decorator: ts.Decorator) => this.visit(decorator)); } return new ParseMethod( location, methodName, tags, parameters, returnType, typeParameters, decorators, ); } /** * @description * Visits an Object Literal, this function is visiting all object members. */ private visitObjectLiteral(node: ts.ObjectLiteralExpression): ParseObjectLiteral { const { location, tags } = this.getBaseProperties(node); let properties: ParseProperty[] = []; if (node.properties) { properties = node.properties .map((property: ts.PropertyAssignment) => this.visit(property)); } return new ParseObjectLiteral(location, tags, properties); } /** * @description * Visits an Array Literal, this function is visiting all array values. */ private visitArrayLiteral(node: ts.ArrayLiteralExpression): ParseArrayLiteral { const { location, tags } = this.getBaseProperties(node); let elements: ParseSimpleType[] = []; if (node.elements) { elements = node.elements .map((element: ts.Node) => this.visit(element)); } return new ParseArrayLiteral(location, tags, elements); } /** * @description * Visits a variable declaration, a variable declaration can consist out of multiple * variable Statements. */ private visitVariableStatement(node: ts.VariableStatement): ParseVariableDeclaration[] { return flatten(node.declarationList.declarations .map((declaration: ts.VariableDeclaration) => this.visit(declaration))); } /** * @description * Visits a typescript variable declaration Node * Can resolve Object and array destruction patterns */ private visitVariableDeclaration(node: ts.VariableDeclaration): ParseVariableDeclaration[] { const { location, name, tags } = this.getBaseProperties(node); const type = this.visitType(node.type); const value = (node.initializer) ? this.visit(node.initializer) : undefined; // if the name is an object binding pattern it is an object or array destruction pattern if (node.name.kind === ts.SyntaxKind.ObjectBindingPattern && node.name.elements) { const declarations = []; (<any>node).name.elements .map((element: ts.BindingElement) => { return { name: getSymbolName(element), pos: element.pos }; }) .forEach((element: {name: string; pos: number}, index: number) => { const elementLocation = new ParseLocation(location.path, element.pos); const elementType = new ParseEmpty(); let elementValue = undefined; // Object destruction if (value instanceof ParseObjectLiteral) { // find matching value for the name elementValue = value.properties .find((prop: ParseProperty) => prop.name === element.name).value; } else if (value instanceof ParseArrayLiteral) { elementValue = value.values[index]; } const declaration = new ParseVariableDeclaration( elementLocation, element.name, tags, elementType, elementValue, ); declarations.push(declaration); }); return declarations; } return [new ParseVariableDeclaration(location, name, tags, type, value)]; } /** * @description * Visits a typescript interface, an interface can have the following member types * - PropertySignature: `prop: number;` * - IndexSignature: `[prop: string]: any;` * - MethodSignature: `method();` * - CallSignature: `(...args): boolean` * - ConstructSignature: `new (...args): boolean;` */ private visitInterfaceDeclaration(node: ts.InterfaceDeclaration): ParseInterfaceDeclaration { const { location, name, tags } = this.getBaseProperties(node); const typeParameters = this.getTypeParametersOfNode(node); const members: ParseProperty[] = node.members ? node.members.map((member: signatureTypes) => this.visitSignature(member)) : []; const extending = this.getHeritageClauses(node, ts.SyntaxKind.ExtendsKeyword); return new ParseInterfaceDeclaration( location, name, tags, members, typeParameters, // there can only be one extends in typescript extending[0], ); } /** * @description * Visits a typescript parenthesized type, this is type that is surrounded by brackets * so that the inner type can be a union type, for example: `type a = (number | string)[]` */ private visitParenthesizedType(node: ts.ParenthesizedTypeNode): ParseParenthesizedType { const location = this.getLocation(node); const type = this.visitType(node.type); return new ParseParenthesizedType(location, type); } /** * @description * Visit a typescript intersection type * An intersection type combines multiple types into onåe. * `method(): T & U {…}` * @see https://www.typescriptlang.org/docs/handbook/advanced-types.html */ private visitIntersectionType(node: ts.IntersectionTypeNode): ParseIntersectionType { const location = this.getLocation(node); const types = node.types ? node.types .map((type: ts.TypeNode) => this.visitType(type)) : []; return new ParseIntersectionType(location, types); } /** * @description * Visits a typescript union type: `type a = 'x' | 'y';` */ private visitUnionType(node: ts.UnionTypeNode): ParseUnionType { const location = this.getLocation(node); const types = node.types.map((type: ts.TypeNode) => this.visitType(type)); return new ParseUnionType(location, types); } /** * Visits and Import or ExportDeclaration Nodes and adds the paths to the * Dependency path array to know which files should be ParseDependency. * In the example below the modules `['/path/to/module', '/path/to/module-b']` would * be added to the `dependencyPaths` array. * When the function `parseAbsoluteModulePath` returns null then it is a **node_module** and * gets ignored. * ```typescript * import { fn } from '../module'; * export * from './module-b'; * ``` */ private visitExportOrImportDeclaration(node: ts.ExportDeclaration | ts.ImportDeclaration): void { const location = this.getLocation(node); const relativePath = getSymbolName(node.moduleSpecifier); // if the if the import has no moduleSpecifier something is wrong! if (!relativePath) { throw Error('Import statement without module specifier found!'); } // get the absolute path from the relative one. // the relative path its the module specifier, so the string after the from statement const absolutePath = parseAbsoluteModulePath( dirname(location.path), relativePath, this.paths, this.nodeModulesPath, ); // if absolutePath is null then it is a node_module so we can skip it! if (absolutePath === null) { return; } // use a set to avoid duplicate import specifier const importSpecifier = new Set<string>(); // if we have a named import than we add the import specifiers to the parse dependency if ( node.kind === ts.SyntaxKind.ImportDeclaration && node.importClause && node.importClause.namedBindings && (node.importClause.namedBindings as ts.NamedImports).elements && (node.importClause.namedBindings as ts.NamedImports).elements.length ) { const elements = (node.importClause.namedBindings as ts.NamedImports).elements; elements.forEach(el => importSpecifier.add(getSymbolName(el.name))); } this.dependencyPaths.push( new ParseDependency(location, absolutePath, importSpecifier), ); } /** * @internal helper function to access the AST * @description * is visiting the HeritageClauses of an interface or class declaration */ private getHeritageClauses( node: ts.ClassDeclaration | ts.InterfaceDeclaration, type: ts.SyntaxKind.ImplementsKeyword | ts.SyntaxKind.ExtendsKeyword, ): ParseReferenceType[] { if (!node.heritageClauses) { return []; } const clauses = node.heritageClauses .filter((clause: ts.HeritageClause) => clause.token === type) .map((clause: ts.HeritageClause) => this.visit(clause)); return flatten(clauses); } /** * @internal helper function to access the AST * @description * provides the location, the name and the tags for a provided node */ private getBaseProperties(node: ts.Node): BaseProperties { const location = this.getLocation(node); const name = getSymbolName(node); const tags = getNodeTags(node); return { location, name, tags }; } /** * @internal helper function to access the AST * @description * get the parameters of a typescript function */ private getMethodParameters(node: methodTypes): ParseProperty[] { let parameters: ParseProperty[] = []; // if the method has parameters if (node.parameters) { parameters = node.parameters .map((parameter: ts.ParameterDeclaration) => this.visit(parameter)); } return parameters; } /** * @internal helper function to access the AST * @description * Get the array of typescript type parameters of a node */ private getTypeParametersOfNode(node: hasTypeParameterNode): ParseTypeParameter[] { let typeParameters: ParseTypeParameter[] = []; // check if the node has type parameters if (node.typeParameters) { typeParameters = node.typeParameters .map((parameter: ts.TypeParameterDeclaration) => this.visitTypeParameter(parameter)); } return typeParameters; } /** * @internal helper function to access the AST * @description * Get the location of any Node as unique identifier * @returns the ParseLocation that consists out of position in the file * and the fileName of the parent sourceFile. */ private getLocation(node: ts.Node | ts.SourceFile): ParseLocation { const sourceFile: ts.SourceFile = node.kind === ts.SyntaxKind.SourceFile ? <ts.SourceFile>node : node.getSourceFile(); return new ParseLocation(sourceFile.fileName, node.pos); } }
the_stack
import { Checkbox, FormControlLabel, IconButton, ListItemIcon, ListItemText, Typography } from '@material-ui/core'; import { MoreVert, OpenInNew, PlayArrow, TrendingFlat } from '@material-ui/icons'; import { Skeleton } from '@material-ui/lab'; import React, { FC } from 'react'; import { useDrag, useDrop} from 'react-dnd'; import ReactJson, { InteractionProps } from 'react-json-view'; import { useSwipeable } from 'react-swipeable'; import { unpad } from 'unigraph-dev-common/lib/utils/entityUtils'; import { DynamicViewRenderer } from '../../global'; import { AutoDynamicViewProps } from '../../types/ObjectView'; import { isMobile, isMultiSelectKeyPressed, selectUid } from '../../utils'; import { ExecutableCodeEditor } from './DefaultCodeEditor'; import { DefaultObjectContextMenu, onUnigraphContextMenu } from './DefaultObjectContextMenu'; import {ErrorBoundary} from 'react-error-boundary' import { DynamicComponentView, getComponentAsView } from './DynamicComponentView'; import { getRandomInt } from 'unigraph-dev-common/lib/api/unigraph'; type ObjectViewOptions = { viewer?: "string" | "json-tree" | "dynamic-view" | "code-editor" | "dynamic-view-detailed", unpad?: boolean, canEdit?: boolean, showContextMenu?: boolean, viewId?: any }; type DefaultObjectViewProps = { object: any, options: ObjectViewOptions, callbacks?: Record<string, any> }; const StringObjectViewer = ({object}: {object: any}) => { const finalObject = unpad(object) return <div style={{maxHeight: "160px", width: "100%", overflowX: "auto"}}> Type: {object?.type?.["unigraph.id"]}<br/> {JSON.stringify(finalObject, null, 2)} </div>; } export const DefaultSkeleton = () => { return <div style={{width: "100%"}}><Skeleton /> <Skeleton /> <Skeleton /></div> } const onPropertyEdit = (edit: InteractionProps, pad: boolean) => { //console.log(edit); let refUpdateHost: any = edit.existing_src; edit.namespace.forEach(el => { if (typeof el === "string") refUpdateHost = refUpdateHost[el]; else {throw new Error("Doesn't support deletion")} }); if (refUpdateHost?.uid && typeof edit.name === "string") { let updater: any = {}; updater[edit.name] = edit.new_value; window.unigraph.updateObject(refUpdateHost.uid, updater, true, pad) } } const JsontreeObjectViewer = ({object, options}: {object: any, options: ObjectViewOptions}) => { const [showPadded, setShowPadded] = React.useState(false); const onedit = (props: InteractionProps) => onPropertyEdit(props, !showPadded); return <div> <Typography variant="h5">Object View</Typography> <FormControlLabel control={<Checkbox checked={showPadded} onChange={() => setShowPadded(!showPadded)} name="showPadded" color="primary" />} label="Show object as padded"/> {JSON.stringify(options)} <ReactJson src={showPadded ? object : unpad(object)} onEdit={options.canEdit ? onedit : false} onAdd={options.canEdit ? onedit : false} /> </div> } export const Executable: DynamicViewRenderer = ({data, callbacks}) => { const unpadded = unpad(data); const icons: any = { "routine/js": <PlayArrow/>, "component/react-jsx": <OpenInNew/>, "lambda/js": <TrendingFlat/> } const actions: any = { "routine/js": () => {window.unigraph.runExecutable(unpadded['unigraph.id'] || data.uid, {})}, "component/react-jsx": () => { // Open in new getComponentAsView(data, {}).then((viewId: any) => { window.newTab(window.layoutModel, { type: "tab", name: "Component view", component: viewId, enableFloat: "true", config: {} }) }) }, "lambda/js": async () => { const res = await window.unigraph.runExecutable(unpadded['unigraph.id'] || data.uid, {}); console.log(res); } } return <React.Fragment> <ListItemIcon style={{paddingLeft: "8px"}} onClick={actions[unpadded.env]}>{icons[unpadded.env]}</ListItemIcon> <ListItemText primary={"Run code: " + unpadded.name} secondary={`Environment: ${unpadded.env}`} /> </React.Fragment> } export const CodeOrComponentView = (props: any) => { if (props.data.get('env').as('primitive') === "component/react-jsx") { return <DynamicComponentView {...props} /> } else { return <ExecutableCodeEditor {...props} /> } } const SubentityDropAcceptor = ({ uid }: any) => { const [{ isOver, canDrop }, dropSub] = useDrop(() => ({ // @ts-expect-error: already checked for namespace map accept: Object.keys(window.unigraph.getNamespaceMap() || {}), drop: (item: {uid: string, itemType: string}, monitor) => { if (!monitor.didDrop()) { window.unigraph.updateObject(uid, { children: [{ type: {"unigraph.id": "$/schema/subentity"}, _value: { //"type": {"unigraph.id": item.itemType}, uid: item.uid } }] }) } }, collect: (monitor) => ({ isOver: !!monitor.isOver(), canDrop: !!monitor.canDrop(), }) })) const opacities: Record<string, number> = {"truetrue": 1, "truefalse": 0.5, "falsefalse": 0, "falsetrue": 0} return <div ref={dropSub} style={{opacity: opacities[canDrop + "" + isOver], width: "100%", height: canDrop ? "16px" : "0px", margin: "0px"}}> <hr style={{height: "50%", backgroundColor: "gray", margin: "0px", marginLeft: "48px"}}/> </div> } export const ViewViewDetailed: DynamicViewRenderer = ({data}) => { if (data.get('view').as('primitive')?.startsWith?.('/pages')) { const pages = window.unigraph.getState('registry/pages').value; return pages[data.get('view').as('primitive').replace('/pages/', '')] .constructor(JSON.parse(data.get('props').as('primitive')).config) } else { const widgets = window.unigraph.getState('registry/widgets').value; return widgets[data.get('view').as('primitive').replace('/widgets/', '')] .constructor() } } export const AutoDynamicView = ({ object, callbacks, component, attributes, inline, allowSubentity, style, noDrag, noDrop, noContextMenu }: AutoDynamicViewProps) => { allowSubentity = allowSubentity === true; const [{ isDragging }, drag] = useDrag(() => ({ type: object?.['type']?.['unigraph.id'] || "$/schema/any", item: {uid: object?.uid, itemType: object?.type?.['unigraph.id']}, collect: (monitor) => ({ isDragging: !!monitor.isDragging() }) })) const [, drop] = useDrop(() => ({ accept: window.unigraph.getState('referenceables/semantic_children').value, drop: (item: {uid: string, itemType: string}, monitor) => { if (!monitor.didDrop()) { window.unigraph.updateObject(object?.uid, { children: [{ "type": {"unigraph.id": "$/schema/interface/semantic"}, "_value": { "type": {"unigraph.id": item.itemType}, uid: item.uid } }] }) } }, })) const handlers = useSwipeable({ onSwipedRight: (eventData) => onUnigraphContextMenu(({clientX: eventData.absX, clientY: eventData.absY} as any), object, contextEntity, callbacks), }); const contextEntity = typeof callbacks?.context === "object" ? callbacks.context : null; const [isSelected, setIsSelected] = React.useState(false); const selectedState = window.unigraph.getState('global/selected'); selectedState.subscribe((sel: any) => {if (sel?.includes?.(object.uid)) setIsSelected(true); else setIsSelected(false);}) const attach = React.useCallback((domElement) => { if (!noDrag) drag(domElement); if (!noDrop) drop(domElement); }, [isDragging, drag, callbacks]) //console.log(object) let el; const DynamicViews = window.unigraph.getState('registry/dynamicView').value if (object?.type && object.type['unigraph.id'] && Object.keys(DynamicViews).includes(object.type['unigraph.id'])) { el = React.createElement(component?.[object.type['unigraph.id']] ? component[object.type['unigraph.id']] : DynamicViews[object.type['unigraph.id']], { data: object, callbacks: callbacks ? callbacks : undefined, ...(attributes ? attributes : {}) }); } else if (object) { el = <StringObjectViewer object={object}/> } return el ? <ErrorBoundary onError={(error: Error, info: {componentStack: string}) => { console.error(error); }} FallbackComponent={({error}) => <div style={{backgroundColor: "floralwhite", borderRadius: "8px"}}> <Typography>Error in AutoDynamicView: </Typography> <p>{error.message}</p> </div>}> <div id={"object-view-"+object?.uid} style={{ backgroundColor: isSelected ? "whitesmoke" : "unset", opacity: isDragging ? 0.5 : 1, display: "inline-flex", alignItems: "center", ...(inline ? {} : {width: "100%"}), ...(isMobile() ? {touchAction: "pan-y"} : {}), ...style }} ref={attach} aria-label={"Object view for uid " + object?.uid + ", of type " + (object?.type?.['unigraph.id'] || "unknown")} onContextMenu={noContextMenu ? () => {} : (event) => onUnigraphContextMenu(event, object, contextEntity, callbacks)} onClickCapture={(ev) => { if (isMultiSelectKeyPressed(ev)) {ev.stopPropagation(); selectUid(object.uid, false) } }} {...(attributes ? attributes : {})} {...(isMobile() ? handlers : {})} > {el} </div> {(allowSubentity && !noDrop) ? <SubentityDropAcceptor uid={object?.uid} /> : []} </ErrorBoundary> : <React.Fragment/>; } const isStub = (object: any) => (typeof object === "object" && Object.keys(object).length === 3 && object['_stub'] && object.uid && object.type && typeof object.type['unigraph.id'] === "string" && typeof object.type['unigraph.id'].startsWith('$/')) export const AutoDynamicViewDetailed: DynamicViewRenderer = ({ object, options, callbacks, context, component, attributes, useFallback }) => { const isObjectStub = isStub(object) const [loadedObj, setLoadedObj] = React.useState<any>(false) const [subsId, setSubsId] = React.useState(getRandomInt()); const DynamicViewsDetailed = {...window.unigraph.getState('registry/dynamicViewDetailed').value, ...(component || {})} React.useEffect(() => { if (isObjectStub) { window.unigraph.unsubscribe(subsId); const newSubs = getRandomInt(); const query = DynamicViewsDetailed[object.type['unigraph.id']].query(object.uid) window.unigraph.subscribeToQuery(query, (objects: any[]) => { setLoadedObj(objects[0]); }, newSubs, true); setSubsId(newSubs); callbacks = {...callbacks, subsId: newSubs} } return function cleanup () { window.unigraph.unsubscribe(subsId); } }, [object]) if (object?.type && object.type['unigraph.id'] && Object.keys(DynamicViewsDetailed).includes(object.type['unigraph.id']) && ((isObjectStub && loadedObj) || !isObjectStub)) { return <ErrorBoundary FallbackComponent={(error) => <div> <Typography>Error in detailed AutoDynamicView: </Typography> <p>{JSON.stringify(error, null, 4)}</p> </div>}> {React.createElement(DynamicViewsDetailed[object.type['unigraph.id']].view, { data: isObjectStub ? loadedObj : object, callbacks, options: options || {}, context, ...(attributes ? attributes : {}) })} </ErrorBoundary>; } else if (useFallback) { return <JsontreeObjectViewer object={isObjectStub ? loadedObj : object} options={options}/> } else return <React.Fragment/> } const DefaultObjectView: FC<DefaultObjectViewProps> = ({ object, options, callbacks }) => { //const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null); const [ContextMenu, setContextMenu] = React.useState<any>(null); if (!object) return <div/> const finalObject = options.unpad ? unpad(object) : object let FinalObjectViewer; const ContextMenuButton: any = options.showContextMenu ? <IconButton aria-label="context-menu" onClick={(ev) => { setContextMenu(<DefaultObjectContextMenu uid={object.uid} object={object} anchorEl={ev.currentTarget} handleClose={()=>{setContextMenu(null)}}/>) }} > <MoreVert /> </IconButton> : null switch (options.viewer) { case "dynamic-view": FinalObjectViewer = <AutoDynamicView object={object} allowSubentity callbacks={callbacks}/>; break; case "dynamic-view-detailed": FinalObjectViewer = <AutoDynamicViewDetailed object={object} options={options} callbacks={callbacks}/>; break; case "json-tree": FinalObjectViewer = <JsontreeObjectViewer object={object} options={options}/>; break; case "code-editor": FinalObjectViewer = <ExecutableCodeEditor object={object} />; break; default: FinalObjectViewer = <StringObjectViewer object={finalObject}/>; break; } return <div style={{display: "flex", flexDirection: "row", width: "100%"}}> {ContextMenuButton} {ContextMenu} <div style={{alignSelf: "center",width: "100%", alignItems: "center", display: "flex", flexFlow: "wrap"}}>{FinalObjectViewer}</div> </div> } export { DefaultObjectView };
the_stack
import { ContractWrapper } from "../core/classes/contract-wrapper"; import { ContractInterceptor } from "../core/classes/contract-interceptor"; import { IStorage } from "../core/interfaces/IStorage"; import { NetworkOrSignerOrProvider, TransactionResultWithId, } from "../core/types"; import { ContractMetadata } from "../core/classes/contract-metadata"; import { ContractEncoder } from "../core/classes/contract-encoder"; import { SDKOptions } from "../schema/sdk-options"; import { Pack as PackContract } from "contracts"; import { PackContractSchema } from "../schema/contracts/packs"; import { ContractRoles } from "../core/classes/contract-roles"; import { ContractRoyalty } from "../core/classes/contract-royalty"; import { Erc1155 } from "../core/classes/erc-1155"; import { GasCostEstimator } from "../core/classes/gas-cost-estimator"; import { ContractEvents } from "../core/classes/contract-events"; import { ContractAnalytics } from "../core/classes/contract-analytics"; import { PackMetadataInput, PackMetadataInputSchema, PackMetadataOutput, PackRewards, PackRewardsOutput, } from "../schema/tokens/pack"; import { ITokenBundle, PackCreatedEvent, PackOpenedEvent, } from "contracts/Pack"; import { BigNumber, BigNumberish, ethers } from "ethers"; import { fetchCurrencyMetadata, hasERC20Allowance, normalizePriceValue, } from "../common/currency"; import { isTokenApprovedForTransfer } from "../common/marketplace"; import { uploadOrExtractURI } from "../common/nft"; import { EditionMetadata, EditionMetadataOwner } from "../schema"; import { Erc1155Enumerable } from "../core/classes/erc-1155-enumerable"; import { QueryAllParams } from "../types"; import { getRoleHash } from "../common/role"; /** * Create lootboxes of NFTs with rarity based open mechanics. * * @example * * ```javascript * import { ThirdwebSDK } from "@thirdweb-dev/sdk"; * * const sdk = new ThirdwebSDK("rinkeby"); * const contract = sdk.getPack("{{contract_address}}"); * ``` * * @public */ export class Pack extends Erc1155<PackContract> { static contractType = "pack" as const; static contractRoles = ["admin", "minter", "pauser", "transfer"] as const; static contractAbi = require("../../abis/Pack.json"); /** * @internal */ static schema = PackContractSchema; public metadata: ContractMetadata<PackContract, typeof Pack.schema>; public roles: ContractRoles<PackContract, typeof Pack.contractRoles[number]>; public encoder: ContractEncoder<PackContract>; public events: ContractEvents<PackContract>; public estimator: GasCostEstimator<PackContract>; /** * @internal */ public analytics: ContractAnalytics<PackContract>; /** * Configure royalties * @remarks Set your own royalties for the entire contract or per pack * @example * ```javascript * // royalties on the whole contract * contract.royalties.setDefaultRoyaltyInfo({ * seller_fee_basis_points: 100, // 1% * fee_recipient: "0x..." * }); * // override royalty for a particular pack * contract.royalties.setTokenRoyaltyInfo(packId, { * seller_fee_basis_points: 500, // 5% * fee_recipient: "0x..." * }); * ``` */ public royalties: ContractRoyalty<PackContract, typeof Pack.schema>; /** * @internal */ public interceptor: ContractInterceptor<PackContract>; private _query = this.query as Erc1155Enumerable; constructor( network: NetworkOrSignerOrProvider, address: string, storage: IStorage, options: SDKOptions = {}, contractWrapper = new ContractWrapper<PackContract>( network, address, Pack.contractAbi, options, ), ) { super(contractWrapper, storage, options); this.metadata = new ContractMetadata( this.contractWrapper, Pack.schema, this.storage, ); this.analytics = new ContractAnalytics(this.contractWrapper); this.roles = new ContractRoles(this.contractWrapper, Pack.contractRoles); this.royalties = new ContractRoyalty(this.contractWrapper, this.metadata); this.encoder = new ContractEncoder(this.contractWrapper); this.estimator = new GasCostEstimator(this.contractWrapper); this.events = new ContractEvents(this.contractWrapper); this.interceptor = new ContractInterceptor(this.contractWrapper); } /** ****************************** * READ FUNCTIONS *******************************/ /** * Get All Packs * * @remarks Get all the data associated with every pack in this contract. * * By default, returns the first 100 packs, use queryParams to fetch more. * * @example * ```javascript * const packs = await contract.getAll(); * console.log(packs; * ``` * @param queryParams - optional filtering to only fetch a subset of results. * @returns The pack metadata for all packs queried. */ public async getAll( queryParams?: QueryAllParams, ): Promise<EditionMetadata[]> { return this._query.all(queryParams); } /** * Get Owned Packs * * @remarks Get all the data associated with the packs owned by a specific wallet. * * @example * ```javascript * // Address of the wallet to get the packs of * const address = "{{wallet_address}}"; * const packss = await contract.getOwned(address); * ``` * * @returns The pack metadata for all the owned packs in the contract. */ public async getOwned( walletAddress?: string, ): Promise<EditionMetadataOwner[]> { return this._query.owned(walletAddress); } /** * Get the number of packs created * @returns the total number of packs minted in this contract * @public */ public async getTotalCount(): Promise<BigNumber> { return this._query.totalCount(); } /** * Get whether users can transfer packs from this contract */ public async isTransferRestricted(): Promise<boolean> { const anyoneCanTransfer = await this.contractWrapper.readContract.hasRole( getRoleHash("transfer"), ethers.constants.AddressZero, ); return !anyoneCanTransfer; } /** * Get Pack Contents * @remarks Get the rewards contained inside a pack. * * @param packId - The id of the pack to get the contents of. * @returns - The contents of the pack. * * @example * ```javascript * const packId = 0; * const contents = await contract.getPackContents(packId); * console.log(contents.erc20Rewards); * console.log(contents.erc721Rewards); * console.log(contents.erc1155Rewards); * ``` */ public async getPackContents( packId: BigNumberish, ): Promise<PackRewardsOutput> { const { contents, perUnitAmounts } = await this.contractWrapper.readContract.getPackContents(packId); const erc20Rewards = []; const erc721Rewards = []; const erc1155Rewards = []; for (let i = 0; i < contents.length; i++) { const reward = contents[i]; const amount = perUnitAmounts[i]; switch (reward.tokenType) { case 0: { const tokenMetadata = await fetchCurrencyMetadata( this.contractWrapper.getProvider(), reward.assetContract, ); const rewardAmount = ethers.utils.formatUnits( reward.totalAmount, tokenMetadata.decimals, ); erc20Rewards.push({ contractAddress: reward.assetContract, quantityPerReward: amount.toString(), totalRewards: BigNumber.from(rewardAmount).div(amount).toString(), }); break; } case 1: { erc721Rewards.push({ contractAddress: reward.assetContract, tokenId: reward.tokenId.toString(), }); break; } case 2: { erc1155Rewards.push({ contractAddress: reward.assetContract, tokenId: reward.tokenId.toString(), quantityPerReward: amount.toString(), totalRewards: BigNumber.from(reward.totalAmount) .div(amount) .toString(), }); break; } } } return { erc20Rewards, erc721Rewards, erc1155Rewards, }; } /** ****************************** * WRITE FUNCTIONS *******************************/ /** * Create Pack * @remarks Create a new pack with the given metadata and rewards and mint it to the connected wallet. * @remarks See {@link Pack.createTo} * * @param metadataWithRewards - the metadata and rewards to include in the pack */ public async create(metadataWithRewards: PackMetadataInput) { const signerAddress = await this.contractWrapper.getSignerAddress(); return this.createTo(signerAddress, metadataWithRewards); } /** * Create Pack To Wallet * @remarks Create a new pack with the given metadata and rewards and mint it to the specified address. * * @param to - the address to mint the pack to * @param metadataWithRewards - the metadata and rewards to include in the pack * * @example * ```javascript * const pack = { * // The metadata for the pack NFT itself * packMetadata: { * name: "My Pack", * description: "This is a new pack", * image: "ipfs://...", * }, * // ERC20 rewards to be included in the pack * erc20Rewards: [ * { * assetContract: "0x...", * quantity: 100, * } * ], * // ERC721 rewards to be included in the pack * erc721Rewards: [ * { * assetContract: "0x...", * tokenId: 0, * } * ], * // ERC1155 rewards to be included in the pack * erc1155Rewards: [ * { * assetContract: "0x...", * tokenId: 0, * quantity: 100, * } * ], * openStartTime: new Date(), // the date that packs can start to be opened, defaults to now * rewardsPerPack: 1, // the number of rewards in each pack, defaults to 1 * } * * const tx = await contract.createTo("0x...", pack); * ``` */ public async createTo( to: string, metadataWithRewards: PackMetadataInput, ): Promise<TransactionResultWithId<EditionMetadata>> { const uri = await uploadOrExtractURI( metadataWithRewards.packMetadata, this.storage, ); const parsedMetadata = PackMetadataInputSchema.parse(metadataWithRewards); const { contents, numOfRewardUnits } = await this.toPackContentArgs( parsedMetadata, ); const receipt = await this.contractWrapper.sendTransaction("createPack", [ contents, numOfRewardUnits, uri, parsedMetadata.openStartTime, parsedMetadata.rewardsPerPack, to, ]); const event = this.contractWrapper.parseLogs<PackCreatedEvent>( "PackCreated", receipt?.logs, ); if (event.length === 0) { throw new Error("PackCreated event not found"); } const packId = event[0].args.packId; return { id: packId, receipt, data: () => this.get(packId), }; } /** * Open Pack * * @remarks - Open a pack to reveal the contained rewards. This will burn the specified pack and * the contained assets will be transferred to the opening users wallet. * * @param tokenId - the token ID of the pack you want to open * @param amount - the amount of packs you want to open * * @example * ```javascript * const tokenId = 0 * const amount = 1 * const tx = await contract.open(tokenId, amount); * ``` */ public async open( tokenId: BigNumberish, amount: BigNumberish = 1, ): Promise<PackRewards> { const receipt = await this.contractWrapper.sendTransaction("openPack", [ tokenId, amount, ]); const event = this.contractWrapper.parseLogs<PackOpenedEvent>( "PackOpened", receipt?.logs, ); if (event.length === 0) { throw new Error("PackOpened event not found"); } const rewards = event[0].args.rewardUnitsDistributed; const erc20Rewards = []; const erc721Rewards = []; const erc1155Rewards = []; for (const reward of rewards) { switch (reward.tokenType) { case 0: { const tokenMetadata = await fetchCurrencyMetadata( this.contractWrapper.getProvider(), reward.assetContract, ); erc20Rewards.push({ contractAddress: reward.assetContract, quantityPerReward: ethers.utils .formatUnits(reward.totalAmount, tokenMetadata.decimals) .toString(), }); break; } case 1: { erc721Rewards.push({ contractAddress: reward.assetContract, tokenId: reward.tokenId.toString(), }); break; } case 2: { erc1155Rewards.push({ contractAddress: reward.assetContract, tokenId: reward.tokenId.toString(), quantityPerReward: reward.totalAmount.toString(), }); break; } } } return { erc20Rewards, erc721Rewards, erc1155Rewards, }; } /** ***************************** * PRIVATE FUNCTIONS *******************************/ private async toPackContentArgs(metadataWithRewards: PackMetadataOutput) { const contents: ITokenBundle.TokenStruct[] = []; const numOfRewardUnits = []; const { erc20Rewards, erc721Rewards, erc1155Rewards } = metadataWithRewards; const provider = this.contractWrapper.getProvider(); const owner = await this.contractWrapper.getSignerAddress(); for (const erc20 of erc20Rewards) { const normalizedQuantity = await normalizePriceValue( provider, erc20.quantityPerReward, erc20.contractAddress, ); // Multiply the quantity of one reward by the number of rewards const totalQuantity = normalizedQuantity.mul(erc20.totalRewards); const hasAllowance = await hasERC20Allowance( this.contractWrapper, erc20.contractAddress, totalQuantity, ); if (!hasAllowance) { throw new Error( `ERC20 token with contract address "${ erc20.contractAddress }" does not have enough allowance to transfer.\n\nYou can set allowance to the multiwrap contract to transfer these tokens by running:\n\nawait sdk.getToken("${ erc20.contractAddress }").setAllowance("${this.getAddress()}", ${totalQuantity});\n\n`, ); } numOfRewardUnits.push(erc20.totalRewards); contents.push({ assetContract: erc20.contractAddress, tokenType: 0, totalAmount: totalQuantity, tokenId: 0, }); } for (const erc721 of erc721Rewards) { const isApproved = await isTokenApprovedForTransfer( this.contractWrapper.getProvider(), this.getAddress(), erc721.contractAddress, erc721.tokenId, owner, ); if (!isApproved) { throw new Error( `ERC721 token "${erc721.tokenId}" with contract address "${ erc721.contractAddress }" is not approved for transfer.\n\nYou can give approval the multiwrap contract to transfer this token by running:\n\nawait sdk.getNFTCollection("${ erc721.contractAddress }").setApprovalForToken("${this.getAddress()}", ${ erc721.tokenId });\n\n`, ); } numOfRewardUnits.push(1); contents.push({ assetContract: erc721.contractAddress, tokenType: 1, totalAmount: 1, tokenId: erc721.tokenId, }); } for (const erc1155 of erc1155Rewards) { const isApproved = await isTokenApprovedForTransfer( this.contractWrapper.getProvider(), this.getAddress(), erc1155.contractAddress, erc1155.tokenId, owner, ); if (!isApproved) { throw new Error( `ERC1155 token "${erc1155.tokenId}" with contract address "${ erc1155.contractAddress }" is not approved for transfer.\n\nYou can give approval the multiwrap contract to transfer this token by running:\n\nawait sdk.getEdition("${ erc1155.contractAddress }").setApprovalForAll("${this.getAddress()}", true);\n\n`, ); } numOfRewardUnits.push(erc1155.totalRewards); contents.push({ assetContract: erc1155.contractAddress, tokenType: 2, totalAmount: BigNumber.from(erc1155.quantityPerReward).mul( BigNumber.from(erc1155.totalRewards), ), tokenId: erc1155.tokenId, }); } return { contents, numOfRewardUnits, }; } }
the_stack
import { assertNever, Commun, EntityActionPermissions, EntityConfig, EntityModel, getEntityRef, isEntityRef } from '@commun/core' import { GraphQLBoolean, GraphQLEnumType, GraphQLFloat, GraphQLID, GraphQLInputObjectType, GraphQLInputType, GraphQLInt, GraphQLList, GraphQLObjectType, GraphQLSchema, GraphQLString } from 'graphql' import { GraphQLFieldConfigMap, GraphQLInputFieldConfigMap, GraphQLInterfaceType, GraphQLNonNull, GraphQLOutputType, GraphQLResolveInfo, Thunk } from 'graphql/type/definition' import graphqlFields from 'graphql-fields' import { GraphQLController } from './controllers/GraphQLController' import { capitalize } from './utils/StringUtils' import { GraphQLUserController } from './controllers/GraphQLUserController' import { GraphQLDate } from './graphql-types/GraphQLDate' import { JSONSchema7 } from 'json-schema' import { GraphQLJSONObject } from 'graphql-type-json' const entityObjectTypesCache: { [key: string]: GraphQLObjectType } = {} const entityFilterTypesCache: { [key: string]: GraphQLInputObjectType } = {} const entityEnumsCache: { [key: string]: GraphQLEnumType } = {} const nodeInterface = new GraphQLInterfaceType({ name: 'Node', fields: { id: { type: GraphQLNonNull(GraphQLID) } }, description: `An object with an ID.` }) const filterComparatorSymbol = new GraphQLEnumType({ name: 'FilterComparatorSymbol', values: { EQUAL: { value: '=' }, NOT_EQUAL: { value: '!=' }, GREATER_THAN: { value: '>' }, GREATER_THAN_OR_EQUAL: { value: '>=' }, LESS_THAN: { value: '<' }, LESS_THAN_OR_EQUAL: { value: '<=' }, }, description: 'Specify how 2 values are going to be compared.' }) const orderByDirectionType = new GraphQLEnumType({ name: 'OrderByDirection', values: { DESC: { value: 'desc' }, ASC: { value: 'asc' }, }, description: 'Specify the direction on which the items are going to be returned.' }) export function createGraphQLSchema (): GraphQLSchema { const queryConfig: any = { name: 'Query', fields: {}, description: 'The query root of the GraphQL interface.', } const mutationConfig: any = { name: 'Mutation', fields: {}, description: 'The root query for implementing GraphQL mutations.', } for (const entity of Object.values(Commun.getEntities())) { const entityType = buildEntityObjectType(entity.config) const getEntityInput = buildEntityInputType(entity.config, 'get') const createEntityInput = buildEntityInputType(entity.config, 'create') const updateEntityInput = buildEntityInputType(entity.config, 'update') const deleteEntityInput = buildEntityInputType(entity.config, 'delete') const filterByEntityInput = buildFilterEntityInputType(entity.config) const orderByEntityInput = buildOrderByEntityInputType(entity.config) queryConfig.fields[entity.config.entityName] = GraphQLController.listEntities(entity, entityType, getEntityInput, filterByEntityInput, orderByEntityInput) queryConfig.fields[entity.config.entitySingularName!] = GraphQLController.getEntity(entity, entityType) mutationConfig.fields[`create${capitalize(entity.config.entitySingularName!)}`] = GraphQLController.createEntity(entity, entityType, createEntityInput) mutationConfig.fields[`update${capitalize(entity.config.entitySingularName!)}`] = GraphQLController.updateEntity(entity, entityType, updateEntityInput) mutationConfig.fields[`delete${capitalize(entity.config.entitySingularName!)}`] = GraphQLController.deleteEntity(entity, entityType, deleteEntityInput) if (entity.config.entityName === 'users') { queryConfig.fields.viewer = GraphQLUserController.getViewer(entityType) queryConfig.fields.accessToken = GraphQLUserController.getAccessToken() mutationConfig.fields.login = GraphQLUserController.login(entityType) mutationConfig.fields.logout = GraphQLUserController.logout() mutationConfig.fields.verifyEmail = GraphQLUserController.verifyEmail() mutationConfig.fields.sendResetPasswordEmail = GraphQLUserController.sendResetPasswordEmail() mutationConfig.fields.resetPassword = GraphQLUserController.resetPassword() mutationConfig.fields.completeSocialAuthentication = GraphQLUserController.completeSocialAuthentication(entityType) } } const queryType = new GraphQLObjectType(queryConfig) const mutationType = new GraphQLObjectType(mutationConfig) return new GraphQLSchema({ query: queryType, mutation: mutationType }) } function buildEntityObjectType (entityConfig: EntityConfig<EntityModel>): GraphQLObjectType { if (entityObjectTypesCache[entityConfig.entityName]) { return entityObjectTypesCache[entityConfig.entityName] } const fields: Thunk<GraphQLFieldConfigMap<any, any>> = {} // create the GraphQL object and cache it before setting the fields, to support circular references entityObjectTypesCache[entityConfig.entityName] = new GraphQLObjectType({ name: capitalize(entityConfig.entitySingularName!), fields: () => fields, interfaces: [nodeInterface], description: `A single ${capitalize(entityConfig.entitySingularName!)}.` }) for (const [key, property] of getEntityPropertiesByAction(entityConfig, 'get')) { if (typeof property === 'boolean') { continue } const type = getAttributeGraphQLType( entityConfig, key, property, 'type', name => capitalize(entityConfig.entitySingularName!) + name ) as GraphQLOutputType const permission = entityConfig.permissions?.properties?.[key]?.get || entityConfig.permissions?.get const hasAnyoneAccess = Array.isArray(permission) ? permission.includes('anyone') : permission === 'anyone' const required = entityConfig.schema.required?.includes(key) && (hasAnyoneAccess || isEntityRef(property)) fields[key] = { type: key === 'id' || required ? new GraphQLNonNull(type) : type, resolve: getAttributeGraphQLResolver(property!, entityConfig) } } for (const [key, joinProperty] of Object.entries(entityConfig.joinProperties || {})) { const entityType = buildEntityObjectType(Commun.getEntity(joinProperty.entity).config) switch (joinProperty.type) { case 'findOne': fields[key] = { type: entityType } break case 'findMany': fields[key] = { type: new GraphQLList(entityType) } break default: assertNever(joinProperty) } } return entityObjectTypesCache[entityConfig.entityName] } function buildEntityInputType (entityConfig: EntityConfig<EntityModel>, action: keyof EntityActionPermissions) { const fields: Thunk<GraphQLInputFieldConfigMap> = {} const apiKey = entityConfig.apiKey || 'id' for (const [key, property] of getEntityPropertiesByAction(entityConfig, action)) { if (typeof property === 'boolean') { continue } const type = getAttributeGraphQLType( entityConfig, key, property, 'input', name => capitalize(action) + capitalize(entityConfig.entitySingularName!) + name + 'Input', ) as GraphQLInputType let attributeRequired: boolean switch (action) { case 'get': attributeRequired = false break case 'create': attributeRequired = entityConfig.schema?.required?.includes(key) || false break case 'update': case 'delete': attributeRequired = key === apiKey break default: continue } fields[key] = { type: attributeRequired ? new GraphQLNonNull(type) : type, } } // Input Objects require at least one field if (!Object.keys(fields).length) { return } return new GraphQLInputObjectType({ name: capitalize(action) + capitalize(entityConfig.entitySingularName!) + 'Input', fields: () => fields, }) } function buildFilterEntityInputType (entityConfig: EntityConfig<EntityModel>) { if (entityFilterTypesCache[entityConfig.entityName]) { return entityFilterTypesCache[entityConfig.entityName] } const fields: Thunk<GraphQLInputFieldConfigMap> = {} for (const [key, property] of getEntityPropertiesByAction(entityConfig, 'get')) { if (typeof property === 'boolean') { continue } fields[key] = { type: new GraphQLInputObjectType({ name: capitalize(entityConfig.entitySingularName!) + capitalize(key) + 'FilterInput', fields: { value: { type: new GraphQLNonNull(getAttributeGraphQLType( entityConfig, key, property, 'input', name => capitalize(entityConfig.entitySingularName!) + capitalize(key) + name + 'FilterInput', ) as GraphQLInputType) }, comparator: { type: filterComparatorSymbol } } }) } } // Input Objects require at least one field if (!Object.keys(fields).length) { return } return entityFilterTypesCache[entityConfig.entityName] = new GraphQLInputObjectType({ name: capitalize(entityConfig.entitySingularName!) + 'FilterInput', fields: () => ({ ...fields, or: { type: new GraphQLList(entityFilterTypesCache[entityConfig.entityName]) }, and: { type: new GraphQLList(entityFilterTypesCache[entityConfig.entityName]) } }), }) } function buildOrderByEntityInputType (entityConfig: EntityConfig<EntityModel>) { const fields: Thunk<GraphQLInputFieldConfigMap> = {} for (const [key] of getEntityPropertiesByAction(entityConfig, 'get')) { fields[key] = { type: orderByDirectionType } } // Input Objects require at least one field if (!Object.keys(fields).length) { return } return new GraphQLInputObjectType({ name: capitalize(entityConfig.entitySingularName!) + 'OrderByInput', fields: () => fields, }) } export function getAttributeGraphQLType ( entityConfig: EntityConfig<EntityModel>, propertyKey: string, property: JSONSchema7, kind: 'type' | 'input', getName: (key: string) => string, ): GraphQLInputType | GraphQLOutputType | undefined { if (property.format === 'id') { return GraphQLID } if (['date', 'time', 'date-time'].includes(property.format || '')) { return GraphQLDate } const refEntityName = getEntityRef(property) if (refEntityName) { return kind === 'type' ? buildEntityObjectType(Commun.getEntity(refEntityName).config) : GraphQLID } if (property.enum) { const name = capitalize(entityConfig.entitySingularName!) + capitalize(propertyKey) + 'EnumValues' if (entityEnumsCache[name]) { return entityEnumsCache[name] } const values = property.enum.reduce((prev: { [key: string]: any }, curr) => { let key = '' + curr if (typeof curr === 'number') { if (curr > 0) { key = `POSITIVE_${curr}` } else if (curr < 0) { key = `NEGATIVE_${Math.abs(curr)}` } else { key = 'ZERO' } } else if (typeof curr == 'string') { key = curr .replace(/[^_a-zA-Z0-9]/g, '') .replace(/^[^_a-zA-Z]/g, '') } prev[key] = { value: curr } return prev }, {}) return entityEnumsCache[name] = new GraphQLEnumType({ name: capitalize(entityConfig.entitySingularName!) + capitalize(propertyKey) + 'Enum', values, }) } if (property.format?.startsWith('eval:')) { return GraphQLString } switch (property.type) { case 'boolean': return GraphQLBoolean case 'string': return GraphQLString case 'integer': return GraphQLInt case 'number': return GraphQLFloat case 'object': if (!property.properties || property.additionalProperties) { return GraphQLJSONObject } const fields: { [key: string]: any } = {} for (const [fieldKey, fieldProperty] of Object.entries(property.properties)) { if (typeof fieldProperty === 'boolean') { continue } fields[fieldKey] = { type: getAttributeGraphQLType( entityConfig, capitalize(propertyKey) + capitalize(fieldKey), fieldProperty, kind, getName, ) } } const graphQLType = kind === 'input' ? GraphQLInputObjectType : GraphQLObjectType return new graphQLType({ name: getName(capitalize(propertyKey)), fields: () => fields, }) case 'array': if (typeof property.items === 'boolean') { return } if (Array.isArray(property.items)) { // TODO support arrays on JSON Schema items return } const listType = getAttributeGraphQLType( entityConfig, propertyKey, property.items as JSONSchema7, kind, getName, ) return listType ? new GraphQLList(listType) : undefined case 'null': return default: throw new Error(`Unknown property type ${property.type}`) } } function getAttributeGraphQLResolver (property: JSONSchema7, entityConfig?: EntityConfig<EntityModel>) { // Resolve entity references const refEntityName = getEntityRef(property) if (refEntityName) { return async (source: any, args: any, context: any, info: GraphQLResolveInfo) => { const requestedKeys = graphqlFields(info) if (!source[info.fieldName]) { return null } if (Object.keys(requestedKeys).filter(key => key !== 'id').length) { context.params = { id: source[info.fieldName]?.id || source[info.fieldName] } const res = await Commun.getEntityController(refEntityName).get(context, { findModelById: true }) return res.item } return source[info.fieldName] } } switch (property.type) { case 'array': return async (source: any, args: any, context: any, info: GraphQLResolveInfo) => { if (typeof property.items === 'boolean' || Array.isArray(property.items)) { return } return source[info.fieldName]?.map((item: any) => getAttributeGraphQLResolver(property.items as JSONSchema7)?.({ [info.fieldName]: item }, args, context, info) ) } case 'object': return async (source: any, args: any, context: any, info: GraphQLResolveInfo) => { if (!property.properties) { return source[info.fieldName] } const obj: { [key: string]: any } = {} for (const [key, objectProperty] of Object.entries(property.properties)) { if (typeof objectProperty === 'boolean') { continue } if (source[info.fieldName][key]) { obj[key] = getAttributeGraphQLResolver(objectProperty) ?.({ [info.fieldName]: source[info.fieldName][key] }, args, context, info) } } return obj } } } function getEntityPropertiesByAction (entityConfig: EntityConfig<EntityModel>, action: keyof EntityActionPermissions) { const apiKey = entityConfig.apiKey || 'id' // apiKey should always be the first property return Object.entries(entityConfig.schema.properties || {}) .sort(([key]) => key === apiKey ? -1 : 1) .filter(([key, property]) => { if (typeof property === 'boolean') { return false } if (action === 'create' && key === 'id') { return false } if (action === 'update' && apiKey !== 'id' && key === 'id') { return false } if (action === 'delete' && key !== apiKey) { return false } // Eval formats are auto-generated by the system and cannot be set if (action === 'create' && property.format?.startsWith('eval:')) { return false } const permissions = { ...(entityConfig.permissions || {}), ...(entityConfig.permissions?.properties?.[key] || {}), } const isIdentificationKey = ['update', 'delete'].includes(action) && key === apiKey return permissions[action] !== 'system' || isIdentificationKey }) }
the_stack
* @packageDocumentation * @module Voice * @preferred * @publicapi */ import { EventEmitter } from 'events'; import Connection from '../connection'; import Device from '../device'; import { RTCSampleTotals } from '../rtc/sample'; import RTCSample from '../rtc/sample'; import RTCWarning from '../rtc/warning'; import { NetworkTiming, TimeMeasurement } from './timing'; /** * Placeholder until we convert peerconnection.js to TypeScript. * Represents the audio output object coming from Client SDK's PeerConnection object. * @internalapi */ export interface AudioOutput { /** * The audio element used to play out the sound. */ audio: HTMLAudioElement; } export declare interface PreflightTest { /** * Raised when [[PreflightTest.status]] has transitioned to [[PreflightTest.Status.Completed]]. * During this time, [[PreflightTest.report]] is available and ready to be inspected. * In some cases, this will not trigger if the test encounters a fatal error prior connecting to Twilio. * See [[PreflightTest.failedEvent]]. * @param report * @example `preflight.on('completed', report => console.log(report))` * @event */ completedEvent(report: PreflightTest.Report): void; /** * Raised when [[PreflightTest.status]] has transitioned to [[PreflightTest.Status.Connected]]. * @example `preflight.on('connected', () => console.log('Test connected'))` * @event */ connectedEvent(): void; /** * Raised when [[PreflightTest.status]] has transitioned to [[PreflightTest.Status.Failed]]. * This happens when establishing a connection to Twilio has failed or when a test call has encountered a fatal error. * This is also raised if [[PreflightTest.stop]] is called while the test is in progress. * @param error * @example `preflight.on('failed', error => console.log(error))` * @event */ failedEvent(error: Device.Error | DOMError): void; /** * Raised when the [[Connection]] gets a webrtc sample object. This event is published every second. * @param sample * @example `preflight.on('sample', sample => console.log(sample))` * @event */ sampleEvent(sample: RTCSample): void; /** * Raised whenever the [[Connection]] encounters a warning. * @param name - The name of the warning. * @example `preflight.on('warning', (name, data) => console.log({ name, data }))` * @event */ warningEvent(name: string, data: PreflightTest.Warning): void; } /** * Runs some tests to identify issues, if any, prohibiting successful calling. */ export declare class PreflightTest extends EventEmitter { /** * Callsid generated for this test call */ private _callSid; /** * The {@link Connection} for this test call */ private _connection; /** * The {@link Device} for this test call */ private _device; /** * The timer when doing an echo test * The echo test is used when fakeMicInput is set to true */ private _echoTimer; /** * The edge that the `Twilio.Device` connected to. */ private _edge; /** * End of test timestamp */ private _endTime; /** * Whether this test has already logged an insights-connection-warning. */ private _hasInsightsErrored; /** * Latest WebRTC sample collected for this test */ private _latestSample; /** * Network related timing measurements for this test */ private _networkTiming; /** * The options passed to {@link PreflightTest} constructor */ private _options; /** * The report for this test. */ private _report; /** * The WebRTC ICE candidates stats information collected during the test */ private _rtcIceCandidateStatsReport; /** * WebRTC samples collected during this test */ private _samples; /** * Timer for setting up signaling connection */ private _signalingTimeoutTimer; /** * Start of test timestamp */ private _startTime; /** * Current status of this test */ private _status; /** * List of warning names and warning data detected during this test */ private _warnings; /** * Construct a {@link PreflightTest} instance. * @constructor * @param token - A Twilio JWT token string. * @param options */ constructor(token: string, options: PreflightTest.ExtendedOptions); /** * Stops the current test and raises a failed event. */ stop(): void; /** * Emit a {PreflightTest.Warning} */ private _emitWarning; /** * Returns call quality base on the RTC Stats */ private _getCallQuality; /** * Returns the report for this test. */ private _getReport; /** * Returns RTC stats totals for this test */ private _getRTCSampleTotals; /** * Returns RTC related stats captured during the test call */ private _getRTCStats; /** * Returns a MediaStream from a media file */ private _getStreamFromFile; /** * Initialize the device */ private _initDevice; /** * Called on {@link Device} error event * @param error */ private _onDeviceError; /** * Called on {@link Device} ready event */ private _onDeviceReady; /** * Called when there is a fatal error * @param error */ private _onFailed; /** * Called when the device goes offline. * This indicates that the test has been completed, but we won't know if it failed or not. * The onError event will be the indicator whether the test failed. */ private _onOffline; /** * Clean up all handlers for device and connection */ private _releaseHandlers; /** * Setup the event handlers for the {@link Connection} of the test call * @param connection */ private _setupConnectionHandlers; /** * The callsid generated for the test call. */ get callSid(): string | undefined; /** * A timestamp in milliseconds of when the test ended. */ get endTime(): number | undefined; /** * The latest WebRTC sample collected. */ get latestSample(): RTCSample | undefined; /** * The report for this test. */ get report(): PreflightTest.Report | undefined; /** * A timestamp in milliseconds of when the test started. */ get startTime(): number; /** * The status of the test. */ get status(): PreflightTest.Status; } export declare namespace PreflightTest { /** * The quality of the call determined by different mos ranges. * Mos is calculated base on the WebRTC stats - rtt, jitter, and packet lost. */ enum CallQuality { /** * If the average mos is over 4.2. */ Excellent = "excellent", /** * If the average mos is between 4.1 and 4.2 both inclusive. */ Great = "great", /** * If the average mos is between 3.7 and 4.0 both inclusive. */ Good = "good", /** * If the average mos is between 3.1 and 3.6 both inclusive. */ Fair = "fair", /** * If the average mos is 3.0 or below. */ Degraded = "degraded" } /** * Possible events that a [[PreflightTest]] might emit. */ enum Events { /** * See [[PreflightTest.completedEvent]] */ Completed = "completed", /** * See [[PreflightTest.connectedEvent]] */ Connected = "connected", /** * See [[PreflightTest.failedEvent]] */ Failed = "failed", /** * See [[PreflightTest.sampleEvent]] */ Sample = "sample", /** * See [[PreflightTest.warningEvent]] */ Warning = "warning" } /** * Possible status of the test. */ enum Status { /** * Connection to Twilio has initiated. */ Connecting = "connecting", /** * Connection to Twilio has been established. */ Connected = "connected", /** * The connection to Twilio has been disconnected and the test call has completed. */ Completed = "completed", /** * The test has stopped and failed. */ Failed = "failed" } /** * The WebRTC API's [RTCIceCandidateStats](https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidateStats) * dictionary which provides information related to an ICE candidate. */ type RTCIceCandidateStats = any; /** * Options that may be passed to {@link PreflightTest} constructor for internal testing. * @internalapi */ interface ExtendedOptions extends Options { /** * The AudioContext instance to use */ audioContext?: AudioContext; /** * Device class to use. */ deviceFactory?: new (token: string, options: Device.Options) => Device; /** * File input stream to use instead of reading from mic */ fileInputStream?: MediaStream; /** * The getRTCIceCandidateStatsReport to use for testing. */ getRTCIceCandidateStatsReport?: Function; /** * An RTCConfiguration to pass to the RTCPeerConnection constructor during `Device.setup`. */ rtcConfiguration?: RTCConfiguration; } /** * A WebRTC stats report containing relevant information about selected and gathered ICE candidates */ interface RTCIceCandidateStatsReport { /** * An array of WebRTC stats for the ICE candidates gathered when connecting to media. */ iceCandidateStats: RTCIceCandidateStats[]; /** * A WebRTC stats for the ICE candidate pair used to connect to media, if candidates were selected. */ selectedIceCandidatePairStats?: RTCSelectedIceCandidatePairStats; } /** * Options passed to {@link PreflightTest} constructor. */ interface Options { /** * An ordered array of codec names that will be used during the test call, * from most to least preferred. * @default ['pcmu','opus'] */ codecPreferences?: Connection.Codec[]; /** * Whether to enable debug logging. * @default false */ debug?: boolean; /** * Specifies which Twilio Data Center to use when initiating the test call. * Please see this * [page](https://www.twilio.com/docs/voice/client/edges) * for the list of available edges. * @default roaming */ edge?: string; /** * If set to `true`, the test call will ignore microphone input and will use a default audio file. * If set to `false`, the test call will capture the audio from the microphone. * Setting this to `true` is only supported on Chrome and will throw a fatal error on other browsers * @default false */ fakeMicInput?: boolean; /** * An array of custom ICE servers to use to connect media. If you provide both STUN and TURN server configurations, * the test will detect whether a TURN server is required to establish a connection. * * The following example demonstrates how to use [Twilio's Network Traversal Service](https://www.twilio.com/stun-turn) * to generate STUN/TURN credentials and how to specify a specific [edge location](https://www.twilio.com/docs/global-infrastructure/edge-locations). * * ```ts * import Client from 'twilio'; * import { Device } from 'twilio-client'; * * // Generate the STUN and TURN server credentials with a ttl of 120 seconds * const client = Client(twilioAccountSid, authToken); * const token = await client.tokens.create({ ttl: 120 }); * * let iceServers = token.iceServers; * * // By default, global will be used as the default edge location. * // You can replace global with a specific edge name for each of the iceServer configuration. * iceServers = iceServers.map(config => { * let { url, urls, ...rest } = config; * url = url.replace('global', 'ashburn'); * urls = urls.replace('global', 'ashburn'); * * return { url, urls, ...rest }; * }); * * // Use the TURN credentials using the iceServers parameter * const preflightTest = Device.runPreflight(token, { iceServers }); * * // Read from the report object to determine whether TURN is required to connect to media * preflightTest.on('completed', (report) => { * console.log(report.isTurnRequired); * }); * ``` * * @default null */ iceServers?: RTCIceServer[]; /** * Amount of time to wait for setting up signaling connection. * @default 10000 */ signalingTimeoutMs?: number; } /** * Represents the WebRTC stats for the ICE candidate pair used to connect to media, if candidates were selected. */ interface RTCSelectedIceCandidatePairStats { /** * An [RTCIceCandidateStats](https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidateStats) * object which provides information related to the selected local ICE candidate. */ localCandidate: RTCIceCandidateStats; /** * An [RTCIceCandidateStats](https://developer.mozilla.org/en-US/docs/Web/API/RTCIceCandidateStats) * object which provides information related to the selected remote ICE candidate. */ remoteCandidate: RTCIceCandidateStats; } /** * Represents RTC related stats that are extracted from RTC samples. */ interface RTCStats { /** * Packets delay variation. */ jitter: Stats; /** * Mean opinion score, 1.0 through roughly 4.5. */ mos: Stats; /** * Round trip time, to the server back to the client. */ rtt: Stats; } /** * Represents general stats for a specific metric. */ interface Stats { /** * The average value for this metric. */ average: number; /** * The maximum value for this metric. */ max: number; /** * The minimum value for this metric. */ min: number; } /** * Represents the report generated from a {@link PreflightTest}. */ interface Report { /** * The quality of the call determined by different mos ranges. */ callQuality?: CallQuality; /** * CallSid generaged during the test. */ callSid: string | undefined; /** * The edge that the test call was connected to. */ edge?: string; /** * An array of WebRTC stats for the ICE candidates gathered when connecting to media. */ iceCandidateStats: RTCIceCandidateStats[]; /** * Whether a TURN server is required to connect to media. * This is dependent on the selected ICE candidates, and will be true if either is of type "relay", * false if both are of another type, or undefined if there are no selected ICE candidates. * See `PreflightTest.Options.iceServers` for more details. */ isTurnRequired?: boolean; /** * Network related time measurements. */ networkTiming: NetworkTiming; /** * WebRTC samples collected during the test. */ samples: RTCSample[]; /** * The edge passed to `Device.runPreflight`. */ selectedEdge?: string; /** * A WebRTC stats for the ICE candidate pair used to connect to media, if candidates were selected. */ selectedIceCandidatePairStats?: RTCSelectedIceCandidatePairStats; /** * RTC related stats captured during the test. */ stats?: RTCStats; /** * Time measurements of test run time. */ testTiming: TimeMeasurement; /** * Calculated totals in RTC statistics samples. */ totals?: RTCSampleTotals; /** * List of warning names and warning data detected during this test. */ warnings: PreflightTest.Warning[]; } /** * A warning that can be raised by Preflight, and returned in the Report.warnings field. */ interface Warning { /** * Description of the Warning */ description: string; /** * Name of the Warning */ name: string; /** * If applicable, the RTCWarning that triggered this warning. */ rtcWarning?: RTCWarning; } }
the_stack
import Translation from "../../models/Translation"; import { ARTICLE_TITLE_MAX_LENGTH, ARTICLE_CONTENT_MIN_LENGTH, ARTICLE_CONTENT_MAX_LENGTH, THREAD_CONTENT_MAX_LENGTH, THREAD_TITLE_MAX_LENGTH, PASSWORD_MIN_LENGTH } from "../constants"; const TRANSLATION: Translation = { locale: "en-US", messages: { // App basic info "app.name": "Typescript MERN Starter", "app.footer": "Copyright © 2020 Company, Inc. All Rights Reserved.", "app.connect_error": "Failed to fetch", // Do not change this phrase, it is used as keywords. // Pages. // pattern: page.<page_name>.<section> "page.home": "Home", "page.about": "About ", "page.about.introduction": "This project is intended to build a RESTful web app for all platforms in TypeScript. With this project you can build a web app including server, website, Android app and iOS app in one programming language.", "page.about.learn_more": "Learn More", "page.me": "Me", "page.me.login": "Sign in", "page.me.forget_password": "Forget password?", "page.me.sign_up": "Sign up", "page.me.profile": "Profile", "page.me.logout": "Log out", "page.me.preferences": "Preferences", "page.me.security": "Change Password", "page.me.change_password": "Change Password", "page.me.reset_password": "Forget Password", "page.me.reset_password_step_1": "Fill Your Account", "page.me.reset_password_step_2": "Verify Email", "page.me.reset_password_step_3": "Reset Password", "page.me.notifications": "Notifications", "page.threads": "Forum", "page.thread.add": "Add thread", "page.thread.empty": "No threads are added up to now.", "page.thread.placeholder": "Anything you would like to post...", "page.thread.removed": ">>> The original thread has been removed <<<", "page.thread.delete": "Delete Thread: {title}", "page.thread.delete_confirmation": "You cannot restore this thread after delete. Are you sure to delete?", "page.avatar.title": "Adjust Your Profile Image", "page.avatar.rotate": "Rotate", "page.avatar.zoom": "Zoom", "page.avatar.inquiry": "Is it okay to use this photo?", "page.consent.greeting": "Hi {email},", "page.consent.description": "{app_name} is requesting access to your account.", "page.consent.inquiry": "Do you approve?", "page.consent.OTP": "Please fill the code sent to your mailbox, it will expire in 10 minutes.", "page.consent.OTP_not_received": "Have not received the code?", "page.consent.OTP_resend": "Resend", "page.article.add": "Add Article", "page.article.edit": "Edit Article", "page.article.preview": "Preview", "page.article.delete": "Delete Article: {title}", "page.article.delete_confirmation": "You cannot restore this article after delete. Are you sure to delete?", "page.article.empty": "No articles are added up to now.", "page.article.load_more": "Load More", "page.article.clear_edit": "Clear Your Editing", "page.article.clear_edit_confirmation": "You cannot restore your editing after clear. Are you sure to clear?", "page.insert_image.title": "Insert Image", "page.insert_image.fill_description": "Image Description", "page.insert_image.fill_link": "Image Link", "page.insert_image.upload": "Upload from Disk", "page.notification.event_comment": " replied your", "page.notification.event_like": " liked your", "page.notification.event_unlike": " cancelled like on your", "page.notification.event_mention": " mentioned you in his/her", "page.notification.object_article": " article ", "page.notification.object_comment": " comment ", "page.notification.object_thread": " thread ", "page.notification.empty": "No new notification.", "page.notification.load_all": "See all read notifications", "page.notification.set_as_read": "Mark as read", // Models. // pattern: <model_name>.<model_property>.<model_property_values> "user.email": "Email", "user.password": "Password", "user.confirm_password": "Confirm Password", "user.old_password": "Old Password", "user.new_password": "New Password", "user.name": "Name", "user.photo": "Photo", "user.gender": "Gender", "user.gender.male": "Male", "user.gender.female": "Female", "user.gender.other": "Other", "user.address": "Address", "user.website": "Web site", "user.OTP": "OTP (Case-insensitive)", "user.invitation_code": "Invitation Code (Case-sensitive)", "preferences.editor_type": "Editor type", "preferences.editor_type.markdown": "Markdown", "preferences.editor_type.wysiwyg": "WYSIWYG", "article.title": "Title", "article.content": "Content", "article.content_placeholder": `no less than ${ARTICLE_CONTENT_MIN_LENGTH} characters`, "post.created_at": "Created at ", "post.updated_at": "Last updated at ", "post.replied_at": "Last replied at ", "post.no_reply_yet": "No reply yet", // Components. // pattern: component.<component_name>.<action> "component.button.file_select": "Choose File", "component.button.submit": "Submit", "component.button.confirm": "OK", "component.button.cancel": "Cancel", "component.button.approve": "Approve", "component.button.deny": "Deny", "component.button.update": "Update", "component.button.delete": "Delete", "component.button.edit": "Edit", "component.button.preview": "Preview", "component.button.see_all": "Read all", "component.button.create": "Create", "component.button.next": "next", "component.button.scroll_up": "Scroll to top", "component.button.clear_edit": "Clear edit", "component.button.refresh": "Refresh", "component.button.refreshing": "Refreshing", "component.comment.title": "Comment", "component.comment.private": "Show after login", "component.comment.placeholder": "Leave a reply", "component.comment.submit": "Add Reply", "component.comment.reply": "Reply", "component.comment.delete": "Delete", "component.comment.delete_title": "Delete Comment", "component.comment.delete_confirmation": "You cannot restore this comment after delete. Are you sure to delete?", "component.footer.nothing_more": "No more articles", // Toasts. // pattern: toast.<model>.<info> "toast.user.general_error": "Cannot find the user, please check.", "toast.user.invalid_token_error": "Please log in first.", "toast.user.sign_in_successfully": "Sign in successfully.", "toast.user.sign_up_successfully": "Sign up successfully.", "toast.user.sign_in_failed": "Sign in failed.", "toast.user.deny_consent": "Please approve to finish signing up.", "toast.user.update_successfully": "Update successfully.", "toast.user.update_failed": "Update failed.", "toast.user.upload_avatar_failed": "Upload avatar failed.", "toast.user.upload_exist_account": "Account with that email address already exists.", "toast.user.account_not_found": "Account cannot be found.", "toast.user.error_OTP": "Error OTP!", "toast.user.expired_OTP": "Expired OTP!", "toast.user.password_not_change": "New password cannot be the same as the old one.", "toast.user.old_password_error": "Old password is incorrect.", "toast.client.invalid": "Invalid client!", "toast.client.incorrect_url": "Incorrect redirectUri!", "toast.post.title_empty": "Title could not be empty.", "toast.post.content_empty": "Content could not be empty.", "toast.thread.title_too_long": `Title could not be longer than ${THREAD_TITLE_MAX_LENGTH} characters.`, "toast.thread.content_too_long": `Thread could not be longer than ${THREAD_CONTENT_MAX_LENGTH} characters.`, "toast.article.title_too_long": `Title could not be longer than ${ARTICLE_TITLE_MAX_LENGTH} characters.`, "toast.article.content_too_short": `Article could not be shorter than ${ARTICLE_CONTENT_MIN_LENGTH} characters.`, "toast.article.content_too_long": `Article could not be longer than ${ARTICLE_CONTENT_MAX_LENGTH} characters.`, "toast.article.save_successfully": "Save your article successfully.", "toast.article.delete_successfully": "Delete your article successfully.", "toast.article.invalid_author": "You are not the author!", "toast.article.not_found": "Article not found!", "toast.user.attack_alert": "Malicious attack is detected.", "toast.user.email": "Invalid email.", "toast.user.email_not_found": "This email is not found.", "toast.user.password_error": "Password is incorrect.", "toast.user.password_too_short": `Password should be longer than or equal to ${PASSWORD_MIN_LENGTH} characters.`, "toast.user.password_empty": "Password could not be empty.", "toast.user.confirm_password": "confirmed password field must have the same value as the password field", "toast.user.name": "Name could not be empty.", "toast.user.gender": "Invalid gender.", "toast.user.otp_send_failed": "Send OTP failed!", "toast.user.preferences.editor_type": "Invalid editor type", "toast.user.invitation_code.empty": "Invitation code cannot be empty", "toast.user.invitation_code.invalid": "Invalid invitation code", "toast.user.invitation_code.used": "Used invitation code", "toast.comment.content_empty": "Comment could not be empty.", "toast.comment.add_successfully": "Comment successfully.", "toast.comment.add_failed": "Comment failed.", "toast.comment.delete_parent": "Sorry, you cannot delete a comment someone has replied to it.", "toast.comment.delete_successfully": "Delete successfully.", "toast.comment.delete_failed": "Delete failed.", "toast.comment.not_found": "Cannot find this comment.", "toast.notification.not_found": "Cannot find this notification", "toast.thread.add_successfully": "Your thread created.", "toast.thread.add_failed": "Your thread cannot be created.", "toast.thread.delete_successfully": "Your thread has been deleted", "toast.thread.delete_failed": "Your thread cannot be deleted.", "toast.post.insert_image_failed": "Failed to insert the image" } }; export default TRANSLATION;
the_stack
import { expect } from "chai"; import { all, DI, Container, inject, lazy, optional, Registration, singleton, } from "./di"; describe("DI.get", function () { let container: Container; // eslint-disable-next-line mocha/no-hooks beforeEach(function () { container = DI.createContainer(); }); describe("@lazy", function () { class Bar {} class Foo { public constructor(@lazy(Bar) public readonly provider: () => Bar) {} } it("@singleton", function () { const bar0 = container.get(Foo).provider(); const bar1 = container.get(Foo).provider(); expect(bar0).to.equal(bar1); }); it("@transient", function () { container.register(Registration.transient(Bar, Bar)); const bar0 = container.get(Foo).provider(); const bar1 = container.get(Foo).provider(); expect(bar0).to.not.equal(bar1); }); }); describe("@scoped", function () { describe("true", function () { @singleton({ scoped: true }) class ScopedFoo {} describe("Foo", function () { const constructor = ScopedFoo; it("children", function () { const root = DI.createContainer(); const child1 = root.createChild(); const child2 = root.createChild(); const a = child1.get(constructor); const b = child2.get(constructor); const c = child1.get(constructor); expect(a).to.equal(c, "a and c are the same"); expect(a).to.not.equal(b, "a and b are not the same"); expect(root.has(constructor, false)).to.equal( false, "root has class" ); expect(child1.has(constructor, false)).to.equal( true, "child1 has class" ); expect(child2.has(constructor, false)).to.equal( true, "child2 has class" ); }); it("root", function () { const root = DI.createContainer(); const child1 = root.createChild(); const child2 = root.createChild(); const a = root.get(constructor); const b = child2.get(constructor); const c = child1.get(constructor); expect(a).to.equal(c, "a and c are the same"); expect(a).to.equal(b, "a and b are the same"); expect(root.has(constructor, false)).to.equal(true, "root has class"); expect(child1.has(constructor, false)).to.equal( false, "child1 does not have class" ); expect(child2.has(constructor, false)).to.equal( false, "child2 does not have class" ); }); }); }); describe("false", function () { @singleton({ scoped: false }) class ScopedFoo {} describe("Foo", function () { const constructor = ScopedFoo; it("children", function () { const root = DI.createContainer(); const child1 = root.createChild(); const child2 = root.createChild(); const a = child1.get(constructor); const b = child2.get(constructor); const c = child1.get(constructor); expect(a).to.equal(c, "a and c are the same"); expect(a).to.equal(b, "a and b are the same"); expect(root.has(constructor, false)).to.equal(true, "root has class"); expect(child1.has(constructor, false)).to.equal( false, "child1 has class" ); expect(child2.has(constructor, false)).to.equal( false, "child2 has class" ); }); }); describe("default", function () { @singleton class DefaultFoo {} const constructor = DefaultFoo; it("children", function () { const root = DI.createContainer(); const child1 = root.createChild(); const child2 = root.createChild(); const a = child1.get(constructor); const b = child2.get(constructor); const c = child1.get(constructor); expect(a).to.equal(c, "a and c are the same"); expect(a).to.equal(b, "a and b are the same"); expect(root.has(constructor, false)).to.equal(true, "root has class"); expect(child1.has(constructor, false)).to.equal( false, "child1 has class" ); expect(child2.has(constructor, false)).to.equal( false, "child2 has class" ); }); }); }); }); describe("@optional", function () { it("with default", function () { class Foo { public constructor( @optional("key") public readonly test: string = "hello" ) {} } expect(container.get(Foo).test).to.equal("hello"); }); it("no default, but param allows undefined", function () { class Foo { public constructor(@optional("key") public readonly test?: string) {} } expect(container.get(Foo).test).to.equal(undefined); }); it("no default, param does not allow undefind", function () { class Foo { public constructor(@optional("key") public readonly test: string) {} } expect(container.get(Foo).test).to.equal(undefined); }); it("interface with default", function () { const Strings = DI.createInterface<string[]>(x => x.instance([])); class Foo { public constructor(@optional(Strings) public readonly test: string[]) {} } expect(container.get(Foo).test).to.equal(undefined); }); it("interface with default and default in constructor", function () { const MyStr = DI.createInterface<string>(x => x.instance("hello")); class Foo { public constructor( @optional(MyStr) public readonly test: string = "test" ) {} } expect(container.get(Foo).test).to.equal("test"); }); it("interface with default registered and default in constructor", function () { const MyStr = DI.createInterface<string>(x => x.instance("hello")); container.register(MyStr); class Foo { public constructor( @optional(MyStr) public readonly test: string = "test" ) {} } expect(container.get(Foo).test).to.equal("hello"); }); }); describe("intrinsic", function () { describe("bad", function () { it("Array", function () { @singleton class Foo { public constructor(@inject(Array) private readonly test: string[]) {} } expect(() => container.get(Foo)).throws(); }); it("ArrayBuffer", function () { @singleton class Foo { public constructor( @inject(ArrayBuffer) private readonly test: ArrayBuffer ) {} } expect(() => container.get(Foo)).throws(); }); it("Boolean", function () { @singleton class Foo { // eslint-disable-next-line @typescript-eslint/ban-types public constructor(@inject(Boolean) private readonly test: Boolean) {} } expect(() => container.get(Foo)).throws(); }); it("DataView", function () { @singleton class Foo { public constructor( @inject(DataView) private readonly test: DataView ) {} } expect(() => container.get(Foo)).throws(); }); it("Date", function () { @singleton class Foo { public constructor(@inject(Date) private readonly test: Date) {} } expect(() => container.get(Foo)).throws(); }); it("Error", function () { @singleton class Foo { public constructor(@inject(Error) private readonly test: Error) {} } expect(() => container.get(Foo)).throws(); }); it("EvalError", function () { @singleton class Foo { public constructor( @inject(EvalError) private readonly test: EvalError ) {} } expect(() => container.get(Foo)).throws(); }); it("Float32Array", function () { @singleton class Foo { public constructor( @inject(Float32Array) private readonly test: Float32Array ) {} } expect(() => container.get(Foo)).throws(); }); it("Float64Array", function () { @singleton class Foo { public constructor( @inject(Float64Array) private readonly test: Float64Array ) {} } expect(() => container.get(Foo)).throws(); }); it("Function", function () { @singleton class Foo { // eslint-disable-next-line @typescript-eslint/ban-types public constructor( @inject(Function) private readonly test: Function ) {} } expect(() => container.get(Foo)).throws(); }); it("Int8Array", function () { @singleton class Foo { public constructor( @inject(Int8Array) private readonly test: Int8Array ) {} } expect(() => container.get(Foo)).throws(); }); it("Int16Array", function () { @singleton class Foo { public constructor( @inject(Int16Array) private readonly test: Int16Array ) {} } expect(() => container.get(Foo)).throws(); }); it("Int32Array", function () { @singleton class Foo { public constructor( @inject(Int32Array) private readonly test: Int16Array ) {} } expect(() => container.get(Foo)).throws(); }); it("Map", function () { @singleton class Foo { public constructor( @inject(Map) private readonly test: Map<unknown, unknown> ) {} } expect(() => container.get(Foo)).throws(); }); it("Number", function () { @singleton class Foo { // eslint-disable-next-line @typescript-eslint/ban-types public constructor(@inject(Number) private readonly test: Number) {} } expect(() => container.get(Foo)).throws(); }); it("Object", function () { @singleton class Foo { // eslint-disable-next-line @typescript-eslint/ban-types public constructor(@inject(Object) private readonly test: Object) {} } expect(() => container.get(Foo)).throws(); }); it("Promise", function () { @singleton class Foo { public constructor( @inject(Promise) private readonly test: Promise<unknown> ) {} } expect(() => container.get(Foo)).throws(); }); it("RangeError", function () { @singleton class Foo { public constructor( @inject(RangeError) private readonly test: RangeError ) {} } expect(() => container.get(Foo)).throws(); }); it("ReferenceError", function () { @singleton class Foo { public constructor( @inject(ReferenceError) private readonly test: ReferenceError ) {} } expect(() => container.get(Foo)).throws(); }); it("RegExp", function () { @singleton class Foo { public constructor(@inject(RegExp) private readonly test: RegExp) {} } expect(() => container.get(Foo)).throws(); }); it("Set", function () { @singleton class Foo { public constructor( @inject(Set) private readonly test: Set<unknown> ) {} } expect(() => container.get(Foo)).throws(); }); // if (typeof SharedArrayBuffer !== 'undefined') { // it('SharedArrayBuffer', function () { // @singleton // class Foo { // public constructor(private readonly test: SharedArrayBuffer) { // } // } // assert.throws(() => container.get(Foo)); // }); // } it("String", function () { @singleton class Foo { // eslint-disable-next-line @typescript-eslint/ban-types public constructor(@inject(String) private readonly test: String) {} } expect(() => container.get(Foo)).throws(); }); it("SyntaxError", function () { @singleton class Foo { public constructor( @inject(SyntaxError) private readonly test: SyntaxError ) {} } expect(() => container.get(Foo)).throws(); }); it("TypeError", function () { @singleton class Foo { public constructor( @inject(TypeError) private readonly test: TypeError ) {} } expect(() => container.get(Foo)).throws(); }); it("Uint8Array", function () { @singleton class Foo { public constructor( @inject(Uint8Array) private readonly test: Uint8Array ) {} } expect(() => container.get(Foo)).throws(); }); it("Uint8ClampedArray", function () { @singleton class Foo { public constructor( @inject(Uint8ClampedArray) private readonly test: Uint8ClampedArray ) {} } expect(() => container.get(Foo)).throws(); }); it("Uint16Array", function () { @singleton class Foo { public constructor( @inject(Uint16Array) private readonly test: Uint16Array ) {} } expect(() => container.get(Foo)).throws(); }); it("Uint32Array", function () { @singleton class Foo { public constructor( @inject(Uint32Array) private readonly test: Uint32Array ) {} } expect(() => container.get(Foo)).throws(); }); it("UriError", function () { @singleton class Foo { public constructor( @inject(URIError) private readonly test: URIError ) {} } expect(() => container.get(Foo)).throws(); }); it("WeakMap", function () { @singleton class Foo { public constructor( @inject(WeakMap) private readonly test: WeakMap<any, unknown> ) {} } expect(() => container.get(Foo)).throws(); }); it("WeakSet", function () { @singleton class Foo { public constructor( @inject(WeakSet) private readonly test: WeakSet<any> ) {} } expect(() => container.get(Foo)).throws(); }); }); describe("good", function () { it("@all()", function () { class Foo { public constructor(@all("test") public readonly test: string[]) {} } expect(container.get(Foo).test).to.eql([]); }); it("@optional()", function () { class Foo { public constructor( @optional("test") public readonly test: string | null = null ) {} } expect(container.get(Foo).test).to.equal(null); }); it("undef instance, with constructor default", function () { container.register(Registration.instance("test", undefined)); class Foo { public constructor( @inject("test") public readonly test: string[] = [] ) {} } expect(container.get(Foo).test).to.eql([]); }); it("can inject if registered", function () { container.register(Registration.instance(String, "test")); @singleton class Foo { public constructor(@inject(String) public readonly test: string) {} } expect(container.get(Foo).test).to.equal("test"); }); }); }); });
the_stack
import { useAnimation } from '@angular/animations'; import { AfterViewInit, ChangeDetectorRef, Component, ViewChild, OnDestroy } from '@angular/core'; import { DisplayDensity, growVerIn, growVerOut, IgxTreeNodeComponent, IgxTreeSearchResolver, IgxTreeComponent, ITreeNodeTogglingEventArgs, ITreeNodeToggledEventArgs, ITreeNodeSelectionEvent, IgxTreeNode } from 'igniteui-angular'; import { Subject } from 'rxjs'; import { cloneDeep } from 'lodash'; import { HIERARCHICAL_SAMPLE_DATA } from '../shared/sample-data'; interface CompanyData { ID: string; CompanyName?: string; ContactName?: string; ContactTitle?: string; Address?: string; City?: string; Region?: string; PostalCode?: string; Country?: string; Phone?: string; Fax?: string; ChildCompanies?: CompanyData[]; selected?: boolean; expanded?: boolean; disabled?: boolean; active?: boolean; } @Component({ selector: 'app-tree-sample', templateUrl: 'tree.sample.html', styleUrls: ['tree.sample.scss'] }) export class TreeSampleComponent implements AfterViewInit, OnDestroy { @ViewChild('tree1', { static: true }) public tree: IgxTreeComponent; @ViewChild('test', { static: true }) public testNode: IgxTreeNodeComponent<any>; public selectionModes = []; public selectionMode = 'Cascading'; public animationDuration = 400; public density: DisplayDensity = DisplayDensity.comfortable; public displayDensities: { label: DisplayDensity; selectMode: DisplayDensity; selected: boolean; togglable: boolean }[] = [ { label: DisplayDensity.comfortable, selectMode: DisplayDensity.comfortable, selected: this.density === DisplayDensity.comfortable, togglable: false }, { label: DisplayDensity.cosy, selectMode: DisplayDensity.cosy, selected: this.density === DisplayDensity.cosy, togglable: false }, { label: DisplayDensity.compact, selectMode: DisplayDensity.compact, selected: this.density === DisplayDensity.compact, togglable: false } ]; public data: CompanyData[]; public singleBranchExpand = false; public asyncItems = new Subject<CompanyData[]>(); public loadDuration = 6000; private iteration = 0; private addedIndex = 0; private initData: CompanyData[]; constructor(private cdr: ChangeDetectorRef) { this.selectionModes = [ { label: 'None', selectMode: 'None', selected: this.selectionMode === 'None', togglable: true }, { label: 'Multiple', selectMode: 'Multiple', selected: this.selectionMode === 'Multiple', togglable: true }, { label: 'Cascade', selectMode: 'Cascading', selected: this.selectionMode === 'Cascading', togglable: true } ]; this.data = cloneDeep(HIERARCHICAL_SAMPLE_DATA); this.initData = cloneDeep(HIERARCHICAL_SAMPLE_DATA); this.mapData(this.data); } public setDummy() { this.data = generateHierarchicalData('ChildCompanies', 3, 6, 0); } public handleNodeExpanding(_event: ITreeNodeTogglingEventArgs) { // do something w/ data } public handleNodeExpanded(_event: ITreeNodeToggledEventArgs) { // do something w/ data } public handleNodeCollapsing(_event: ITreeNodeTogglingEventArgs) { // do something w/ data } public handleNodeCollapsed(_event: ITreeNodeToggledEventArgs) { // do something w/ data } public addDataChild(key: string) { const targetNode = this.getNodeByName(key); if (!targetNode.data.ChildCompanies) { targetNode.data.ChildCompanies = []; } const data = targetNode.data.ChildCompanies; data.push(Object.assign({}, data[data.length - 1], { CompanyName: `Added ${this.addedIndex++}`, selected: this.addedIndex % 2 === 0, ChildCompanies: [] })); this.cdr.detectChanges(); } public deleteLastChild(key: string) { const targetNode = this.getNodeByName(key); if (!targetNode.data.ChildCompanies) { targetNode.data.ChildCompanies = []; } const data = targetNode.data.ChildCompanies; data.splice(data.length - 1, 1); } public deleteNodesFromParent(key: string, deleteNodes: string) { const parent = this.getNodeByName(key); const nodeIds = deleteNodes.split(';'); nodeIds.forEach((nodeId) => { const index = parent.data.ChildCompanies.findIndex(e => e.ID === nodeId); parent.data.ChildCompanies.splice(index, 1); }); } public addSeveralNodes(key: string) { const targetNode = this.getNodeByName(key); if (!targetNode.data.ChildCompanies) { targetNode.data.ChildCompanies = []; } const arr = [{ ID: 'Some1', CompanyName: 'Test 1', selected: false, ChildCompanies: [{ ID: 'Some4', CompanyName: 'Test 5', selected: true, }] }, { ID: 'Some2', CompanyName: 'Test 2', selected: false }, { ID: 'Some3', CompanyName: 'Test 3', selected: false }]; this.getNodeByName(key).data.ChildCompanies = arr; this.cdr.detectChanges(); } public handleRemote(node: IgxTreeNodeComponent<any>, event: boolean) { console.log(event); node.loading = true; setTimeout(() => { const newData: CompanyData[] = []; for (let i = 0; i < 10; i++) { newData.push({ ID: `Remote ${i}`, CompanyName: `Remote ${i}` }); } node.loading = false; this.asyncItems.next(newData); }, this.loadDuration); } public ngAfterViewInit() { this.tree.nodes.toArray().forEach(node => { node.selectedChange.subscribe((ev) => { // console.log(ev); }); }); } public ngOnDestroy() { } public toggleSelectionMode(args) { // this.tree.selection = this.selectionModes[args.index].selectMode; } public changeDensity(args) { this.density = this.displayDensities[args.index].selectMode; } public addItem() { const newArray = [...this.data]; const children = Math.floor(Math.random() * 4); const createChildren = (count: number): CompanyData[] => { const array = []; for (let i = 0; i < count; i++) { this.iteration++; array.push({ ID: `TEST${this.iteration}`, CompanyName: `TEST${this.iteration}` }); } return array; }; this.iteration++; newArray.push({ ID: `TEST${this.iteration}`, CompanyName: `TEST${this.iteration}`, ChildCompanies: createChildren(children) }); this.data = newArray; } public resetData() { this.data = [...this.initData]; } public get animationSettings() { return { openAnimation: useAnimation(growVerIn, { params: { duration: `${this.animationDuration}ms` } }), closeAnimation: useAnimation(growVerOut, { params: { duration: `${this.animationDuration}ms` } }) }; } public selectSpecific() { this.tree.nodes.toArray()[0].selected = true; this.tree.nodes.toArray()[14].selected = true; this.tree.nodes.toArray()[1].selected = true; this.tree.nodes.toArray()[4].selected = true; } public selectAll() { this.tree.nodes.toArray().forEach(node => node.selected = true); } public deselectSpecific() { const arr = [ this.tree.nodes.toArray()[0], this.tree.nodes.toArray()[14], this.tree.nodes.toArray()[1], this.tree.nodes.toArray()[4] ]; this.tree.deselectAll(arr); } public deselectAll() { this.tree.deselectAll(); } public changeNodeSelectionState() { this.tree.nodes.toArray()[8].selected = !this.tree.nodes.toArray()[8].selected; } public changeNodeData() { this.tree.nodes.toArray()[8].data.selected = !this.tree.nodes.toArray()[8].data.selected; this.cdr.detectChanges(); } public nodeSelection(event: ITreeNodeSelectionEvent) { // console.log(event); if (event.newSelection.find(x => x.data.ID === 'igxTreeNode_1')) { //event.newSelection = [...event.newSelection, this.tree.nodes.toArray()[0]]; } } public customSearch(term: string) { const searchResult = this.tree.findNodes(term, this.containsComparer); // console.log(searchResult); return searchResult; } public activeNodeChanged(_event: IgxTreeNode<any>) { // active node changed } public keydown(_event: KeyboardEvent) { // console.log(evt); } private mapData(data: any[]) { data.forEach(x => { x.selected = false; if (x.hasOwnProperty('ChildCompanies') && x.ChildCompanies.length) { this.mapData(x.ChildCompanies); } }); } private containsComparer: IgxTreeSearchResolver = (term: any, node: IgxTreeNodeComponent<any>) => node.data?.ID?.toLowerCase()?.indexOf(term.toLowerCase()) > -1; private getNodeByName(key: string) { return this.tree.findNodes(key, (_term: string, n: IgxTreeNodeComponent<any>) => n.data?.ID === _term)[0]; } } const generateHierarchicalData = (childKey: string, level = 7, children = 6, iter = 0): any[] => { const returnArray = []; if (level === 0) { return returnArray; } for (let i = 0; i < children; i++) { // create Root member iter++; returnArray.push({ ID: `Dummy${iter}`, CompanyName: `Dummy-${iter}`, [childKey]: generateHierarchicalData(childKey, children, level - 1) }); } return returnArray; };
the_stack
import { TextBlock, StackPanel, AdvancedDynamicTexture, Image, Button, Rectangle, Control, Grid } from "@babylonjs/gui"; import { Scene, Sound, ParticleSystem, PostProcess, Effect, SceneSerializer } from "@babylonjs/core"; export class Hud { private _scene: Scene; //Game Timer public time: number; //keep track to signal end game REAL TIME private _prevTime: number = 0; private _clockTime: TextBlock = null; //GAME TIME private _startTime: number; private _stopTimer: boolean; private _sString = "00"; private _mString = 11; private _lanternCnt: TextBlock; //Animated UI sprites private _sparklerLife: Image; private _spark: Image; //Timer handlers public stopSpark: boolean; private _handle; private _sparkhandle; //Pause toggle public gamePaused: boolean; //Quit game public quit: boolean; public transition: boolean = false; //UI Elements public pauseBtn: Button; public fadeLevel: number; private _playerUI; private _pauseMenu; private _controls; constructor(scene: Scene) { this._scene = scene; const playerUI = AdvancedDynamicTexture.CreateFullscreenUI("UI"); this._playerUI = playerUI; this._playerUI.idealHeight = 720; const lanternCnt = new TextBlock(); lanternCnt.name = "lantern count"; lanternCnt.textVerticalAlignment = TextBlock.VERTICAL_ALIGNMENT_CENTER; lanternCnt.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_RIGHT; lanternCnt.verticalAlignment = Control.VERTICAL_ALIGNMENT_TOP; lanternCnt.fontSize = "22px"; lanternCnt.color = "white"; lanternCnt.text = "Lanterns: 1 / 22"; lanternCnt.top = "32px"; lanternCnt.left = "-64px"; lanternCnt.width = "25%"; lanternCnt.fontFamily = "Viga"; lanternCnt.resizeToFit = true; playerUI.addControl(lanternCnt); this._lanternCnt = lanternCnt; const stackPanel = new StackPanel(); stackPanel.height = "100%"; stackPanel.width = "100%"; stackPanel.top = "14px"; stackPanel.verticalAlignment = 0; playerUI.addControl(stackPanel); //Game timer text const clockTime = new TextBlock(); clockTime.name = "clock"; clockTime.textHorizontalAlignment = TextBlock.HORIZONTAL_ALIGNMENT_CENTER; clockTime.fontSize = "48px"; clockTime.color = "white"; clockTime.text = "11:00"; clockTime.resizeToFit = true; clockTime.height = "96px"; clockTime.width = "220px"; clockTime.fontFamily = "Viga"; stackPanel.addControl(clockTime); this._clockTime = clockTime; //sparkler bar animation const sparklerLife = new Image("sparkLife", "./sprites/sparkLife.png"); sparklerLife.width = "54px"; sparklerLife.height = "162px"; sparklerLife.cellId = 0; sparklerLife.cellHeight = 108; sparklerLife.cellWidth = 36; sparklerLife.sourceWidth = 36; sparklerLife.sourceHeight = 108; sparklerLife.horizontalAlignment = 0; sparklerLife.verticalAlignment = 0; sparklerLife.left = "14px"; sparklerLife.top = "14px"; playerUI.addControl(sparklerLife); this._sparklerLife = sparklerLife; const spark = new Image("spark", "./sprites/spark.png"); spark.width = "40px"; spark.height = "40px"; spark.cellId = 0; spark.cellHeight = 20; spark.cellWidth = 20; spark.sourceWidth = 20; spark.sourceHeight = 20; spark.horizontalAlignment = 0; spark.verticalAlignment = 0; spark.left = "21px"; spark.top = "20px"; playerUI.addControl(spark); this._spark = spark; const pauseBtn = Button.CreateImageOnlyButton("pauseBtn", "./sprites/pauseBtn.png"); pauseBtn.width = "48px"; pauseBtn.height = "86px"; pauseBtn.thickness = 0; pauseBtn.verticalAlignment = 0; pauseBtn.horizontalAlignment = 1; pauseBtn.top = "-16px"; playerUI.addControl(pauseBtn); pauseBtn.zIndex = 10; this.pauseBtn = pauseBtn; //when the button is down, make pause menu visable and add control to it pauseBtn.onPointerDownObservable.add(() => { this._pauseMenu.isVisible = true; playerUI.addControl(this._pauseMenu); this.pauseBtn.isHitTestVisible = false; //when game is paused, make sure that the next start time is the time it was when paused this.gamePaused = true; this._prevTime = this.time; }); this._createPauseMenu(); this._createControlsMenu(); } public updateHud(): void { if (!this._stopTimer && this._startTime != null) { let curTime = Math.floor((new Date().getTime() - this._startTime) / 1000) + this._prevTime; // divide by 1000 to get seconds this.time = curTime; //keeps track of the total time elapsed in seconds this._clockTime.text = this._formatTime(curTime); } } public updateLanternCount(numLanterns: number): void { this._lanternCnt.text = "Lanterns: " + numLanterns + " / 22"; } //---- Game Timer ---- public startTimer(): void { this._startTime = new Date().getTime(); this._stopTimer = false; } public stopTimer(): void { this._stopTimer = true; } //format the time so that it is relative to 11:00 -- game time private _formatTime(time: number): string { let minsPassed = Math.floor(time / 60); //seconds in a min let secPassed = time % 240; // goes back to 0 after 4mins/240sec //gameclock works like: 4 mins = 1 hr // 4sec = 1/15 = 1min game time if (secPassed % 4 == 0) { this._mString = Math.floor(minsPassed / 4) + 11; this._sString = (secPassed / 4 < 10 ? "0" : "") + secPassed / 4; } let day = (this._mString == 11 ? " PM" : " AM"); return (this._mString + ":" + this._sString + day); } //---- Sparkler Timers ---- //start and restart sparkler, handles setting the texture and animation frame public startSparklerTimer(): void { //reset the sparkler timers & animation frames this.stopSpark = false; this._sparklerLife.cellId = 0; this._spark.cellId = 0; if (this._handle) { clearInterval(this._handle); } if (this._sparkhandle) { clearInterval(this._sparkhandle); } this._scene.getLightByName("sparklight").intensity = 35; //sparkler animation, every 2 seconds update for 10 bars of sparklife this._handle = setInterval(() => { if (!this.gamePaused) { if (this._sparklerLife.cellId < 10) { this._sparklerLife.cellId++; } if (this._sparklerLife.cellId == 10) { this.stopSpark = true; clearInterval(this._handle); } } }, 2000); this._sparkhandle = setInterval(() => { if (!this.gamePaused) { if (this._sparklerLife.cellId < 10 && this._spark.cellId < 5) { this._spark.cellId++; } else if (this._sparklerLife.cellId < 10 && this._spark.cellId >= 5) { this._spark.cellId = 0; } else { this._spark.cellId = 0; clearInterval(this._sparkhandle); } } }, 185); } //stop the sparkler, resets the texture public stopSparklerTimer(): void { this.stopSpark = true; this._scene.getLightByName("sparklight").intensity = 0; } //---- Pause Menu Popup ---- private _createPauseMenu(): void { this.gamePaused = false; const pauseMenu = new Rectangle(); pauseMenu.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_CENTER; pauseMenu.verticalAlignment = Control.VERTICAL_ALIGNMENT_CENTER; pauseMenu.height = 0.8; pauseMenu.width = 0.5; pauseMenu.thickness = 0; pauseMenu.isVisible = false; //background image const image = new Image("pause", "sprites/pause.jpeg"); pauseMenu.addControl(image); //stack panel for the buttons const stackPanel = new StackPanel(); stackPanel.width = .83; pauseMenu.addControl(stackPanel); const resumeBtn = Button.CreateSimpleButton("resume", "RESUME"); resumeBtn.width = 0.18; resumeBtn.height = "44px"; resumeBtn.color = "white"; resumeBtn.fontFamily = "Viga"; resumeBtn.paddingBottom = "14px"; resumeBtn.cornerRadius = 14; resumeBtn.fontSize = "12px"; resumeBtn.textBlock.resizeToFit = true; resumeBtn.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; resumeBtn.verticalAlignment = Control.VERTICAL_ALIGNMENT_CENTER; stackPanel.addControl(resumeBtn); this._pauseMenu = pauseMenu; //when the button is down, make menu invisable and remove control of the menu resumeBtn.onPointerDownObservable.add(() => { this._pauseMenu.isVisible = false; this._playerUI.removeControl(pauseMenu); this.pauseBtn.isHitTestVisible = true; //game unpaused, our time is now reset this.gamePaused = false; this._startTime = new Date().getTime(); }); const controlsBtn = Button.CreateSimpleButton("controls", "CONTROLS"); controlsBtn.width = 0.18; controlsBtn.height = "44px"; controlsBtn.color = "white"; controlsBtn.fontFamily = "Viga"; controlsBtn.paddingBottom = "14px"; controlsBtn.cornerRadius = 14; controlsBtn.fontSize = "12px"; resumeBtn.textBlock.resizeToFit = true; controlsBtn.verticalAlignment = Control.VERTICAL_ALIGNMENT_CENTER; controlsBtn.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; stackPanel.addControl(controlsBtn); //when the button is down, make menu invisable and remove control of the menu controlsBtn.onPointerDownObservable.add(() => { //open controls screen this._controls.isVisible = true; this._pauseMenu.isVisible = false; }); const quitBtn = Button.CreateSimpleButton("quit", "QUIT"); quitBtn.width = 0.18; quitBtn.height = "44px"; quitBtn.color = "white"; quitBtn.fontFamily = "Viga"; quitBtn.paddingBottom = "12px"; quitBtn.cornerRadius = 14; quitBtn.fontSize = "12px"; resumeBtn.textBlock.resizeToFit = true; quitBtn.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_LEFT; quitBtn.verticalAlignment = Control.VERTICAL_ALIGNMENT_CENTER; stackPanel.addControl(quitBtn); //set up transition effect Effect.RegisterShader("fade", "precision highp float;" + "varying vec2 vUV;" + "uniform sampler2D textureSampler; " + "uniform float fadeLevel; " + "void main(void){" + "vec4 baseColor = texture2D(textureSampler, vUV) * fadeLevel;" + "baseColor.a = 1.0;" + "gl_FragColor = baseColor;" + "}"); this.fadeLevel = 1.0; quitBtn.onPointerDownObservable.add(() => { const postProcess = new PostProcess("Fade", "fade", ["fadeLevel"], null, 1.0, this._scene.getCameraByName("cam")); postProcess.onApply = (effect) => { effect.setFloat("fadeLevel", this.fadeLevel); }; this.transition = true; }) } //---- Controls Menu Popup ---- private _createControlsMenu(): void { const controls = new Rectangle(); controls.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_CENTER; controls.verticalAlignment = Control.VERTICAL_ALIGNMENT_CENTER; controls.height = 0.8; controls.width = 0.5; controls.thickness = 0; controls.color = "white"; controls.isVisible = false; this._playerUI.addControl(controls); this._controls = controls; //background image const image = new Image("controls", "sprites/controls.jpeg"); controls.addControl(image); const title = new TextBlock("title", "CONTROLS"); title.resizeToFit = true; title.verticalAlignment = Control.VERTICAL_ALIGNMENT_TOP; title.fontFamily = "Viga"; title.fontSize = "32px"; title.top = "14px"; controls.addControl(title); const backBtn = Button.CreateImageOnlyButton("back", "./sprites/lanternbutton.jpeg"); backBtn.width = "40px"; backBtn.height = "40px"; backBtn.top = "14px"; backBtn.thickness = 0; backBtn.horizontalAlignment = Control.HORIZONTAL_ALIGNMENT_RIGHT; backBtn.verticalAlignment = Control.VERTICAL_ALIGNMENT_TOP; controls.addControl(backBtn); //when the button is down, make menu invisable and remove control of the menu backBtn.onPointerDownObservable.add(() => { this._pauseMenu.isVisible = true; this._controls.isVisible = false; }); } }
the_stack
import fs from 'fs'; import AxiosError from 'axios-error'; import FormData from 'form-data'; import axios, { AxiosInstance, AxiosResponse } from 'axios'; import invariant from 'ts-invariant'; import warning from 'warning'; import { OnRequestFunction, camelcaseKeys, createRequestInterceptor, onRequest, snakecaseKeys, } from 'messaging-api-common'; import * as WechatTypes from './WechatTypes'; function throwErrorIfAny(response: AxiosResponse): AxiosResponse { const { errcode, errmsg } = response.data; if (!errcode || errcode === 0) return response; const msg = `WeChat API - ${errcode} ${errmsg}`; throw new AxiosError(msg, { response, config: response.config, request: response.request, }); } export default class WechatClient { /** * @deprecated Use `new WechatClient(...)` instead. */ static connect(config: WechatTypes.ClientConfig): WechatClient { warning( false, '`WechatClient.connect(...)` is deprecated. Use `new WechatClient(...)` instead.' ); return new WechatClient(config); } /** * The underlying axios instance. */ readonly axios: AxiosInstance; /** * The current access token used by the client. */ accessToken = ''; /** * The callback to be called when receiving requests. */ private onRequest?: OnRequestFunction; /** * The app ID used by the client. */ private appId: string; /** * The app secret used by the client. */ private appSecret: string; /** * The timestamp of the token expired time. */ private tokenExpiresAt = 0; constructor(config: WechatTypes.ClientConfig) { invariant( typeof config !== 'string', `WechatClient: do not allow constructing client with ${config} string. Use object instead.` ); this.appId = config.appId; this.appSecret = config.appSecret; this.onRequest = config.onRequest || onRequest; const { origin } = config; this.axios = axios.create({ baseURL: `${origin || 'https://api.weixin.qq.com'}/cgi-bin/`, headers: { 'Content-Type': 'application/json', }, }); this.axios.interceptors.request.use( createRequestInterceptor({ onRequest: this.onRequest, }) ); } private async refreshToken(): Promise<void> { const { accessToken, expiresIn } = await this.getAccessToken(); this.accessToken = accessToken; this.tokenExpiresAt = Date.now() + expiresIn * 1000; } private async refreshTokenWhenExpired(): Promise<void> { if (Date.now() > this.tokenExpiresAt) { await this.refreshToken(); } } /** * 获取 access_token * * @returns Access token info * * @see https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140183 * * @example * * ```js * await client.getAccessToken(); * // { * // accessToken: "ACCESS_TOKEN", * // expiresIn: 7200 * // } * ``` */ getAccessToken(): Promise<WechatTypes.AccessToken> { return this.axios .get< | { access_token: string; expires_in: number } | WechatTypes.FailedResponseData >( `/token?grant_type=client_credential&appid=${this.appId}&secret=${this.appSecret}` ) .then(throwErrorIfAny) .then( (res) => camelcaseKeys(res.data, { deep: true, }) as any ); } /** * 临时素材 * * 媒体文件保存时间为 3 天,即 3 天后 media_id 失效。 * * 图片(image)- 2M,支持 PNG,JPEG,JPG,GIF 格式 * 语音(voice)- 2M,播放长度不超过 60s,支持 AMR,MP3 格式 * 视频(video)- 10MB,支持 MP4 格式 * 缩略图(thumb)- 64KB,支持 JPG 格式 */ /** * 多媒体文件上传接口 * * @param type - Type of the media to upload. * @param media - Buffer or stream of the media to upload. * @returns Info of the uploaded media. * * @see https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738726 * * @example * * ```js * const fs = require('fs'); * * const buffer = fs.readFileSync('test.jpg'); * * await client.uploadMedia('image', buffer); * // { * // type: 'image', * // mediaId: 'MEDIA_ID', * // createdAt: 123456789 * // } * ``` */ async uploadMedia( type: WechatTypes.MediaType, media: Buffer | fs.ReadStream ): Promise<WechatTypes.UploadedMedia> { await this.refreshTokenWhenExpired(); const form = new FormData(); form.append('media', media); return this.axios .post< | { type: string; media_id: string; created_at: number } | WechatTypes.FailedResponseData >(`/media/upload?access_token=${this.accessToken}&type=${type}`, form, { headers: form.getHeaders(), }) .then(throwErrorIfAny) .then( (res) => camelcaseKeys(res.data, { deep: true, }) as any ); } /** * 下载多媒体文件接口 * * @param mediaId - ID of the media to get. * @returns Info of the media. * * @see https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738727 * * @example * * ```js * await client.getMedia(MEDIA_ID); * // { * // videoUrl: "..." * // } * ``` */ async getMedia(mediaId: string): Promise<WechatTypes.Media> { await this.refreshTokenWhenExpired(); return this.axios .get<{ video_url: string } | WechatTypes.FailedResponseData>( `/media/get?access_token=${this.accessToken}&media_id=${mediaId}` ) .then(throwErrorIfAny) .then( (res) => camelcaseKeys(res.data, { deep: true, }) as any ); } /** * 发送消息-客服消息 * * @internal * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 */ async sendRawBody( body: { touser: string; } & WechatTypes.SendMessageOptions & ( | { msgtype: 'text'; text: { content: string; }; } | { msgtype: 'image'; image: { mediaId: string; }; } | { msgtype: 'voice'; voice: { mediaId: string; }; } | { msgtype: 'video'; video: WechatTypes.Video; } | { msgtype: 'music'; music: WechatTypes.Music; } | { msgtype: 'news'; news: WechatTypes.News; } | { msgtype: 'mpnews'; mpnews: { mediaId: string; }; } | { msgtype: 'msgmenu'; msgmenu: WechatTypes.MsgMenu; } | { msgtype: 'wxcard'; wxcard: { cardId: string; }; } | { msgtype: 'miniprogrampage'; miniprogrampage: WechatTypes.MiniProgramPage; } ) ): Promise<WechatTypes.SucceededResponseData> { await this.refreshTokenWhenExpired(); return this.axios .post<WechatTypes.ResponseData>( `/message/custom/send?access_token=${this.accessToken}`, snakecaseKeys(body, { deep: true }) ) .then(throwErrorIfAny) .then( (res) => camelcaseKeys(res.data, { deep: true, }) as any ); } /** * 发送文本消息 * * @param userId - User ID of the recipient * @param text - Text to be sent. * @param options - The other parameters. * @returns Error code and error message. * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 * * @example * * ```js * await client.sendText(USER_ID, 'Hello!'); * ``` */ sendText( userId: string, text: string, options?: WechatTypes.SendMessageOptions ): Promise<WechatTypes.SucceededResponseData> { return this.sendRawBody({ touser: userId, msgtype: 'text', text: { content: text, }, ...options, }); } /** * 发送图片消息 * * @param userId - User ID of the recipient * @param mediaId - ID of the media to be sent. * @param options - The other parameters. * @returns Error code and error message. * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 * * @example * * ```js * await client.sendImage(USER_ID, 'MEDIA_ID'); * ``` */ sendImage( userId: string, mediaId: string, options?: WechatTypes.SendMessageOptions ): Promise<WechatTypes.SucceededResponseData> { return this.sendRawBody({ touser: userId, msgtype: 'image', image: { mediaId, }, ...options, }); } /** * 发送语音消息 * * @param userId - User ID of the recipient * @param mediaId - ID of the media to be sent. * @param options - The other parameters. * @returns Error code and error message. * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 * * @example * * ```js * await client.sendVoice(USER_ID, 'MEDIA_ID'); * ``` */ sendVoice( userId: string, mediaId: string, options?: WechatTypes.SendMessageOptions ): Promise<WechatTypes.SucceededResponseData> { return this.sendRawBody({ touser: userId, msgtype: 'voice', voice: { mediaId, }, ...options, }); } /** * 发送视频消息 * * @param userId - User ID of the recipient * @param video - Info of the video to be sent. * @param options - The other parameters. * @returns Error code and error message. * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 * * @example * * ```js * await client.sendVideo(USER_ID, { * mediaId: 'MEDIA_ID', * thumbMediaId: 'THUMB_MEDIA_ID', * title: 'VIDEO_TITLE', * description: 'VIDEO_DESCRIPTION', * }); * ``` */ sendVideo( userId: string, video: WechatTypes.Video, options?: WechatTypes.SendMessageOptions ): Promise<WechatTypes.SucceededResponseData> { return this.sendRawBody({ touser: userId, msgtype: 'video', video, ...options, }); } /** * 发送音乐消息 * * @param userId - User ID of the recipient * @param news - Data of the music to be sent. * @param options - The other parameters. * @returns Error code and error message. * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 * * @example * * ```js * await client.sendMusic(USER_ID, { * musicurl: 'MUSIC_URL', * hqmusicurl: 'HQ_MUSIC_URL', * thumbMediaId: 'THUMB_MEDIA_ID', * title: 'MUSIC_TITLE', * description: 'MUSIC_DESCRIPTION', * }); * ``` */ sendMusic( userId: string, music: WechatTypes.Music, options?: WechatTypes.SendMessageOptions ): Promise<WechatTypes.SucceededResponseData> { return this.sendRawBody({ touser: userId, msgtype: 'music', music, ...options, }); } /** * 发送图文消息(点击跳转到外链) * * 图文消息条数限制在 8 条以内,注意,如果图文数超过 8,则将会无响应。 * * @param userId - User ID of the recipient * @param news - Data of the news to be sent. * @param options - The other parameters. * @returns Error code and error message. * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 * * @example * * ```js * await client.sendNews(USER_ID, { * articles: [ * { * title: 'Happy Day', * description: 'Is Really A Happy Day', * url: 'URL', * picurl: 'PIC_URL', * }, * { * title: 'Happy Day', * description: 'Is Really A Happy Day', * url: 'URL', * picurl: 'PIC_URL', * }, * ], * }); * ``` */ sendNews( userId: string, news: WechatTypes.News, options?: WechatTypes.SendMessageOptions ): Promise<WechatTypes.SucceededResponseData> { return this.sendRawBody({ touser: userId, msgtype: 'news', news, ...options, }); } /** * 发送图文消息(点击跳转到图文消息页面) * * 图文消息条数限制在 8 条以内,注意,如果图文数超过 8,则将会无响应。 * * @param userId - User ID of the recipient * @param mediaId - ID of the media to be sent. * @param options - The other parameters. * @returns Error code and error message. * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 * * @example * * ```js * await client.sendMPNews(USER_ID, 'MEDIA_ID'); * ``` */ sendMPNews( userId: string, mediaId: string, options?: WechatTypes.SendMessageOptions ): Promise<WechatTypes.SucceededResponseData> { return this.sendRawBody({ touser: userId, msgtype: 'mpnews', mpnews: { mediaId, }, ...options, }); } /** * 发送菜单消息 * * @param userId - User ID of the recipient * @param msgMenu - Data of the msg menu to be sent. * @param options - The other parameters. * @returns Error code and error message. * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 * * @example * * ```js * await client.sendMsgMenu(USER_ID, { * headContent: 'HEAD', * list: [ * { * id: '101', * content: 'Yes', * }, * { * id: '102', * content: 'No', * }, * ], * 'tailContent': 'Tail', * }); * ``` */ sendMsgMenu( userId: string, msgMenu: WechatTypes.MsgMenu, options?: WechatTypes.SendMessageOptions ): Promise<WechatTypes.SucceededResponseData> { return this.sendRawBody({ touser: userId, msgtype: 'msgmenu', msgmenu: msgMenu, ...options, }); } /** * 发送卡券 * * @param userId - User ID of the recipient * @param cardId - ID of the card to be sent. * @param options - The other parameters. * @returns Error code and error message. * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 * * @example * * ```js * await client.sendWXCard(USER_ID, '123dsdajkasd231jhksad'); * ``` */ sendWXCard( userId: string, cardId: string, options?: WechatTypes.SendMessageOptions ): Promise<WechatTypes.SucceededResponseData> { return this.sendRawBody({ touser: userId, msgtype: 'wxcard', wxcard: { cardId, }, ...options, }); } /** * 发送小程序卡片(要求小程序与公众号已关联) * * @param userId - User ID of the recipient * @param miniProgramPage - Info of the mini program page to be sent. * @param options - The other parameters. * @returns Error code and error message. * * @see https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Service_Center_messages.html#7 * * @example * * ```js * await client.sendMiniProgramPage(USER_ID, { * title: 'title', * appid: 'appid', * pagepath: 'pagepath', * thumbMediaId: 'thumb_media_id', * }); * ``` */ sendMiniProgramPage( userId: string, miniProgramPage: WechatTypes.MiniProgramPage, options?: WechatTypes.SendMessageOptions ): Promise<WechatTypes.SucceededResponseData> { return this.sendRawBody({ touser: userId, msgtype: 'miniprogrampage', miniprogrampage: miniProgramPage, ...options, }); } // TODO: implement typing // TODO: 客服帳號相關 }
the_stack
import { JavaArrayList, JavaBigDecimal, JavaBigInteger, JavaBoolean, JavaByte, JavaDate, JavaDouble, JavaEnum, JavaFloat, JavaHashMap, JavaHashSet, JavaInteger, JavaLong, JavaOptional, JavaShort, JavaString } from "../../../java-wrappers"; import { DefaultMarshaller } from "../DefaultMarshaller"; import { MarshallingContext } from "../../MarshallingContext"; import { ErraiObjectConstants } from "../../model/ErraiObjectConstants"; import { MarshallerProvider } from "../../MarshallerProvider"; import { Portable } from "../../Portable"; import { NumValBasedErraiObject } from "../../model/NumValBasedErraiObject"; import { ValueBasedErraiObject } from "../../model/ValueBasedErraiObject"; import { JavaType } from "../../../java-wrappers/JavaType"; import { NumberUtils } from "../../../util/NumberUtils"; import { UnmarshallingContext } from "../../UnmarshallingContext"; import { EnumStringValueBasedErraiObject } from "../../model/EnumStringValueBasedErraiObject"; beforeEach(() => { MarshallerProvider.initialize(); }); describe("marshall", () => { const objectId = ErraiObjectConstants.OBJECT_ID; const encodedType = ErraiObjectConstants.ENCODED_TYPE; const value = ErraiObjectConstants.VALUE; const enumStringValue = ErraiObjectConstants.ENUM_STRING_VALUE; describe("pojo marshalling", () => { test("custom pojo, should return serialize it normally", () => { const input = new User({ name: "my name", sendSpam: false, age: new JavaInteger("10"), address: new Address({ line1: "address line 1", type: AddressType.WORK }), bestFriend: new User({ name: "my name 2", sendSpam: true, address: new Address({ line1: "address 2 line 1" }) }) }); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: "com.app.my.Pojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), name: "my name", age: 10, sendSpam: false, address: { [encodedType]: "com.app.my.Address", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), line1: "address line 1", type: new EnumStringValueBasedErraiObject("com.app.my.AddressType", AddressType.WORK.name).asErraiObject() }, bestFriend: { [encodedType]: "com.app.my.Pojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), name: "my name 2", sendSpam: true, age: null, address: { [encodedType]: "com.app.my.Address", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), line1: "address 2 line 1", type: null }, bestFriend: null } }); }); test("custom pojo with function, should serialize it normally and ignore the function", () => { const input = { _fqcn: "com.app.my.Pojo", foo: "bar", doSomething: () => { return "hey!"; } }; const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: "com.app.my.Pojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), foo: "bar" }); }); test("custom pojo without fqcn, should throw error", () => { const input = { foo: "bar" }; const context = new MarshallingContext(); const marshaller = new DefaultMarshaller(); expect(() => marshaller.marshall(input, context)).toThrowError(); }); test("custom pojo with a pojo without fqcn as property, should throw error", () => { const input = { _fqcn: "com.app.my.Pojo", name: "my name", childPojo: { foo: "bar" } }; const context = new MarshallingContext(); const marshaller = new DefaultMarshaller(); expect(() => marshaller.marshall(input, context)).toThrowError(); }); test("custom pojo with java types, should serialize it normally", () => { const date = new Date(); const input = new JavaTypesPojo({ bigDecimal: new JavaBigDecimal("1.1"), bigInteger: new JavaBigInteger("2"), boolean: false, byte: new JavaByte("3"), double: new JavaDouble("1.2"), float: new JavaFloat("1.3"), integer: new JavaInteger("4"), long: new JavaLong("5"), short: new JavaShort("6"), string: "str", date: new Date(date), optional: new JavaOptional<string>("optstr") }); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: "com.app.my.Pojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), bigDecimal: { [encodedType]: JavaType.BIG_DECIMAL, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: "1.1" }, bigInteger: { [encodedType]: JavaType.BIG_INTEGER, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: "2" }, boolean: false, byte: 3, double: 1.2, float: 1.3, integer: 4, long: new NumValBasedErraiObject(JavaType.LONG, "5").asErraiObject(), short: 6, string: "str", date: new ValueBasedErraiObject(JavaType.DATE, `${date.getTime()}`).asErraiObject(), optional: new ValueBasedErraiObject(JavaType.OPTIONAL, "optstr").asErraiObject() }); }); test("custom pojo with collection type, should serialize it normally", () => { const input = { _fqcn: "com.app.my.Pojo", list: ["1", "2", "3"], set: new Set(["3", "2", "1"]), map: new Map([["k1", "v1"], ["k2", "v2"]]) }; const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: "com.app.my.Pojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), list: { [encodedType]: JavaType.ARRAY_LIST, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: ["1", "2", "3"] }, set: { [encodedType]: JavaType.HASH_SET, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: ["3", "2", "1"] }, map: { [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: { k1: "v1", k2: "v2" } } }); }); test("custom pojo with enum type, should serialize it normally", () => { const input = { _fqcn: "com.app.my.Pojo", str: "foo", enum: AddressType.HOME }; const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: "com.app.my.Pojo", [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), str: "foo", enum: new EnumStringValueBasedErraiObject("com.app.my.AddressType", AddressType.HOME.name).asErraiObject() }); }); }); describe("object caching", () => { test("custom pojo with repeated pojo objects, should cache the object and don't repeat data", () => { // === scenario // repeatedNode appears two times in the hierarchy, all other nodes are unique const repeatedNode = new Node({ data: "repeatedNode" }); const input = new Node({ data: "root", right: new Node({ data: "rightNode", left: repeatedNode, right: new Node({ data: "rightLeaf" }) }), left: repeatedNode }); // === test const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); // === assertion // expects all nodes to contain their data and a unique objectId, except for the deepest left node. // the deepest left node should contain only its encodedType and objectId, which needs to be the same as the root's left node const rootObjId = output![objectId]; expect(output![encodedType]).toEqual("com.app.my.Node"); expect((output as any).data).toEqual("root"); const firstLeftLeaf = (output as any).left; const firstLeftLeafObjId = firstLeftLeaf[objectId]; expect(firstLeftLeaf.data).toEqual("repeatedNode"); const rightNodeOut = (output as any).right; const rightNodeObjId = rightNodeOut[objectId]; expect(rightNodeOut.data).toEqual("rightNode"); const repeatedLeftLeaf = (rightNodeOut as any).left; const repeatedLeftLeafObjId = repeatedLeftLeaf[objectId]; expect(repeatedLeftLeaf.data).toBeUndefined(); const rightLeafOut = (rightNodeOut as any).right; const rightLeafObjId = rightLeafOut[objectId]; expect(rightLeafOut.data).toEqual("rightLeaf"); expect(firstLeftLeafObjId).toEqual(repeatedLeftLeafObjId); // reuse same id const allObjIds = [rootObjId, firstLeftLeafObjId, rightNodeObjId, repeatedLeftLeafObjId, rightLeafObjId]; expect(allObjIds.forEach(id => expect(id).toMatch(NumberUtils.nonNegativeIntegerRegex))); // all ids unique (excluding the reused one) const uniqueObjIds = new Set(allObjIds); expect(uniqueObjIds).toStrictEqual(new Set([rootObjId, firstLeftLeafObjId, rightNodeObjId, rightLeafObjId])); }); test("custom pojo with repeated JavaBigDecimal objects, should not cache it and not reuse data", () => { const repeatedValue = new JavaBigDecimal("1.1"); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaBigDecimal("1.2") }), right: new Node({ data: repeatedValue }) }); // === test const context = new MarshallingContext(); const output = new DefaultMarshaller().marshall(input, context); // === assertions const rootObjId = output![objectId]; const rootDataObjId = (output as any).data[objectId]; expect((output as any).data[value]).toEqual("1.1"); const leftObjId = (output as any).left[objectId]; const leftDataObjId = (output as any).left.data[objectId]; expect((output as any).left.data[value]).toEqual("1.2"); const rightObjId = (output as any).right[objectId]; const rightDataObjId = (output as any).right.data[objectId]; expect((output as any).right.data[value]).toEqual("1.1"); const allObjectIds = [rootObjId, rootDataObjId, leftObjId, leftDataObjId, rightObjId, rightDataObjId]; allObjectIds.forEach(id => expect(id).toBeDefined()); // create new object ids even for same obj references expect(new Set(allObjectIds)).toStrictEqual(new Set(allObjectIds)); // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated JavaBigInteger objects, should not cache it", () => { const repeatedValue = new JavaBigInteger("1"); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaBigInteger("2") }), right: new Node({ data: repeatedValue }) }); // === test const context = new MarshallingContext(); const output = new DefaultMarshaller().marshall(input, context); // === assertions const rootObjId = output![objectId]; const rootDataObjId = (output as any).data[objectId]; expect((output as any).data[value]).toEqual("1"); const leftObjId = (output as any).left[objectId]; const leftDataObjId = (output as any).left.data[objectId]; expect((output as any).left.data[value]).toEqual("2"); const rightObjId = (output as any).right[objectId]; const rightDataObjId = (output as any).right.data[objectId]; expect((output as any).right.data[value]).toEqual("1"); const allObjectIds = [rootObjId, rootDataObjId, leftObjId, leftDataObjId, rightObjId, rightDataObjId]; allObjectIds.forEach(id => expect(id).toBeDefined()); // create new object ids even for same obj references expect(new Set(allObjectIds)).toStrictEqual(new Set(allObjectIds)); // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated JavaBoolean objects, should not cache it", () => { const repeatedValue = new JavaBoolean(false); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaBoolean(true) }), right: new Node({ data: repeatedValue }) }); const context = new MarshallingContext(); new DefaultMarshaller().marshall(input, context); // in this test we're not interested in the output structure, because Boolean types are not wrapped into an // ErraiObject, so, it doesn't even have an objectId assigned. // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated JavaByte objects, should not cache it", () => { const repeatedValue = new JavaByte("1"); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaByte("2") }), right: new Node({ data: repeatedValue }) }); const context = new MarshallingContext(); new DefaultMarshaller().marshall(input, context); // in this test we're not interested in the output structure, because Byte types are not wrapped into an // ErraiObject, so, it doesn't even have an objectId assigned. // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated array objects, should cache the object and don't repeat data", () => { const repeatedValue = ["a", "b", "c"]; const arrayInput = new Node({ data: repeatedValue, left: new Node({ data: ["d", "e"] }), right: new Node({ data: repeatedValue }) }); const javaArrayListInput = new Node({ data: new JavaArrayList(repeatedValue), left: new Node({ data: new JavaArrayList(["d", "e"]) }), right: new Node({ data: new JavaArrayList(repeatedValue) }) }); [arrayInput, javaArrayListInput].forEach(input => { const context = new MarshallingContext(); const output = new DefaultMarshaller().marshall(input, context); // === assertions const rootObjId = output![objectId]; const rootDataObjId = (output as any).data[objectId]; expect((output as any).data).toStrictEqual({ [encodedType]: JavaType.ARRAY_LIST, [objectId]: expect.anything(), [value]: ["a", "b", "c"] }); const leftObjId = (output as any).left[objectId]; const leftDataObjId = (output as any).left.data[objectId]; expect((output as any).left.data).toStrictEqual({ [encodedType]: JavaType.ARRAY_LIST, [objectId]: expect.anything(), [value]: ["d", "e"] }); const rightObjId = (output as any).right[objectId]; const rightDataObjId = (output as any).right.data[objectId]; expect((output as any).right.data).toStrictEqual({ [encodedType]: JavaType.ARRAY_LIST, [objectId]: expect.anything() // missing value since it is cached }); const allObjectIds = [rootObjId, rootDataObjId, leftObjId, leftDataObjId, rightObjId, rightDataObjId]; allObjectIds.forEach(id => expect(id).toBeDefined()); // all ids are unique except for the right data id, that was reused expect(new Set(allObjectIds)).toStrictEqual( new Set([rootObjId, rootDataObjId, leftObjId, leftDataObjId, rightObjId]) ); // do not cache repeated object const cached = context.getCached(repeatedValue); expect(ValueBasedErraiObject.from(cached!)).toStrictEqual( new ValueBasedErraiObject(JavaType.ARRAY_LIST, undefined, rootDataObjId) ); }); }); test("custom pojo with repeated set objects, should cache the object and don't repeat data", () => { const repeatedValue = new Set(["a", "b", "c"]); const setInput = new Node({ data: repeatedValue, left: new Node({ data: new Set(["d", "e"]) }), right: new Node({ data: repeatedValue }) }); const javaHashSetInput = new Node({ data: new JavaHashSet(repeatedValue), left: new Node({ data: new JavaHashSet(new Set(["d", "e"])) }), right: new Node({ data: new JavaHashSet(repeatedValue) }) }); [setInput, javaHashSetInput].forEach(input => { const context = new MarshallingContext(); const output = new DefaultMarshaller().marshall(input, context); // === assertions const rootObjId = output![objectId]; const rootDataObjId = (output as any).data[objectId]; expect((output as any).data).toStrictEqual({ [encodedType]: JavaType.HASH_SET, [objectId]: expect.anything(), [value]: ["a", "b", "c"] }); const leftObjId = (output as any).left[objectId]; const leftDataObjId = (output as any).left.data[objectId]; expect((output as any).left.data).toStrictEqual({ [encodedType]: JavaType.HASH_SET, [objectId]: expect.anything(), [value]: ["d", "e"] }); const rightObjId = (output as any).right[objectId]; const rightDataObjId = (output as any).right.data[objectId]; expect((output as any).right.data).toStrictEqual({ [encodedType]: JavaType.HASH_SET, [objectId]: expect.anything() // missing value since it is cached }); const allObjectIds = [rootObjId, rootDataObjId, leftObjId, leftDataObjId, rightObjId, rightDataObjId]; allObjectIds.forEach(id => expect(id).toBeDefined()); // all ids are unique except for the right data id, that was reused expect(new Set(allObjectIds)).toStrictEqual( new Set([rootObjId, rootDataObjId, leftObjId, leftDataObjId, rightObjId]) ); // do not cache repeated object const cached = context.getCached(repeatedValue); expect(ValueBasedErraiObject.from(cached!)).toStrictEqual( new ValueBasedErraiObject(JavaType.HASH_SET, undefined, rootDataObjId) ); }); }); test("custom pojo with repeated map objects, should cache the object and don't repeat data", () => { const repeatedMap = new Map([["k1", "v1"]]); const mapInput = new Node({ data: repeatedMap, left: new Node({ data: new Map([["k2", "v2"]]) }), right: new Node({ data: repeatedMap }) }); const javaHashMapInput = new Node({ data: new JavaHashMap(repeatedMap), left: new Node({ data: new JavaHashMap(new Map([["k2", "v2"]])) }), right: new Node({ data: new JavaHashMap(repeatedMap) }) }); [mapInput, javaHashMapInput].forEach(input => { const context = new MarshallingContext(); const output = new DefaultMarshaller().marshall(input, context); // === assertions const rootObjId = output![objectId]; const rootDataObjId = (output as any).data[objectId]; expect((output as any).data).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.anything(), [value]: { k1: "v1" } }); const leftObjId = (output as any).left[objectId]; const leftDataObjId = (output as any).left.data[objectId]; expect((output as any).left.data).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.anything(), [value]: { k2: "v2" } }); const rightObjId = (output as any).right[objectId]; const rightDataObjId = (output as any).right.data[objectId]; expect((output as any).right.data).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.anything() // missing value since it is cached }); const allObjectIds = [rootObjId, rootDataObjId, leftObjId, leftDataObjId, rightObjId, rightDataObjId]; allObjectIds.forEach(id => expect(id).toBeDefined()); // all ids are unique except for the right data id, that was reused expect(new Set(allObjectIds)).toStrictEqual( new Set([rootObjId, rootDataObjId, leftObjId, leftDataObjId, rightObjId]) ); // do not cache repeated object's data const cached = context.getCached(repeatedMap); expect(ValueBasedErraiObject.from(cached!)).toStrictEqual( new ValueBasedErraiObject(JavaType.HASH_MAP, undefined, rootDataObjId) ); }); }); test("custom pojo with repeated JavaDouble objects, should not cache it", () => { const repeatedValue = new JavaDouble("1.1"); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaDouble("1.2") }), right: new Node({ data: repeatedValue }) }); const context = new MarshallingContext(); new DefaultMarshaller().marshall(input, context); // in this test we're not interested in the output structure, because Double types are not wrapped into an // ErraiObject, so, it doesn't even have an objectId assigned. // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated JavaFloat objects, should not cache it", () => { const repeatedValue = new JavaFloat("1.1"); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaFloat("1.2") }), right: new Node({ data: repeatedValue }) }); const context = new MarshallingContext(); new DefaultMarshaller().marshall(input, context); // in this test we're not interested in the output structure, because Float types are not wrapped into an // ErraiObject, so, it doesn't even have an objectId assigned. // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated JavaInteger objects, should not cache it", () => { const repeatedValue = new JavaInteger("1"); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaInteger("2") }), right: new Node({ data: repeatedValue }) }); const context = new MarshallingContext(); new DefaultMarshaller().marshall(input, context); // in this test we're not interested in the output structure, because Integer types are not wrapped into an // ErraiObject, so, it doesn't even have an objectId assigned. // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated JavaLong objects, should not cache it", () => { const repeatedValue = new JavaLong("1"); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaLong("2") }), right: new Node({ data: repeatedValue }) }); // === test const context = new MarshallingContext(); const output = new DefaultMarshaller().marshall(input, context); // === assertions const rootObjId = output![objectId]; const rootData = NumValBasedErraiObject.from((output as any).data); expect(rootData.numVal).toEqual("1"); const leftObj = NumValBasedErraiObject.from((output as any).left); const leftData = NumValBasedErraiObject.from((output as any).left.data); expect(leftData.numVal).toEqual("2"); const rightObj = NumValBasedErraiObject.from((output as any).right); const rightData = NumValBasedErraiObject.from((output as any).right.data); expect(rightData.numVal).toEqual("1"); const allObjectIds = [rootObjId, rootData.objId, leftObj.objId, leftData.objId, rightObj.objId, rightData.objId]; allObjectIds.forEach(id => expect(id).toBeDefined()); // create new object ids even for same obj references expect(new Set(allObjectIds)).toStrictEqual(new Set(allObjectIds)); // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated JavaShort objects, should not cache it", () => { const repeatedValue = new JavaShort("1"); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaShort("2") }), right: new Node({ data: repeatedValue }) }); const context = new MarshallingContext(); new DefaultMarshaller().marshall(input, context); // in this test we're not interested in the output structure, because Short types are not wrapped into an // ErraiObject, so, it doesn't even have an objectId assigned. // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated JavaString objects, should not cache it", () => { const repeatedValue = new JavaString("str1"); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaString("str2") }), right: new Node({ data: repeatedValue }) }); const context = new MarshallingContext(); new DefaultMarshaller().marshall(input, context); // in this test we're not interested in the output structure, because String types are not wrapped into an // ErraiObject, so, it doesn't even have an objectId assigned. // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated JavaOptional objects, should not cache it", () => { const repeatedValue = new JavaOptional<string>("str1"); const input = new Node({ data: repeatedValue, left: new Node({ data: new JavaOptional<string>("str2") }), right: new Node({ data: repeatedValue }) }); // === test const context = new MarshallingContext(); const output = new DefaultMarshaller().marshall(input, context); // === assertions const rootObjId = output![objectId]; const rootDataObjId = (output as any).data[objectId]; expect((output as any).data[value]).toStrictEqual("str1"); const leftObjId = (output as any).left[objectId]; const leftDataObjId = (output as any).left.data[objectId]; expect((output as any).left.data[value]).toEqual("str2"); const rightObjId = (output as any).right[objectId]; const rightDataObjId = (output as any).right.data[objectId]; expect((output as any).right.data[value]).toEqual("str1"); const allObjectIds = [rootObjId, rootDataObjId, leftObjId, leftDataObjId, rightObjId, rightDataObjId]; allObjectIds.forEach(id => expect(id).toBeDefined()); // optional objects always use the same object id (its value doesn't matter) expect(new Set(allObjectIds)).toStrictEqual(new Set([rootObjId, rootDataObjId, leftObjId, rightObjId])); expect(rootDataObjId).toEqual(leftDataObjId); expect(rootDataObjId).toEqual(rightDataObjId); // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); test("custom pojo with repeated JavaEnum objects, should not cache it", () => { const repeatedValue = AddressType.WORK; const input = new Node({ data: repeatedValue, left: new Node({ data: AddressType.HOME }), right: new Node({ data: repeatedValue }) }); // === test const context = new MarshallingContext(); const output = new DefaultMarshaller().marshall(input, context); // === assertions const rootObjId = output![objectId]; const rootDataObjId = (output as any).data[objectId]; expect((output as any).data[enumStringValue]).toStrictEqual(AddressType.WORK.name); const leftObjId = (output as any).left[objectId]; const leftDataObjId = (output as any).left.data[objectId]; expect((output as any).left.data[enumStringValue]).toEqual(AddressType.HOME.name); const rightObjId = (output as any).right[objectId]; const rightDataObjId = (output as any).right.data[objectId]; expect((output as any).right.data[enumStringValue]).toEqual(AddressType.WORK.name); // every Node object has an unique id expect(new Set([rootObjId, leftObjId, rightObjId])).toStrictEqual(new Set([rootObjId, leftObjId, rightObjId])); // every enum field doesn't have an object id defined [rootDataObjId, rightDataObjId, leftDataObjId].forEach(id => expect(id).toBeUndefined()); // do not cache repeated object expect(context.getCached(repeatedValue)).toBeUndefined(); }); }); describe("non-pojo root types", () => { test("root null object, should serialize to null", () => { const input = null as any; const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toBeNull(); }); test("root undefined object, should serialize to null", () => { const input = undefined as any; const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toBeNull(); }); test("root JavaBigDecimal object, should serialize it normally", () => { const input = new JavaBigDecimal("1.2"); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: JavaType.BIG_DECIMAL, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: "1.2" }); }); test("root JavaBigInteger object, should serialize it normally", () => { const input = new JavaBigInteger("1"); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: JavaType.BIG_INTEGER, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: "1" }); }); test("root JavaByte object, should serialize it to byte raw value", () => { const input = new JavaByte("1"); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toEqual(1); }); test("root JavaDouble object, should serialize it to double raw value", () => { const input = new JavaDouble("1.1"); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toEqual(1.1); }); test("root JavaFloat object, should serialize it to float raw value", () => { const input = new JavaFloat("1.1"); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toEqual(1.1); }); test("root JavaInteger object, should serialize it to integer raw value", () => { const input = new JavaInteger("1"); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toEqual(1); }); test("root JavaLong object, should serialize it normally", () => { const input = new JavaLong("1"); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual(new NumValBasedErraiObject(JavaType.LONG, "1").asErraiObject()); }); test("root JavaShort object, should serialize it normally to short raw value", () => { const input = new JavaShort("1"); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toEqual(1); }); test("root JavaOptional object, should serialize it normally", () => { const input = new JavaOptional<string>("str"); const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual(new ValueBasedErraiObject(JavaType.OPTIONAL, "str").asErraiObject()); }); test("root JavaEnum object, should serialize it normally", () => { const input = AddressType.WORK; const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual( new EnumStringValueBasedErraiObject(AddressType.__fqcn(), AddressType.WORK.name).asErraiObject() ); }); test("root string object, should serialize it to string raw value", () => { const stringInput = "str"; const javaStringInput = new JavaString("str"); [stringInput, javaStringInput].forEach(input => { const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toEqual("str"); }); }); test("root date object, should serialize it normally", () => { const date = new Date(); const javaDate = new JavaDate(date); [date, javaDate].forEach(input => { const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual(new ValueBasedErraiObject(JavaType.DATE, `${date.getTime()}`).asErraiObject()); }); }); test("root boolean object, should serialize it to boolean raw value", () => { const booleanInput = false; const javaBooleanInput = new JavaBoolean(false); [booleanInput, javaBooleanInput].forEach(input => { const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toEqual(false); }); }); test("root number object, should throw error", () => { const input = 125.1; const marshaller = new DefaultMarshaller(); const ctx = new MarshallingContext(); expect(() => marshaller.marshall(input, ctx)).toThrowError(); }); test("root array object, should serialize it normally", () => { const arrayInput = ["1", "2", "3"]; const javaArrayListInput = new JavaArrayList(["1", "2", "3"]); [arrayInput, javaArrayListInput].forEach(input => { const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: JavaType.ARRAY_LIST, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: ["1", "2", "3"] }); }); }); test("root set object, should serialize it normally", () => { const setInput = new Set(["1", "2", "3"]); const javaHashSetInput = new JavaHashSet(new Set(["1", "2", "3"])); [setInput, javaHashSetInput].forEach(input => { const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: JavaType.HASH_SET, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: ["1", "2", "3"] }); }); }); test("root map object, should serialize it normally", () => { const mapInput = new Map([["k1", "v1"], ["k2", "v2"]]); const javaHashMapInput = new JavaHashMap(new Map([["k1", "v1"], ["k2", "v2"]])); [mapInput, javaHashMapInput].forEach(input => { const output = new DefaultMarshaller().marshall(input, new MarshallingContext()); expect(output).toStrictEqual({ [encodedType]: JavaType.HASH_MAP, [objectId]: expect.stringMatching(NumberUtils.nonNegativeIntegerRegex), [value]: { k1: "v1", k2: "v2" } }); }); }); }); class Node implements Portable<Node> { private readonly _fqcn = "com.app.my.Node"; public readonly data?: any = undefined; public readonly left?: Node = undefined; public readonly right?: Node = undefined; constructor(self: { data?: any; left?: Node; right?: Node }) { Object.assign(this, self); } } }); describe("unmarshall", () => { describe("non-pojo root types", () => { test("root null object, should unmarshall to undefined", () => { const marshaller = new DefaultMarshaller(); const input = null as any; const marshalledInput = marshaller.marshall(input, new MarshallingContext()) as any; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toBeUndefined(); }); test("root undefined object, should unmarshall to null", () => { const marshaller = new DefaultMarshaller(); const input = undefined as any; const marshalledInput = marshaller.marshall(input, new MarshallingContext()) as any; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toBeUndefined(); }); test("root JavaBigDecimal object, should unmarshall it normally", () => { const marshaller = new DefaultMarshaller(); const input = new JavaBigDecimal("1.1"); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaBigDecimal("1.1")); }); test("root JavaBigInteger object, should unmarshall it normally", () => { const marshaller = new DefaultMarshaller(); const input = new JavaBigInteger("1"); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaBigInteger("1")); }); test("root JavaByte object, should unmarshall it normally", () => { const marshaller = new DefaultMarshaller(); const input = 1; const marshalledInput = new NumValBasedErraiObject(JavaType.BYTE, input).asErraiObject(); const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaByte("1")); }); test("root JavaDouble object, should unmarshall it normally", () => { const marshaller = new DefaultMarshaller(); const input = 1.1; const marshalledInput = new NumValBasedErraiObject(JavaType.DOUBLE, input).asErraiObject(); const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaDouble("1.1")); }); test("root JavaFloat object, should unmarshall it normally", () => { const marshaller = new DefaultMarshaller(); const input = 1.1; const marshalledInput = new NumValBasedErraiObject(JavaType.FLOAT, input).asErraiObject(); const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaFloat("1.1")); }); test("root JavaInteger object, should unmarshall it normally", () => { const marshaller = new DefaultMarshaller(); const input = 1; const marshalledInput = new NumValBasedErraiObject(JavaType.INTEGER, input).asErraiObject(); const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaInteger("1")); }); test("root JavaLong object, should unmarshall it normally", () => { const marshaller = new DefaultMarshaller(); const input = new JavaLong("1"); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaLong("1")); }); test("root JavaShort object, should unmarshall it normally", () => { const marshaller = new DefaultMarshaller(); const input = 1; const marshalledInput = new NumValBasedErraiObject(JavaType.SHORT, input).asErraiObject(); const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaShort("1")); }); test("root JavaOptional object, should serialize it normally", () => { const marshaller = new DefaultMarshaller(); const input = new JavaOptional("1"); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new JavaOptional("1")); }); test("root JavaEnum object, should serialize it normally", () => { const marshaller = new DefaultMarshaller(); const input = AddressType.WORK; const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const factory = new Map([ [ "com.app.my.AddressType", ((name: string) => { switch (name) { case "HOME": return AddressType.HOME; case "WORK": return AddressType.WORK; default: throw new Error(`Unknown value ${name} for enum AddressType!`); } }) as any ] ]); const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(factory)); expect(output).toStrictEqual(AddressType.WORK); }); test("root string object, should unmarshall it to native string", () => { const marshaller = new DefaultMarshaller(); const stringInput = "foo"; const javaStringInput = new JavaString("foo"); [stringInput, javaStringInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual("foo"); }); }); test("root date object, should unmarshall it to native date", () => { const marshaller = new DefaultMarshaller(); const baseDate = new Date(); const dateInput = new Date(baseDate); const javaDateInput = new JavaDate(new Date(baseDate)); [dateInput, javaDateInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(baseDate); }); }); test("root boolean object, should unmarshall it to native boolean", () => { const marshaller = new DefaultMarshaller(); const booleanInput = false; const javaBooleanInput = new JavaBoolean(false); [booleanInput, javaBooleanInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(false); }); }); test("root array object, should unmarshall it to native array", () => { const marshaller = new DefaultMarshaller(); const arrayInput = ["foo"]; const javaArrayInput = new JavaArrayList(["foo"]); [arrayInput, javaArrayInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(["foo"]); }); }); test("root set object, should unmarshall it to native set", () => { const marshaller = new DefaultMarshaller(); const setInput = new Set(["foo"]); const javaSetInput = new JavaHashSet(new Set(["foo"])); [setInput, javaSetInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new Set(["foo"])); }); }); test("root map object, should unmarshall it native map", () => { const marshaller = new DefaultMarshaller(); const mapInput = new Map([["foo", "bar"]]); const javaMapInput = new JavaHashMap(new Map([["foo", "bar"]])); [mapInput, javaMapInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(new Map())); expect(output).toEqual(new Map([["foo", "bar"]])); }); }); test("root integer number object, should throw error", () => { const marshaller = new DefaultMarshaller(); const input = 1; expect(() => marshaller.unmarshall(input as any, new UnmarshallingContext(new Map()))).toThrowError(); }); test("root float number object, should throw error", () => { const marshaller = new DefaultMarshaller(); const input = 1.1; expect(() => marshaller.unmarshall(input as any, new UnmarshallingContext(new Map()))).toThrowError(); }); }); describe("pojo root types", () => { test("with custom pojo, should unmarshall correctly", () => { const oracle = new Map([ ["com.app.my.Pojo", () => new User({ age: new JavaInteger("0") }) as any], ["com.app.my.Address", () => new Address({} as any) as any], [ "com.app.my.AddressType", ((name: string) => { switch (name) { case "HOME": return AddressType.HOME; case "WORK": return AddressType.WORK; default: throw new Error(`Unknown value ${name} for enum AddressType!`); } }) as any ] ]); const marshaller = new DefaultMarshaller(); const input = new User({ name: "my name", sendSpam: false, age: new JavaInteger("10"), address: new Address({ line1: "address line 1", type: AddressType.HOME }), bestFriend: new User({ name: "my name 2", sendSpam: true, address: new Address({ line1: "address 2 line 1" }) }) }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(oracle)); expect(output).toEqual(input); }); test("with custom pojo with function, should unmarshall to a correct object containing the function", () => { const oracle = new Map([["com.app.my.PojoWithFunction", () => new PojoWithFunction({})]]); const marshaller = new DefaultMarshaller(); const input = new PojoWithFunction({ foo: "bar" }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(oracle)) as PojoWithFunction; expect(output).toEqual(input); // generates a full functional object of the correct type expect(output.whatToSay()).toEqual("Hello, bar!"); }); test("with custom pojo with java types, should unmarshall normally", () => { const marshaller = new DefaultMarshaller(); const oracle = new Map([ [ "com.app.my.Pojo", () => new JavaTypesPojo({ bigDecimal: new JavaBigDecimal("0"), bigInteger: new JavaBigInteger("0"), byte: new JavaByte("0"), double: new JavaDouble("0"), float: new JavaFloat("0"), integer: new JavaInteger("0"), short: new JavaShort("0") }) ] ]); const input = new JavaTypesPojo({ bigDecimal: new JavaBigDecimal("1.1"), bigInteger: new JavaBigInteger("2"), boolean: false, byte: new JavaByte("3"), double: new JavaDouble("1.2"), float: new JavaFloat("1.3"), integer: new JavaInteger("4"), long: new JavaLong("5"), short: new JavaShort("6"), string: "str", date: new Date(), optional: new JavaOptional<string>("optstr") }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(oracle)); expect(output).toEqual(input); }); test("with custom pojo with java collection types, should unmarshall normally", () => { const marshaller = new DefaultMarshaller(); const oracle = new Map([["com.app.my.JavaCollectionTypesPojo", () => new JavaCollectionTypesPojo({})]]); const input = new JavaCollectionTypesPojo({ list: ["1", "2"], set: new Set<string>(["3", "2"]), map: new Map([["k1", "v1"], ["k2", "v2"]]) }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, new UnmarshallingContext(oracle)); expect(output).toEqual(input); }); test("with custom pojo without fqcn, should throw error", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([["com.app.my.Pojo", () => new User({ age: new JavaInteger("0") })]]) ); const input = new User({}); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; // remove its fqcn delete marshalledInput[ErraiObjectConstants.ENCODED_TYPE]; expect(() => marshaller.unmarshall(marshalledInput, unmarshallContext)).toThrowError(); }); test("with custom pojo without factory, should throw error", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext(new Map()); const input = new User({}); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; expect(() => marshaller.unmarshall(marshalledInput, unmarshallContext)).toThrowError(); }); test("with custom pojo with property without fqcn, should throw error", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([ ["com.app.my.Pojo", () => new User({ age: new JavaInteger("0") }) as any], ["com.app.my.Address", () => new Address({} as any) as any] ]) ); const input = new User({ name: "foo", address: new Address({ line1: "bla" }) }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; // remove its fqcn delete (marshalledInput as any).address[ErraiObjectConstants.ENCODED_TYPE]; expect(() => marshaller.unmarshall(marshalledInput, unmarshallContext)).toThrowError(); }); class PojoWithFunction implements Portable<PojoWithFunction> { private readonly _fqcn = "com.app.my.PojoWithFunction"; public readonly foo?: string = undefined; constructor(self: { foo?: string }) { Object.assign(this, self); } public whatToSay() { return `Hello, ${this.foo}!`; } } class JavaCollectionTypesPojo implements Portable<JavaCollectionTypesPojo> { private readonly _fqcn = "com.app.my.JavaCollectionTypesPojo"; public readonly list?: string[] = undefined; public readonly set?: Set<string> = undefined; public readonly map?: Map<string, string> = undefined; constructor(self: { list?: string[]; set?: Set<string>; map?: Map<string, string> }) { Object.assign(this, self); } } }); describe("object caching", () => { test("custom pojo with repeated pojo objects, should cache the object and reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([ ["com.app.my.Address", () => new Address({}) as any], ["com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({}) as any] ]) ); const repeatedObject = new Address({ line1: "bla address" }); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<Address>; expect(output).toEqual(input); expect(output.field1!).toBe(output.field2!); }); test("custom pojo with repeated JavaBigDecimal objects, should not cache it and don't reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([["com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({}) as any]]) ); const repeatedObject = new JavaBigDecimal("1.1"); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<JavaBigDecimal>; expect(output).toEqual(input); expect(output.field1!).not.toBe(output.field2!); }); test("custom pojo with repeated JavaBigInteger objects, should not cache it and don't reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([["com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({}) as any]]) ); const repeatedObject = new JavaBigInteger("1"); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<JavaBigInteger>; expect(output).toEqual(input); expect(output.field1!).not.toBe(output.field2!); }); test("custom pojo with repeated JavaByte objects, should not cache it and don't reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([ [ "com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({ field1: new JavaByte("0"), field2: new JavaByte("0") }) as any ] ]) ); const repeatedObject = new JavaByte("1"); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<JavaByte>; expect(output).toEqual(input); expect(output.field1!).not.toBe(output.field2!); }); test("custom pojo with repeated JavaDouble objects, should not cache it and don't reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([ [ "com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({ field1: new JavaDouble("0"), field2: new JavaDouble("0") }) as any ] ]) ); const repeatedObject = new JavaDouble("1.1"); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<JavaDouble>; expect(output).toEqual(input); expect(output.field1!).not.toBe(output.field2!); }); test("custom pojo with repeated JavaFloat objects, should not cache it and don't reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([ [ "com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({ field1: new JavaFloat("0"), field2: new JavaFloat("0") }) as any ] ]) ); const repeatedObject = new JavaFloat("1.1"); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<JavaFloat>; expect(output).toEqual(input); expect(output.field1!).not.toBe(output.field2!); }); test("custom pojo with repeated JavaInteger objects, should not cache it and don't reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([ [ "com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({ field1: new JavaInteger("0"), field2: new JavaInteger("0") }) as any ] ]) ); const repeatedObject = new JavaInteger("1"); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<JavaInteger>; expect(output).toEqual(input); expect(output.field1!).not.toBe(output.field2!); }); test("custom pojo with repeated JavaLong objects, should not cache it and don't reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([["com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({}) as any]]) ); const repeatedObject = new JavaLong("1"); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<JavaLong>; expect(output).toEqual(input); expect(output.field1!).not.toBe(output.field2!); }); test("custom pojo with repeated JavaShort objects, should not cache it and don't reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([ [ "com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({ field1: new JavaShort("0"), field2: new JavaShort("0") }) as any ] ]) ); const repeatedObject = new JavaShort("1"); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<JavaShort>; expect(output).toEqual(input); expect(output.field1!).not.toBe(output.field2!); }); test("custom pojo with repeated JavaOptional objects, should not cache it and don't reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([["com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({}) as any]]) ); const repeatedObject = new JavaOptional("foo"); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo< JavaOptional<string> >; expect(output).toEqual(input); expect(output.field1!).not.toBe(output.field2!); }); test("custom pojo with repeated JavaEnum objects, should not cache it and don't reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([ ["com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({}) as any], [ "com.app.my.AddressType", ((name: string) => { switch (name) { case "HOME": return AddressType.HOME; case "WORK": return AddressType.WORK; default: throw new Error(`Unknown value ${name} for enum AddressType!`); } }) as any ] ]) ); const repeatedObject = AddressType.HOME; const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<AddressType>; expect(output).toEqual(input); expect(output.field1!).toBe(output.field2!); }); test("custom pojo with repeated array objects, should cache the object and reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([["com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({}) as any]]) ); const repeatedInlineArray = ["foo", "bar"]; const inlineArrayInput = new RepeatedFieldsPojo({ field1: repeatedInlineArray, field2: repeatedInlineArray }); const repeatedNewArray = new Array("foo", "bar"); const newArrayInput = new RepeatedFieldsPojo({ field1: repeatedNewArray, field2: repeatedNewArray }); [inlineArrayInput, newArrayInput].forEach(input => { const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<string[]>; expect(output).toEqual(input); expect(output.field1!).toBe(output.field2!); }); }); test("custom pojo with repeated set objects, should cache the object and reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([["com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({}) as any]]) ); const repeatedObject = new Set(["foo", "bar"]); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo<Set<string>>; expect(output).toEqual(input); expect(output.field1!).toBe(output.field2!); }); test("custom pojo with repeated map objects, should cache the object and reuse data", () => { const marshaller = new DefaultMarshaller(); const unmarshallContext = new UnmarshallingContext( new Map([["com.app.my.RepeatedFieldsPojo", () => new RepeatedFieldsPojo({}) as any]]) ); const repeatedObject = new Map([["foo1", "bar1"], ["foo2", "bar2"]]); const input = new RepeatedFieldsPojo({ field1: repeatedObject, field2: repeatedObject }); const marshalledInput = marshaller.marshall(input, new MarshallingContext())!; const output = marshaller.unmarshall(marshalledInput, unmarshallContext) as RepeatedFieldsPojo< Map<string, string> >; expect(output).toEqual(input); expect(output.field1!).toBe(output.field2!); }); class RepeatedFieldsPojo<T> implements Portable<RepeatedFieldsPojo<T>> { private readonly _fqcn = "com.app.my.RepeatedFieldsPojo"; public field1?: T = undefined; public field2?: T = undefined; constructor(self: { field1?: T; field2?: T }) { Object.assign(this, self); } } }); }); class User implements Portable<User> { private readonly _fqcn = "com.app.my.Pojo"; public readonly name?: string = undefined; public readonly sendSpam?: boolean = undefined; public readonly age?: JavaInteger = undefined; public readonly address?: Address = undefined; public readonly bestFriend?: User = undefined; constructor(self: { name?: string; sendSpam?: boolean; age?: JavaInteger; address?: Address; bestFriend?: User }) { Object.assign(this, self); } } class Address implements Portable<Address> { private readonly _fqcn = "com.app.my.Address"; public line1?: string = undefined; public type?: AddressType = undefined; constructor(self: { line1?: string; type?: AddressType }) { Object.assign(this, self); } } class AddressType extends JavaEnum<AddressType> { public static readonly HOME: AddressType = new AddressType("HOME"); public static readonly WORK: AddressType = new AddressType("WORK"); protected readonly _fqcn: string = AddressType.__fqcn(); public static __fqcn(): string { return "com.app.my.AddressType"; } public static values() { return [AddressType.HOME, AddressType.WORK]; } } class JavaTypesPojo implements Portable<JavaTypesPojo> { private readonly _fqcn = "com.app.my.Pojo"; public readonly bigDecimal?: JavaBigDecimal = undefined; public readonly bigInteger?: JavaBigInteger = undefined; public readonly boolean?: boolean = undefined; public readonly byte?: JavaByte = undefined; public readonly double?: JavaDouble = undefined; public readonly float?: JavaFloat = undefined; public readonly integer?: JavaInteger = undefined; public readonly long?: JavaLong = undefined; public readonly short?: JavaShort = undefined; public readonly string?: string = undefined; public readonly date?: Date = undefined; public readonly optional?: JavaOptional<string> = undefined; constructor(self: { bigDecimal?: JavaBigDecimal; bigInteger?: JavaBigInteger; boolean?: boolean; byte?: JavaByte; double?: JavaDouble; float?: JavaFloat; integer?: JavaInteger; long?: JavaLong; short?: JavaShort; string?: string; date?: Date; optional?: JavaOptional<string>; }) { Object.assign(this, self); } }
the_stack
import {BrowserUtils} from "../browserUtils"; import {ClientInfo} from "../clientInfo"; import {ClientType} from "../clientType"; import {ClipperUrls} from "../clipperUrls"; import {CookieUtils} from "../cookieUtils"; import {Constants} from "../constants"; import {Polyfills} from "../polyfills"; import {AuthType, UserInfo, UpdateReason} from "../userInfo"; import {Settings} from "../settings"; import {TooltipProps} from "../clipperUI/tooltipProps"; import {TooltipType} from "../clipperUI/tooltipType"; import {Communicator} from "../communicator/communicator"; import {MessageHandler} from "../communicator/messageHandler"; import {SmartValue} from "../communicator/smartValue"; import {ClipperCachedHttp} from "../http/clipperCachedHttp"; import {Localization} from "../localization/localization"; import {LocalizationHelper} from "../localization/localizationHelper"; import * as Log from "../logging/log"; import {LogHelpers} from "../logging/logHelpers"; import {SessionLogger} from "../logging/sessionLogger"; import {ClipperData} from "../storage/clipperData"; import {ClipperStorageKeys} from "../storage/clipperStorageKeys"; import {ChangeLog} from "../versioning/changeLog"; import {AuthenticationHelper} from "./authenticationHelper"; import {ExtensionBase} from "./extensionBase"; import {InvokeInfo} from "./invokeInfo"; import {InvokeSource} from "./invokeSource"; import {InvokeMode, InvokeOptions} from "./invokeOptions"; /** * The abstract base class for all of the extension workers */ export abstract class ExtensionWorkerBase<TTab, TTabIdentifier> { private onUnloading: () => void; private loggerId: string; private clipperFunnelAlreadyLogged = false; protected tab: TTab; protected tabId: TTabIdentifier; protected auth: AuthenticationHelper; protected clipperData: ClipperData; protected uiCommunicator: Communicator; protected pageNavUiCommunicator: Communicator; protected debugLoggingInjectCommunicator: Communicator; protected injectCommunicator: Communicator; protected pageNavInjectCommunicator: Communicator; protected logger: SessionLogger; protected clientInfo: SmartValue<ClientInfo>; protected sessionId: SmartValue<string>; constructor(clientInfo: SmartValue<ClientInfo>, auth: AuthenticationHelper, clipperData: ClipperData, uiMessageHandlerThunk: () => MessageHandler, injectMessageHandlerThunk: () => MessageHandler) { Polyfills.init(); this.onUnloading = () => { }; this.uiCommunicator = new Communicator(uiMessageHandlerThunk(), Constants.CommunicationChannels.extensionAndUi); this.pageNavUiCommunicator = new Communicator(uiMessageHandlerThunk(), Constants.CommunicationChannels.extensionAndPageNavUi); this.debugLoggingInjectCommunicator = new Communicator(injectMessageHandlerThunk(), Constants.CommunicationChannels.debugLoggingInjectedAndExtension); this.injectCommunicator = new Communicator(injectMessageHandlerThunk(), Constants.CommunicationChannels.injectedAndExtension); this.pageNavInjectCommunicator = new Communicator(injectMessageHandlerThunk(), Constants.CommunicationChannels.pageNavInjectedAndExtension); this.sessionId = new SmartValue<string>(); this.logger = LogManager.createExtLogger(this.sessionId, LogHelpers.isConsoleOutputEnabled() ? this.debugLoggingInjectCommunicator : undefined); this.logger.logSessionStart(); this.clipperData = clipperData; this.clipperData.setLogger(this.logger); this.auth = auth; this.clientInfo = clientInfo; // TODO Remove this function after ~some~ amount of time has passed // This is a temporary event shipping with v3.2.0 that is needed to map // the "accidental" device ids we were logging (that came from a cookie) // to the "real" device ids (ON-xxx) found in local storage that we weren't logging this.logDeviceIdMapEvent(); this.initializeCommunicators(); this.initializeContextProperties(); } private initializeContextProperties() { let clientInfo = this.clientInfo.get(); this.logger.setContextProperty(Log.Context.Custom.AppInfoId, Settings.getSetting("App_Id")); this.logger.setContextProperty(Log.Context.Custom.ExtensionLifecycleId, ExtensionBase.getExtensionId()); this.logger.setContextProperty(Log.Context.Custom.UserInfoId, undefined); this.logger.setContextProperty(Log.Context.Custom.AuthType, "None"); this.logger.setContextProperty(Log.Context.Custom.AppInfoVersion, clientInfo.clipperVersion); this.logger.setContextProperty(Log.Context.Custom.DeviceInfoId, clientInfo.clipperId); this.logger.setContextProperty(Log.Context.Custom.ClipperType, ClientType[clientInfo.clipperType]); // Sometimes the worker is created really early (e.g., pageNav, inline extension), so we need to wait // for flighting info to be returned before we set the context property if (!clientInfo.flightingInfo) { let clientInfoSetCb = ((newClientInfo) => { if (newClientInfo.flightingInfo) { this.clientInfo.unsubscribe(clientInfoSetCb); this.logger.setContextProperty(Log.Context.Custom.FlightInfo, newClientInfo.flightingInfo.join(",")); } }).bind(this); this.clientInfo.subscribe(clientInfoSetCb, { callOnSubscribe: false }); } else { this.logger.setContextProperty(Log.Context.Custom.FlightInfo, clientInfo.flightingInfo.join(",")); } } /** * Get the unique id associated with this worker's tab. The type is any type that allows us to distinguish * between tabs, and is dependent on the browser itself. */ public getUniqueId(): TTabIdentifier { return this.tabId; } /** * Get the url associated with this worker's tab */ public abstract getUrl(): string; /** * Launches the sign in window, rejecting with an error object if something went wrong on the server during * authentication. Otherwise, it resolves with true if the redirect endpoint was hit as a result of a successful * sign in attempt, and false if it was not hit (e.g., user manually closed the popup) */ protected abstract doSignInAction(authType: AuthType): Promise<boolean>; /** * Signs the user out */ protected abstract doSignOutAction(authType: AuthType); /** * Notify the UI to invoke the clipper. Resolve with true if it was thought to be successfully * injected; otherwise resolves with false. Also performs logging. */ protected abstract invokeClipperBrowserSpecific(): Promise<boolean>; /** * Notify the UI to invoke the frontend script that handles logging to the conosle. Resolve with * true if it was thought to be successfully injected; otherwise resolves with false. */ protected abstract invokeDebugLoggingBrowserSpecific(): Promise<boolean>; /** * Notify the UI to invoke the What's New tooltip. Resolve with true if it was thought to be successfully * injected; otherwise resolves with false. */ protected abstract invokeWhatsNewTooltipBrowserSpecific(newVersions: ChangeLog.Update[]): Promise<boolean>; /** * Notify the UI to invoke a specific tooltip. Resolve with true if successfully injected, and false otherwise; */ protected abstract invokeTooltipBrowserSpecific(tooltipType: TooltipType): Promise<boolean>; /** * Returns true if the user has allowed our extension to access file:/// links. Edge does not have a function to * check this as of 10/3/2016 */ protected abstract isAllowedFileSchemeAccessBrowserSpecific(callback: (isAllowed: boolean) => void): void; /** * Gets the visible tab's screenshot as an image url */ protected abstract takeTabScreenshot(): Promise<string>; /** * Closes all active frames and notifies the UI to invoke the clipper. */ public closeAllFramesAndInvokeClipper(invokeInfo: InvokeInfo, options: InvokeOptions) { this.pageNavInjectCommunicator.callRemoteFunction(Constants.FunctionKeys.closePageNavTooltip); this.invokeClipper(invokeInfo, options); } public getLogger() { return this.logger; } /** * Skeleton method that notifies the UI to invoke the Clipper. Also performs logging. */ public invokeClipper(invokeInfo: InvokeInfo, options: InvokeOptions) { // For safety, we enforce that the object we send is never undefined. let invokeOptionsToSend: InvokeOptions = { invokeDataForMode: options ? options.invokeDataForMode : undefined, invokeMode: options ? options.invokeMode : InvokeMode.Default }; this.sendInvokeOptionsToInject(invokeOptionsToSend); this.isAllowedFileSchemeAccessBrowserSpecific((isAllowed) => { if (!isAllowed) { this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.extensionNotAllowedToAccessLocalFiles); } }); this.invokeClipperBrowserSpecific().then((wasInvoked) => { if (wasInvoked && !this.clipperFunnelAlreadyLogged) { this.logger.logUserFunnel(Log.Funnel.Label.Invoke); this.clipperFunnelAlreadyLogged = true; } this.logClipperInvoke(invokeInfo, invokeOptionsToSend); }); } /** * Notify the UI to invoke the What's New experience. Resolve with true if it was thought to be successfully * injected; otherwise resolves with false. */ public invokeWhatsNewTooltip(newVersions: ChangeLog.Update[]): Promise<boolean> { let invokeWhatsNewEvent = new Log.Event.PromiseEvent(Log.Event.Label.InvokeWhatsNew); return this.registerLocalizedStringsForPageNav().then((successful) => { if (successful) { this.registerWhatsNewCommunicatorFunctions(newVersions); return this.invokeWhatsNewTooltipBrowserSpecific(newVersions).then((wasInvoked) => { if (!wasInvoked) { invokeWhatsNewEvent.setStatus(Log.Status.Failed); invokeWhatsNewEvent.setFailureInfo({ error: "invoking the What's New experience failed" }); } this.logger.logEvent(invokeWhatsNewEvent); return Promise.resolve(wasInvoked); }); } else { invokeWhatsNewEvent.setStatus(Log.Status.Failed); invokeWhatsNewEvent.setFailureInfo({ error: "getLocalizedStringsForBrowser returned undefined/null" }); this.logger.logEvent(invokeWhatsNewEvent); return Promise.resolve(false); } }); } public invokeTooltip(tooltipType: TooltipType): Promise<boolean> { let tooltipInvokeEvent = new Log.Event.PromiseEvent(Log.Event.Label.InvokeTooltip); tooltipInvokeEvent.setCustomProperty(Log.PropertyName.Custom.TooltipType, TooltipType[tooltipType]); return this.registerLocalizedStringsForPageNav().then((successful) => { if (successful) { this.registerTooltipCommunicatorFunctions(tooltipType); return this.invokeTooltipBrowserSpecific(tooltipType).then((wasInvoked) => { this.logger.logEvent(tooltipInvokeEvent); return Promise.resolve(wasInvoked); }); } else { tooltipInvokeEvent.setStatus(Log.Status.Failed); tooltipInvokeEvent.setFailureInfo({ error: "getLocalizedStringsForBrowser returned undefined/null" }); this.logger.logEvent(tooltipInvokeEvent); return Promise.resolve(false); } }); } /** * Sets the hook method that will be called when this worker object goes away. */ public setOnUnloading(callback: () => void) { this.onUnloading = callback; } /** * Clean up anything related to the worker before it stops being used (aka the tab or window was closed) */ public destroy() { this.logger.logSessionEnd(Log.Session.EndTrigger.Unload); } /** * Returns the current version of localized strings used in the UI. */ protected getLocalizedStrings(locale: string, callback?: Function) { this.logger.setContextProperty(Log.Context.Custom.BrowserLanguage, locale); let storedLocale = this.clipperData.getValue(ClipperStorageKeys.locale); let localeInStorageIsDifferent = !storedLocale || storedLocale !== locale; let getLocaleEvent = new Log.Event.BaseEvent(Log.Event.Label.GetLocale); getLocaleEvent.setCustomProperty(Log.PropertyName.Custom.StoredLocaleDifferentThanRequested, localeInStorageIsDifferent); this.logger.logEvent(getLocaleEvent); let fetchStringDataFunction = () => { return LocalizationHelper.makeLocStringsFetchRequest(locale); }; let updateInterval = localeInStorageIsDifferent ? 0 : ClipperCachedHttp.getDefaultExpiry(); let getLocalizedStringsEvent = new Log.Event.PromiseEvent(Log.Event.Label.GetLocalizedStrings); getLocalizedStringsEvent.setCustomProperty(Log.PropertyName.Custom.ForceRetrieveFreshLocStrings, localeInStorageIsDifferent); this.clipperData.getFreshValue(ClipperStorageKeys.locStrings, fetchStringDataFunction, updateInterval).then((response) => { this.clipperData.setValue(ClipperStorageKeys.locale, locale); if (callback) { callback(response ? response.data : undefined); } }, (error: OneNoteApi.GenericError) => { getLocalizedStringsEvent.setStatus(Log.Status.Failed); getLocalizedStringsEvent.setFailureInfo(error); // Still proceed, as we have backup strings on the client if (callback) { callback(undefined); } }).then(() => { this.logger.logEvent(getLocalizedStringsEvent); }); } protected getLocalizedStringsForBrowser(callback: Function) { let localeOverride = this.clipperData.getValue(ClipperStorageKeys.displayLanguageOverride); // navigator.userLanguage is only available in IE, and Typescript will not recognize this property let locale = localeOverride || navigator.language || (<any>navigator).userLanguage; this.getLocalizedStrings(locale, callback); } protected getUserSessionIdQueryParamValue(): string { let usidQueryParamValue = this.logger.getUserSessionId(); return usidQueryParamValue ? usidQueryParamValue : this.clientInfo.get().clipperId; } protected invokeDebugLoggingIfEnabled(): Promise<boolean> { if (LogHelpers.isConsoleOutputEnabled()) { return this.invokeDebugLoggingBrowserSpecific(); } return Promise.resolve(false); } protected launchPopupAndWaitForClose(url: string): Promise<boolean> { return new Promise<boolean>((resolve, reject) => { let signInWindow: Window = BrowserUtils.openPopupWindow(url); let errorObject; let popupMessageHandler = (event: MessageEvent) => { if (event.source === signInWindow) { let dataAsJson: any; try { dataAsJson = JSON.parse(event.data); } catch (e) { this.logger.logJsonParseUnexpected(event.data); } if (dataAsJson && (dataAsJson[Constants.Urls.QueryParams.error] || dataAsJson[Constants.Urls.QueryParams.errorDescription])) { errorObject = { correlationId: dataAsJson[Constants.Urls.QueryParams.correlationId], error: dataAsJson[Constants.Urls.QueryParams.error], errorDescription: dataAsJson[Constants.Urls.QueryParams.errorDescription] }; } } }; window.addEventListener("message", popupMessageHandler); let timer = setInterval(() => { if (!signInWindow || signInWindow.closed) { clearInterval(timer); window.removeEventListener("message", popupMessageHandler); // We always resolve with true in the non-error case as we can't reliably detect redirects // on non-IE bookmarklets errorObject ? reject(errorObject) : resolve(true); } }, 100); }); } protected logClipperInvoke(invokeInfo: InvokeInfo, options: InvokeOptions) { let invokeClipperEvent = new Log.Event.BaseEvent(Log.Event.Label.InvokeClipper); invokeClipperEvent.setCustomProperty(Log.PropertyName.Custom.InvokeSource, InvokeSource[invokeInfo.invokeSource]); invokeClipperEvent.setCustomProperty(Log.PropertyName.Custom.InvokeMode, InvokeMode[options.invokeMode]); this.logger.logEvent(invokeClipperEvent); } /** * Registers the tooltip type that needs to appear in the Page Nav experience, as well as any props it needs */ protected registerTooltipToRenderInPageNav(tooltipType: TooltipType, tooltipProps?: any) { this.pageNavUiCommunicator.registerFunction(Constants.FunctionKeys.getTooltipToRenderInPageNav, () => { return Promise.resolve(tooltipType); }); this.pageNavUiCommunicator.registerFunction(Constants.FunctionKeys.getPageNavTooltipProps, () => { return Promise.resolve(tooltipProps); }); } /** * Register communicator functions specific to the What's New experience */ protected registerWhatsNewCommunicatorFunctions(newVersions: ChangeLog.Update[]) { this.registerTooltipToRenderInPageNav(TooltipType.WhatsNew, { updates: newVersions } as TooltipProps.WhatsNew); } protected registerTooltipCommunicatorFunctions(tooltipType: TooltipType) { this.registerTooltipToRenderInPageNav(tooltipType); } protected sendInvokeOptionsToInject(options: InvokeOptions) { this.injectCommunicator.callRemoteFunction(Constants.FunctionKeys.setInvokeOptions, { param: options }); } protected setUpNoOpTrackers(url: string) { // No-op tracker for communication with inject let injectNoOpTrackerTimeout = Log.ErrorUtils.setNoOpTrackerRequestTimeout({ label: Log.NoOp.Label.InitializeCommunicator, channel: Constants.CommunicationChannels.injectedAndExtension, clientInfo: this.clientInfo, url: url }, true); this.injectCommunicator.callRemoteFunction(Constants.FunctionKeys.noOpTracker, { param: new Date().getTime(), callback: () => { clearTimeout(injectNoOpTrackerTimeout); } }); // No-op tracker for communication with the UI let uiNoOpTrackerTimeout = Log.ErrorUtils.setNoOpTrackerRequestTimeout({ label: Log.NoOp.Label.InitializeCommunicator, channel: Constants.CommunicationChannels.extensionAndUi, clientInfo: this.clientInfo, url: url }, true); this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.noOpTracker, { param: new Date().getTime(), callback: () => { clearTimeout(uiNoOpTrackerTimeout); } }); } /** * Signs the user out on in the frontend. TODO: this was implemented as an Edge workaround, and * should be removed when they fix their iframes not properly loading in the background. */ private doSignOutActionInFrontEnd(authType: AuthType) { let usidQueryParamValue = this.getUserSessionIdQueryParamValue(); let signOutUrl = ClipperUrls.generateSignOutUrl(this.clientInfo.get().clipperId, usidQueryParamValue, AuthType[authType]); this.uiCommunicator.callRemoteFunction(Constants.FunctionKeys.createHiddenIFrame, { param: signOutUrl }); } private initializeCommunicators() { this.initializeDebugLoggingCommunicators(); this.initializeClipperCommunicators(); this.initializePageNavCommunicators(); } private initializeClipperCommunicators() { this.initializeClipperUiCommunicator(); this.initializeClipperInjectCommunicator(); } private initializeClipperUiCommunicator() { this.uiCommunicator.broadcastAcrossCommunicator(this.auth.user, Constants.SmartValueKeys.user); this.uiCommunicator.broadcastAcrossCommunicator(this.clientInfo, Constants.SmartValueKeys.clientInfo); this.uiCommunicator.broadcastAcrossCommunicator(this.sessionId, Constants.SmartValueKeys.sessionId); this.uiCommunicator.registerFunction(Constants.FunctionKeys.clipperStrings, () => { return new Promise<string>((resolve) => { this.getLocalizedStringsForBrowser((dataResult: string) => { resolve(dataResult); }); }); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.getStorageValue, (key: string) => { return new Promise<string>((resolve) => { let value = this.clipperData.getValue(key); resolve(value); }); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.getMultipleStorageValues, (keys: string[]) => { return new Promise<{ [key: string]: string }>((resolve) => { let values: { [key: string]: string } = {}; for (let key of keys) { values[key] = this.clipperData.getValue(key); } resolve(values); }); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.setStorageValue, (keyValuePair: { key: string, value: string }) => { this.clipperData.setValue(keyValuePair.key, keyValuePair.value); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.getInitialUser, () => { return this.auth.updateUserInfoData(this.clientInfo.get().clipperId, UpdateReason.InitialRetrieval); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.signInUser, (authType: AuthType) => { return this.doSignInAction(authType).then((redirectOccurred) => { // Recently, a change in sign-in flow broke our redirect detection, so now we give the benefit of the doubt // and always attempt to update userInfo regardless return this.auth.updateUserInfoData(this.clientInfo.get().clipperId, UpdateReason.SignInAttempt).then((updatedUser: UserInfo) => { // While redirect detection is somewhat unreliable, it's still sometimes correct. So we try and // detect this case only after we try get the latest userInfo if ((!updatedUser || !updatedUser.user) && !redirectOccurred) { let userInfoToSet: UserInfo = { updateReason: UpdateReason.SignInCancel }; this.auth.user.set(userInfoToSet); return Promise.resolve(userInfoToSet); } return Promise.resolve(updatedUser); }); }).catch((errorObject) => { // Set the user info object to undefined as a result of an attempted sign in this.auth.user.set({ updateReason: UpdateReason.SignInAttempt }); // Right now we're adding the update reason to the errorObject as well so that it is preserved in the callback. // The right thing to do is revise the way we use callbacks in the communicator and instead use Promises so that // we are able to return distinct objects. errorObject.updateReason = UpdateReason.SignInAttempt; return Promise.reject(errorObject); }); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.signOutUser, (authType: AuthType) => { if (this.clientInfo.get().clipperType === ClientType.EdgeExtension) { this.doSignOutActionInFrontEnd(authType); } else { this.doSignOutAction(authType); } this.auth.user.set({ updateReason: UpdateReason.SignOutAction }); this.clipperData.setValue(ClipperStorageKeys.userInformation, undefined); this.clipperData.setValue(ClipperStorageKeys.currentSelectedSection, undefined); this.clipperData.setValue(ClipperStorageKeys.cachedNotebooks, undefined); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.telemetry, (data: Log.LogDataPackage) => { Log.parseAndLogDataPackage(data, this.logger); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.ensureFreshUserBeforeClip, () => { return this.auth.updateUserInfoData(this.clientInfo.get().clipperId, UpdateReason.TokenRefreshForPendingClip); }); this.uiCommunicator.registerFunction(Constants.FunctionKeys.takeTabScreenshot, () => { return this.takeTabScreenshot(); }); this.uiCommunicator.setErrorHandler((e: Error) => { Log.ErrorUtils.handleCommunicatorError(Constants.CommunicationChannels.extensionAndUi, e, this.clientInfo); }); } private initializeClipperInjectCommunicator() { this.injectCommunicator.broadcastAcrossCommunicator(this.clientInfo, Constants.SmartValueKeys.clientInfo); this.injectCommunicator.registerFunction(Constants.FunctionKeys.unloadHandler, () => { this.tearDownCommunicators(); this.onUnloading(); }); this.injectCommunicator.registerFunction(Constants.FunctionKeys.setStorageValue, (keyValuePair: { key: string, value: string }) => { this.clipperData.setValue(keyValuePair.key, keyValuePair.value); }); this.injectCommunicator.setErrorHandler((e: Error) => { Log.ErrorUtils.handleCommunicatorError(Constants.CommunicationChannels.injectedAndExtension, e, this.clientInfo); }); } private initializeDebugLoggingCommunicators() { this.debugLoggingInjectCommunicator.registerFunction(Constants.FunctionKeys.unloadHandler, () => { this.tearDownCommunicators(); this.onUnloading(); }); } private initializePageNavCommunicators() { this.initializePageNavUiCommunicator(); this.initializePageNavInjectCommunicator(); } private initializePageNavUiCommunicator() { this.pageNavUiCommunicator.registerFunction(Constants.FunctionKeys.telemetry, (data: Log.LogDataPackage) => { Log.parseAndLogDataPackage(data, this.logger); }); this.pageNavUiCommunicator.registerFunction(Constants.FunctionKeys.invokeClipperFromPageNav, (invokeSource: InvokeSource) => { this.closeAllFramesAndInvokeClipper({ invokeSource: invokeSource }, { invokeMode: InvokeMode.Default }); }); } private initializePageNavInjectCommunicator() { this.pageNavInjectCommunicator.registerFunction(Constants.FunctionKeys.telemetry, (data: Log.LogDataPackage) => { Log.parseAndLogDataPackage(data, this.logger); }); this.pageNavInjectCommunicator.registerFunction(Constants.FunctionKeys.unloadHandler, () => { this.tearDownCommunicators(); this.onUnloading(); }); } /** * Fetches fresh localized strings and prepares a remote function for the Page Nav UI to fetch them. * Resolves with true if successful; false otherwise. */ private registerLocalizedStringsForPageNav(): Promise<boolean> { return new Promise<boolean>((resolve) => { this.getLocalizedStringsForBrowser((localizedStrings) => { if (localizedStrings) { this.pageNavUiCommunicator.registerFunction(Constants.FunctionKeys.clipperStringsFrontLoaded, () => { return Promise.resolve(localizedStrings); }); } resolve(!!localizedStrings); }); }); } private tearDownCommunicators() { this.uiCommunicator.tearDown(); this.pageNavUiCommunicator.tearDown(); this.injectCommunicator.tearDown(); this.pageNavInjectCommunicator.tearDown(); } // TODO Temporary workaround introduced in v3.2.0 // Remove after some time... private logDeviceIdMapEvent() { let deviceIdInStorage = this.clientInfo.get().clipperId; let deviceIdInCookie = CookieUtils.readCookie("MicrosoftApplicationsTelemetryDeviceId"); if (deviceIdInCookie !== deviceIdInStorage) { let deviceIdMapEvent = new Log.Event.BaseEvent(Log.Event.Label.DeviceIdMap); deviceIdMapEvent.setCustomProperty(Log.PropertyName.Custom.DeviceIdInStorage, deviceIdInStorage); deviceIdMapEvent.setCustomProperty(Log.PropertyName.Custom.DeviceIdInCookie, deviceIdInCookie); this.logger.logEvent(deviceIdMapEvent); } } }
the_stack
import { BufferComposer, ComposableBuffer } from '@defichain/jellyfish-buffer' import { CTokenBalance, CTokenBalanceVarInt, TokenBalance, TokenBalanceVarInt } from './dftx_balance' import BigNumber from 'bignumber.js' import { Script } from '../../tx' import { CScript } from '../../tx_composer' import { CCurrencyPair, CurrencyPair } from './dftx_price' /** * CreateLoanScheme / UpdateLoanScheme DeFi Transaction */ export interface SetLoanScheme { ratio: number // -----------------------| 4 bytes unsigned, Minimum collateralization ratio rate: BigNumber // ---------------------| 8 bytes unsigned, Interest rate identifier: string // ------------------| c = VarUInt{1-9 bytes}, + c bytes UTF encoded string, Unique identifier of the loan scheme update: BigNumber // -------------------| 8 bytes unsigned integer, Activation block height. 0 for createLoanScheme, > 0 for updateLoanScheme } /** * DestroyLoanScheme DeFi Transaction */ export interface DestroyLoanScheme { identifier: string // ------------------| c = VarUInt{1-9 bytes} + c bytes UTF encoded string, Unique identifier of the loan scheme height: BigNumber // -------------------| 8 bytes unsigned integer, Activation block height } /** * SetDefaultLoanScheme DeFi Transaction */ export interface SetDefaultLoanScheme { identifier: string // ------------------| c = VarUInt{1-9 bytes}, + c bytes UTF encoded string, Unique identifier of the loan scheme } /** * SetCollateralToken DeFi Transaction */ export interface SetCollateralToken { token: number // ----------------| VarUInt{1-9 bytes}, Symbol or id of collateral token factor: BigNumber // ------------| 8 bytes unsigned, Collateralization factor currencyPair: CurrencyPair // ---| c1 = VarUInt{1-9 bytes} + c1 bytes UTF encoded string for token + c2 = VarUInt{1-9 bytes} + c2 bytes UTF encoded string for currency, token/currency pair to use for price of token activateAfterBlock: number // ---| 4 bytes unsigned, Changes will be active after the block height } /** * SetLoanToken DeFi Transaction */ export interface SetLoanToken { symbol: string // -------------| c = VarUInt{1-9 bytes}, + c bytes UTF encoded string, Symbol or id of collateral token name: string // ---------------| c = VarUInt{1-9 bytes}, + c bytes UTF encoded string, Token's name, no longer than 128 characters currencyPair: CurrencyPair // -| c1 = VarUInt{1-9 bytes} + c1 bytes UTF encoded string for token + c2 = VarUInt{1-9 bytes} + c2 bytes UTF encoded string for currency, token/currency pair to use for price of token mintable: boolean // ----------| 1 byte, mintable, Token's 'Mintable' property interest: BigNumber // --------| 8 bytes unsigned, interest rate } /** * UpdateLoanToken DeFi Transaction */ export interface UpdateLoanToken { symbol: string // --------------| c = VarUInt{1-9 bytes}, + c bytes UTF encoded string, Symbol or id of collateral token name: string // ----------------| c = VarUInt{1-9 bytes}, + c bytes UTF encoded string, Token's name, no longer than 128 characters currencyPair: CurrencyPair // --| c1 = VarUInt{1-9 bytes} + c1 bytes UTF encoded string for token + c2 = VarUInt{1-9 bytes} + c2 bytes UTF encoded string for currency, token/currency pair to use for price of token mintable: boolean // -----------| 1 byte, mintable, Token's 'Mintable' property interest: BigNumber // ---------| 8 bytes unsigned, interest rate tokenTx: string // -------------| 32 bytes, hex string Txid of tokens's creation tx } /** * Composable CreateLoanScheme and UpdateLoanScheme, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CSetLoanScheme extends ComposableBuffer<SetLoanScheme> { static OP_CODE = 0x4c // 'L' static OP_NAME = 'OP_DEFI_TX_SET_LOAN_SCHEME' composers (sls: SetLoanScheme): BufferComposer[] { return [ ComposableBuffer.uInt32(() => sls.ratio, v => sls.ratio = v), ComposableBuffer.satoshiAsBigNumber(() => sls.rate, v => sls.rate = v), ComposableBuffer.varUIntUtf8BE(() => sls.identifier, v => sls.identifier = v), ComposableBuffer.bigNumberUInt64(() => sls.update, v => sls.update = v) ] } } /** * Composable DestroyLoanScheme, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CDestroyLoanScheme extends ComposableBuffer<DestroyLoanScheme> { static OP_CODE = 0x44 // 'D' static OP_NAME = 'OP_DEFI_TX_DESTROY_LOAN_SCHEME' composers (dls: DestroyLoanScheme): BufferComposer[] { return [ ComposableBuffer.varUIntUtf8BE(() => dls.identifier, v => dls.identifier = v), ComposableBuffer.bigNumberUInt64(() => dls.height, v => dls.height = v) ] } } /** * Composable SetDefaultLoanScheme, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CSetDefaultLoanScheme extends ComposableBuffer<SetDefaultLoanScheme> { static OP_CODE = 0x64 // 'd' static OP_NAME = 'OP_DEFI_TX_SET_DEFAULT_LOAN_SCHEME' composers (sdls: SetDefaultLoanScheme): BufferComposer[] { return [ ComposableBuffer.varUIntUtf8BE(() => sdls.identifier, v => sdls.identifier = v) ] } } /** * Composable SetCollateralToken, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CSetCollateralToken extends ComposableBuffer<SetCollateralToken> { static OP_CODE = 0x63 // 'c' static OP_NAME = 'OP_DEFI_TX_SET_COLLATERAL_TOKEN' composers (sct: SetCollateralToken): BufferComposer[] { return [ ComposableBuffer.varUInt(() => sct.token, v => sct.token = v), ComposableBuffer.satoshiAsBigNumber(() => sct.factor, v => sct.factor = v), ComposableBuffer.single(() => sct.currencyPair, v => sct.currencyPair = v, sct => new CCurrencyPair(sct)), ComposableBuffer.uInt32(() => sct.activateAfterBlock, v => sct.activateAfterBlock = v) ] } } /** * Composable SetLoanToken, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CSetLoanToken extends ComposableBuffer<SetLoanToken> { static OP_CODE = 0x67 // 'g' static OP_NAME = 'OP_DEFI_TX_SET_LOAN_TOKEN' composers (slt: SetLoanToken): BufferComposer[] { return [ ComposableBuffer.varUIntUtf8BE(() => slt.symbol, v => slt.symbol = v), ComposableBuffer.varUIntUtf8BE(() => slt.name, v => slt.name = v), ComposableBuffer.single(() => slt.currencyPair, v => slt.currencyPair = v, v => new CCurrencyPair(v)), ComposableBuffer.uBool8(() => slt.mintable, v => slt.mintable = v), ComposableBuffer.satoshiAsBigNumber(() => slt.interest, v => slt.interest = v) ] } } /** * Composable UpdateLoanToken, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CUpdateLoanToken extends ComposableBuffer<UpdateLoanToken> { static OP_CODE = 0x78 // 'x' static OP_NAME = 'OP_DEFI_TX_UPDATE_LOAN_TOKEN' composers (ult: UpdateLoanToken): BufferComposer[] { return [ ComposableBuffer.varUIntUtf8BE(() => ult.symbol, v => ult.symbol = v), ComposableBuffer.varUIntUtf8BE(() => ult.name, v => ult.name = v), ComposableBuffer.single(() => ult.currencyPair, v => ult.currencyPair = v, v => new CCurrencyPair(v)), ComposableBuffer.uBool8(() => ult.mintable, v => ult.mintable = v), ComposableBuffer.satoshiAsBigNumber(() => ult.interest, v => ult.interest = v), ComposableBuffer.hexBEBufferLE(32, () => ult.tokenTx, v => ult.tokenTx = v) ] } } /** * CreateVault DeFi Transaction */ export interface CreateVault { ownerAddress: Script // --------------------| n = VarUInt{1-9 bytes}, + n bytes, Vault's owner address schemeId: string // ------------------------| c = VarUInt{1-9 bytes}, + c bytes UTF encoded string, Vault's loan scheme id } /** * Composable CreateVault, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CCreateVault extends ComposableBuffer<CreateVault> { static OP_CODE = 0x56 // 'V' static OP_NAME = 'OP_DEFI_TX_CREATE_VAULT' composers (cv: CreateVault): BufferComposer[] { return [ ComposableBuffer.single<Script>(() => cv.ownerAddress, v => cv.ownerAddress = v, v => new CScript(v)), ComposableBuffer.varUIntUtf8BE(() => cv.schemeId, v => cv.schemeId = v) ] } } /** * UpdateVault DeFi Transaction */ export interface UpdateVault { vaultId: string // -------------------------| 32 bytes hex string ownerAddress: Script // --------------------| n = VarUInt{1-9 bytes}, + n bytes, Vault's owner address schemeId: string // ------------------------| c = VarUInt{1-9 bytes}, + c bytes UTF encoded string, Vault's loan scheme id } /** * Composable UpdateVault, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CUpdateVault extends ComposableBuffer<UpdateVault> { static OP_CODE = 0x76 // 'v' static OP_NAME = 'OP_DEFI_TX_UPDATE_VAULT' composers (uv: UpdateVault): BufferComposer[] { return [ ComposableBuffer.hexBEBufferLE(32, () => uv.vaultId, v => uv.vaultId = v), ComposableBuffer.single<Script>(() => uv.ownerAddress, v => uv.ownerAddress = v, v => new CScript(v)), ComposableBuffer.varUIntUtf8BE(() => uv.schemeId, v => uv.schemeId = v) ] } } /** * DepositToVault DeFi Transaction */ export interface DepositToVault { vaultId: string // ------------------| 32 bytes, Vault Id from: Script // ---------------------| n = VarUInt{1-9 bytes}, + n bytes, Address containing collateral tokenAmount: TokenBalanceVarInt // --| VarUInt{1-9 bytes} for token Id + 8 bytes for amount, Amount of collateral } /** * Composable DepositToVault, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CDepositToVault extends ComposableBuffer<DepositToVault> { static OP_CODE = 0x53 // 'S' static OP_NAME = 'OP_DEFI_TX_DEPOSIT_TO_VAULT' composers (dtv: DepositToVault): BufferComposer[] { return [ ComposableBuffer.hexBEBufferLE(32, () => dtv.vaultId, v => dtv.vaultId = v), ComposableBuffer.single<Script>(() => dtv.from, v => dtv.from = v, v => new CScript(v)), ComposableBuffer.single<TokenBalanceVarInt>(() => dtv.tokenAmount, v => dtv.tokenAmount = v, v => new CTokenBalanceVarInt(v)) ] } } /** * WithdrawFromVault DeFi Transaction */ export interface WithdrawFromVault { vaultId: string // ------------------| 32 bytes, Vault Id to: Script // -----------------------| n = VarUInt{1-9 bytes}, + n bytes, Address to receive withdrawn collateral tokenAmount: TokenBalanceVarInt // --| VarUInt{1-9 bytes} for token Id + 8 bytes for amount, Amount of collateral } /** * Composable WithdrawFromVault, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CWithdrawFromVault extends ComposableBuffer<WithdrawFromVault> { static OP_CODE = 0x4A // 'J' static OP_NAME = 'OP_DEFI_TX_WITHDRAW_FROM_VAULT' composers (dtv: WithdrawFromVault): BufferComposer[] { return [ ComposableBuffer.hexBEBufferLE(32, () => dtv.vaultId, v => dtv.vaultId = v), ComposableBuffer.single<Script>(() => dtv.to, v => dtv.to = v, v => new CScript(v)), ComposableBuffer.single<TokenBalanceVarInt>(() => dtv.tokenAmount, v => dtv.tokenAmount = v, v => new CTokenBalanceVarInt(v)) ] } } /** * TakeLoan DeFi Transaction */ export interface TakeLoan { vaultId: string // ------------------| 32 bytes, Id of vault used for loan to: Script // -----------------------| n = VarUInt{1-9 bytes}, + n bytes, Address to transfer tokens, empty stack when no address is specified. tokenAmounts: TokenBalance[] // -----| c = VarUInt{1-9 bytes} + c x TokenBalance(4 bytes for token Id + 8 bytes for amount), loan token amounts } /** * Composable TakeLoan, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CTakeLoan extends ComposableBuffer<TakeLoan> { static OP_CODE = 0x58 // 'X' static OP_NAME = 'OP_DEFI_TX_TAKE_LOAN' composers (tl: TakeLoan): BufferComposer[] { return [ ComposableBuffer.hexBEBufferLE(32, () => tl.vaultId, v => tl.vaultId = v), ComposableBuffer.single<Script>(() => tl.to, v => tl.to = v, v => new CScript(v)), ComposableBuffer.varUIntArray(() => tl.tokenAmounts, v => tl.tokenAmounts = v, v => new CTokenBalance(v)) ] } } /** * PaybackLoan DeFi Transaction */ export interface PaybackLoan { vaultId: string // --------------------| 32 bytes, Vault Id from: Script // -----------------------| n = VarUInt{1-9 bytes}, + n bytes, Address containing collateral tokenAmounts: TokenBalance[] // -------| c = VarUInt{1-9 bytes} + c x TokenBalance(4 bytes for token Id + 8 bytes for amount), Amount to pay loan } /** * Composable PaybackLoan, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CPaybackLoan extends ComposableBuffer<PaybackLoan> { static OP_CODE = 0x48 // 'H' static OP_NAME = 'OP_DEFI_TX_PAYBACK_LOAN' composers (pl: PaybackLoan): BufferComposer[] { return [ ComposableBuffer.hexBEBufferLE(32, () => pl.vaultId, v => pl.vaultId = v), ComposableBuffer.single<Script>(() => pl.from, v => pl.from = v, v => new CScript(v)), ComposableBuffer.varUIntArray(() => pl.tokenAmounts, v => pl.tokenAmounts = v, v => new CTokenBalance(v)) ] } } /** * CloseVault DeFi Transaction */ export interface CloseVault { vaultId: string // ------------------| 32 bytes, Vault Id to: Script // -----------------------| n = VarUInt{1-9 bytes}, + n bytes, Address } /** * Composable CloseVault, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CCloseVault extends ComposableBuffer<CloseVault> { static OP_CODE = 0x65 // 'e' static OP_NAME = 'OP_DEFI_TX_CLOSE_VAULT' composers (cv: CloseVault): BufferComposer[] { return [ ComposableBuffer.hexBEBufferLE(32, () => cv.vaultId, v => cv.vaultId = v), ComposableBuffer.single<Script>(() => cv.to, v => cv.to = v, v => new CScript(v)) ] } } /** * PlaceAuctionBid DeFi Transaction */ export interface PlaceAuctionBid { vaultId: string // ------------------| 32 bytes, Vault Id index: number // --------------------| 4 bytes, Auction batches index from: Script // ---------------------| n = VarUInt{1-9 bytes}, + n bytes, Address containing collateral tokenAmount: TokenBalanceVarInt // --| VarUInt{1-9 bytes} for token Id + 8 bytes for amount, Amount of collateral } /** * Composable PlaceAuctionBid, C stands for Composable. * Immutable by design, bi-directional fromBuffer, toBuffer deep composer. */ export class CPlaceAuctionBid extends ComposableBuffer<PlaceAuctionBid> { static OP_CODE = 0x49 // 'I' static OP_NAME = 'OP_DEFI_TX_AUCTION_BID' composers (pab: PlaceAuctionBid): BufferComposer[] { return [ ComposableBuffer.hexBEBufferLE(32, () => pab.vaultId, v => pab.vaultId = v), ComposableBuffer.uInt32(() => pab.index, v => pab.index = v), ComposableBuffer.single<Script>(() => pab.from, v => pab.from = v, v => new CScript(v)), ComposableBuffer.single<TokenBalanceVarInt>(() => pab.tokenAmount, v => pab.tokenAmount = v, v => new CTokenBalanceVarInt(v)) ] } }
the_stack
import { GuildSubscriptionEntity, TwitchSubscriptionEntity } from '#lib/database'; import { envIsDefined } from '#lib/env'; import { LanguageKeys } from '#lib/i18n/languageKeys'; import { SkyraCommand, SkyraPaginatedMessage } from '#lib/structures'; import type { GuildMessage } from '#lib/types'; import { TwitchEventSubTypes, TwitchHelixUsersSearchResult } from '#lib/types/definitions/Twitch'; import { PermissionLevels } from '#lib/types/Enums'; import { sendLoadingMessage } from '#utils/util'; import { channelMention } from '@discordjs/builders'; import { ApplyOptions, RequiresClientPermissions } from '@sapphire/decorators'; import { Args, CommandOptionsRunTypeEnum, container } from '@sapphire/framework'; import { send } from '@sapphire/plugin-editable-commands'; import type { TFunction } from '@sapphire/plugin-i18next'; import { chunk, isNullish, isNullishOrEmpty } from '@sapphire/utilities'; import { PermissionFlagsBits } from 'discord-api-types/v9'; import { Guild, MessageEmbed } from 'discord.js'; @ApplyOptions<SkyraCommand.Options>({ enabled: envIsDefined('TWITCH_CALLBACK', 'TWITCH_CLIENT_ID', 'TWITCH_TOKEN', 'TWITCH_EVENTSUB_SECRET'), aliases: ['twitch-subscription', 't-subscription', 't-sub'], description: LanguageKeys.Commands.Twitch.TwitchSubscriptionDescription, detailedDescription: LanguageKeys.Commands.Twitch.TwitchSubscriptionExtended, permissionLevel: PermissionLevels.Administrator, requiredClientPermissions: [PermissionFlagsBits.EmbedLinks], runIn: [CommandOptionsRunTypeEnum.GuildAny], subCommands: ['add', 'remove', 'reset', { input: 'show', default: true }] }) export class UserCommand extends SkyraCommand { public async add(message: GuildMessage, args: SkyraCommand.Args) { const streamer = await args.pick(UserCommand.streamer); const channel = await args.pick('channelName'); const subscriptionType = await args.pick(UserCommand.status); const customMessage = await args.rest('string', { maximum: 200 }).catch(() => null); if (subscriptionType === TwitchEventSubTypes.StreamOffline && isNullishOrEmpty(customMessage)) { this.error(LanguageKeys.Commands.Twitch.TwitchSubscriptionAddMessageForOfflineRequired); } const { twitchSubscriptions, guildSubscriptions } = this.container.db; // Get a potential pre-existing subscription for this streamer and subscriptionType const streamerForType = await twitchSubscriptions.findOne({ where: { streamerId: streamer.id, subscriptionType } }); const guildSubscriptionsForGuild = await guildSubscriptions.find({ where: { guildId: message.guild.id, channelId: channel.id } }); // Check if there is already a subscription for the given streamer, subscription type, and channel: const alreadyHasEntry = guildSubscriptionsForGuild.some( (guildSubscription) => guildSubscription.subscription.streamerId === streamer.id && guildSubscription.subscription.subscriptionType === subscriptionType ); // If that is the case then throw an error if (alreadyHasEntry) { this.error(LanguageKeys.Commands.Twitch.TwitchSubscriptionAddDuplicated); } // Add a new entry to the "guildSubscriptionsForGuild" for streamer, subscription type, channel and message const guildSubscription = new GuildSubscriptionEntity(); guildSubscription.guildId = message.guild.id; guildSubscription.channelId = channel.id; guildSubscription.message = customMessage ?? undefined; if (streamerForType) { guildSubscription.subscription = streamerForType; } else { // Subscribe to the streamer on the Twitch API, returning the ID of the subscription const subscriptionId = await this.container.client.twitch.subscriptionsStreamHandle(streamer.id, subscriptionType); const twitchSubscriptionEntity = new TwitchSubscriptionEntity(); twitchSubscriptionEntity.streamerId = streamer.id; twitchSubscriptionEntity.subscriptionType = subscriptionType; twitchSubscriptionEntity.subscriptionId = subscriptionId; guildSubscription.subscription = twitchSubscriptionEntity; } await guildSubscription.save(); const content = args.t( subscriptionType === TwitchEventSubTypes.StreamOnline ? LanguageKeys.Commands.Twitch.TwitchSubscriptionAddSuccessLive : LanguageKeys.Commands.Twitch.TwitchSubscriptionAddSuccessOffline, { name: streamer.display_name, channel: channel.toString() } ); return send(message, content); } public async remove(message: GuildMessage, args: SkyraCommand.Args) { const guildSubscriptions = await this.getGuildSubscriptions(message.guild); // Only get the args if there are any subscriptions to process const streamer = await args.pick(UserCommand.streamer); const channel = await args.pick('channelName'); const subscriptionType = await args.pick(UserCommand.status); // Get all subscriptions for the provided streamer const streamers = guildSubscriptions.filter((guildSubscription) => guildSubscription.subscription.streamerId === streamer.id); // If there are no subscriptions for this streamer, throw if (!streamers.length) { this.error(LanguageKeys.Commands.Twitch.TwitchSubscriptionRemoveStreamerNotSubscribed, { streamer: streamer.display_name }); } // Get all subscriptions for the specified streamer and status const statuses = streamers.filter((guildSubscription) => guildSubscription.subscription.subscriptionType === subscriptionType); // If there are no subscriptions for this status then throw if (!statuses.length) { const statuses = args.t(LanguageKeys.Commands.Twitch.TwitchSubscriptionShowStatus); this.error(LanguageKeys.Commands.Twitch.TwitchSubscriptionRemoveStreamerStatusNotMatch, { streamer: streamer.display_name, status: this.getSubscriptionStatus(subscriptionType, statuses) }); } // Get all subscriptions for this streamer, status and channel const streamerWithStatusHasChannel = statuses.find((guildSubscription) => guildSubscription.channelId === channel.id); // If there are no subscriptions configured for this channel then throw if (!streamerWithStatusHasChannel) { this.error(LanguageKeys.Commands.Twitch.TwitchSubscriptionRemoveNotToProvidedChannel, { channel }); } // Remove the guild subscription. We always have just 1 left here. await streamerWithStatusHasChannel.remove(); // Remove the subscription from the twitch API (if needed) await this.removeSubscription(streamerWithStatusHasChannel.subscription.subscriptionId); const content = args.t( subscriptionType === TwitchEventSubTypes.StreamOnline ? LanguageKeys.Commands.Twitch.TwitchSubscriptionRemoveSuccessLive : LanguageKeys.Commands.Twitch.TwitchSubscriptionRemoveSuccessOffline, { name: streamer.display_name, channel: channelMention(channel.id) } ); return send(message, content); } public async reset(message: GuildMessage, args: SkyraCommand.Args) { const guildSubscriptions = await this.getGuildSubscriptions(message.guild); // Only get the arg if there are any subscriptions to process const streamer = args.finished ? null : await args.pick(UserCommand.streamer); let count = 0; const removals: Promise<GuildSubscriptionEntity>[] = []; // Loop over all guildSubscriptions and remove them for (const guildSubscription of guildSubscriptions) { // If the streamer is defined if (streamer) { // Then only remove if the streamerId matches if (guildSubscription.subscription.streamerId === streamer.id) { removals.push(guildSubscription.remove()); count++; } // Otherwise always remove } else { removals.push(guildSubscription.remove()); count++; } } // Remove GuildSubscriptionEntities await Promise.all(removals); // Reset twitch subscriptions await this.resetSubscriptions(streamer); const content = args.t(LanguageKeys.Commands.Twitch.TwitchSubscriptionResetSuccess, { count }); return send(message, content); } @RequiresClientPermissions(['ADD_REACTIONS', 'EMBED_LINKS', 'MANAGE_MESSAGES', 'READ_MESSAGE_HISTORY']) public async show(message: GuildMessage, args: SkyraCommand.Args) { const streamer = args.finished ? null : await args.pick(UserCommand.streamer); const { t } = args; // Create the response message. const response = await sendLoadingMessage(message, t); // Fetch the content to show in the reply message const lines = isNullish(streamer) ? await this.showAll(message.guild, t) : await this.showSingle(message.guild, streamer, t); // Create the pages and the URD to display them. const pages = chunk(lines, 10); const display = new SkyraPaginatedMessage({ template: new MessageEmbed() .setAuthor(message.author.username, message.author.displayAvatarURL({ size: 128, format: 'png', dynamic: true })) .setColor(await this.container.db.fetchColor(message)) }); for (const page of pages) display.addPageEmbed((embed) => embed.setDescription(page.join('\n'))); // Start the display and return the message. await display.run(response, message.author); return response; } private async showSingle(guild: Guild, streamer: TwitchHelixUsersSearchResult, t: TFunction) { const guildSubscriptions = await this.getGuildSubscriptions(guild); const subscriptionsForStreamer = guildSubscriptions.filter((guildSubscription) => guildSubscription.subscription.streamerId === streamer.id); if (!subscriptionsForStreamer.length) { this.error(LanguageKeys.Commands.Twitch.TwitchSubscriptionShowStreamerNotSubscribed); } // Return the line this guild and streamer. const statuses = t(LanguageKeys.Commands.Twitch.TwitchSubscriptionShowStatus); const lines: string[] = []; for (const guildSubscription of subscriptionsForStreamer) { lines.push( `${streamer.display_name} - ${channelMention(guildSubscription.channelId)} → ${this.getSubscriptionStatus( guildSubscription.subscription.subscriptionType, statuses )}` ); } return lines; } private async showAll(guild: Guild, t: TFunction) { const guildSubscriptions = await this.getGuildSubscriptions(guild); // Get all the streamer IDs for this guild, put into a Set to remove duplicates // (i.e. different channels, different subscription types) const streamerIds = new Set([...guildSubscriptions.map((guildSubscription) => guildSubscription.subscription.streamerId)]); const profiles = await this.container.client.twitch.fetchUsers(streamerIds, []); const names = new Map<string, string>(); for (const profile of profiles.data) names.set(profile.id, profile.display_name); // Print all entries for this guild. const statuses = t(LanguageKeys.Commands.Twitch.TwitchSubscriptionShowStatus); const lines: string[] = []; for (const guildSubscription of guildSubscriptions) { const name = names.get(guildSubscription.subscription.streamerId) ?? t(LanguageKeys.Commands.Twitch.TwitchSubscriptionShowUnknownUser); lines.push( `${name} - ${channelMention(guildSubscription.channelId)} → ${this.getSubscriptionStatus( guildSubscription.subscription.subscriptionType, statuses )}` ); } return lines; } private async removeSubscription(subscriptionId: string) { const { twitchSubscriptions } = this.container.db; // Get all subscriptions for the provided streamer and subscription type const subscription = await twitchSubscriptions.findOne({ relations: ['guildSubscription'], where: { subscriptionId } }); // If there are no subscriptions for that streamer and subscription type then return if (!subscription) return; if (subscription.guildSubscription.length === 0) { await Promise.all([ this.container.client.twitch.removeSubscription(subscription.subscriptionId), // subscription.remove() ]); } } private async resetSubscriptions(streamer: TwitchHelixUsersSearchResult | null) { const { twitchSubscriptions } = this.container.db; // Get all subscriptions const subscriptions = await twitchSubscriptions.find({ relations: ['guildSubscription'], ...(!isNullish(streamer) && { where: { streamerId: streamer.id } }) }); // If there are no subscriptions then return if (!subscriptions) return; // Loop over all subscriptions for (const subscription of subscriptions) { // If the subscription has no servers then remove it if (subscription.guildSubscription.length === 0) { await Promise.all([ this.container.client.twitch.removeSubscription(subscription.subscriptionId), // subscription.remove() ]); } } } private async getGuildSubscriptions(guild: Guild): Promise<GuildSubscriptionEntity[]> { const { guildSubscriptions } = this.container.db; // Get all subscriptions for the current server and channel combination const guildSubscriptionForGuild = await guildSubscriptions.find({ where: { guildId: guild.id } }); if (guildSubscriptionForGuild.length === 0) { this.error(LanguageKeys.Commands.Twitch.TwitchSubscriptionNoSubscriptions); } return guildSubscriptionForGuild; } private getSubscriptionStatus(subscriptionType: TwitchEventSubTypes, statuses: { live: string; offline: string }) { return subscriptionType === TwitchEventSubTypes.StreamOnline ? statuses.live : statuses.offline; } private static streamer = Args.make<TwitchHelixUsersSearchResult>(async (parameter, { argument }) => { try { const { data } = await container.client.twitch.fetchUsers([], [parameter]); if (data.length > 0) return Args.ok(data[0]); return Args.error({ parameter, argument, identifier: LanguageKeys.Commands.Twitch.TwitchSubscriptionStreamerNotFound }); } catch { return Args.error({ parameter, argument, identifier: LanguageKeys.Commands.Twitch.TwitchSubscriptionStreamerNotFound }); } }); private static status = Args.make<TwitchEventSubTypes>((parameter, { args, argument }) => { const index = args.t(LanguageKeys.Commands.Twitch.TwitchSubscriptionStatusValues).indexOf(parameter.toLowerCase()); if (index === -1) return Args.error({ parameter, argument, identifier: LanguageKeys.Commands.Twitch.TwitchSubscriptionInvalidStatus }); if (index === 0) return Args.ok(TwitchEventSubTypes.StreamOnline); return Args.ok(TwitchEventSubTypes.StreamOffline); }); }
the_stack
import { BentleyError, BentleyStatus } from "@itwin/core-bentley"; import { UnitConversion, UnitExtraData, UnitProps, UnitsProvider } from "@itwin/core-quantity"; import { ISchemaLocater, SchemaContext } from "../Context"; import { SchemaItem } from "../Metadata/SchemaItem"; import { SchemaItemKey, SchemaKey } from "../SchemaKey"; import { Unit } from "../Metadata/Unit"; import { SchemaItemType } from "../ECObjects"; import { UnitConverter } from "../UnitConversion/UnitConverter"; /** * Class used to find Units in SchemaContext by attributes such as Phenomenon and DisplayLabel. * @alpha */ export class SchemaUnitProvider implements UnitsProvider { private _unitConverter: UnitConverter; private _context: SchemaContext; /** * * @param contextOrLocater The SchemaContext or a different ISchemaLocater implementation used to retrieve the schema. The SchemaContext * class implements the ISchemaLocater interface. If the provided locater is not a SchemaContext instance a new SchemaContext will be * created and the locater will be added. * @param _unitExtraData Additional data like alternate display label not found in Units Schema to match with Units; Defaults to empty array. */ constructor(contextOrLocater: ISchemaLocater, private _unitExtraData: UnitExtraData[] = []){ if (contextOrLocater instanceof SchemaContext) { this._context = contextOrLocater; } else { this._context = new SchemaContext(); this._context.addLocater(contextOrLocater); } this._unitConverter = new UnitConverter(this._context); } /** * Find unit in a schema that has unitName. * @param unitName Full name of unit. * @returns UnitProps interface from @itwin/core-quantity whose name matches unitName. */ public async findUnitByName(unitName: string): Promise<UnitProps> { const unit = await this.findECUnitByName(unitName); return this.getUnitsProps(unit); } /** * Find all units in context that belongs to given phenomenon. * @param phenomenon Full name of phenomenon. * @returns Array of UnitProps (from @itwin/core-quantity) interface objects whose name matches phenomenon param. */ public async getUnitsByFamily(phenomenon: string): Promise<Array<UnitProps>> { // Check if schema exists and phenomenon exists in schema const [schemaName, schemaItemName] = SchemaItem.parseFullName(phenomenon); const schemaKey = new SchemaKey(schemaName); const schema = await this._context.getSchema(schemaKey); if (!schema) { throw new BentleyError(BentleyStatus.ERROR, "Cannot find schema for phenomenon", () => { return { phenomenon, schema: schemaName }; }); } const itemKey = new SchemaItemKey(schemaItemName, schema.schemaKey); const phenom = await this._context.getSchemaItem(itemKey); if (!phenom) throw new BentleyError(BentleyStatus.ERROR, "Cannot find schema item/phenomenon", () => { return { item: schemaItemName, schema: schemaName }; }); if (phenom.schemaItemType !== SchemaItemType.Phenomenon) throw new BentleyError(BentleyStatus.ERROR, "Item is not a phenomenon", () => { return { itemType: phenom.key.fullName }; }); // Find units' full name that match given phenomenon param. const filteredUnits: Array<UnitProps> = []; const schemaItems = this._context.getSchemaItems(); let { value, done } = schemaItems.next(); while (!done) { if (Unit.isUnit(value)) { const foundPhenomenon = await value.phenomenon; if (foundPhenomenon && foundPhenomenon.key.matchesFullName(phenomenon)) { const unitProps = this.getUnitsProps(value); filteredUnits.push(unitProps); } } ({ value, done } = schemaItems.next()); } return filteredUnits; } /** * Find alternate display labels associated with unitName, if any. * @param unitName Full name of Unit. */ public getAlternateDisplayLabels(unitName: string): Array<string> { let alternateLabels: Array<string> = []; for (const entry of this._unitExtraData) { if (entry.name.toLowerCase() === unitName.toLowerCase()) { alternateLabels = entry.altDisplayLabels; } } return alternateLabels; } /** * Finds Unit by unitLabel, which could be a display label in the schema or alternate an display label defined in * this._unitExtraData. If there are duplicates of the same display label in the context or teh same alternate display * labels, specify schemaName, phenomenon, or unitSystem to get a specific unit. * * @param unitLabel Display label or alternate display label to query unit by. * @param schemaName Ensure Unit with unitLabel belongs to Schema with schemaName. * @param phenomenon Full name of phenomenon that Unit belongs to. * @param unitSystem Full name of unitSystem that Unit belongs to. * @returns The UnitProps interface from the @itwin/core-quantity package. */ public async findUnit(unitLabel: string, schemaName?: string, phenomenon?: string, unitSystem?: string): Promise<UnitProps> { const findLabel = unitLabel.toLowerCase(); const findSchema = schemaName ? schemaName.toLowerCase() : undefined; const findPhenomenon = phenomenon ? phenomenon.toLowerCase() : undefined; const findUnitSystem = unitSystem ? unitSystem.toLowerCase() : undefined; let foundUnit: Unit | undefined; try { try { foundUnit = await this.findUnitByDisplayLabel(findLabel, findSchema, findPhenomenon, findUnitSystem); } catch (err) { // If there is no Unit with display label that matches label, then check for alternate display labels that may match foundUnit = await this.findUnitByAltDisplayLabel(findLabel, findSchema, findPhenomenon, findUnitSystem); } } catch (err) { throw new BentleyError(BentleyStatus.ERROR, "Cannot find unit with label", () => { return { unitLabel }; }); } return this.getUnitsProps(foundUnit); } /** * Gets the @itwin/core-quantity UnitConversion for the given fromUnit and toUnit. * @param fromUnit The UnitProps of the 'from' unit. * @param toUnit The UnitProps of the 'to' unit. * @returns The UnitConversion interface from the @itwin/core-quantity package. */ public async getConversion(fromUnit: UnitProps, toUnit: UnitProps): Promise<UnitConversion> { const conversion = await this._unitConverter.calculateConversion(fromUnit.name, toUnit.name); return { factor: conversion.factor, offset: conversion.offset, }; } /** * Find unit in a schema that has unitName. * @param unitName Full name of unit. * @returns Unit whose full name matches unitName. */ private async findECUnitByName(unitName: string): Promise<Unit> { // Check if schema exists and unit exists in schema const [schemaName, schemaItemName] = SchemaItem.parseFullName(unitName); const schemaKey = new SchemaKey(schemaName); const schema = await this._context.getSchema(schemaKey); if (!schema) { throw new BentleyError(BentleyStatus.ERROR, "Cannot find schema for unit", () => { return { schema: schemaName, unit: unitName }; }); } const itemKey = new SchemaItemKey(schemaItemName, schema.schemaKey); const item = await this._context.getSchemaItem<Unit>(itemKey); if (!item) throw new BentleyError(BentleyStatus.ERROR, "Cannot find schema item/unit", () => { return { item: schemaItemName, schema: schemaName }; }); if (item.schemaItemType === SchemaItemType.Unit) return item; throw new BentleyError(BentleyStatus.ERROR, "Item is not a unit", () => { return { itemType: item.key.fullName }; }); } /** * Gets the @itwin/core UnitProps for the given Unit. * @param unit The Unit to convert. * @returns UnitProps interface from @itwin/core. */ private getUnitsProps(unit: Unit): UnitProps { return { name: unit.fullName, label: unit.label ?? "", phenomenon: unit.phenomenon ? unit.phenomenon.fullName : "", isValid: true, system: unit.unitSystem === undefined ? "" : unit.unitSystem.fullName, }; } /** * Finds Unit by displayLabel and that it belongs to schemaName, phenomenon, and unitSystem if defined. * @internal */ private async findUnitByDisplayLabel(displayLabel: string, schemaName?: string, phenomenon?: string, unitSystem?: string): Promise<Unit> { const schemaItems = this._context.getSchemaItems(); let { value, done } = schemaItems.next(); while (!done) { if (Unit.isUnit(value) && value.label?.toLowerCase() === displayLabel) { const currPhenomenon = await value.phenomenon; const currUnitSystem = await value.unitSystem; if (!schemaName || value.schema.name.toLowerCase() === schemaName) if (!phenomenon || (currPhenomenon && currPhenomenon.key.matchesFullName(phenomenon))) if (!unitSystem || (currUnitSystem && currUnitSystem.key.matchesFullName(unitSystem))) return value; } ({ value, done } = schemaItems.next()); } throw new BentleyError(BentleyStatus.ERROR, "Cannot find unit with display label", () => { return { displayLabel }; }); } /** * Finds Unit by altDisplayLabel and that it belongs to schemaName, phenomenon, and unitSystem if defined. * @internal */ private async findUnitByAltDisplayLabel(altDisplayLabel: string, schemaName?: string, phenomenon?: string, unitSystem?: string): Promise<Unit> { for (const entry of this._unitExtraData) { if (entry.altDisplayLabels && entry.altDisplayLabels.length > 0) { if (entry.altDisplayLabels.findIndex((ref: string) => ref.toLowerCase() === altDisplayLabel) !== -1) { // Found altDisplayLabel that matches label to find const unit = await this.findECUnitByName(entry.name); const foundPhenomenon = await unit.phenomenon; const foundUnitSystem = await unit.unitSystem; if (!schemaName || unit.schema.name.toLowerCase() === schemaName) if (!phenomenon || (foundPhenomenon && foundPhenomenon.key.matchesFullName(phenomenon))) if (!unitSystem || (foundUnitSystem && foundUnitSystem.key.matchesFullName(unitSystem))) return unit; } } } throw new BentleyError(BentleyStatus.ERROR, "Cannot find unit with alternate display label", () => { return { altDisplayLabel }; }); } }
the_stack
import * as LogManager from 'aurelia-logging'; import { Container } from 'aurelia-dependency-injection'; import { History, NavigationOptions } from 'aurelia-history'; import { Router } from './router'; import { PipelineProvider } from './pipeline-provider'; import { isNavigationCommand } from './navigation-commands'; import { EventAggregator } from 'aurelia-event-aggregator'; import { NavigationInstruction } from './navigation-instruction'; import { ViewPort, ConfiguresRouter, PipelineResult } from './interfaces'; import { RouterEvent } from './router-event'; import { RouterConfiguration } from './router-configuration'; /**@internal */ declare module 'aurelia-dependency-injection' { interface Container { viewModel?: any; } } const logger = LogManager.getLogger('app-router'); /** * The main application router. */ export class AppRouter extends Router { /**@internal */ static inject() { return [Container, History, PipelineProvider, EventAggregator]; } events: EventAggregator; /**@internal */ maxInstructionCount: number; /**@internal */ _queue: NavigationInstruction[]; /**@internal */ isActive: boolean; constructor(container: Container, history: History, pipelineProvider: PipelineProvider, events: EventAggregator) { super(container, history); // Note the super will call reset internally. this.pipelineProvider = pipelineProvider; this.events = events; } /** * Fully resets the router's internal state. Primarily used internally by the framework when multiple calls to setRoot are made. * Use with caution (actually, avoid using this). Do not use this to simply change your navigation model. */ reset(): void { super.reset(); this.maxInstructionCount = 10; if (!this._queue) { this._queue = []; } else { this._queue.length = 0; } } /** * Loads the specified URL. * * @param url The URL fragment to load. */ loadUrl(url: string): Promise<NavigationInstruction> { return this ._createNavigationInstruction(url) .then(instruction => this._queueInstruction(instruction)) .catch(error => { logger.error(error); restorePreviousLocation(this); }); } /** * Registers a viewPort to be used as a rendering target for activated routes. * * @param viewPort The viewPort. This is typically a <router-view/> element in Aurelia default impl * @param name The name of the viewPort. 'default' if unspecified. */ registerViewPort(viewPort: /*ViewPort*/ any, name?: string): Promise<any> { // having strong typing without changing public API const $viewPort: ViewPort = viewPort; super.registerViewPort($viewPort, name); // beside adding viewport to the registry of this instance // AppRouter also configure routing/history to start routing functionality // There are situation where there are more than 1 <router-view/> element at root view // in that case, still only activate once via the following guard if (!this.isActive) { const viewModel = this._findViewModel($viewPort); if ('configureRouter' in viewModel) { // If there are more than one <router-view/> element at root view // use this flag to guard against configure method being invoked multiple times // this flag is set inside method configure if (!this.isConfigured) { // replace the real resolve with a noop to guarantee that any action in base class Router // won't resolve the configurePromise prematurely const resolveConfiguredPromise = this._resolveConfiguredPromise; this._resolveConfiguredPromise = () => {/**/}; return this .configure(config => Promise .resolve(viewModel.configureRouter(config, this)) // an issue with configure interface. Should be fixed there // todo: fix this via configure interface in router .then(() => config) as any ) .then(() => { this.activate(); resolveConfiguredPromise(); }); } } else { this.activate(); } } // when a viewport is added dynamically to a root view that is already activated // just process the navigation instruction else { this._dequeueInstruction(); } return Promise.resolve(); } /** * Activates the router. This instructs the router to begin listening for history changes and processing instructions. * * @params options The set of options to activate the router with. */ activate(options?: NavigationOptions): void { if (this.isActive) { return; } this.isActive = true; // route handler property is responsible for handling url change // the interface of aurelia-history isn't clear on this perspective this.options = Object.assign({ routeHandler: this.loadUrl.bind(this) }, this.options, options); this.history.activate(this.options); this._dequeueInstruction(); } /** * Deactivates the router. */ deactivate(): void { this.isActive = false; this.history.deactivate(); } /**@internal */ _queueInstruction(instruction: NavigationInstruction): Promise<any> { return new Promise((resolve) => { instruction.resolve = resolve; this._queue.unshift(instruction); this._dequeueInstruction(); }); } /**@internal */ _dequeueInstruction(instructionCount: number = 0): Promise<PipelineResult | void> { return Promise.resolve().then(() => { if (this.isNavigating && !instructionCount) { // ts complains about inconsistent returns without void 0 return void 0; } let instruction = this._queue.shift(); this._queue.length = 0; if (!instruction) { // ts complains about inconsistent returns without void 0 return void 0; } this.isNavigating = true; let navtracker: number = this.history.getState('NavigationTracker'); let currentNavTracker = this.currentNavigationTracker; if (!navtracker && !currentNavTracker) { this.isNavigatingFirst = true; this.isNavigatingNew = true; } else if (!navtracker) { this.isNavigatingNew = true; } else if (!currentNavTracker) { this.isNavigatingRefresh = true; } else if (currentNavTracker < navtracker) { this.isNavigatingForward = true; } else if (currentNavTracker > navtracker) { this.isNavigatingBack = true; } if (!navtracker) { navtracker = Date.now(); this.history.setState('NavigationTracker', navtracker); } this.currentNavigationTracker = navtracker; instruction.previousInstruction = this.currentInstruction; let maxInstructionCount = this.maxInstructionCount; if (!instructionCount) { this.events.publish(RouterEvent.Processing, { instruction }); } else if (instructionCount === maxInstructionCount - 1) { logger.error(`${instructionCount + 1} navigation instructions have been attempted without success. Restoring last known good location.`); restorePreviousLocation(this); return this._dequeueInstruction(instructionCount + 1); } else if (instructionCount > maxInstructionCount) { throw new Error('Maximum navigation attempts exceeded. Giving up.'); } let pipeline = this.pipelineProvider.createPipeline(!this.couldDeactivate); return pipeline .run(instruction) .then(result => processResult(instruction, result, instructionCount, this)) .catch(error => { return { output: error instanceof Error ? error : new Error(error) } as PipelineResult; }) .then(result => resolveInstruction(instruction, result, !!instructionCount, this)); }); } /**@internal */ _findViewModel(viewPort: ViewPort): ConfiguresRouter | undefined { if (this.container.viewModel) { return this.container.viewModel; } if (viewPort.container) { let container = viewPort.container; while (container) { if (container.viewModel) { this.container.viewModel = container.viewModel; return container.viewModel; } container = container.parent; } } return undefined; } } const processResult = ( instruction: NavigationInstruction, result: PipelineResult, instructionCount: number, router: AppRouter ): Promise<PipelineResult> => { if (!(result && 'completed' in result && 'output' in result)) { result = result || {} as PipelineResult; result.output = new Error(`Expected router pipeline to return a navigation result, but got [${JSON.stringify(result)}] instead.`); } let finalResult: PipelineResult = null; let navigationCommandResult = null; if (isNavigationCommand(result.output)) { navigationCommandResult = result.output.navigate(router); } else { finalResult = result; if (!result.completed) { if (result.output instanceof Error) { logger.error(result.output.toString()); } restorePreviousLocation(router); } } return Promise.resolve(navigationCommandResult) .then(_ => router._dequeueInstruction(instructionCount + 1)) .then(innerResult => finalResult || innerResult || result); }; const resolveInstruction = ( instruction: NavigationInstruction, result: PipelineResult, isInnerInstruction: boolean, router: AppRouter ): PipelineResult => { instruction.resolve(result); let eventAggregator = router.events; let eventArgs = { instruction, result }; if (!isInnerInstruction) { router.isNavigating = false; router.isExplicitNavigation = false; router.isExplicitNavigationBack = false; router.isNavigatingFirst = false; router.isNavigatingNew = false; router.isNavigatingRefresh = false; router.isNavigatingForward = false; router.isNavigatingBack = false; router.couldDeactivate = false; let eventName: string; if (result.output instanceof Error) { eventName = RouterEvent.Error; } else if (!result.completed) { eventName = RouterEvent.Canceled; } else { let queryString = instruction.queryString ? ('?' + instruction.queryString) : ''; router.history.previousLocation = instruction.fragment + queryString; eventName = RouterEvent.Success; } eventAggregator.publish(eventName, eventArgs); eventAggregator.publish(RouterEvent.Complete, eventArgs); } else { eventAggregator.publish(RouterEvent.ChildComplete, eventArgs); } return result; }; const restorePreviousLocation = (router: AppRouter): void => { let previousLocation = router.history.previousLocation; if (previousLocation) { router.navigate(previousLocation, { trigger: false, replace: true }); } else if (router.fallbackRoute) { router.navigate(router.fallbackRoute, { trigger: true, replace: true }); } else { logger.error('Router navigation failed, and no previous location or fallbackRoute could be restored.'); } };
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/syncGroupsMappers"; import * as Parameters from "../models/parameters"; import { StorageSyncManagementClientContext } from "../storageSyncManagementClientContext"; /** Class representing a SyncGroups. */ export class SyncGroups { private readonly client: StorageSyncManagementClientContext; /** * Create a SyncGroups. * @param {StorageSyncManagementClientContext} client Reference to the service client. */ constructor(client: StorageSyncManagementClientContext) { this.client = client; } /** * Get a SyncGroup List. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param [options] The optional parameters * @returns Promise<Models.SyncGroupsListByStorageSyncServiceResponse> */ listByStorageSyncService(resourceGroupName: string, storageSyncServiceName: string, options?: msRest.RequestOptionsBase): Promise<Models.SyncGroupsListByStorageSyncServiceResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param callback The callback */ listByStorageSyncService(resourceGroupName: string, storageSyncServiceName: string, callback: msRest.ServiceCallback<Models.SyncGroupArray>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param options The optional parameters * @param callback The callback */ listByStorageSyncService(resourceGroupName: string, storageSyncServiceName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SyncGroupArray>): void; listByStorageSyncService(resourceGroupName: string, storageSyncServiceName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SyncGroupArray>, callback?: msRest.ServiceCallback<Models.SyncGroupArray>): Promise<Models.SyncGroupsListByStorageSyncServiceResponse> { return this.client.sendOperationRequest( { resourceGroupName, storageSyncServiceName, options }, listByStorageSyncServiceOperationSpec, callback) as Promise<Models.SyncGroupsListByStorageSyncServiceResponse>; } /** * Create a new SyncGroup. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param syncGroupName Name of Sync Group resource. * @param parameters Sync Group Body * @param [options] The optional parameters * @returns Promise<Models.SyncGroupsCreateResponse> */ create(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, parameters: Models.SyncGroupCreateParameters, options?: msRest.RequestOptionsBase): Promise<Models.SyncGroupsCreateResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param syncGroupName Name of Sync Group resource. * @param parameters Sync Group Body * @param callback The callback */ create(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, parameters: Models.SyncGroupCreateParameters, callback: msRest.ServiceCallback<Models.SyncGroup>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param syncGroupName Name of Sync Group resource. * @param parameters Sync Group Body * @param options The optional parameters * @param callback The callback */ create(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, parameters: Models.SyncGroupCreateParameters, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SyncGroup>): void; create(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, parameters: Models.SyncGroupCreateParameters, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SyncGroup>, callback?: msRest.ServiceCallback<Models.SyncGroup>): Promise<Models.SyncGroupsCreateResponse> { return this.client.sendOperationRequest( { resourceGroupName, storageSyncServiceName, syncGroupName, parameters, options }, createOperationSpec, callback) as Promise<Models.SyncGroupsCreateResponse>; } /** * Get a given SyncGroup. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param syncGroupName Name of Sync Group resource. * @param [options] The optional parameters * @returns Promise<Models.SyncGroupsGetResponse> */ get(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.SyncGroupsGetResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param syncGroupName Name of Sync Group resource. * @param callback The callback */ get(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, callback: msRest.ServiceCallback<Models.SyncGroup>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param syncGroupName Name of Sync Group resource. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.SyncGroup>): void; get(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.SyncGroup>, callback?: msRest.ServiceCallback<Models.SyncGroup>): Promise<Models.SyncGroupsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, storageSyncServiceName, syncGroupName, options }, getOperationSpec, callback) as Promise<Models.SyncGroupsGetResponse>; } /** * Delete a given SyncGroup. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param syncGroupName Name of Sync Group resource. * @param [options] The optional parameters * @returns Promise<Models.SyncGroupsDeleteResponse> */ deleteMethod(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.SyncGroupsDeleteResponse>; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param syncGroupName Name of Sync Group resource. * @param callback The callback */ deleteMethod(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, callback: msRest.ServiceCallback<void>): void; /** * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param storageSyncServiceName Name of Storage Sync Service resource. * @param syncGroupName Name of Sync Group resource. * @param options The optional parameters * @param callback The callback */ deleteMethod(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, storageSyncServiceName: string, syncGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<Models.SyncGroupsDeleteResponse> { return this.client.sendOperationRequest( { resourceGroupName, storageSyncServiceName, syncGroupName, options }, deleteMethodOperationSpec, callback) as Promise<Models.SyncGroupsDeleteResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByStorageSyncServiceOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.storageSyncServiceName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SyncGroupArray, headersMapper: Mappers.SyncGroupsListByStorageSyncServiceHeaders }, default: { bodyMapper: Mappers.StorageSyncError } }, serializer }; const createOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.storageSyncServiceName, Parameters.syncGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.SyncGroupCreateParameters, required: true } }, responses: { 200: { bodyMapper: Mappers.SyncGroup, headersMapper: Mappers.SyncGroupsCreateHeaders }, default: { bodyMapper: Mappers.StorageSyncError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.storageSyncServiceName, Parameters.syncGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.SyncGroup, headersMapper: Mappers.SyncGroupsGetHeaders }, default: { bodyMapper: Mappers.StorageSyncError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorageSync/storageSyncServices/{storageSyncServiceName}/syncGroups/{syncGroupName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.storageSyncServiceName, Parameters.syncGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { headersMapper: Mappers.SyncGroupsDeleteHeaders }, 204: { headersMapper: Mappers.SyncGroupsDeleteHeaders }, default: { bodyMapper: Mappers.StorageSyncError } }, serializer };
the_stack
import { MigrationAPI } from './MigrationAPI' import { MigrationWhenAPI } from './MigrationWhenAPI' import { MigrationOperation } from './MigrationOperation' // Utils import chalk from 'chalk' import { toShortPluginId, isPlugin, } from '@nodepack/plugins-resolution' import { logWithSpinner, stopSpinner, ensureConfigFile, readConfigFile, writeConfigFile, readPkg, FILE_APP_MIGRATIONS_PLUGIN_VERSIONS, FILE_APP_MIGRATIONS_RECORDS, Preset, } from '@nodepack/utils' import consola from 'consola' import inquirer from 'inquirer' import { getVersion, hasPlugin } from '../util/plugins' import { printNoRollbackWarn } from '../util/printNoRollbackWarn' import { MigrationPlugin } from './MigrationPlugin' import { MigrationOptions } from './MigrationOptions' export type MigrationAllOptions = { [key: string]: { [key2: string]: any } } export interface MigratorOptions { plugins?: MigrationPlugin[] completeCbs?: Function[] } export interface MigrationRecord { id: string pluginId: string pluginVersion: string options: any date: string } export interface Migration { plugin: MigrationPlugin options: MigrationOptions } export type NoticeType = 'info' | 'warn' | 'error' | 'done' | 'success' | 'log' export interface Notice { pluginId: string type: NoticeType message: string } const logTypes = { log: consola.log, info: consola.info, done: consola.success, success: consola.success, warn: consola.warn, error: consola.error, } export class Migrator { cwd: string plugins: MigrationPlugin[] completeCbs: Function[] upPrepared = false downPrepared = false migrations: Migration[] = [] queuedMigrations: Migration[] = [] migrationRecords: MigrationRecord[] = [] migratedIds: Map<string, boolean> = new Map() notices: Notice[] = [] pkg: any constructor (cwd: string, { plugins = [], completeCbs = [], }: MigratorOptions = {}) { this.cwd = cwd this.plugins = plugins this.completeCbs = completeCbs } async prepareUp () { if (!this.upPrepared) { await this.setup() // Migrations that will be applied this.queuedMigrations = await this.resolveMigrations() this.upPrepared = true } return { migrations: this.queuedMigrations, } } async up (preset: Preset = null) { if (!this.upPrepared) { await this.prepareUp() } let options: MigrationAllOptions = null let extractConfigFiles = false if (preset) { extractConfigFiles = preset.useConfigFiles || false if (preset.appMigrations) { options = preset.appMigrations } } const migrations = this.queuedMigrations // Prompts const rootOptions = options || await this.resolvePrompts(migrations) let migrationCount = 0 for (const migration of migrations) { // Prompts results const pluginOptions = rootOptions[migration.plugin.id] const migrationOptions = (pluginOptions && pluginOptions[migration.options.id]) || {} const operation = new MigrationOperation(this, migration, { options: migrationOptions, rootOptions, }) logWithSpinner('✔️', `${chalk.grey(migration.plugin.id)} ${migration.options.title}`) try { await operation.run('up', { extractConfigFiles, }) } catch (e) { consola.error(`An error occured while performing app migration: ${chalk.grey(migration.plugin.id)} ${chalk.bold(migration.options.title)}`) stopSpinner(false) console.error(e) process.exit(1) } stopSpinner() // Mark migration as completed this.migrationRecords.push({ id: migration.options.id, pluginId: migration.plugin.id, pluginVersion: migration.plugin.currentVersion || '', options: operation.options, date: new Date().toISOString(), }) migrationCount++ } // Write config files await this.writeMigrationRecords() await this.writePluginVersions() await this.applyCompleteCbs() await this.displayNotices() return { allOptions: rootOptions, migrationCount, } } async prepareRollback (removedPlugins: string[]) { if (!this.downPrepared) { await this.setup() // Migrations that will be rollbacked this.queuedMigrations = await this.resolveRollbacks(removedPlugins) this.downPrepared = true } return { migrations: this.queuedMigrations, } } async down (removedPlugins: string[]) { if (!this.downPrepared) { await this.prepareRollback(removedPlugins) } const rootOptions = {} for (const record of this.migrationRecords) { const options = rootOptions[record.pluginId] = rootOptions[record.pluginId] || {} options[record.id] = record.options } let rollbackCount = 0 for (const migration of this.queuedMigrations) { // Prompts results const pluginOptions = rootOptions[migration.plugin.id] const migrationOptions = (pluginOptions && pluginOptions[migration.options.id]) || {} const operation = new MigrationOperation(this, migration, { options: migrationOptions, rootOptions, }) logWithSpinner('✔️', `${chalk.grey(migration.plugin.id)} ${migration.options.title}`) await operation.run('down', { extractConfigFiles: false, }) stopSpinner() // Remove migration from records const index = this.migrationRecords.findIndex(m => m.id === migration.options.id && m.pluginId === migration.plugin.id) if (index !== -1) this.migrationRecords.splice(index, 1) rollbackCount++ } // Write config files await this.writeMigrationRecords() await this.writePluginVersions(removedPlugins) await this.applyCompleteCbs() await this.displayNotices() return { allOptions: rootOptions, rollbackCount, } } /** * @private */ async setup () { // Ensure the config files exists in '.nodepack' folder await ensureConfigFile(this.cwd, FILE_APP_MIGRATIONS_RECORDS, []) await ensureConfigFile(this.cwd, FILE_APP_MIGRATIONS_PLUGIN_VERSIONS, {}) // Read package.json this.pkg = readPkg(this.cwd) // Register the migrations await this.applyPlugins() await this.readMigrationRecords() await this.readPluginVersions() } /** * @private */ async applyPlugins () { for (const plugin of this.plugins) { await plugin.apply(new MigrationAPI(plugin, this)) } } /** * @private */ async readMigrationRecords () { this.migrationRecords = await readConfigFile(this.cwd, FILE_APP_MIGRATIONS_RECORDS) // Cache ids for (const record of this.migrationRecords) { this.migratedIds.set(`${record.pluginId}${record.id}`, true) } } /** * @private */ async writeMigrationRecords () { await writeConfigFile(this.cwd, FILE_APP_MIGRATIONS_RECORDS, this.migrationRecords) } /** * @private */ async resolveMigrations (): Promise<Migration[]> { const list: Migration[] = [] for (const migration of this.migrations) { // Skip if migration already applied if (this.migratedIds.get(`${migration.plugin.id}${migration.options.id}`)) { continue } // Migration requires plugins if (migration.options.requirePlugins && !migration.options.requirePlugins.every( id => hasPlugin(id, this.plugins, this.pkg), )) { continue } // Custom condition if (migration.options.when) { const whenApi = new MigrationWhenAPI(migration.plugin, this, { pkg: this.pkg, }) const result = await migration.options.when(whenApi) if (!result) { continue } } if (!migration.options.down) { printNoRollbackWarn(migration) } list.push(migration) } return list } /** * @private */ async resolveRollbacks (removedPlugins: string[]) { const list: Migration[] = [] for (const migration of this.migrations) { // Skip if the migration wasn't applied if (!this.migratedIds.get(`${migration.plugin.id}${migration.options.id}`)) { continue } // We rollback has soon has one of the required plugins is removed if (migration.options.requirePlugins && migration.options.requirePlugins.some( id => removedPlugins.includes(id), )) { list.push(migration) continue } if (removedPlugins.includes(migration.plugin.id)) { list.push(migration) } } return list.filter(migration => { // Skip if no rollback was defined if (!migration.options.down) { printNoRollbackWarn(migration) return false } return true }) } async resolvePrompts (migrations: Migration[]) { const rootOptions: MigrationAllOptions = {} for (const migration of migrations) { if (migration.options.prompts) { // Prompts const prompts = await migration.options.prompts(rootOptions) if (!prompts.length) continue // Answers let options = rootOptions[migration.plugin.id] if (!options) { options = rootOptions[migration.plugin.id] = {} } consola.log(chalk.grey(`${migration.plugin.id} is prompting:`)) let answers = await inquirer.prompt(prompts) // Check if answers are seriazable try { const oldAnswers = answers answers = JSON.parse(JSON.stringify(answers)) if (Object.keys(answers).length !== Object.keys(oldAnswers).length) { throw new Error(`Missing answers`) } } catch (e) { consola.error(`Answers are not serializable into JSON for plugin ${migration.plugin.id} migration ${migration.options.id}`) } options[migration.options.id] = answers } } return rootOptions } /** * Read the current and previous versions of plugins. * * @private */ async readPluginVersions () { const pluginVersions = await readConfigFile(this.cwd, FILE_APP_MIGRATIONS_PLUGIN_VERSIONS) for (const plugin of this.plugins) { plugin.currentVersion = getVersion(plugin.id, this.cwd) plugin.previousVersion = pluginVersions[plugin.id] } } /** * Write the current versions of plugins * into the 'plugin-versions.json' config file. * * @private */ async writePluginVersions (removedPlugins: string[] = []) { const result = {} for (const plugin of this.plugins) { if (!removedPlugins.includes(plugin.id)) { result[plugin.id] = plugin.currentVersion } } // Plugins without migrations // should also have their version saved const deps = { ...this.pkg.dependencies, ...this.pkg.devDependencies, } for (const id in deps) { if (!result[id] && isPlugin(id) && !removedPlugins.includes(id)) { result[id] = getVersion(id, this.cwd) } } await writeConfigFile(this.cwd, FILE_APP_MIGRATIONS_PLUGIN_VERSIONS, result) } /** * @private */ async applyCompleteCbs () { for (const cb of this.completeCbs) { await cb() } } /** * @private */ async displayNotices () { if (this.notices.length) { this.notices.forEach(({ pluginId, message, type }) => { const shortId = toShortPluginId(pluginId) const logFn = logTypes[type] if (!logFn) { consola.error(`Invalid api.addNotice type '${type}'.`, shortId) } else { const tag = message ? shortId : null logFn(message, tag) } }) consola.log('') } } }
the_stack
import fs from 'fs-extra' import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { Boilerplate, Lang } from '@vrn-deco/boilerplate-protocol' import { logger } from '@vrn-deco/cli-log' import { testShared } from '@vrn-deco/cli-shared' logger.setLevel('silent') const prompt = vi.fn().mockRejectedValue(new Error('Deliberate Mistakes')) vi.mock('@vrn-deco/cli-command', async () => { const cliCommandModule = await vi.importActual<typeof import('@vrn-deco/cli-command')>('@vrn-deco/cli-command') return { ...cliCommandModule, prompt, } }) const mkdirpSyncSpy = vi.spyOn(fs, 'mkdirpSync').mockImplementation(() => void 0) const pathExistsSyncSpy = vi.spyOn(fs, 'pathExistsSync').mockImplementation(() => true) const { Command, runAction } = await import('@vrn-deco/cli-command') const { CreateAction } = await import('../../create/create.action.js') beforeAll(() => { testShared.injectTestEnv() }) beforeEach(() => { mkdirpSyncSpy.mockClear() pathExistsSyncSpy.mockClear() }) afterAll(() => { mkdirpSyncSpy.mockRestore() pathExistsSyncSpy.mockRestore() }) describe('@vrn-deco/cli-command-boilerplate -> create -> create.action.ts', () => { it('When folderName is invalid, will throw a error', async () => { expect.assertions(1) try { await runAction(CreateAction)('一个亿的项目', undefined, {}, new Command()) } catch (error) { expect(error.message).toBe("the 'folderName' must conform to the npm package name specification: 一个亿的项目") } }) it('When the target directory already exists, will throw a error', async () => { expect.assertions(3) try { // call pathExistsSync twice // the first time to check baseDirectory // the second time to check targetDirectory pathExistsSyncSpy.mockImplementationOnce(() => true) // baseDirectory exists, not mkdir pathExistsSyncSpy.mockImplementationOnce(() => true) // targetDirectory exists, throw error await runAction(CreateAction)('my-project', undefined, {}, new Command()) } catch (error) { expect(pathExistsSyncSpy).toBeCalledTimes(2) expect(mkdirpSyncSpy).not.toBeCalled() expect(error.message).toContain('already exists') } }) it('When the base directory already exists, will create it', async () => { expect.assertions(3) try { // call pathExistsSync twice // the first time to check baseDirectory // the second time to check targetDirectory pathExistsSyncSpy.mockImplementationOnce(() => false) // baseDirectory not exist, mkdir pathExistsSyncSpy.mockImplementationOnce(() => false) // targetDirectory not exist, good! await runAction(CreateAction)('my-project', undefined, {}, new Command()) // after passing the directory check, you will enter the baseInfo inquiry, // where we intentionally throw an error in the prompt // to interrupt the subsequent operation } catch (error) { expect(pathExistsSyncSpy).toBeCalledTimes(2) expect(mkdirpSyncSpy).toBeCalled() expect(error.message).toContain('Deliberate Mistakes') } }) // non-interactive it('When the --yes options is passed, will check --name option, it is required and valid', async () => { expect.assertions(2) try { // call pathExistsSync twice // the first time to check baseDirectory // the second time to check targetDirectory pathExistsSyncSpy.mockImplementationOnce(() => false) // baseDirectory exist, not mkdir pathExistsSyncSpy.mockImplementationOnce(() => false) // targetDirectory not exist, good! await runAction(CreateAction)('my-project', undefined, { yes: true, name: '一个亿的项目' }, new Command()) } catch (error) { expect(pathExistsSyncSpy).toBeCalledTimes(2) expect(error.message).toContain('missing option --name or not a valid npm package name') } }) it('When the --yes options is passed, will check --version option, it is required and valid', async () => { expect.assertions(2) try { // call pathExistsSync twice // the first time to check baseDirectory // the second time to check targetDirectory pathExistsSyncSpy.mockImplementationOnce(() => false) // baseDirectory exist, not mkdir pathExistsSyncSpy.mockImplementationOnce(() => false) // targetDirectory not exist, good! await runAction(CreateAction)( 'my-project', undefined, { yes: true, name: 'my-project', version: '1' }, new Command(), ) } catch (error) { expect(pathExistsSyncSpy).toBeCalledTimes(2) expect(error.message).toContain('missing option --version or not a valid version') } }) it('When the --yes options is passed, will check --author option, it is required', async () => { expect.assertions(2) try { // call pathExistsSync twice // the first time to check baseDirectory // the second time to check targetDirectory pathExistsSyncSpy.mockImplementationOnce(() => false) // baseDirectory exist, not mkdir pathExistsSyncSpy.mockImplementationOnce(() => false) // targetDirectory not exist, good! await runAction(CreateAction)( 'my-project', undefined, { yes: true, name: 'my-project', version: '1.0.0', author: undefined }, new Command(), ) } catch (error) { expect(pathExistsSyncSpy).toBeCalledTimes(2) expect(error.message).toContain('missing option --author') } }) it('When the --yes options is passed and all option are valid, will get baseInfo', async () => { // call pathExistsSync twice // the first time to check baseDirectory // the second time to check targetDirectory pathExistsSyncSpy.mockImplementationOnce(() => false) // baseDirectory exist, not mkdir pathExistsSyncSpy.mockImplementationOnce(() => false) // targetDirectory not exist, good! const createAction = await runAction(CreateAction)( 'my-project', undefined, { yes: true, name: 'my-project', version: '1.0.0', author: 'Cphayim' }, new Command(), ) expect(pathExistsSyncSpy).toBeCalledTimes(2) expect(createAction.baseInfo).toEqual({ name: 'my-project', version: '1.0.0', author: 'Cphayim' }) }) // v1.2.2 // Calls without arguments do not support non-interactive it('When the --yes options is passed and called without arguments, will throw a error', async () => { expect.assertions(1) try { await runAction(CreateAction)( undefined, undefined, { yes: true, name: 'my-project', version: '1.0.0', author: 'Cphayim' }, new Command(), ) } catch (error) { expect(error.message).toBe('missing arguments: folderName') } }) // interactive it('When user has answered the projectName, version, and author, will get baseInfo', async () => { // call pathExistsSync twice // the first time to check baseDirectory // the second time to check targetDirectory pathExistsSyncSpy.mockImplementationOnce(() => false) // baseDirectory exist, not mkdir pathExistsSyncSpy.mockImplementationOnce(() => false) // targetDirectory not exist, good! prompt.mockReturnValueOnce(Promise.resolve({ name: 'my-project', version: '1.0.0', author: 'Cphayim' })) const createAction = await runAction(CreateAction)('my-project', undefined, {}, new Command()) expect(pathExistsSyncSpy).toBeCalledTimes(2) expect(createAction.baseInfo).toEqual({ name: 'my-project', version: '1.0.0', author: 'Cphayim' }) }) // v1.2.2 // Calling with no arguments will ask the user for the folder name it('Calling with no arguments will ask the user for the folder name', async () => { // call pathExistsSync twice // the first time to check baseDirectory // the second time to check targetDirectory prompt.mockReturnValueOnce(Promise.resolve({ folderName: 'my-project' })) pathExistsSyncSpy.mockImplementationOnce(() => false) // baseDirectory exist, not mkdir pathExistsSyncSpy.mockImplementationOnce(() => false) // targetDirectory not exist, good! prompt.mockReturnValueOnce(Promise.resolve({ name: 'my-project', version: '1.0.0', author: 'Cphayim' })) const createAction = await runAction(CreateAction)(undefined, undefined, {}, new Command()) expect(createAction.folderName).toBe('my-project') expect(pathExistsSyncSpy).toBeCalledTimes(2) expect(createAction.baseInfo).toEqual({ name: 'my-project', version: '1.0.0', author: 'Cphayim' }) }) // getBoilerplateChoiceName it('Can get correct boilerplate choice name', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const createAction = new CreateAction('my-project', '.', {} as any, new Command()) const boilerplate: Boilerplate = { name: 'my-boilerplate', desc: 'description-content', package: '@vrn-deco/my-boilerplate', version: '1.0.0', tags: ['web', 'mobile'], recommended: true, deprecated: false, } const boilerplateChoiceName = createAction.getBoilerplateChoiceName(boilerplate) expect(boilerplateChoiceName).toContain(boilerplate.name) expect(boilerplateChoiceName).toContain(boilerplate.tags?.join(', ')) expect(boilerplateChoiceName).toContain('<recommended>') boilerplate.recommended = false boilerplate.deprecated = true expect(createAction.getBoilerplateChoiceName(boilerplate)).toContain('<deprecated>') }) // getLangChoiceName it('Can get correct lang choice name', () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const createAction = new CreateAction('my-project', '.', {} as any, new Command()) const lang: Lang = { name: 'TypeScript', boilerplate: [], recommended: true, deprecated: false, } const langChoiceName = createAction.getLanguageChoiceName(lang) expect(langChoiceName).toContain(lang.name) expect(langChoiceName).toContain('<recommended>') lang.recommended = false lang.deprecated = true expect(createAction.getLanguageChoiceName(lang)).toContain('<deprecated>') }) })
the_stack