text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {fabric} from "fabric";
import {MobileElementRect} from "../../models/mobile-element-rect.model";
import {DevicesService} from "../../services/devices.service";
import {NotificationsService, NotificationType} from "angular2-notifications";
import {MobileElement} from "../../models/mobile-element.model";
import {Position} from "../../models/position.model";
import {SearchElementsModalComponent} from "./search-elements-modal.component";
import {ScreenDimensions} from "../../models/screen-dimensions.model";
import {MobileRecordingComponent} from "./mobile-recording.component";
import {MatDialog} from "@angular/material/dialog";
import {Platform} from "../../../enums/platform.enum";
import {BaseComponent} from "../../../shared/components/base.component";
import {AuthenticationGuard} from "../../../shared/guards/authentication.guard";
import {AgentService} from "../../services/agent.service";
import {ActivatedRoute, Router} from "@angular/router";
import {TranslateService} from '@ngx-translate/core';
import {ToastrService} from "ngx-toastr";
import {JsonPipe} from "@angular/common";
import {MirroringData} from "../../models/mirroring-data.model";
import {Element} from "../../../models/element.model";
import {ElementLocatorType} from "../../../enums/element-locator-type.enum";
import {SendKeysRequest} from 'app/agents/models/send-keys-request.model';
import {Image} from "fabric/fabric-impl";
@Component({
selector: 'app-mirroring-container',
templateUrl: './mirroring-container.component.html',
providers: [JsonPipe]
})
export class MirroringContainerComponent extends BaseComponent implements OnInit {
@ViewChild('mirroringContainer') mirroringContainer: ElementRef;
@Input() public dataSource!: any;
@Output() public dataSourceChange = new EventEmitter<any>();
@Input()public loading!: boolean;
@Output() loadingChange = new EventEmitter<boolean>();
@Input() public loadingActions: boolean;
@Input() public currentPageSource: MobileElement;
@Input() public isIosNative: boolean;
@Input() public isEdit: boolean;
@Input() public uiId: number;
@Input() public data: MirroringData;
@Input() public sessionId: String;
@Input() public mirroring: boolean;
@Input() public selectedElement: Element;
@Output() saveTapOnDeviceStep: EventEmitter<Position> = new EventEmitter<Position>();
@Output() saveChangeOrientationStep: EventEmitter<Boolean> = new EventEmitter<Boolean>();
@Output() saveNavigateBackStep: EventEmitter<void> = new EventEmitter<void>();
@Output() saveTapStep: EventEmitter<MobileElement> = new EventEmitter<MobileElement>();
@Output() saveEnterStep = new EventEmitter<SendKeysRequest>();
@Output() saveClearStep = new EventEmitter<MobileElement>();
@Output() updateRecordedElement: EventEmitter<void> = new EventEmitter<void>();
private devicesService: DevicesService; //CloudDevicesService
public inspectedElement: MobileElementRect = null;
public isLandscapeMode: Boolean;
public fabricCanvas: fabric.Canvas;
public actionType: String;
public screenScaledInitially: boolean;
private platform: Platform;
private orientationConflict: boolean;
public viewType: string = 'NATIVE_APP';
public canvasHeight: number;
public canvasWidth: number;
private screenWidth: number;
private screenHeight: number;
public screenOriginalHeight: number;
public screenOriginalWidth: number;
private deviceDimensions = {
'portrait': {width: 252, height: 448},
'landscape': {width: 448, height: 252},
};
private locatorTypes = {
accessibility_id: {variableName: "accessibilityId"},
id_value: {variableName: "id"},
xpath: {variableName: "xpath"},
class_name: {variableName: "type"},
name: {variableName: "name"}
};
private currentImage: Image;
private hoveredElement: MobileElementRect;
private xpathOptimized: boolean = false;
public optimisingXpath: boolean = false;
get isNativeAppEnabled() {
return this.viewType == 'NATIVE_APP';
}
get hasWebContexts() {
return this.currentPageSource?.contextNames?.find((contextName: String) => contextName.indexOf("WEBVIEW") > -1);
}
constructor(
public authGuard: AuthenticationGuard,
public notificationsService: NotificationsService,
public translate: TranslateService,
public toastrService: ToastrService,
private agentService: AgentService,
private route: ActivatedRoute,
private router: Router,
private dialog: MatDialog,
private JsonPipe: JsonPipe,
private localDeviceService: DevicesService) {
super(authGuard, notificationsService, translate, toastrService);
}
//private userService: UserService,
//private cloudDeviceService: CloudDevicesService
ngOnInit(): void {
this.uiId = this.data.uiId
this.devicesService = this.data.testsigmaAgentEnabled ? this.localDeviceService : this.localDeviceService;//this.cloudDeviceService;
this.platform = this.isIosNative? Platform.iOS : Platform.Android;
if (this.data?.device) {
this.screenWidth = this.data.device.screenWidth;
this.screenHeight = this.data.device.screenHeight;
}
}
public switchToMirroringMode() {
this.mirroring = true;
this.removeInspectionElements();
this.devicesService.deleteSession(this.sessionId).subscribe();
this.sessionId = null;
}
public switchToActionMode(actionType: String) {
this.actionType = actionType;
this.removeInspectionElements();
this.clearSelection();
}
public removeInspectionElements() {
this.fabricCanvas?.getObjects()?.forEach((element, index) => {
if (index) {
this.fabricCanvas.remove(element);
}
});
this.inspectedElement = null;
}
public navigateBack() {
if (this.data.recording) {
this.devicesService.sessionNavigateBack(this.sessionId).subscribe(
() => {
if (this.data.recording) {
if(this.data.isStepRecord) this.saveNavigateBackStep.emit()
this.handleActionSuccess()
}
},
(err) => this.handleActionFailure(err, "mobile_recorder.notification.navigate_back.failure")
);
} else {
this.devicesService.navigateBack(this.data.device).subscribe(
() => { if (this.data.recording) this.handleActionSuccess()},
(err) => this.handleActionFailure(err, "mobile_recorder.notification.navigate_back.failure")
);
}
}
public goToHome() {
this.beforeAction();
this.devicesService.goToHome(this.sessionId).subscribe(
() => this.handleActionSuccess(),
(err) => this.handleActionFailure(err, "mobile_recorder.notification.go_to_home.failure")
);
}
public renderCurrentScreenshot() {
this.recorderDialog.renderCurrentScreenshot();
}
public changeOrientation() {
this.beforeAction()
this.devicesService.changeOrientation(this.sessionId).subscribe({
next: () => {
this.devicesService.getScreenDimensions(this.sessionId).subscribe((screenDimensions: ScreenDimensions) => {
this.screenOriginalWidth = screenDimensions.screenWidth;
this.screenOriginalHeight = screenDimensions.screenHeight;
})
let width = this.screenWidth;
let height = this.screenHeight;
this.screenHeight = width;
this.screenWidth = height;
this.isLandscapeMode = !this.isLandscapeMode;
if(this.data.isStepRecord) this.saveChangeOrientationStep.emit(this.isLandscapeMode);
this.handleActionSuccess();
},
error: (err) =>
this.handleActionFailure(err, "mobile_recorder.notification.change_orientation_failed")
});
}
public _onImageLoad(img: HTMLImageElement) {
let oImg = new fabric.Image(img);
const mode = this.isLandscapeMode ? 'landscape' : 'portrait';
this.canvasWidth = this.deviceDimensions[mode].width;
this.canvasHeight = this.deviceDimensions[mode].height;
if (this.isLandscapeMode == (oImg.width < oImg.height)) {
this.orientationConflict = true;
this.canvasHeight = this.canvasHeight * (oImg.height / oImg.width)
}
if (!this.isIosNative) {
this.screenWidth = oImg.width;
this.screenHeight = oImg.height;
}
let scaleXFactor = this.canvasWidth / oImg.width;
let scaleYFactor = this.canvasHeight / oImg.height;
let fullscreenScalingFactor = this.getFullScreenScalingFactor(oImg, scaleXFactor);
oImg._set('scaleX', scaleXFactor * fullscreenScalingFactor);
oImg._set('scaleY', scaleXFactor * fullscreenScalingFactor);
oImg.set('selectable', false);
if (this.isLandscapeMode && oImg.width < oImg.height) {
// Pratheepv : Reason for not fully relaying on landscape value is some times image from browserstack is coming in portrait mode
oImg.rotate(90);
oImg.center();
oImg._set('scaleX', (this.canvasHeight / oImg.width) * fullscreenScalingFactor);
oImg._set('scaleY', (this.canvasWidth / oImg.height) * fullscreenScalingFactor);
oImg.set('top', 0);
oImg.set('left', this.canvasWidth * fullscreenScalingFactor);
}
this.canvasHeight *= fullscreenScalingFactor;
this.canvasWidth *= fullscreenScalingFactor;
this.fabricCanvas.setWidth(this.canvasWidth);
this.fabricCanvas.setHeight(this.canvasHeight);
this.fabricCanvas.clear();
this.fabricCanvas.add(oImg);
this.currentImage = oImg
this.screenScaledInitially = true;
this.addTapAndSwipeListeners();
if (!this.mirroring && this.sessionId) {
// TODO: Need to add debounce [Pratheepv]
this.recorderDialog.getCurrentPageSource();
}
this.loading = false;
this.loadingChange.emit(this.loading)
if (this.isEdit && this.uiId) {
this.inspectedElement = new MobileElementRect();
this.inspectedElement.mobileElement = new MobileElement();
this.inspectedElement.mobileElement.contentDesc = "";
this.inspectedElement.mobileElement[this.locatorTypes[this.selectedElement?.locatorType]?.variableName]
= this.uiId ? this.selectedElement?.locatorValue : "";
this.selectElement(this.inspectedElement);
}
}
public openSearchDialog() {
let pageSourceElement = null;
const dialogRef = this.dialog.open(SearchElementsModalComponent, {
data: {
sessionId: this.sessionId,
platform: this.platform,
testsigmaAgentEnabled: this.data.testsigmaAgentEnabled
},
panelClass: ['mat-dialog', 'rds-none'],
width: '700px',
disableClose: true
});
dialogRef.componentInstance.onSelect.subscribe((mobileElement) => {
pageSourceElement = this.findElementByCoOrdinates(mobileElement.x1, mobileElement.x2, mobileElement.y1, mobileElement.y2, this.dataSource)
if (pageSourceElement != undefined) {
this.highlightOnSelection(pageSourceElement);
} else {
this.highlightOnSelection(mobileElement);
}
});
dialogRef.componentInstance.onAction.subscribe((result) => {
if (result?.action == "tap")
this.searchAndTap(result.type, result.value, result.index, result.mobileElement);
else if (result?.action == "sendKeys") {
this.searchAndSendKeys(result.type, result.value, result.index, result.keys, result.mobileElement);
} else if (result?.action == "clear") {
this.searchAndClear(result.type, result.value, result.index, result.mobileElement);
}
});
}
public highlightOnSelection(mobileElement: MobileElement) {
this.removeInspectionElements();
this.clearSelection();
this.drawElement(mobileElement, true);
this.drawElements(this.currentPageSource);
}
private findElementByCoOrdinates(x1, x2, y1, y2, elements) {
for (let element of elements) {
if (element.x1 == x1 && element.x2 == x2 && element.y1 == y1 && element.y2 == y2)
return element;
else if (element.childElements) {
let foundElement = this.findElementByCoOrdinates(x1, x2, y1, y2, element.childElements);
if (foundElement)
return foundElement;
}
}
}
public switchViewMode(viewType: string) {
if (this.viewType == viewType) return;
this.removeInspectionElements();
this.clearSelection();
this.viewType = viewType;
this.fabricCanvas.renderAll();
this.drawElements(this.currentPageSource);
this.dataSource = [JSON.parse(this.JsonPipe.transform(this.currentPageSource))];
this.dataSourceChange.emit(this.dataSource);
}
public drawElements(source: MobileElement) {
let allElements = [];
this.flattenElements(source, allElements);
if (allElements.length > 0 && allElements[1].hasWebViewChild)
source.hasWebViewChild = true;
allElements.sort((a, b) => this.sortByArea(a, b)).reverse().forEach((element) => {
if((this.isNativeAppEnabled && !element?.webViewName) || (!this.isNativeAppEnabled && element?.hasWebViewChild))
this.drawElement(element);
});
this.fabricCanvas.renderAll();
}
private drawElement(element: MobileElement,toSelect?:boolean, toHighlight?: boolean) {
if (element.x1 == null) {
return;
}
let elementDimensions = this.boundToCanvasDimensions(element);
let mobileElementRect = new MobileElementRect({
left: elementDimensions.x,
top: elementDimensions.y,
height: elementDimensions.height,
width: elementDimensions.width,
fill: "#fff",
opacity: 0,
});
mobileElementRect.set('selectable', false);
mobileElementRect.set('mobileElement', element);
this.fabricCanvas.add(mobileElementRect);
if(Boolean(toSelect))
this.selectElement(mobileElementRect, true);
if(Boolean(toHighlight)) {
this.highlightOnHover(mobileElementRect);
this.hoveredElement = mobileElementRect;
}
}
private boundToCanvasDimensions(element: MobileElement) {
let scalingXFactor = this.canvasWidth / this.screenWidth;
let scalingYFactor = this.orientationConflict ? this.canvasHeight / this.screenHeight : scalingXFactor;
return {
x: element.x1.valueOf() * scalingXFactor,
y: element.y1.valueOf() * scalingYFactor,
height: (element.y2.valueOf() - element.y1.valueOf()) * scalingYFactor,
width: (element.x2.valueOf() - element.x1.valueOf()) * scalingXFactor
}
}
private addHoverEventsToCanvas() {
this.attachMouseOverEvent();
this.attachMouseUpEvent();
this.attachMouseOutEvent();
}
private attachMouseOverEvent() {
this.fabricCanvas.on('mouse:over', (options: any) => {
let mobileElementRect = <MobileElementRect>options.target;
this.highlightOnHover(mobileElementRect);
});
}
private highlightOnHover(mobileElementRect:MobileElementRect,){
if (mobileElementRect) {
if (mobileElementRect._originalElement) {
return;
}
mobileElementRect.set('fill', '#f5fb1d');
mobileElementRect.set('opacity', 0.2);
this.fabricCanvas.renderAll();
}
}
public mouseInFromAppSource(element:MobileElement){
if (element.x1 == null || element.uuid == this.inspectedElement?.mobileElement?.uuid) return;
if(this.hoveredElement && this.inspectedElement?.mobileElement?.uuid != this.hoveredElement.mobileElement?.uuid)
this.fabricCanvas.remove(this.hoveredElement);
this.drawElement(element, false, true);
}
public mouseOutFromAppSource(){
if(this.hoveredElement && this.inspectedElement?.mobileElement?.uuid != this.hoveredElement.mobileElement?.uuid)
this.fabricCanvas.remove(this.hoveredElement);
}
private attachMouseUpEvent() {
this.fabricCanvas.on('mouse:up', (options) => {
this.selectElement(<MobileElementRect>options.target);
});
}
private attachMouseOutEvent() {
this.fabricCanvas.on('mouse:out', (options: any) => {
let mobileElementRect = options.target;
if (mobileElementRect) {
if (mobileElementRect._originalElement) {
return;
}
if (mobileElementRect.get('elementSelected')) {
mobileElementRect.set('opacity', 0.2);
mobileElementRect.set('fill', '#6467f7');
} else {
mobileElementRect.set('opacity', 0);
mobileElementRect.set('fill', '#ffffff');
}
this.fabricCanvas.renderAll();
}
});
}
private sortByArea(element1: MobileElement, element2: MobileElement) {
let element1Dimensions = this.boundToCanvasDimensions(element1);
let element2Dimensions = this.boundToCanvasDimensions(element2);
let element1Area = element1Dimensions.width * element1Dimensions.height;
let element2Area = element2Dimensions.width * element2Dimensions.height;
if (element1Area == element2Area) {
return element2.depth.valueOf() - element1.depth.valueOf();
}
return element1Area - element2Area;
};
public switchToInspectMode() {
this.mirroring = false;
if (this.actionType) {
this.actionType = null;
this.renderCurrentScreenshot();
this.renderCurrentScreenshot();
}
if (!this.data.recording)
this.recorderDialog.startSession();
}
private addTapAndSwipeListeners() {
let _this = this;
this.fabricCanvas.getObjects().forEach((object: fabric.Object) => {
let mouseDownPosition;
object.on('mousedown', function (options: fabric.IEvent) {
mouseDownPosition = this.getLocalPointer(options.e);
});
object.on('mouseup', function (options: fabric.IEvent) {
let mouseUpPosition = this.getLocalPointer(options.e);
if ((mouseDownPosition && mouseUpPosition) && (mouseDownPosition.x !== mouseUpPosition.x || mouseDownPosition.y !== mouseUpPosition.y)) {
_this.swipeOnDevice([
_this.convertToMobilePosition(mouseDownPosition),
_this.convertToMobilePosition(mouseUpPosition)
]);
} else {
_this.tapOnDevice(_this.convertToMobilePosition(mouseUpPosition));
}
});
});
}
private swipeOnDevice(tapPoints: Position[]) {
if (this.data.recording) {
this.devicesService.sessionSwipe(this.sessionId, tapPoints).subscribe({
next: () => this.handleActionSuccess(),
error: (err) => this.handleActionFailure(err, "mobile_recorder.notification.swipe.failure")
});
} else {
this.devicesService.deviceSwipe(this.data.device, tapPoints).subscribe({
next: () => this.handleActionSuccess(),
error: (err) => this.handleActionFailure(err, "mobile_recorder.notification.swipe.failure")
});
}
};
private tapOnDevice(tapPoint: Position) {
if (this.data.recording) {
if (tapPoint.x > this.screenOriginalWidth || tapPoint.y > this.screenOriginalHeight) {
this.showNotification(NotificationType.Error, this.translate.instant("mobile_recorder.notification.tap.out_of_bound.failure", {
screenWidth: this.screenOriginalWidth,
screenHeight: this.screenOriginalHeight
}));
this.renderCurrentScreenshot();
this.renderCurrentScreenshot();
return;
}
this.devicesService.sessionTap(this.sessionId, tapPoint).subscribe({
next: () => {
if (this.data.recording) {
if(this.data.isStepRecord) this.saveTapOnDeviceStep.emit(tapPoint);
this.handleActionSuccess();
}
},
error: (err) => this.handleActionFailure(err, "mobile_recorder.notification.tap.failure")
});
} else {
this.devicesService.deviceTap(this.data.device, tapPoint).subscribe({
next: () => {
if (this.data.recording) this.handleActionSuccess();
},
error: (err) => this.handleActionFailure(err, "mobile_recorder.notification.tap.failure")
});
}
}
public clearSelection(){
if (this.inspectedElement) {
this.inspectedElement.set('fill', '#fff');
this.inspectedElement.set('opacity', 0);
this.inspectedElement.set('elementSelected', false);
this.fabricCanvas.renderAll();
}
this.inspectedElement = null;
this.recorderDialog.element = null
}
private convertToMobilePosition(position: any) {
let positionWidth = this.screenWidth;
let positionHeight = this.screenHeight;
let xPosition = position.x * (positionWidth / this.canvasWidth);
let yPosition = position.y * (positionHeight / this.canvasHeight);
if (this.isLandscapeMode && !this.orientationConflict) {
xPosition = position.x * (positionHeight / this.canvasHeight);
yPosition = position.y * (positionWidth / this.canvasWidth);
}
let mobilePosition: Position = new Position();
mobilePosition.x = xPosition;
mobilePosition.y = yPosition;
if (this.isLandscapeMode && this.orientationConflict) {
mobilePosition.x = yPosition;
mobilePosition.y = xPosition;
}
if(this.orientationConflict ) {
mobilePosition.x = <number>mobilePosition.x - this.screenWidth;
if(mobilePosition.x < 0)
mobilePosition.x = <number>mobilePosition.x*-1;
}
return mobilePosition;
}
private getFullScreenScalingFactor( oImg, scaleXFactor): number {
if (!(this.isLandscapeMode && oImg.width < oImg.height)) {
this.canvasHeight = oImg.height * scaleXFactor;
}
let initialScalingFactor = (this.mirroringContainer.nativeElement.clientWidth - 73) / this.deviceDimensions.portrait.width;
if (this.canvasFitsLayout(initialScalingFactor)) {
return initialScalingFactor;
} else if (this.canvasHeightExceedsLayout(initialScalingFactor) && !this.canvasWidthExceedsLayout(initialScalingFactor)) {
return this.fitHeightToLayout();
} else if (this.canvasWidthExceedsLayout(initialScalingFactor) && !this.canvasHeightExceedsLayout(initialScalingFactor)) {
return this.fitWidthToLayout();
} else if (this.canvasWidthExceedsLayout(initialScalingFactor) && this.canvasHeightExceedsLayout(initialScalingFactor)) {
if (this.canvasFitsLayout(this.fitHeightToLayout())) {
return this.fitHeightToLayout();
} else if (this.canvasFitsLayout(this.fitWidthToLayout())) {
return this.fitWidthToLayout();
} else {
console.log("not scaled")
return 1;
}
}
}
private canvasWidthExceedsLayout = (initialScalingFactor) =>
(this.canvasWidth * initialScalingFactor) > (this.mirroringContainer.nativeElement.clientWidth - (73 - (this.isLandscapeMode ? 42 : 0)));
public canvasHeightExceedsLayout = (initialScalingFactor) =>
(this.canvasHeight * initialScalingFactor) > (this.mirroringContainer.nativeElement.clientHeight - (30 + (this.isLandscapeMode ? 72 : 0)));
private canvasFitsLayout = (initialScalingFactor) =>
!this.canvasWidthExceedsLayout(initialScalingFactor) && !this.canvasHeightExceedsLayout(initialScalingFactor);
private fitWidthToLayout = () =>
(this.mirroringContainer.nativeElement.clientWidth - (73 - (this.isLandscapeMode ? 42 : 0))) / this.canvasWidth;
public fitHeightToLayout = () =>
(this.mirroringContainer?.nativeElement.clientHeight - (30 + (this.isLandscapeMode ? 72 : 0))) / this.canvasHeight;
public createCanvas(screenDimensions?: ScreenDimensions) {
if(Boolean(screenDimensions)){
this.screenWidth = screenDimensions.screenWidth;
this.screenHeight = screenDimensions.screenHeight;
this.screenOriginalWidth = screenDimensions.screenWidth;
this.screenOriginalHeight = screenDimensions.screenHeight;
}
this.fabricCanvas = new fabric.Canvas('mobile_mirroring_canvas', {
hoverCursor: 'pointer',
width: this.deviceDimensions.portrait.width,
height: this.deviceDimensions.portrait.height
});
this.addHoverEventsToCanvas();
}
private searchAndTap(locatorType: ElementLocatorType, byValue: string, index: number, mobileElement: MobileElement) {
this.beforeAction();
this.devicesService.searchAndTapElement(this.sessionId, this.platform, locatorType, byValue, index, mobileElement.webViewName)
.subscribe({
next: () => {
if(this.data.isStepRecord) this.saveTapStep.emit(mobileElement);
this.handleActionSuccess();
this.removeInspectionElements();
this.clearSelection();
},
error: (error) => {
this.handleActionFailure(error, "mobile_recorder.notification.tap.failure");
this.inspectedElement = null;
}
});
}
private searchAndSendKeys(locatorType: ElementLocatorType, byValue: string, index: number, keys: string, mobileElement: MobileElement) {
this.beforeAction(true);
this.devicesService.searchAndSendKeys(this.sessionId, this.platform, locatorType, byValue, index, keys, mobileElement.webViewName)
.subscribe({
next: () => {
if(this.data.isStepRecord) {
let sendKeysRequest = new SendKeysRequest();
sendKeysRequest.mobileElement = mobileElement;
sendKeysRequest.keys = keys;
this.saveEnterStep.emit(sendKeysRequest);
}
this.handleActionSuccess()
},
error: (err) => this.handleActionFailure(err, "mobile_recorder.notification.send_keys.failure")
});
}
private searchAndClear(locatorType: ElementLocatorType, byValue: string, index: number, mobileElement: MobileElement) {
this.beforeAction();
this.devicesService.searchAndClearElement(this.sessionId, this.platform, locatorType, byValue, index, mobileElement.webViewName)
.subscribe({
next: () => {
if(this.data.isStepRecord) this.saveClearStep.emit(mobileElement);
this.handleActionSuccess()
},
error: (err) => this.handleActionFailure(err, "mobile_recorder.notification.clear.failure")
});
}
private markHasWebViewFlag(element: MobileElement) {
element.hasWebViewChild = true;
if (element.parent)
this.markHasWebViewFlag(element.parent)
}
private selectElement(mobileElementRect: MobileElementRect, nonCanvasSelection?: boolean) {
if (mobileElementRect) {
if (mobileElementRect._originalElement) {
return;
}
if (this.inspectedElement) {
this.inspectedElement.set('fill', '#fff');
this.inspectedElement.set('opacity', 0);
this.inspectedElement.set('elementSelected', false);
}
mobileElementRect.set('opacity', 0.2);
mobileElementRect.set('fill', Boolean(nonCanvasSelection)? '#6467f7' :'#5bfb1d');
mobileElementRect.set('elementSelected', true);
this.inspectedElement = mobileElementRect;
this.fabricCanvas.renderAll();
}
if(!Boolean(this.data.isStepRecord))
this.recorderDialog.initElement();
else
this.updateRecordedElement.emit()
this.optimiseXpath();
}
private optimiseXpath(){
if(!this.xpathOptimized){
this.optimisingXpath = true;
this.devicesService.findUniqueXpath(this.sessionId, this.platform, this.inspectedElement.mobileElement).subscribe(res =>{
if(res != ''){
this.xpathOptimized = true;
this.inspectedElement.mobileElement.xpath = res;
if(!Boolean(this.data.isStepRecord))
this.recorderDialog.initElement();
else
this.updateRecordedElement.emit()
}
this.optimisingXpath = false;
})
} else {
this.xpathOptimized = false;
this.optimisingXpath = false;
}
}
private flattenElements(parentElement: MobileElement, allElements: MobileElement[]) {
let _this = this;
if (this.isNativeAppEnabled && parentElement.webViewName)
return
else if (!this.isNativeAppEnabled && parentElement.webViewName)
this.markHasWebViewFlag(parentElement)
if (parentElement.x1 != null) {
allElements.push(parentElement);
}
if (Array.isArray(parentElement.childElements)) {
parentElement.childElements.forEach(function (childElement) {
childElement.parent = parentElement;
_this.flattenElements(childElement, allElements);
childElement.parent = null;
});
}
}
private beforeAction(sendKeys?: boolean) {
let recorderDialog: MobileRecordingComponent = this.recorderDialog;
if (Boolean(sendKeys)) {
recorderDialog.loadingActions = true;
recorderDialog.viewType = "NATIVE_APP";
} else
recorderDialog.beforeAction();
}
private handleActionFailure(error, messageKey: string) {
this.recorderDialog.handleActionFailure(error, messageKey);
}
private handleActionSuccess() {
this.recorderDialog.handleActionSuccess();
}
private get recorderDialog():MobileRecordingComponent{
return this.dialog.openDialogs.find(dialog => dialog.componentInstance instanceof MobileRecordingComponent).componentInstance;
}
} | the_stack |
import { CircuitValue } from './circuit_value';
import { Bool, Field, Circuit, Poseidon, AsFieldElements } from '../snarky';
let indexId = 0;
export class IndexBase {
id: IndexId;
value: Array<Bool>;
constructor(value: Array<Bool>) {
this.value = value;
this.id = indexId++;
}
}
class MerkleProofBase {
path: Array<Field>;
constructor(path: Array<Field>) {
this.path = path;
}
verify(root: Field, index: Index, leaf: Field): Bool {
return root.equals(impliedRoot(index.value, this.path, leaf));
}
assertVerifies(root: Field, index: Index, leaf: Field): void {
checkMerklePath(root, index.value, this.path, leaf);
}
}
export function MerkleProofFactory(depth: number) {
return class MerkleProof extends MerkleProofBase {
constructor(path: Array<Field>) {
super(path);
}
static sizeInFieldElements(): number {
return depth;
}
static toFieldElements(x: MerkleProof): Array<Field> {
return x.path;
}
static ofFieldElements(xs: Array<Field>): MerkleProof {
if (xs.length !== depth) {
throw new Error(
`MerkleTree: ofFieldElements expected array of length ${depth}, got ${xs.length}`
);
}
return new MerkleProof(xs);
}
};
}
export function IndexFactory(depth: number) {
return class Index extends IndexBase {
constructor(value: Array<Bool>) {
super(value);
}
static sizeInFieldElements(): number {
return depth;
}
static fromInt(n: number): Index {
if (n >= 1 << depth) {
throw new Error('Index is too large');
}
let res = [];
for (let i = 0; i < depth; ++i) {
res.push(new Bool(((n >> i) & 1) === 1));
}
return new Index(res);
}
static ofFieldElements(xs: Field[]): Index {
return new Index(xs.map((x) => Bool.Unsafe.ofField(x)));
}
static toFieldElements(i: Index): Field[] {
return i.value.map((b) => b.toField());
}
static check(i: Index) {
i.value.forEach((b) => b.toField().assertBoolean());
}
};
}
type Constructor<T> = { new (...args: any[]): T };
function range(n: number): Array<number> {
let res = [];
for (let i = 0; i < n; ++i) {
res.push(i);
}
return res;
}
export const MerkleProof = range(128).map(MerkleProofFactory);
export const Index = range(128).map(IndexFactory);
export type MerkleProof = InstanceType<typeof MerkleProof[0]>;
export type Index = InstanceType<typeof Index[0]>;
// TODO: Put better value
const emptyHashes: Field[] = [];
function emptyHash(depth: number): Field {
if (emptyHashes.length === 0) emptyHashes.push(new Field(1234561789));
if (depth >= emptyHashes.length) {
for (let i = emptyHashes.length; i < depth + 1; ++i) {
const h = emptyHashes[i - 1];
emptyHashes.push(Poseidon.hash([h, h]));
}
}
return emptyHashes[depth];
}
type IndexId = number;
type BinTree<A> =
| { kind: 'empty'; hash: Field; depth: number }
| { kind: 'leaf'; hash: Field; value: A }
| { kind: 'node'; hash: Field; left: BinTree<A>; right: BinTree<A> };
function treeOfArray<A>(
depth: number,
hashElement: (a: A) => Field,
xs: A[]
): BinTree<A> {
if (xs.length === 0) {
return emptyTree(depth);
}
if (xs.length > 1 << depth) {
throw new Error(
`Length of elements (${xs.length}) is greater than 2^depth = ${
1 << depth
}`
);
}
let trees: BinTree<A>[] = xs.map((x) => ({
kind: 'leaf',
hash: hashElement(x),
value: x,
}));
for (let treesDepth = 0; treesDepth < depth; ++treesDepth) {
const newTrees: BinTree<A>[] = [];
for (let j = 0; j < trees.length >> 1; ++j) {
const left = trees[2 * j];
const right = trees[2 * j + 1] || emptyTree(treesDepth);
newTrees.push({
kind: 'node',
hash: Poseidon.hash([left.hash, right.hash]),
left,
right,
});
}
trees = newTrees;
}
console.assert(trees.length === 1);
return trees[0];
}
function impliedRoot(
index: Array<Bool>,
path: Array<Field>,
leaf: Field
): Field {
let impliedRoot = leaf;
for (let i = 0; i < index.length; ++i) {
let [left, right] = Circuit.if(
index[i],
[path[i], impliedRoot],
[impliedRoot, path[i]]
);
impliedRoot = Poseidon.hash([left, right]);
}
return impliedRoot;
}
function checkMerklePath(
root: Field,
index: Array<Bool>,
path: Array<Field>,
leaf: Field
) {
root.assertEquals(impliedRoot(index, path, leaf));
}
function emptyTree<A>(depth: number): BinTree<A> {
return { kind: 'empty', depth, hash: emptyHash(depth) };
}
export class Tree<A> {
value: BinTree<A>;
constructor(depth: number, hashElement: (a: A) => Field, values: Array<A>) {
this.value = treeOfArray(depth, hashElement, values);
}
root(): Field {
return this.value.hash;
}
setValue(index: Array<boolean>, x: A, eltHash: Field) {
let stack = [];
let tree = this.value;
for (let i = index.length - 1; i >= 0; --i) {
stack.push(tree);
switch (tree.kind) {
case 'leaf':
throw new Error('Tree/index depth mismatch');
case 'empty':
(tree as any).kind = 'node';
(tree as any).left = emptyTree(tree.depth - 1);
(tree as any).right = emptyTree(tree.depth - 1);
delete (tree as any).depth;
tree = index[i] ? (tree as any).right : (tree as any).left;
break;
case 'node':
tree = index[i] ? tree.right : tree.left;
break;
default:
throw 'unreachable';
}
}
switch (tree.kind) {
case 'empty':
(tree as any).kind = 'leaf';
(tree as any).value = x;
delete (tree as any).depth;
tree.hash = eltHash;
break;
case 'leaf':
tree.hash = eltHash;
tree.value = x;
break;
default:
break;
}
for (let i = stack.length - 1; i >= 0; --i) {
tree = stack[i];
if (tree.kind !== 'node') {
throw 'unreachable';
}
tree.hash = Poseidon.hash([tree.left.hash, tree.right.hash]);
}
}
get(index: Array<boolean>): { value: A | null; hash: Field } {
let tree = this.value;
let i = index.length - 1;
for (let i = index.length - 1; i >= 0; --i) {
switch (tree.kind) {
case 'empty':
return { value: null, hash: tree.hash };
case 'leaf':
return tree;
case 'node':
tree = index[i] ? tree.right : tree.left;
break;
default:
break;
}
}
throw new Error('Malformed merkle tree');
}
getValue(index: Array<boolean>): A | null {
return this.get(index).value;
}
getElementHash(index: Array<boolean>): Field {
return this.get(index).hash;
}
getMerklePath(index: Array<boolean>): Array<Field> {
let res = [];
let tree = this.value;
let keepGoing = true;
let i = index.length - 1;
for (let i = index.length - 1; i >= 0; --i) {
switch (tree.kind) {
case 'empty':
res.push(emptyHash(i));
break;
case 'node':
res.push(index[i] ? tree.left.hash : tree.right.hash);
tree = index[i] ? tree.right : tree.left;
break;
case 'leaf':
throw new Error('Index/tree length mismatch.');
default:
throw 'unreachable';
}
}
res.reverse();
return res;
}
}
export interface MerkleTree<A> {
setValue: (index: Array<boolean>, x: A, eltHash: Field) => void;
getValue: (index: Array<boolean>) => A | null;
getElementHash: (index: Array<boolean>) => Field;
getMerklePath: (index: Array<boolean>) => Array<Field>;
root: () => Field;
}
function constantIndex(xs: Array<Bool>): Array<boolean> {
return xs.map((b) => b.toBoolean());
}
export class Collection<A> {
eltTyp: AsFieldElements<A>;
values:
| { computed: true; value: MerkleTree<A> }
| { computed: false; f: () => MerkleTree<A> };
// Maintains a set of currently valid path witnesses.
// If the root changes, witnesses will be invalidated.
cachedPaths: Map<IndexId, Array<Field>>;
cachedValues: Map<IndexId, { value: A; hash: Field }>;
root: Field | null;
getRoot(): Field {
if (this.root === null) {
this.root = this.getValues().root();
}
return this.root;
}
constructor(eltTyp: AsFieldElements<A>, f: () => Tree<A>, root?: Field) {
this.eltTyp = eltTyp;
this.cachedPaths = new Map();
this.cachedValues = new Map();
this.values = { computed: false, f };
this.root = null;
}
private getValues(): MerkleTree<A> {
if (this.values.computed) {
return this.values.value;
} else {
let value = this.values.f();
this.values = { computed: true, value };
return value;
}
}
set(i: Index, x: A) {
let cachedPath = this.cachedPaths.get(i.id);
let path: Array<Field>;
if (cachedPath !== undefined) {
path = cachedPath;
} else {
let depth = i.value.length;
let typ = Circuit.array(Field, depth);
let oldEltHash = Circuit.witness(Field, () =>
this.getValues().getElementHash(constantIndex(i.value))
);
path = Circuit.witness(typ, () => {
return this.getValues().getMerklePath(constantIndex(i.value));
});
checkMerklePath(this.getRoot(), i.value, path, oldEltHash);
}
let eltHash = Poseidon.hash(this.eltTyp.toFieldElements(x));
// Must clear the caches as we don't know if other indices happened to be equal to this one.
this.cachedPaths.clear();
this.cachedValues.clear();
this.cachedPaths.set(i.id, path);
this.cachedValues.set(i.id, { value: x, hash: eltHash });
let newRoot = impliedRoot(i.value, path, eltHash);
Circuit.asProver(() => {
this.getValues().setValue(
constantIndex(i.value),
x,
Field.toConstant(eltHash)
);
});
this.root = newRoot;
}
get(i: Index): A {
let cached = this.cachedValues.get(i.id);
if (cached !== undefined) {
return cached.value;
}
let depth = i.value.length;
let typ = Circuit.array(Field, depth);
let merkleProof: Array<Field> = Circuit.witness(typ, () => {
return this.getValues().getMerklePath(constantIndex(i.value));
});
let res: A = Circuit.witness(this.eltTyp, () => {
let res = this.getValues().getValue(constantIndex(i.value));
if (res === null) {
throw new Error('Index not present in collection');
}
return res;
});
let eltHash = Poseidon.hash(this.eltTyp.toFieldElements(res));
this.cachedValues.set(i.id, { value: res, hash: eltHash });
this.cachedPaths.set(i.id, merkleProof);
checkMerklePath(this.getRoot(), i.value, merkleProof, eltHash);
return res;
}
} | the_stack |
export const description = `
Basic command buffer rendering tests.
`;
import { makeTestGroup } from '../../../../common/framework/test_group.js';
import { now } from '../../../../common/util/util.js';
import { GPUTest } from '../../../gpu_test.js';
import { checkElementsEqual } from '../../../util/check_contents.js';
export const g = makeTestGroup(GPUTest);
g.test('clear').fn(async t => {
const dst = t.device.createBuffer({
size: 4,
usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
});
const colorAttachment = t.device.createTexture({
format: 'rgba8unorm',
size: { width: 1, height: 1, depthOrArrayLayers: 1 },
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
});
const colorAttachmentView = colorAttachment.createView();
const encoder = t.device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [
{
view: colorAttachmentView,
loadValue: { r: 0.0, g: 1.0, b: 0.0, a: 1.0 },
storeOp: 'store',
},
],
});
pass.endPass();
encoder.copyTextureToBuffer(
{ texture: colorAttachment, mipLevel: 0, origin: { x: 0, y: 0, z: 0 } },
{ buffer: dst, bytesPerRow: 256 },
{ width: 1, height: 1, depthOrArrayLayers: 1 }
);
t.device.queue.submit([encoder.finish()]);
t.expectGPUBufferValuesEqual(dst, new Uint8Array([0x00, 0xff, 0x00, 0xff]));
});
g.test('fullscreen_quad').fn(async t => {
const dst = t.device.createBuffer({
size: 4,
usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
});
const colorAttachment = t.device.createTexture({
format: 'rgba8unorm',
size: { width: 1, height: 1, depthOrArrayLayers: 1 },
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
});
const colorAttachmentView = colorAttachment.createView();
const pipeline = t.device.createRenderPipeline({
vertex: {
module: t.device.createShaderModule({
code: `
[[stage(vertex)]] fn main(
[[builtin(vertex_index)]] VertexIndex : u32
) -> [[builtin(position)]] vec4<f32> {
var pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
vec2<f32>(-1.0, -3.0),
vec2<f32>(3.0, 1.0),
vec2<f32>(-1.0, 1.0));
return vec4<f32>(pos[VertexIndex], 0.0, 1.0);
}
`,
}),
entryPoint: 'main',
},
fragment: {
module: t.device.createShaderModule({
code: `
[[stage(fragment)]] fn main() -> [[location(0)]] vec4<f32> {
return vec4<f32>(0.0, 1.0, 0.0, 1.0);
}
`,
}),
entryPoint: 'main',
targets: [{ format: 'rgba8unorm' }],
},
primitive: { topology: 'triangle-list' },
});
const encoder = t.device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [
{
view: colorAttachmentView,
storeOp: 'store',
loadValue: { r: 1.0, g: 0.0, b: 0.0, a: 1.0 },
},
],
});
pass.setPipeline(pipeline);
pass.draw(3);
pass.endPass();
encoder.copyTextureToBuffer(
{ texture: colorAttachment, mipLevel: 0, origin: { x: 0, y: 0, z: 0 } },
{ buffer: dst, bytesPerRow: 256 },
{ width: 1, height: 1, depthOrArrayLayers: 1 }
);
t.device.queue.submit([encoder.finish()]);
t.expectGPUBufferValuesEqual(dst, new Uint8Array([0x00, 0xff, 0x00, 0xff]));
});
g.test('large_draw')
.desc(
`Test reasonably-sized large {draw, drawIndexed} (see also stress tests).
Tests that draw calls behave reasonably with large vertex counts for
non-indexed draws, large index counts for indexed draws, and large instance
counts in both cases. Various combinations of these counts are tested with
both direct and indrect draw calls.
Draw call sizes are increased incrementally over these parameters until we the
run out of values or completion of a draw call exceeds a fixed time limit of
100ms.
To validate that the drawn vertices actually made it though the pipeline on
each draw call, we render a 3x3 target with the positions of the first and
last vertices of the first and last instances in different respective corners,
and everything else positioned to cover only one of the intermediate
fragments. If the output image is completely yellow, then we can reasonably
infer that all vertices were drawn.
Params:
- indexed= {true, false} - whether to test indexed or non-indexed draw calls
- indirect= {true, false} - whether to use indirect or direct draw calls`
)
.params(u =>
u //
.combine('indexed', [true, false])
.combine('indirect', [true, false])
)
.fn(async t => {
const { indexed, indirect } = t.params;
const kBytesPerRow = 256;
const dst = t.device.createBuffer({
size: 3 * kBytesPerRow,
usage: GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
});
const paramsBuffer = t.device.createBuffer({
size: 8,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const indirectBuffer = t.device.createBuffer({
size: 20,
usage: GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_DST,
});
const writeIndirectParams = (count: number, instanceCount: number) => {
const params = new Uint32Array(5);
params[0] = count; // Vertex or index count
params[1] = instanceCount;
params[2] = 0; // First vertex or index
params[3] = 0; // First instance (non-indexed) or base vertex (indexed)
params[4] = 0; // First instance (indexed)
t.device.queue.writeBuffer(indirectBuffer, 0, params, 0, 5);
};
let indexBuffer: null | GPUBuffer = null;
if (indexed) {
const kMaxIndices = 16 * 1024 * 1024;
indexBuffer = t.device.createBuffer({
size: kMaxIndices * Uint32Array.BYTES_PER_ELEMENT,
usage: GPUBufferUsage.INDEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true,
});
t.trackForCleanup(indexBuffer);
const indexData = new Uint32Array(indexBuffer.getMappedRange());
for (let i = 0; i < kMaxIndices; ++i) {
indexData[i] = i;
}
indexBuffer.unmap();
}
const colorAttachment = t.device.createTexture({
format: 'rgba8unorm',
size: { width: 3, height: 3, depthOrArrayLayers: 1 },
usage: GPUTextureUsage.COPY_SRC | GPUTextureUsage.RENDER_ATTACHMENT,
});
const colorAttachmentView = colorAttachment.createView();
const bgLayout = t.device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.VERTEX,
buffer: {},
},
],
});
const bindGroup = t.device.createBindGroup({
layout: bgLayout,
entries: [
{
binding: 0,
resource: { buffer: paramsBuffer },
},
],
});
const pipeline = t.device.createRenderPipeline({
layout: t.device.createPipelineLayout({ bindGroupLayouts: [bgLayout] }),
vertex: {
module: t.device.createShaderModule({
code: `
struct Params {
numVertices: u32;
numInstances: u32;
};
fn selectValue(index: u32, maxIndex: u32) -> f32 {
let highOrMid = select(0.0, 2.0 / 3.0, index == maxIndex - 1u);
return select(highOrMid, -2.0 / 3.0, index == 0u);
}
[[group(0), binding(0)]] var<uniform> params: Params;
[[stage(vertex)]] fn main(
[[builtin(vertex_index)]] v: u32,
[[builtin(instance_index)]] i: u32)
-> [[builtin(position)]] vec4<f32> {
let x = selectValue(v, params.numVertices);
let y = -selectValue(i, params.numInstances);
return vec4<f32>(x, y, 0.0, 1.0);
}
`,
}),
entryPoint: 'main',
},
fragment: {
module: t.device.createShaderModule({
code: `
[[stage(fragment)]] fn main() -> [[location(0)]] vec4<f32> {
return vec4<f32>(1.0, 1.0, 0.0, 1.0);
}
`,
}),
entryPoint: 'main',
targets: [{ format: 'rgba8unorm' }],
},
primitive: { topology: 'point-list' },
});
const runPipeline = async (numVertices: number, numInstances: number) => {
const encoder = t.device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [
{
view: colorAttachmentView,
storeOp: 'store',
loadValue: { r: 0.0, g: 0.0, b: 1.0, a: 1.0 },
},
],
});
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindGroup);
if (indexBuffer !== null) {
pass.setIndexBuffer(indexBuffer, 'uint32');
}
if (indirect) {
writeIndirectParams(numVertices, numInstances);
if (indexed) {
pass.drawIndexedIndirect(indirectBuffer, 0);
} else {
pass.drawIndirect(indirectBuffer, 0);
}
} else {
if (indexed) {
pass.drawIndexed(numVertices, numInstances);
} else {
pass.draw(numVertices, numInstances);
}
}
pass.endPass();
encoder.copyTextureToBuffer(
{ texture: colorAttachment, mipLevel: 0, origin: { x: 0, y: 0, z: 0 } },
{ buffer: dst, bytesPerRow: kBytesPerRow },
{ width: 3, height: 3, depthOrArrayLayers: 1 }
);
const params = new Uint32Array([numVertices, numInstances]);
t.device.queue.writeBuffer(paramsBuffer, 0, params, 0, 2);
t.device.queue.submit([encoder.finish()]);
const yellow = [0xff, 0xff, 0x00, 0xff];
const allYellow = new Uint8Array([...yellow, ...yellow, ...yellow]);
for (const row of [0, 1, 2]) {
t.expectGPUBufferValuesPassCheck(dst, data => checkElementsEqual(data, allYellow), {
srcByteOffset: row * 256,
type: Uint8Array,
typedLength: 12,
});
}
};
// If any iteration takes longer than this, we stop incrementing along that
// branch and move on to the next instance count. Note that the max
// supported vertex count for any iteration is 2**24 due to our choice of
// index buffer size.
const maxDurationMs = 100;
const counts = [
{
numInstances: 4,
vertexCounts: [2 ** 10, 2 ** 16, 2 ** 18, 2 ** 20, 2 ** 22, 2 ** 24],
},
{
numInstances: 2 ** 8,
vertexCounts: [2 ** 10, 2 ** 16, 2 ** 18, 2 ** 20, 2 ** 22],
},
{
numInstances: 2 ** 10,
vertexCounts: [2 ** 8, 2 ** 10, 2 ** 12, 2 ** 16, 2 ** 18, 2 ** 20],
},
{
numInstances: 2 ** 16,
vertexCounts: [2 ** 4, 2 ** 8, 2 ** 10, 2 ** 12, 2 ** 14],
},
{
numInstances: 2 ** 20,
vertexCounts: [2 ** 4, 2 ** 8, 2 ** 10],
},
];
for (const { numInstances, vertexCounts } of counts) {
for (const numVertices of vertexCounts) {
const start = now();
runPipeline(numVertices, numInstances);
await t.device.queue.onSubmittedWorkDone();
const duration = now() - start;
if (duration >= maxDurationMs) {
break;
}
}
}
}); | the_stack |
import {
debounce,
editorEvents,
editorOptions,
getAceInstance
} from "./editorOptions";
const ace = getAceInstance();
import { Ace, Range } from "ace-builds";
import Editor = Ace.Editor;
import { Split } from "ace-builds/src-noconflict/ext-split";
import * as PropTypes from "prop-types";
import * as React from "react";
const isEqual = require("lodash.isequal");
const get = require("lodash.get");
import {
IAceOptions,
IAnnotation,
ICommand,
IEditorProps,
IMarker
} from "./types";
interface IAceEditorClass extends Editor {
[index: string]: any;
$options?: any;
}
export interface ISplitEditorProps {
[index: string]: any;
name?: string;
style?: object;
/** For available modes see https://github.com/thlorenz/brace/tree/master/mode */
mode?: string;
/** For available themes see https://github.com/thlorenz/brace/tree/master/theme */
theme?: string;
height?: string;
width?: string;
className?: string;
fontSize?: number | string;
showGutter?: boolean;
showPrintMargin?: boolean;
highlightActiveLine?: boolean;
focus?: boolean;
splits: number;
debounceChangePeriod?: number;
cursorStart?: number;
wrapEnabled?: boolean;
readOnly?: boolean;
minLines?: number;
maxLines?: number;
enableBasicAutocompletion?: boolean | string[];
enableLiveAutocompletion?: boolean | string[];
tabSize?: number;
value?: string[];
defaultValue?: string[];
scrollMargin?: number[];
orientation?: string;
onSelectionChange?: (value: any, event?: any) => void;
onCursorChange?: (value: any, event?: any) => void;
onInput?: (event?: any) => void;
onLoad?: (editor: IEditorProps) => void;
onBeforeLoad?: (ace: any) => void;
onChange?: (value: string[], event?: any) => void;
onSelection?: (selectedText: string, event?: any) => void;
onCopy?: (value: string) => void;
onPaste?: (value: string) => void;
onFocus?: (value: Event) => void;
onBlur?: (value: Event) => void;
onScroll?: (editor: IEditorProps) => void;
editorProps?: IEditorProps;
setOptions?: IAceOptions;
keyboardHandler?: string;
commands?: ICommand[];
annotations?: IAnnotation[][];
markers?: IMarker[][];
}
export default class SplitComponent extends React.Component<
ISplitEditorProps,
undefined
> {
[index: string]: any;
public static propTypes: PropTypes.ValidationMap<ISplitEditorProps> = {
className: PropTypes.string,
debounceChangePeriod: PropTypes.number,
defaultValue: PropTypes.arrayOf(PropTypes.string),
focus: PropTypes.bool,
fontSize: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.string,
mode: PropTypes.string,
name: PropTypes.string,
onBlur: PropTypes.func,
onChange: PropTypes.func,
onCopy: PropTypes.func,
onFocus: PropTypes.func,
onInput: PropTypes.func,
onLoad: PropTypes.func,
onPaste: PropTypes.func,
onScroll: PropTypes.func,
orientation: PropTypes.string,
showGutter: PropTypes.bool,
splits: PropTypes.number,
theme: PropTypes.string,
value: PropTypes.arrayOf(PropTypes.string),
width: PropTypes.string,
onSelectionChange: PropTypes.func,
onCursorChange: PropTypes.func,
onBeforeLoad: PropTypes.func,
minLines: PropTypes.number,
maxLines: PropTypes.number,
readOnly: PropTypes.bool,
highlightActiveLine: PropTypes.bool,
tabSize: PropTypes.number,
showPrintMargin: PropTypes.bool,
cursorStart: PropTypes.number,
editorProps: PropTypes.object,
setOptions: PropTypes.object,
style: PropTypes.object,
scrollMargin: PropTypes.array,
annotations: PropTypes.array,
markers: PropTypes.array,
keyboardHandler: PropTypes.string,
wrapEnabled: PropTypes.bool,
enableBasicAutocompletion: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.array
]),
enableLiveAutocompletion: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.array
]),
commands: PropTypes.array
};
public static defaultProps: Partial<ISplitEditorProps> = {
name: "ace-editor",
focus: false,
orientation: "beside",
splits: 2,
mode: "",
theme: "",
height: "500px",
width: "500px",
value: [],
fontSize: 12,
showGutter: true,
onChange: null,
onPaste: null,
onLoad: null,
onScroll: null,
minLines: null,
maxLines: null,
readOnly: false,
highlightActiveLine: true,
showPrintMargin: true,
tabSize: 4,
cursorStart: 1,
editorProps: {},
style: {},
scrollMargin: [0, 0, 0, 0],
setOptions: {},
wrapEnabled: false,
enableBasicAutocompletion: false,
enableLiveAutocompletion: false
};
public editor: IAceEditorClass;
public refEditor: HTMLElement;
public silent: boolean;
public split: IAceEditorClass;
public splitEditor: IAceEditorClass;
public debounce: (fn: any, delay: number) => (...args: any) => void;
constructor(props: ISplitEditorProps) {
super(props);
editorEvents.forEach(method => {
this[method] = this[method].bind(this);
});
this.debounce = debounce;
}
public isInShadow(node: HTMLElement): boolean {
let parent = node && node.parentNode;
while (parent) {
if (parent.toString() === "[object ShadowRoot]") {
return true;
}
parent = parent.parentNode;
}
return false;
}
public componentDidMount() {
const {
className,
onBeforeLoad,
mode,
focus,
theme,
fontSize,
value,
defaultValue,
cursorStart,
showGutter,
wrapEnabled,
showPrintMargin,
scrollMargin = [0, 0, 0, 0],
keyboardHandler,
onLoad,
commands,
annotations,
markers,
splits
} = this.props;
this.editor = ace.edit(this.refEditor);
if (this.isInShadow(this.refEditor)) {
this.editor.renderer.attachToShadowRoot();
}
this.editor.setTheme(`ace/theme/${theme}`);
if (onBeforeLoad) {
onBeforeLoad(ace);
}
const editorProps = Object.keys(this.props.editorProps);
const split = new Split(
this.editor.container,
`ace/theme/${theme}`,
splits
);
this.editor.env.split = split;
this.splitEditor = split.getEditor(0);
this.split = split;
// in a split scenario we don't want a print margin for the entire application
this.editor.setShowPrintMargin(false);
this.editor.renderer.setShowGutter(false);
// get a list of possible options to avoid 'misspelled option errors'
const availableOptions = this.splitEditor.$options;
if (this.props.debounceChangePeriod) {
this.onChange = this.debounce(
this.onChange,
this.props.debounceChangePeriod
);
}
split.forEach((editor: IAceEditorClass, index: number) => {
for (let i = 0; i < editorProps.length; i++) {
editor[editorProps[i]] = this.props.editorProps[editorProps[i]];
}
const defaultValueForEditor = get(defaultValue, index);
const valueForEditor = get(value, index, "");
editor.session.setUndoManager(new ace.UndoManager());
editor.setTheme(`ace/theme/${theme}`);
editor.renderer.setScrollMargin(
scrollMargin[0],
scrollMargin[1],
scrollMargin[2],
scrollMargin[3]
);
editor.getSession().setMode(`ace/mode/${mode}`);
editor.setFontSize(fontSize as any);
editor.renderer.setShowGutter(showGutter);
editor.getSession().setUseWrapMode(wrapEnabled);
editor.setShowPrintMargin(showPrintMargin);
editor.on("focus", this.onFocus);
editor.on("blur", this.onBlur);
editor.on("input" as any, this.onInput);
editor.on("copy", this.onCopy as any);
editor.on("paste", this.onPaste as any);
editor.on("change", this.onChange);
editor
.getSession()
.selection.on("changeSelection", this.onSelectionChange);
editor.getSession().selection.on("changeCursor", this.onCursorChange);
editor.session.on("changeScrollTop", this.onScroll);
editor.setValue(
defaultValueForEditor === undefined
? valueForEditor
: defaultValueForEditor,
cursorStart
);
const newAnnotations = get(annotations, index, []);
const newMarkers = get(markers, index, []);
editor.getSession().setAnnotations(newAnnotations);
if (newMarkers && newMarkers.length > 0) {
this.handleMarkers(newMarkers, editor);
}
for (let i = 0; i < editorOptions.length; i++) {
const option = editorOptions[i];
if (availableOptions.hasOwnProperty(option)) {
editor.setOption(option as any, this.props[option]);
} else if (this.props[option]) {
console.warn(
`ReaceAce: editor option ${option} was activated but not found. Did you need to import a related tool or did you possibly mispell the option?`
);
}
}
this.handleOptions(this.props, editor);
if (Array.isArray(commands)) {
commands.forEach(command => {
if (typeof command.exec === "string") {
(editor.commands as any).bindKey(command.bindKey, command.exec);
} else {
(editor.commands as any).addCommand(command);
}
});
}
if (keyboardHandler) {
editor.setKeyboardHandler("ace/keyboard/" + keyboardHandler);
}
});
if (className) {
this.refEditor.className += " " + className;
}
if (focus) {
this.splitEditor.focus();
}
const sp = this.editor.env.split;
sp.setOrientation(
this.props.orientation === "below" ? sp.BELOW : sp.BESIDE
);
sp.resize(true);
if (onLoad) {
onLoad(sp);
}
}
public componentDidUpdate(prevProps: ISplitEditorProps) {
const oldProps = prevProps;
const nextProps = this.props;
const split = this.editor.env.split;
if (nextProps.splits !== oldProps.splits) {
split.setSplits(nextProps.splits);
}
if (nextProps.orientation !== oldProps.orientation) {
split.setOrientation(
nextProps.orientation === "below" ? split.BELOW : split.BESIDE
);
}
split.forEach((editor: IAceEditorClass, index: number) => {
if (nextProps.mode !== oldProps.mode) {
editor.getSession().setMode("ace/mode/" + nextProps.mode);
}
if (nextProps.keyboardHandler !== oldProps.keyboardHandler) {
if (nextProps.keyboardHandler) {
editor.setKeyboardHandler(
"ace/keyboard/" + nextProps.keyboardHandler
);
} else {
editor.setKeyboardHandler(null);
}
}
if (nextProps.fontSize !== oldProps.fontSize) {
editor.setFontSize(nextProps.fontSize as any);
}
if (nextProps.wrapEnabled !== oldProps.wrapEnabled) {
editor.getSession().setUseWrapMode(nextProps.wrapEnabled);
}
if (nextProps.showPrintMargin !== oldProps.showPrintMargin) {
editor.setShowPrintMargin(nextProps.showPrintMargin);
}
if (nextProps.showGutter !== oldProps.showGutter) {
editor.renderer.setShowGutter(nextProps.showGutter);
}
for (let i = 0; i < editorOptions.length; i++) {
const option = editorOptions[i];
if (nextProps[option] !== oldProps[option]) {
editor.setOption(option as any, nextProps[option]);
}
}
if (!isEqual(nextProps.setOptions, oldProps.setOptions)) {
this.handleOptions(nextProps, editor);
}
const nextValue = get(nextProps.value, index, "");
if (editor.getValue() !== nextValue) {
// editor.setValue is a synchronous function call, change event is emitted before setValue return.
this.silent = true;
const pos = (editor.session.selection as any).toJSON();
editor.setValue(nextValue, nextProps.cursorStart);
(editor.session.selection as any).fromJSON(pos);
this.silent = false;
}
const newAnnotations = get(nextProps.annotations, index, []);
const oldAnnotations = get(oldProps.annotations, index, []);
if (!isEqual(newAnnotations, oldAnnotations)) {
editor.getSession().setAnnotations(newAnnotations);
}
const newMarkers = get(nextProps.markers, index, []);
const oldMarkers = get(oldProps.markers, index, []);
if (!isEqual(newMarkers, oldMarkers) && Array.isArray(newMarkers)) {
this.handleMarkers(newMarkers, editor);
}
});
if (nextProps.className !== oldProps.className) {
const appliedClasses = this.refEditor.className;
const appliedClassesArray = appliedClasses.trim().split(" ");
const oldClassesArray = oldProps.className.trim().split(" ");
oldClassesArray.forEach(oldClass => {
const index = appliedClassesArray.indexOf(oldClass);
appliedClassesArray.splice(index, 1);
});
this.refEditor.className =
" " + nextProps.className + " " + appliedClassesArray.join(" ");
}
if (nextProps.theme !== oldProps.theme) {
split.setTheme("ace/theme/" + nextProps.theme);
}
if (nextProps.focus && !oldProps.focus) {
this.splitEditor.focus();
}
if (
nextProps.height !== this.props.height ||
nextProps.width !== this.props.width
) {
this.editor.resize();
}
}
public componentWillUnmount() {
this.editor.destroy();
this.editor = null;
}
public onChange(event: any) {
if (this.props.onChange && !this.silent) {
const value: any = [];
this.editor.env.split.forEach((editor: IAceEditorClass) => {
value.push(editor.getValue());
});
this.props.onChange(value, event);
}
}
public onSelectionChange(event: any) {
if (this.props.onSelectionChange) {
const value: any = [];
this.editor.env.split.forEach((editor: IAceEditorClass) => {
value.push(editor.getSelection());
});
this.props.onSelectionChange(value, event);
}
}
public onCursorChange(event: any) {
if (this.props.onCursorChange) {
const value: any = [];
this.editor.env.split.forEach((editor: IAceEditorClass) => {
value.push(editor.getSelection());
});
this.props.onCursorChange(value, event);
}
}
public onFocus(event: any) {
if (this.props.onFocus) {
this.props.onFocus(event);
}
}
public onInput(event: any) {
if (this.props.onInput) {
this.props.onInput(event);
}
}
public onBlur(event: any) {
if (this.props.onBlur) {
this.props.onBlur(event);
}
}
public onCopy(text: string) {
if (this.props.onCopy) {
this.props.onCopy(text);
}
}
public onPaste(text: string) {
if (this.props.onPaste) {
this.props.onPaste(text);
}
}
public onScroll() {
if (this.props.onScroll) {
this.props.onScroll(this.editor);
}
}
public handleOptions(props: ISplitEditorProps, editor: IAceEditorClass) {
const setOptions = Object.keys(props.setOptions);
for (let y = 0; y < setOptions.length; y++) {
editor.setOption(setOptions[y] as any, props.setOptions[setOptions[y]]);
}
}
public handleMarkers(markers: IMarker[], editor: IAceEditorClass) {
// remove foreground markers
let currentMarkers = editor.getSession().getMarkers(true);
for (const i in currentMarkers) {
if (currentMarkers.hasOwnProperty(i)) {
editor.getSession().removeMarker(currentMarkers[i].id);
}
}
// remove background markers
currentMarkers = editor.getSession().getMarkers(false);
for (const i in currentMarkers) {
if (currentMarkers.hasOwnProperty(i)) {
editor.getSession().removeMarker(currentMarkers[i].id);
}
}
// add new markers
markers.forEach(
({
startRow,
startCol,
endRow,
endCol,
className,
type,
inFront = false
}) => {
const range = new Range(startRow, startCol, endRow, endCol);
editor
.getSession()
.addMarker(range as any, className, type as any, inFront);
}
);
}
public updateRef(item: HTMLElement) {
this.refEditor = item;
}
public render() {
const { name, width, height, style } = this.props;
const divStyle = { width, height, ...style };
return <div ref={this.updateRef} id={name} style={divStyle} />;
}
} | the_stack |
import {
CommandClasses,
decryptAES128CCM,
encodeBitMask,
encryptAES128CCM,
getCCName,
isTransmissionError,
isZWaveError,
Maybe,
MessageOrCCLogEntry,
MessageRecord,
parseBitMask,
parseCCList,
S2SecurityClass,
SecurityClass,
securityClassIsS2,
securityClassOrder,
SecurityManager2,
SECURITY_S2_AUTH_TAG_LENGTH,
SPANState,
validatePayload,
ZWaveError,
ZWaveErrorCodes,
} from "@zwave-js/core";
import { buffer2hex, getEnumMemberName, pick } from "@zwave-js/shared";
import type { ZWaveController } from "../controller/Controller";
import { SendDataBridgeRequest } from "../controller/SendDataBridgeMessages";
import { SendDataRequest } from "../controller/SendDataMessages";
import { TransmitOptions } from "../controller/SendDataShared";
import type { Driver } from "../driver/Driver";
import { FunctionType, MessagePriority } from "../message/Constants";
import { CCAPI } from "./API";
import {
API,
CCCommand,
CCCommandOptions,
CommandClass,
commandClass,
CommandClassDeserializationOptions,
CommandClassOptions,
expectedCCResponse,
gotDeserializationOptions,
implementedVersion,
} from "./CommandClass";
import { MultiChannelCC } from "./MultiChannelCC";
import {
MGRPExtension,
Security2Extension,
SPANExtension,
} from "./Security2/Extension";
import { ECDHProfiles, KEXFailType, KEXSchemes } from "./Security2/shared";
// All the supported commands
export enum Security2Command {
NonceGet = 0x01,
NonceReport = 0x02,
MessageEncapsulation = 0x03,
KEXGet = 0x04,
KEXReport = 0x05,
KEXSet = 0x06,
KEXFail = 0x07,
PublicKeyReport = 0x08,
NetworkKeyGet = 0x09,
NetworkKeyReport = 0x0a,
NetworkKeyVerify = 0x0b,
TransferEnd = 0x0c,
CommandsSupportedGet = 0x0d,
CommandsSupportedReport = 0x0e,
}
function securityClassToBitMask(key: SecurityClass): Buffer {
return encodeBitMask(
[key],
SecurityClass.S0_Legacy,
SecurityClass.S2_Unauthenticated,
);
}
function bitMaskToSecurityClass(buffer: Buffer, offset: number): SecurityClass {
const keys = parseBitMask(
buffer.slice(offset, offset + 1),
SecurityClass.S2_Unauthenticated,
);
validatePayload(keys.length === 1);
return keys[0];
}
function getAuthenticationData(
sendingNodeId: number,
destination: number,
homeId: number,
commandLength: number,
unencryptedPayload: Buffer,
): Buffer {
const ret = Buffer.allocUnsafe(8 + unencryptedPayload.length);
ret[0] = sendingNodeId;
ret[1] = destination;
ret.writeUInt32BE(homeId, 2);
ret.writeUInt16BE(commandLength, 6);
// This includes the sequence number and all unencrypted extensions
unencryptedPayload.copy(ret, 8, 0);
return ret;
}
/** Validates that a sequence number is not a duplicate and updates the SPAN table if it is accepted */
function validateSequenceNumber(this: Security2CC, sequenceNumber: number) {
const peerNodeID = this.nodeId as number;
validatePayload.withReason("Duplicate command")(
!this.driver.securityManager2!.isDuplicateSinglecast(
peerNodeID,
sequenceNumber,
),
);
// Not a duplicate, store it
this.driver.securityManager2!.storeSequenceNumber(
peerNodeID,
sequenceNumber,
);
}
function assertSecurity(this: Security2CC, options: CommandClassOptions): void {
const verb = gotDeserializationOptions(options) ? "decoded" : "sent";
if (!this.driver.controller.ownNodeId) {
throw new ZWaveError(
`Secure commands (S2) can only be ${verb} when the controller's node id is known!`,
ZWaveErrorCodes.Driver_NotReady,
);
} else if (!this.driver.securityManager2) {
throw new ZWaveError(
`Secure commands (S2) can only be ${verb} when the network keys for the driver are set!`,
ZWaveErrorCodes.Driver_NoSecurity,
);
}
}
const DECRYPT_ATTEMPTS = 5;
@API(CommandClasses["Security 2"])
export class Security2CCAPI extends CCAPI {
public supportsCommand(_cmd: Security2Command): Maybe<boolean> {
// All commands are mandatory
return true;
}
/**
* Sends a nonce to the node, either in response to a NonceGet request or a message that failed to decrypt. The message is sent without any retransmission etc.
* The return value indicates whether a nonce was successfully sent
*/
public async sendNonce(): Promise<boolean> {
this.assertSupportsCommand(
Security2Command,
Security2Command.NonceReport,
);
this.assertPhysicalEndpoint(this.endpoint);
if (!this.driver.securityManager2) {
throw new ZWaveError(
`Nonces can only be sent if secure communication is set up!`,
ZWaveErrorCodes.Driver_NoSecurity,
);
}
const receiverEI = this.driver.securityManager2.generateNonce(
this.endpoint.nodeId,
);
const cc = new Security2CCNonceReport(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
SOS: true,
MOS: false,
receiverEI,
});
const SendDataConstructor = this.driver.controller.isFunctionSupported(
FunctionType.SendDataBridge,
)
? SendDataBridgeRequest
: SendDataRequest;
const msg = new SendDataConstructor(this.driver, {
command: cc,
// Seems we need these options or some nodes won't accept the nonce
transmitOptions: TransmitOptions.ACK | TransmitOptions.AutoRoute,
// Only try sending a nonce once
maxSendAttempts: 1,
});
try {
await this.driver.sendMessage(msg, {
...this.commandOptions,
// Nonce requests must be handled immediately
priority: MessagePriority.Handshake,
// We don't want failures causing us to treat the node as asleep or dead
changeNodeStatusOnMissingACK: false,
});
} catch (e) {
if (isTransmissionError(e)) {
// The nonce could not be sent, invalidate it
this.driver.securityManager2.deleteNonce(this.endpoint.nodeId);
return false;
} else {
// Pass other errors through
throw e;
}
}
return true;
}
/**
* Requests a nonce from the target node
*/
public async requestNonce(): Promise<void> {
this.assertSupportsCommand(Security2Command, Security2Command.NonceGet);
this.assertPhysicalEndpoint(this.endpoint);
if (!this.driver.securityManager2) {
throw new ZWaveError(
`Nonces can only be sent if secure communication is set up!`,
ZWaveErrorCodes.Driver_NoSecurity,
);
}
const cc = new Security2CCNonceGet(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
});
await this.driver.sendCommand(cc, {
...this.commandOptions,
priority: MessagePriority.PreTransmitHandshake,
// Only try getting a nonce once
maxSendAttempts: 1,
// We don't want failures causing us to treat the node as asleep or dead
// The "real" transaction will do that for us
changeNodeStatusOnMissingACK: false,
});
}
/**
* Queries the securely supported commands for the current security class
* @param securityClass Can be used to overwrite the security class to use. If this doesn't match the current one, new nonces will need to be exchanged.
*/
public async getSupportedCommands(
securityClass:
| SecurityClass.S2_AccessControl
| SecurityClass.S2_Authenticated
| SecurityClass.S2_Unauthenticated,
): Promise<CommandClasses[] | undefined> {
this.assertSupportsCommand(
Security2Command,
Security2Command.CommandsSupportedGet,
);
let cc: CommandClass = new Security2CCCommandsSupportedGet(
this.driver,
{
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
},
);
// Security2CCCommandsSupportedGet is special because we cannot reply on the driver to do the automatic
// encapsulation because it would use a different security class. Therefore the entire possible stack
// of encapsulation needs to be done here
if (MultiChannelCC.requiresEncapsulation(cc)) {
cc = MultiChannelCC.encapsulate(this.driver, cc);
}
cc = Security2CC.encapsulate(this.driver, cc, securityClass);
const response =
await this.driver.sendCommand<Security2CCCommandsSupportedReport>(
cc,
{
...this.commandOptions,
autoEncapsulate: false,
},
);
return response?.supportedCCs;
}
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
public async getKeyExchangeParameters() {
this.assertSupportsCommand(Security2Command, Security2Command.KEXGet);
const cc = new Security2CCKEXGet(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
});
const response = await this.driver.sendCommand<Security2CCKEXReport>(
cc,
this.commandOptions,
);
if (response) {
return pick(response, [
"requestCSA",
"echo",
"supportedKEXSchemes",
"supportedECDHProfiles",
"requestedKeys",
]);
}
}
/** Grants the joining node the given keys */
public async grantKeys(
params: Omit<Security2CCKEXSetOptions, "echo">,
): Promise<void> {
this.assertSupportsCommand(Security2Command, Security2Command.KEXSet);
const cc = new Security2CCKEXSet(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
...params,
echo: false,
});
await this.driver.sendCommand(cc, this.commandOptions);
}
/** Confirms the keys that were granted to a node */
public async confirmGrantedKeys(
params: Omit<Security2CCKEXReportOptions, "echo">,
): Promise<void> {
this.assertSupportsCommand(
Security2Command,
Security2Command.KEXReport,
);
const cc = new Security2CCKEXReport(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
...params,
echo: true,
});
await this.driver.sendCommand(cc, this.commandOptions);
}
/** Notifies the other node that the ongoing key exchange was aborted */
public async abortKeyExchange(failType: KEXFailType): Promise<void> {
this.assertSupportsCommand(Security2Command, Security2Command.KEXFail);
const cc = new Security2CCKEXFail(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
failType,
});
await this.driver.sendCommand(cc, this.commandOptions);
}
public async sendPublicKey(publicKey: Buffer): Promise<void> {
this.assertSupportsCommand(
Security2Command,
Security2Command.PublicKeyReport,
);
const cc = new Security2CCPublicKeyReport(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
includingNode: true,
publicKey,
});
await this.driver.sendCommand(cc, this.commandOptions);
}
public async sendNetworkKey(
securityClass: SecurityClass,
networkKey: Buffer,
): Promise<void> {
this.assertSupportsCommand(
Security2Command,
Security2Command.NetworkKeyReport,
);
const cc = new Security2CCNetworkKeyReport(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
grantedKey: securityClass,
networkKey,
});
await this.driver.sendCommand(cc, this.commandOptions);
}
public async confirmKeyVerification(): Promise<void> {
this.assertSupportsCommand(
Security2Command,
Security2Command.TransferEnd,
);
const cc = new Security2CCTransferEnd(this.driver, {
nodeId: this.endpoint.nodeId,
endpoint: this.endpoint.index,
keyVerified: true,
keyRequestComplete: false,
});
await this.driver.sendCommand(cc, {
...this.commandOptions,
// Don't wait for an ACK from the node
transmitOptions: TransmitOptions.DEFAULT & ~TransmitOptions.ACK,
});
}
}
@commandClass(CommandClasses["Security 2"])
@implementedVersion(1)
export class Security2CC extends CommandClass {
declare ccCommand: Security2Command;
public async interview(): Promise<void> {
const node = this.getNode()!;
const endpoint = this.getEndpoint()!;
const api = endpoint.commandClasses["Security 2"].withOptions({
priority: MessagePriority.NodeQuery,
});
// Only on the highest security class the reponse includes the supported commands
let hasReceivedSecureCommands = false;
let possibleSecurityClasses: S2SecurityClass[];
if (endpoint.index === 0) {
possibleSecurityClasses = [
SecurityClass.S2_Unauthenticated,
SecurityClass.S2_Authenticated,
SecurityClass.S2_AccessControl,
];
} else {
const secClass = node.getHighestSecurityClass();
if (!securityClassIsS2(secClass)) {
this.driver.controllerLog.logNode(node.id, {
endpoint: endpoint.index,
message: `Cannot query securely supported commands for endpoint because the node's security class isn't known...`,
level: "error",
});
return;
}
possibleSecurityClasses = [secClass];
}
for (const secClass of possibleSecurityClasses) {
// We might not know all assigned security classes yet, so we work our way up from low to high and try to request the supported commands.
// This way, each command is encrypted with the security class we're currently testing.
// If the node does not respond, it wasn't assigned the security class.
// If it responds with a non-empty list, we know this is the highest class it supports.
// If the list is empty, the security class is still supported.
// If we already know the class is not supported, skip it
if (node.hasSecurityClass(secClass) === false) continue;
// If no key is configured for this security class, skip it
if (
!this.driver.securityManager2?.hasKeysForSecurityClass(secClass)
) {
this.driver.controllerLog.logNode(node.id, {
endpoint: endpoint.index,
message: `Cannot query securely supported commands (${getEnumMemberName(
SecurityClass,
secClass,
)}) - network key is not configured...`,
level: "warn",
});
continue;
}
this.driver.controllerLog.logNode(node.id, {
endpoint: endpoint.index,
message: `Querying securely supported commands (${getEnumMemberName(
SecurityClass,
secClass,
)})...`,
direction: "outbound",
});
// Query the supported commands but avoid remembering the wrong security class in case of a failure
let supportedCCs: CommandClasses[] | undefined;
try {
supportedCCs = await api.getSupportedCommands(secClass);
} catch (e) {
if (
isZWaveError(e) &&
e.code === ZWaveErrorCodes.Security2CC_CannotDecode
) {
// This has to be expected when we're using a non-granted security class
supportedCCs = undefined;
} else {
throw e;
}
}
if (supportedCCs == undefined) {
if (endpoint.index === 0) {
// No supported commands found, mark the security class as not granted
node.securityClasses.set(secClass, false);
this.driver.controllerLog.logNode(node.id, {
message: `The node was NOT granted the security class ${getEnumMemberName(
SecurityClass,
secClass,
)}`,
direction: "inbound",
});
}
continue;
}
if (endpoint.index === 0) {
// Mark the security class as granted
node.securityClasses.set(secClass, true);
this.driver.controllerLog.logNode(node.id, {
message: `The node was granted the security class ${getEnumMemberName(
SecurityClass,
secClass,
)}`,
direction: "inbound",
});
}
if (!hasReceivedSecureCommands && supportedCCs.length > 0) {
hasReceivedSecureCommands = true;
const logLines: string[] = [
`received secure commands (${getEnumMemberName(
SecurityClass,
secClass,
)})`,
"supported CCs:",
];
for (const cc of supportedCCs) {
logLines.push(`· ${getCCName(cc)}`);
}
this.driver.controllerLog.logNode(node.id, {
endpoint: endpoint.index,
message: logLines.join("\n"),
direction: "inbound",
});
// Remember which commands are supported securely
for (const cc of supportedCCs) {
endpoint.addCC(cc, {
isSupported: true,
secure: true,
});
}
}
}
// Remember that the interview is complete
this.interviewComplete = true;
}
/** Tests if a command should be sent secure and thus requires encapsulation */
public static requiresEncapsulation(cc: CommandClass): boolean {
// Everything that's not an S2 CC needs to be encapsulated if the CC is secure
if (!cc.secure) return false;
if (!(cc instanceof Security2CC)) return true;
// These S2 commands need additional encapsulation
switch (cc.ccCommand) {
case Security2Command.CommandsSupportedGet:
case Security2Command.CommandsSupportedReport:
case Security2Command.NetworkKeyGet:
case Security2Command.NetworkKeyReport:
case Security2Command.NetworkKeyVerify:
case Security2Command.TransferEnd:
return true;
case Security2Command.KEXSet:
case Security2Command.KEXReport:
// KEXSet/Report need to be encrypted for the confirmation only
return (cc as Security2CCKEXSet | Security2CCKEXReport).echo;
case Security2Command.KEXFail: {
switch ((cc as Security2CCKEXFail).failType) {
case KEXFailType.Decrypt:
case KEXFailType.WrongSecurityLevel:
case KEXFailType.KeyNotGranted:
case KEXFailType.NoVerify:
return true;
default:
return false;
}
}
}
return false;
}
/** Encapsulates a command that should be sent encrypted */
public static encapsulate(
driver: Driver,
cc: CommandClass,
securityClass?: SecurityClass,
): Security2CCMessageEncapsulation {
return new Security2CCMessageEncapsulation(driver, {
nodeId: cc.nodeId,
encapsulated: cc,
securityClass,
});
}
}
interface Security2CCMessageEncapsulationOptions extends CCCommandOptions {
/** Can be used to override the default security class for the command */
securityClass?: SecurityClass;
extensions?: Security2Extension[];
encapsulated: CommandClass;
}
function getCCResponseForMessageEncapsulation(
sent: Security2CCMessageEncapsulation,
) {
if (sent.encapsulated?.expectsCCResponse()) {
return Security2CCMessageEncapsulation;
}
}
@CCCommand(Security2Command.MessageEncapsulation)
@expectedCCResponse(
getCCResponseForMessageEncapsulation,
() => "checkEncapsulated",
)
export class Security2CCMessageEncapsulation extends Security2CC {
// Define the securityManager and controller.ownNodeId as existing
// We check it in the constructor
declare driver: Driver & {
securityManager2: SecurityManager2;
controller: ZWaveController & {
ownNodeId: number;
};
};
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| Security2CCMessageEncapsulationOptions,
) {
super(driver, options);
// Make sure that we can send/receive secure commands
assertSecurity.call(this, options);
if (gotDeserializationOptions(options)) {
validatePayload(this.payload.length >= 2);
// Check the sequence number to avoid duplicates
// TODO: distinguish between multicast and singlecast
this._sequenceNumber = this.payload[0];
// Don't accept duplicate commands
validateSequenceNumber.call(this, this._sequenceNumber);
// Ensure the node has a security class
const peerNodeID = this.nodeId as number;
const node = this.getNode()!;
const securityClass = node.getHighestSecurityClass();
validatePayload.withReason("No security class granted")(
securityClass !== SecurityClass.None,
);
const hasExtensions = !!(this.payload[1] & 0b1);
const hasEncryptedExtensions = !!(this.payload[1] & 0b10);
let offset = 2;
this.extensions = [];
const parseExtensions = (buffer: Buffer) => {
while (true) {
// we need to read at least the length byte
validatePayload(buffer.length >= offset + 1);
const extensionLength =
Security2Extension.getExtensionLength(
buffer.slice(offset),
);
// Parse the extension
const ext = Security2Extension.from(
buffer.slice(offset, offset + extensionLength),
);
this.extensions.push(ext);
offset += extensionLength;
// Check if that was the last extension
if (!ext.moreToFollow) break;
}
};
if (hasExtensions) parseExtensions(this.payload);
const unencryptedPayload = this.payload.slice(0, offset);
const ciphertext = this.payload.slice(
offset,
-SECURITY_S2_AUTH_TAG_LENGTH,
);
const authTag = this.payload.slice(-SECURITY_S2_AUTH_TAG_LENGTH);
const messageLength =
super.computeEncapsulationOverhead() + this.payload.length;
const authData = getAuthenticationData(
this.nodeId as number,
this.getDestinationIDRX(),
this.driver.controller.homeId!,
messageLength,
unencryptedPayload,
);
// Decrypt payload and verify integrity
const spanState =
this.driver.securityManager2.getSPANState(peerNodeID);
const failNoSPAN = () => {
return validatePayload.fail(ZWaveErrorCodes.Security2CC_NoSPAN);
};
// If we are not able to establish an SPAN yet, fail the decryption
if (spanState.type === SPANState.None) {
return failNoSPAN();
} else if (spanState.type === SPANState.RemoteEI) {
// TODO: The specs are not clear how to handle this case
// For now, do the same as if we didn't have any EI
return failNoSPAN();
}
const decrypt = (): {
plaintext: Buffer;
authOK: boolean;
decryptionKey?: Buffer;
} => {
const getNonceAndDecrypt = () => {
const iv = this.driver.securityManager2.nextNonce(node.id);
const { keyCCM: key } =
this.driver.securityManager2.getKeysForNode(node);
return {
decryptionKey: key,
...decryptAES128CCM(
key,
iv,
ciphertext,
authData,
authTag,
),
};
};
if (spanState.type === SPANState.SPAN) {
// This can only happen if the security class is known
return getNonceAndDecrypt();
} else if (spanState.type === SPANState.LocalEI) {
// We've sent the other our receiver's EI and received its sender's EI,
// meaning we can now establish an SPAN
const senderEI = this.getSenderEI();
if (!senderEI) return failNoSPAN();
const receiverEI = spanState.receiverEI;
// How we do this depends on whether we know the security class of the other node
if (this.driver.securityManager2.tempKeys.has(peerNodeID)) {
// We're currently bootstrapping the node, it might be using a temporary key
this.driver.securityManager2.initializeTempSPAN(
node,
senderEI,
receiverEI,
);
const ret = getNonceAndDecrypt();
// Decryption with the temporary key worked
if (ret.authOK) return ret;
// Reset the SPAN state and try with the recently granted security class
this.driver.securityManager2.setSPANState(
node.id,
spanState,
);
}
if (securityClass != undefined) {
this.driver.securityManager2.initializeSPAN(
node,
securityClass,
senderEI,
receiverEI,
);
return getNonceAndDecrypt();
} else {
// Not knowing it can happen if we just took over an existing network
// Try multiple security classes
const possibleSecurityClasses = securityClassOrder
.filter((s) => securityClassIsS2(s))
.filter((s) => node.hasSecurityClass(s) !== false);
for (const secClass of possibleSecurityClasses) {
// Initialize an SPAN with that security class
this.driver.securityManager2.initializeSPAN(
node,
secClass,
senderEI,
receiverEI,
);
const ret = getNonceAndDecrypt();
// It worked, return the result and remember the security class
if (ret.authOK) {
node.securityClasses.set(secClass, true);
return ret;
}
// Reset the SPAN state and try with the next security class
this.driver.securityManager2.setSPANState(
node.id,
spanState,
);
}
}
}
// Nothing worked, fail the decryption
return { plaintext: Buffer.from([]), authOK: false };
};
let plaintext: Buffer | undefined;
let authOK = false;
let decryptionKey: Buffer | undefined;
// If the Receiver is unable to authenticate the singlecast message with the current SPAN,
// the Receiver SHOULD try decrypting the message with one or more of the following SPAN values,
// stopping when decryption is successful or the maximum number of iterations is reached.
for (let i = 0; i < DECRYPT_ATTEMPTS; i++) {
({ plaintext, authOK, decryptionKey } = decrypt());
if (!!authOK && !!plaintext) break;
}
// If authentication fails, do so with an error code that instructs the
// driver to tell the node we have no nonce
if (!authOK || !plaintext) {
return validatePayload.fail(
ZWaveErrorCodes.Security2CC_CannotDecode,
);
}
offset = 0;
if (hasEncryptedExtensions) parseExtensions(plaintext);
// Not every S2 message includes an encapsulated CC
const decryptedCCBytes = plaintext.slice(offset);
if (decryptedCCBytes.length > 0) {
// make sure this contains a complete CC command that's worth splitting
validatePayload(decryptedCCBytes.length >= 2);
// and deserialize the CC
this.encapsulated = CommandClass.from(this.driver, {
data: decryptedCCBytes,
fromEncapsulation: true,
encapCC: this,
});
}
this.decryptionKey = decryptionKey;
} else {
this._securityClass = options.securityClass;
this.encapsulated = options.encapsulated;
options.encapsulated.encapsulatingCC = this as any;
this.extensions = options.extensions ?? [];
if (
typeof this.nodeId !== "number" &&
!this.extensions.some((e) => e instanceof MGRPExtension)
) {
throw new ZWaveError(
"Multicast Security S2 encapsulation requires the MGRP extension",
ZWaveErrorCodes.Security2CC_MissingExtension,
);
}
}
}
private _securityClass?: SecurityClass;
public readonly decryptionKey?: Buffer;
private _sequenceNumber: number | undefined;
/**
* Return the sequence number of this command.
*
* **WARNING:** If the sequence number hasn't been set before, this will create a new one.
* When sending messages, this should only happen immediately before serializing.
*/
public get sequenceNumber(): number {
if (this._sequenceNumber == undefined) {
this._sequenceNumber =
this.driver.securityManager2.nextSequenceNumber(
this.nodeId as number,
);
}
return this._sequenceNumber;
}
public encapsulated?: CommandClass;
public extensions: Security2Extension[];
private _wasRetriedAfterDecodeFailure: boolean = false;
/** Indicates whether sending this command was retried after the target node failed to decode it */
public get wasRetriedAfterDecodeFailure(): boolean {
return this._wasRetriedAfterDecodeFailure;
}
public prepareRetryAfterDecodeFailure(): void {
if (this._wasRetriedAfterDecodeFailure) {
throw new ZWaveError(
`S2 encapsulated messages may only be retried once after the target failed to decode them!`,
ZWaveErrorCodes.Controller_MessageDropped,
);
}
this._wasRetriedAfterDecodeFailure = true;
this._sequenceNumber = undefined;
}
private getDestinationIDTX(): number {
const mgrpExtension = this.extensions.find(
(e): e is MGRPExtension => e instanceof MGRPExtension,
);
if (mgrpExtension) return mgrpExtension.groupId;
else if (typeof this.nodeId === "number") return this.nodeId;
throw new ZWaveError(
"Multicast Security S2 encapsulation requires the MGRP extension",
ZWaveErrorCodes.Security2CC_MissingExtension,
);
}
private getDestinationIDRX(): number {
const mgrpExtension = this.extensions.find(
(e): e is MGRPExtension => e instanceof MGRPExtension,
);
if (mgrpExtension) return mgrpExtension.groupId;
return this.driver.controller.ownNodeId;
}
/** Returns the Sender's Entropy Input if this command contains an SPAN extension */
private getSenderEI(): Buffer | undefined {
const spanExtension = this.extensions.find(
(e): e is SPANExtension => e instanceof SPANExtension,
);
return spanExtension?.senderEI;
}
public requiresPreTransmitHandshake(): boolean {
// We need the receiver's EI to be able to send an encrypted command
const secMan = this.driver.securityManager2;
const peerNodeId = this.nodeId as number;
const spanState = secMan.getSPANState(peerNodeId);
return (
spanState.type === SPANState.None ||
spanState.type === SPANState.LocalEI
);
}
public async preTransmitHandshake(): Promise<void> {
// Request a nonce
return this.getNode()!.commandClasses["Security 2"].requestNonce();
// Yeah, that's it :)
}
public serialize(): Buffer {
// TODO: Support Multicast
const node = this.getNode()!;
// Include Sender EI in the command if we only have the receiver's EI
const spanState = this.driver.securityManager2.getSPANState(node.id);
if (
spanState.type === SPANState.None ||
spanState.type === SPANState.LocalEI
) {
// Can't do anything here if we don't have the receiver's EI
throw new ZWaveError(
`Security S2 CC requires the receiver's nonce to be sent!`,
ZWaveErrorCodes.Security2CC_NoSPAN,
);
} else if (spanState.type === SPANState.RemoteEI) {
// We have the receiver's EI, generate our input and send it over
// With both, we can create an SPAN
const senderEI =
this.driver.securityManager2.generateNonce(undefined);
const receiverEI = spanState.receiverEI;
// While bootstrapping a node, the controller only sends commands encrypted
// with the temporary key
if (this.driver.securityManager2.tempKeys.has(node.id)) {
this.driver.securityManager2.initializeTempSPAN(
node,
senderEI,
receiverEI,
);
} else {
const securityClass =
this._securityClass ?? node.getHighestSecurityClass();
if (securityClass == undefined) {
throw new ZWaveError(
"No security class defined for this command!",
ZWaveErrorCodes.Security2CC_NoSPAN,
);
}
this.driver.securityManager2.initializeSPAN(
node,
securityClass,
senderEI,
receiverEI,
);
}
// Add or update the SPAN extension
let spanExtension = this.extensions.find(
(e): e is SPANExtension => e instanceof SPANExtension,
);
if (spanExtension) {
spanExtension.senderEI = senderEI;
} else {
spanExtension = new SPANExtension({ senderEI });
this.extensions.push(spanExtension);
}
}
const unencryptedExtensions = this.extensions.filter(
(e) => !e.isEncrypted(),
);
const encryptedExtensions = this.extensions.filter((e) =>
e.isEncrypted(),
);
const unencryptedPayload = Buffer.concat([
Buffer.from([
this.sequenceNumber,
(encryptedExtensions.length > 0 ? 0b10 : 0) |
(unencryptedExtensions.length > 0 ? 1 : 0),
]),
...unencryptedExtensions.map((e, index) =>
e.serialize(index < unencryptedExtensions.length - 1),
),
]);
const serializedCC = this.encapsulated?.serialize() ?? Buffer.from([]);
const plaintextPayload = Buffer.concat([
...encryptedExtensions.map((e, index) =>
e.serialize(index < encryptedExtensions.length - 1),
),
serializedCC,
]);
// Generate the authentication data for CCM encryption
const messageLength =
this.computeEncapsulationOverhead() + serializedCC.length;
const authData = getAuthenticationData(
this.driver.controller.ownNodeId,
this.getDestinationIDTX(),
this.driver.controller.homeId!,
messageLength,
unencryptedPayload,
);
const iv = this.driver.securityManager2.nextNonce(node.id);
const { keyCCM: key } =
// Prefer the overridden security class if it was given
this._securityClass != undefined
? this.driver.securityManager2.getKeysForSecurityClass(
this._securityClass,
)
: this.driver.securityManager2.getKeysForNode(node);
const { ciphertext: ciphertextPayload, authTag } = encryptAES128CCM(
key,
iv,
plaintextPayload,
authData,
SECURITY_S2_AUTH_TAG_LENGTH,
);
this.payload = Buffer.concat([
unencryptedPayload,
ciphertextPayload,
authTag,
]);
return super.serialize();
}
protected computeEncapsulationOverhead(): number {
// Security S2 adds:
// * 1 byte sequence number
// * 1 byte control
// * N bytes extensions
// * SECURITY_S2_AUTH_TAG_LENGTH bytes auth tag
const extensionBytes = this.extensions
.map((e) => e.computeLength())
.reduce((a, b) => a + b, 0);
return (
super.computeEncapsulationOverhead() +
2 +
SECURITY_S2_AUTH_TAG_LENGTH +
extensionBytes
);
}
public toLogEntry(): MessageOrCCLogEntry {
const message: MessageRecord = {
"sequence number": this.sequenceNumber,
};
if (this.extensions.length > 0) {
message.extensions = this.extensions
.map((e) => e.toLogEntry())
.join("");
}
return {
...super.toLogEntry(),
message,
};
}
}
export type Security2CCNonceReportOptions =
| {
MOS: boolean;
SOS: true;
receiverEI: Buffer;
}
| {
MOS: true;
SOS: false;
receiverEI?: undefined;
};
@CCCommand(Security2Command.NonceReport)
export class Security2CCNonceReport extends Security2CC {
// Define the securityManager and controller.ownNodeId as existing
// We check it in the constructor
declare driver: Driver & {
securityManager2: SecurityManager2;
controller: ZWaveController & {
ownNodeId: number;
};
};
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| (CCCommandOptions & Security2CCNonceReportOptions),
) {
super(driver, options);
// Make sure that we can send/receive secure commands
assertSecurity.call(this, options);
if (gotDeserializationOptions(options)) {
validatePayload(this.payload.length >= 2);
this._sequenceNumber = this.payload[0];
// Don't accept duplicate commands
validateSequenceNumber.call(this, this._sequenceNumber);
this.MOS = !!(this.payload[1] & 0b10);
this.SOS = !!(this.payload[1] & 0b1);
validatePayload(this.MOS || this.SOS);
if (this.SOS) {
// If the SOS flag is set, the REI field MUST be included in the command
validatePayload(this.payload.length >= 18);
this.receiverEI = this.payload.slice(2, 18);
// In that case we also need to store it, so the next sent command
// can use it for encryption
this.driver.securityManager2.storeRemoteEI(
this.nodeId as number,
this.receiverEI,
);
}
} else {
this.SOS = options.SOS;
this.MOS = options.MOS;
if (options.SOS) this.receiverEI = options.receiverEI;
}
}
private _sequenceNumber: number | undefined;
/**
* Return the sequence number of this command.
*
* **WARNING:** If the sequence number hasn't been set before, this will create a new one.
* When sending messages, this should only happen immediately before serializing.
*/
public get sequenceNumber(): number {
if (this._sequenceNumber == undefined) {
this._sequenceNumber =
this.driver.securityManager2.nextSequenceNumber(
this.nodeId as number,
);
}
return this._sequenceNumber;
}
public readonly SOS: boolean;
public readonly MOS: boolean;
public readonly receiverEI?: Buffer;
public serialize(): Buffer {
this.payload = Buffer.from([
this.sequenceNumber,
(this.MOS ? 0b10 : 0) + (this.SOS ? 0b1 : 0),
]);
if (this.SOS) {
this.payload = Buffer.concat([this.payload, this.receiverEI!]);
}
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
const message: MessageRecord = {
"sequence number": this.sequenceNumber,
SOS: this.SOS,
MOS: this.MOS,
};
if (this.receiverEI) {
message["receiver entropy"] = buffer2hex(this.receiverEI);
}
return {
...super.toLogEntry(),
message,
};
}
}
@CCCommand(Security2Command.NonceGet)
@expectedCCResponse(Security2CCNonceReport)
export class Security2CCNonceGet extends Security2CC {
// TODO: A node sending this command MUST accept a delay up to <Previous Round-trip-time to peer node> +
// 250 ms before receiving the Security 2 Nonce Report Command.
// Define the securityManager and controller.ownNodeId as existing
// We check it in the constructor
declare driver: Driver & {
securityManager2: SecurityManager2;
controller: ZWaveController & {
ownNodeId: number;
};
};
public constructor(driver: Driver, options: CCCommandOptions) {
super(driver, options);
// Make sure that we can send/receive secure commands
assertSecurity.call(this, options);
if (gotDeserializationOptions(options)) {
validatePayload(this.payload.length >= 1);
this._sequenceNumber = this.payload[0];
// Don't accept duplicate commands
validateSequenceNumber.call(this, this._sequenceNumber);
} else {
// No options here
}
}
private _sequenceNumber: number | undefined;
/**
* Return the sequence number of this command.
*
* **WARNING:** If the sequence number hasn't been set before, this will create a new one.
* When sending messages, this should only happen immediately before serializing.
*/
public get sequenceNumber(): number {
if (this._sequenceNumber == undefined) {
this._sequenceNumber =
this.driver.securityManager2.nextSequenceNumber(
this.nodeId as number,
);
}
return this._sequenceNumber;
}
public serialize(): Buffer {
this.payload = Buffer.from([this.sequenceNumber]);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: { "sequence number": this.sequenceNumber },
};
}
}
interface Security2CCKEXReportOptions {
requestCSA: boolean;
echo: boolean;
supportedKEXSchemes: KEXSchemes[];
supportedECDHProfiles: ECDHProfiles[];
requestedKeys: SecurityClass[];
}
@CCCommand(Security2Command.KEXReport)
export class Security2CCKEXReport extends Security2CC {
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| (CCCommandOptions & Security2CCKEXReportOptions),
) {
super(driver, options);
if (gotDeserializationOptions(options)) {
validatePayload(this.payload.length >= 4);
this.requestCSA = !!(this.payload[0] & 0b10);
this.echo = !!(this.payload[0] & 0b1);
// The bit mask starts at 0, but bit 0 is not used
this.supportedKEXSchemes = parseBitMask(
this.payload.slice(1, 2),
0,
).filter((s) => s !== 0);
this.supportedECDHProfiles = parseBitMask(
this.payload.slice(2, 3),
ECDHProfiles.Curve25519,
);
this.requestedKeys = parseBitMask(
this.payload.slice(3, 4),
SecurityClass.S2_Unauthenticated,
);
} else {
this.requestCSA = options.requestCSA;
this.echo = options.echo;
this.supportedKEXSchemes = options.supportedKEXSchemes;
this.supportedECDHProfiles = options.supportedECDHProfiles;
this.requestedKeys = options.requestedKeys;
}
}
public readonly requestCSA: boolean;
public readonly echo: boolean;
public readonly supportedKEXSchemes: readonly KEXSchemes[];
public readonly supportedECDHProfiles: readonly ECDHProfiles[];
public readonly requestedKeys: readonly SecurityClass[];
public serialize(): Buffer {
this.payload = Buffer.concat([
Buffer.from([(this.requestCSA ? 0b10 : 0) + (this.echo ? 0b1 : 0)]),
// The bit mask starts at 0, but bit 0 is not used
encodeBitMask(this.supportedKEXSchemes, 7, 0),
encodeBitMask(
this.supportedECDHProfiles,
7,
ECDHProfiles.Curve25519,
),
encodeBitMask(
this.requestedKeys,
SecurityClass.S0_Legacy,
SecurityClass.S2_Unauthenticated,
),
]);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
echo: this.echo,
"supported schemes": this.supportedKEXSchemes
.map((s) => `\n· ${getEnumMemberName(KEXSchemes, s)}`)
.join(""),
"supported ECDH profiles": this.supportedECDHProfiles
.map((s) => `\n· ${getEnumMemberName(ECDHProfiles, s)}`)
.join(""),
"CSA requested": this.requestCSA,
"requested security classes": this.requestedKeys
.map((s) => `\n· ${getEnumMemberName(SecurityClass, s)}`)
.join(""),
},
};
}
}
@CCCommand(Security2Command.KEXGet)
@expectedCCResponse(Security2CCKEXReport)
export class Security2CCKEXGet extends Security2CC {}
interface Security2CCKEXSetOptions {
permitCSA: boolean;
echo: boolean;
selectedKEXScheme: KEXSchemes;
selectedECDHProfile: ECDHProfiles;
grantedKeys: SecurityClass[];
}
@CCCommand(Security2Command.KEXSet)
export class Security2CCKEXSet extends Security2CC {
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| (CCCommandOptions & Security2CCKEXSetOptions),
) {
super(driver, options);
if (gotDeserializationOptions(options)) {
validatePayload(this.payload.length >= 4);
this.permitCSA = !!(this.payload[0] & 0b10);
this.echo = !!(this.payload[0] & 0b1);
// The bit mask starts at 0, but bit 0 is not used
const selectedKEXSchemes = parseBitMask(
this.payload.slice(1, 2),
0,
).filter((s) => s !== 0);
validatePayload(selectedKEXSchemes.length === 1);
this.selectedKEXScheme = selectedKEXSchemes[0];
const selectedECDHProfiles = parseBitMask(
this.payload.slice(2, 3),
ECDHProfiles.Curve25519,
);
validatePayload(selectedECDHProfiles.length === 1);
this.selectedECDHProfile = selectedECDHProfiles[0];
this.grantedKeys = parseBitMask(
this.payload.slice(3, 4),
SecurityClass.S2_Unauthenticated,
);
} else {
this.permitCSA = options.permitCSA;
this.echo = options.echo;
this.selectedKEXScheme = options.selectedKEXScheme;
this.selectedECDHProfile = options.selectedECDHProfile;
this.grantedKeys = options.grantedKeys;
}
}
public permitCSA: boolean;
public echo: boolean;
public selectedKEXScheme: KEXSchemes;
public selectedECDHProfile: ECDHProfiles;
public grantedKeys: SecurityClass[];
public serialize(): Buffer {
this.payload = Buffer.concat([
Buffer.from([(this.permitCSA ? 0b10 : 0) + (this.echo ? 0b1 : 0)]),
// The bit mask starts at 0, but bit 0 is not used
encodeBitMask([this.selectedKEXScheme], 7, 0),
encodeBitMask(
[this.selectedECDHProfile],
7,
ECDHProfiles.Curve25519,
),
encodeBitMask(
this.grantedKeys,
SecurityClass.S0_Legacy,
SecurityClass.S2_Unauthenticated,
),
]);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
echo: this.echo,
"selected scheme": getEnumMemberName(
KEXSchemes,
this.selectedKEXScheme,
),
"selected ECDH profile": getEnumMemberName(
ECDHProfiles,
this.selectedECDHProfile,
),
"CSA permitted": this.permitCSA,
"granted security classes": this.grantedKeys
.map((s) => `\n· ${getEnumMemberName(SecurityClass, s)}`)
.join(""),
},
};
}
}
interface Security2CCKEXFailOptions extends CCCommandOptions {
failType: KEXFailType;
}
@CCCommand(Security2Command.KEXFail)
export class Security2CCKEXFail extends Security2CC {
public constructor(
driver: Driver,
options: CommandClassDeserializationOptions | Security2CCKEXFailOptions,
) {
super(driver, options);
if (gotDeserializationOptions(options)) {
validatePayload(this.payload.length >= 1);
this.failType = this.payload[0];
} else {
this.failType = options.failType;
}
}
public failType: KEXFailType;
public serialize(): Buffer {
this.payload = Buffer.from([this.failType]);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: { reason: getEnumMemberName(KEXFailType, this.failType) },
};
}
}
interface Security2CCPublicKeyReportOptions extends CCCommandOptions {
includingNode: boolean;
publicKey: Buffer;
}
@CCCommand(Security2Command.PublicKeyReport)
export class Security2CCPublicKeyReport extends Security2CC {
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| Security2CCPublicKeyReportOptions,
) {
super(driver, options);
if (gotDeserializationOptions(options)) {
validatePayload(this.payload.length >= 17);
this.includingNode = !!(this.payload[0] & 0b1);
this.publicKey = this.payload.slice(1);
} else {
this.includingNode = options.includingNode;
this.publicKey = options.publicKey;
}
}
public includingNode: boolean;
public publicKey: Buffer;
public serialize(): Buffer {
this.payload = Buffer.concat([
Buffer.from([this.includingNode ? 1 : 0]),
this.publicKey,
]);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
"is including node": this.includingNode,
"public key": buffer2hex(this.publicKey),
},
};
}
}
interface Security2CCNetworkKeyReportOptions extends CCCommandOptions {
grantedKey: SecurityClass;
networkKey: Buffer;
}
@CCCommand(Security2Command.NetworkKeyReport)
export class Security2CCNetworkKeyReport extends Security2CC {
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| Security2CCNetworkKeyReportOptions,
) {
super(driver, options);
if (gotDeserializationOptions(options)) {
// TODO: Deserialize payload
throw new ZWaveError(
`${this.constructor.name}: deserialization not implemented`,
ZWaveErrorCodes.Deserialization_NotImplemented,
);
} else {
this.grantedKey = options.grantedKey;
this.networkKey = options.networkKey;
}
}
public grantedKey: SecurityClass;
public networkKey: Buffer;
public serialize(): Buffer {
this.payload = Buffer.concat([
securityClassToBitMask(this.grantedKey),
this.networkKey,
]);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
"security class": getEnumMemberName(
SecurityClass,
this.grantedKey,
),
"network key": buffer2hex(this.networkKey),
},
};
}
}
interface Security2CCNetworkKeyGetOptions extends CCCommandOptions {
requestedKey: SecurityClass;
}
@CCCommand(Security2Command.NetworkKeyGet)
@expectedCCResponse(Security2CCNetworkKeyReport)
export class Security2CCNetworkKeyGet extends Security2CC {
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| Security2CCNetworkKeyGetOptions,
) {
super(driver, options);
if (gotDeserializationOptions(options)) {
validatePayload(this.payload.length >= 1);
this.requestedKey = bitMaskToSecurityClass(this.payload, 0);
} else {
this.requestedKey = options.requestedKey;
}
}
public requestedKey: SecurityClass;
public serialize(): Buffer {
this.payload = securityClassToBitMask(this.requestedKey);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
"security class": getEnumMemberName(
SecurityClass,
this.requestedKey,
),
},
};
}
}
@CCCommand(Security2Command.NetworkKeyVerify)
export class Security2CCNetworkKeyVerify extends Security2CC {}
interface Security2CCTransferEndOptions extends CCCommandOptions {
keyVerified: boolean;
keyRequestComplete: boolean;
}
@CCCommand(Security2Command.TransferEnd)
export class Security2CCTransferEnd extends Security2CC {
public constructor(
driver: Driver,
options:
| CommandClassDeserializationOptions
| Security2CCTransferEndOptions,
) {
super(driver, options);
if (gotDeserializationOptions(options)) {
validatePayload(this.payload.length >= 1);
this.keyVerified = !!(this.payload[0] & 0b10);
this.keyRequestComplete = !!(this.payload[0] & 0b1);
} else {
this.keyVerified = options.keyVerified;
this.keyRequestComplete = options.keyRequestComplete;
}
}
public keyVerified: boolean;
public keyRequestComplete: boolean;
public serialize(): Buffer {
this.payload = Buffer.from([
(this.keyVerified ? 0b10 : 0) + (this.keyRequestComplete ? 0b1 : 0),
]);
return super.serialize();
}
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
"key verified": this.keyVerified,
"request complete": this.keyRequestComplete,
},
};
}
}
@CCCommand(Security2Command.CommandsSupportedReport)
export class Security2CCCommandsSupportedReport extends Security2CC {
public constructor(
driver: Driver,
options: CommandClassDeserializationOptions,
) {
super(driver, options);
const CCs = parseCCList(this.payload);
// SDS13783: A sending node MAY terminate the list of supported command classes with the
// COMMAND_CLASS_MARK command class identifier.
// A receiving node MUST stop parsing the list of supported command classes if it detects the
// COMMAND_CLASS_MARK command class identifier in the Security 2 Commands Supported Report
this.supportedCCs = CCs.supportedCCs;
}
public readonly supportedCCs: CommandClasses[];
public toLogEntry(): MessageOrCCLogEntry {
return {
...super.toLogEntry(),
message: {
supportedCCs: this.supportedCCs
.map((cc) => getCCName(cc))
.map((cc) => `\n· ${cc}`)
.join(""),
},
};
}
}
@CCCommand(Security2Command.CommandsSupportedGet)
@expectedCCResponse(Security2CCCommandsSupportedReport)
export class Security2CCCommandsSupportedGet extends Security2CC {} | the_stack |
import { asmcode } from "../asm/asmcode";
import { Register } from "../assembler";
import { NetworkHandler, NetworkIdentifier } from "../bds/networkidentifier";
import { createPacketRaw, ExtendedStreamReadResult, Packet, PacketSharedPtr, StreamReadResult } from "../bds/packet";
import { MinecraftPacketIds } from "../bds/packetids";
import { PacketIdToType } from "../bds/packets";
import { proc, procHacker } from "../bds/proc";
import { abstract, CANCEL } from "../common";
import { VoidPointer } from "../core";
import { decay } from "../decay";
import { events } from "../event";
import { bedrockServer } from "../launcher";
import { makefunc } from "../makefunc";
import { NativeClass, nativeClass, nativeField } from "../nativeclass";
import { bool_t, int32_t, int64_as_float_t, void_t } from "../nativetype";
import { nethook } from "../nethook";
import { CxxStringWrapper } from "../pointer";
import { SharedPtr } from "../sharedpointer";
import { remapAndPrintError } from "../source-map-support";
import { _tickCallback } from "../util";
@nativeClass(null)
class ReadOnlyBinaryStream extends NativeClass {
@nativeField(CxxStringWrapper.ref(), 0x38)
data:CxxStringWrapper;
read(dest:VoidPointer, size:number):boolean {
abstract();
}
}
ReadOnlyBinaryStream.prototype.read = makefunc.js([0x8], bool_t, {this: ReadOnlyBinaryStream}, VoidPointer, int64_as_float_t);
@nativeClass(null)
class OnPacketRBP extends NativeClass {
@nativeField(SharedPtr.make(Packet), 0xb8)
packet:SharedPtr<Packet>;
@nativeField(ReadOnlyBinaryStream, 0x100)
stream:ReadOnlyBinaryStream;
}
asmcode.createPacketRaw = proc["MinecraftPackets::createPacket"];
function onPacketRaw(rbp:OnPacketRBP, packetId:MinecraftPacketIds, conn:NetworkHandler.Connection):PacketSharedPtr|null {
try {
const target = events.packetRaw(packetId);
const ni = conn.networkIdentifier;
nethook.lastSender = ni;
if (target !== null && !target.isEmpty()) {
const s = rbp.stream;
const data = s.data;
const rawpacketptr = data.valueptr;
const ptrs:VoidPointer[] = [];
try {
for (const listener of target.allListeners()) {
const ptr = rawpacketptr.add();
ptrs.push(ptr);
try {
if (listener(ptr, data.length, ni, packetId) === CANCEL) {
_tickCallback();
return null;
}
} catch (err) {
events.errorFire(err);
}
}
_tickCallback();
} finally {
for (const ptr of ptrs) {
decay(ptr);
}
}
}
return createPacketRaw(rbp.packet, packetId);
} catch (err) {
remapAndPrintError(err);
return null;
}
}
function onPacketBefore(result:ExtendedStreamReadResult, rbp:OnPacketRBP, packetId:MinecraftPacketIds):ExtendedStreamReadResult {
try {
if (result.streamReadResult !== StreamReadResult.Pass) return result;
const target = events.packetBefore(packetId);
if (target !== null && !target.isEmpty()) {
const packet = rbp.packet.p!;
const ni = nethook.lastSender;
const TypedPacket = PacketIdToType[packetId] || Packet;
const typedPacket = packet.as(TypedPacket);
try {
for (const listener of target.allListeners()) {
try {
if (listener(typedPacket, ni, packetId) === CANCEL) {
result.streamReadResult = StreamReadResult.Ignore;
return result;
}
} catch (err) {
events.errorFire(err);
}
}
} finally {
_tickCallback();
decay(typedPacket);
}
}
} catch (err) {
remapAndPrintError(err);
}
return result;
}
function onPacketAfter(rbp:OnPacketRBP):void {
try {
const packet = rbp.packet.p!;
const packetId = packet.getId();
const target = events.packetAfter(packetId);
if (target !== null && !target.isEmpty()) {
const ni = nethook.lastSender;
const TypedPacket = PacketIdToType[packetId] || Packet;
const typedPacket = packet.as(TypedPacket);
try {
for (const listener of target.allListeners()) {
try {
if (listener(typedPacket, ni, packetId) === CANCEL) {
break;
}
} catch (err) {
events.errorFire(err);
}
}
} finally {
_tickCallback();
decay(typedPacket);
}
}
} catch (err) {
remapAndPrintError(err);
}
}
function onPacketSend(handler:NetworkHandler, ni:NetworkIdentifier, packet:Packet):number{
try {
const packetId = packet.getId();
const target = events.packetSend(packetId);
if (target !== null && !target.isEmpty()) {
const TypedPacket = PacketIdToType[packetId] || Packet;
const typedPacket = packet.as(TypedPacket);
try {
for (const listener of target.allListeners()) {
try {
if (listener(typedPacket, ni, packetId) === CANCEL) {
return 1;
}
} catch (err) {
events.errorFire(err);
}
}
} finally {
_tickCallback();
decay(typedPacket);
}
}
} catch (err) {
remapAndPrintError(err);
}
return 0;
}
function onPacketSendInternal(handler:NetworkHandler, ni:NetworkIdentifier, packet:Packet, data:CxxStringWrapper):number {
try {
const packetId = packet.getId();
const target = events.packetSendRaw(packetId);
if (target !== null && !target.isEmpty()) {
const dataptr = data.valueptr;
try {
for (const listener of target.allListeners()) {
try {
if (listener(dataptr, data.length, ni, packetId) === CANCEL) {
return 1;
}
} catch (err) {
events.errorFire(err);
}
}
} finally {
_tickCallback();
decay(dataptr);
}
}
} catch (err) {
remapAndPrintError(err);
}
return 0;
}
bedrockServer.withLoading().then(()=>{
// hook raw
asmcode.onPacketRaw = makefunc.np(onPacketRaw, PacketSharedPtr, null, OnPacketRBP, int32_t, NetworkHandler.Connection);
procHacker.patching('hook-packet-raw', 'NetworkHandler::_sortAndPacketizeEvents', 0x1f1,
asmcode.packetRawHook, Register.rax, true, [
0x8B, 0xD6, // mov edx,esi
0x48, 0x8D, 0x8D, 0xB8, 0x00, 0x00, 0x00, // lea rcx,qword ptr ss:[rbp+78]
0xE8, 0xFF, 0xFF, 0xFF, 0xFF, // call <bedrock_server.public: static class std::shared_ptr<class Packet> __cdecl MinecraftPackets::createPacket(enum MinecraftPacketIds)>
0x90 // nop
], [10, 14]);
// hook before
asmcode.onPacketBefore = makefunc.np(onPacketBefore, ExtendedStreamReadResult, {name: 'onPacketBefore'}, ExtendedStreamReadResult, OnPacketRBP, int32_t);
procHacker.patching('hook-packet-before', 'NetworkHandler::_sortAndPacketizeEvents', 0x2f4,
asmcode.packetBeforeHook, // original code depended
Register.rax,
true, [
0x48, 0x8B, 0x01, // mov rax,qword ptr ds:[rcx]
0x4C, 0x8D, 0x85, 0x00, 0x01, 0x00, 0x00, // lea r8,qword ptr ss:[rbp+100]
0x48, 0x8D, 0x55, 0xE0, //lea rdx,qword ptr ss:[rbp-20]
0xFF, 0x50, 0x20, // call qword ptr ds:[rax+20]
], []);
// skip packet when result code is 0x7f
const packetViolationOriginalCode = [
0x48, 0x89, 0x5C, 0x24, 0x10, // mov qword ptr ss:[rsp+10],rbx
0x55, // push rbp
0x56, // push rsi
0x57, // push rdi
0x41, 0x54, // push r12
0x41, 0x55, // push r13
0x41, 0x56, // push r14
];
asmcode.PacketViolationHandlerHandleViolationAfter = proc['PacketViolationHandler::_handleViolation'].add(packetViolationOriginalCode.length);
procHacker.patching('hook-packet-before-skip', 'PacketViolationHandler::_handleViolation', 0,
asmcode.packetBeforeCancelHandling,
Register.rax, false, packetViolationOriginalCode, []);
// hook after
asmcode.onPacketAfter = makefunc.np(onPacketAfter, void_t, null, OnPacketRBP);
procHacker.patching('hook-packet-after', 'NetworkHandler::_sortAndPacketizeEvents', 0x475,
asmcode.packetAfterHook, // original code depended
Register.rax, true, [
0x48, 0x8B, 0x01, // mov rax,qword ptr ds:[rcx]
0x4C, 0x8D, 0x8D, 0xB8, 0x00, 0x00, 0x00, // lea r9,qword ptr ss:[rbp+b8]
0x4C, 0x8B, 0xC6, // mov r8,rsi
0x49, 0x8B, 0xD6, // mov rdx,r14
0xFF, 0x50, 0x08, // call qword ptr ds:[rax+8]
], []);
asmcode.onPacketSend = makefunc.np(onPacketSend, int32_t, null, NetworkHandler, NetworkIdentifier, Packet);
asmcode.sendOriginal = procHacker.hookingRaw('NetworkHandler::send', asmcode.packetSendHook);
asmcode.packetSendAllCancelPoint = proc['LoopbackPacketSender::sendToClients'].add(0xb5);
procHacker.patching('hook-packet-send-all', 'LoopbackPacketSender::sendToClients', 0x90,
asmcode.packetSendAllHook, // original code depended
Register.rax, true, [
0x49, 0x8B, 0x07, // mov rax,qword ptr ds:[r15]
0x49, 0x8D, 0x96, 0x48, 0x02, 0x00, 0x00, // lea rdx,qword ptr ds:[r14+248]
0x49, 0x8B, 0xCF, // mov rcx,r15
0xFF, 0x50, 0x18, // call qword ptr ds:[rax+18]
], []);
asmcode.onPacketSendInternal = makefunc.np(onPacketSendInternal, int32_t, null, NetworkHandler, NetworkIdentifier, Packet, CxxStringWrapper);
asmcode.sendInternalOriginal = procHacker.hookingRaw('NetworkHandler::_sendInternal', asmcode.packetSendInternalHook);
}); | the_stack |
import * as React from "react"
import { isEmpty, difference, clone, uniq } from "../clientUtils/Util"
import {
observable,
computed,
action,
reaction,
runInAction,
IReactionDisposer,
} from "mobx"
import { observer } from "mobx-react"
import { Redirect } from "react-router-dom"
import parse from "csv-parse"
import { BindString, NumericSelectField, FieldsRow } from "./Forms"
import { AdminLayout } from "./AdminLayout"
import { AdminAppContext, AdminAppContextType } from "./AdminAppContext"
import { faSpinner } from "@fortawesome/free-solid-svg-icons/faSpinner"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
declare const window: any
class EditableVariable {
@observable name: string = ""
@observable unit: string = ""
@observable description: string = ""
@observable coverage: string = ""
@observable timespan: string = ""
// Existing variable to be overwritten by this one
@observable overwriteId?: number
@observable values: string[] = []
}
interface ExistingVariable {
id: number
name: string
}
interface ExistingDataset {
id: number
namespace: string
name: string
description: string
variables: ExistingVariable[]
}
class EditableDataset {
@observable id?: number
@observable name: string = ""
@observable description: string = ""
@observable existingVariables: ExistingVariable[] = []
@observable newVariables: EditableVariable[] = []
@observable years: number[] = []
@observable entities: string[] = []
@observable source: {
name: string
dataPublishedBy: string
dataPublisherSource: string
link: string
retrievedDate: string
additionalInfo: string
} = {
name: "",
dataPublishedBy: "",
dataPublisherSource: "",
link: "",
retrievedDate: "",
additionalInfo: "",
}
update(json: any) {
for (const key in this) {
if (key in json) this[key] = json[key]
}
}
@computed get isLoading() {
return this.id && !this.existingVariables.length
}
}
@observer
class DataPreview extends React.Component<{ csv: CSV }> {
@observable rowOffset: number = 0
@observable visibleRows: number = 10
@computed get numRows(): number {
return this.props.csv.rows.length
}
@action.bound onScroll(ev: React.UIEvent<Element>) {
const { scrollTop, scrollHeight } = ev.currentTarget
const { numRows } = this
const rowOffset = Math.round((scrollTop / scrollHeight) * numRows)
ev.currentTarget.scrollTop = Math.round(
(rowOffset / numRows) * scrollHeight
)
this.rowOffset = rowOffset
}
render() {
const { rows } = this.props.csv
const { rowOffset, visibleRows, numRows } = this
const height = 50
return (
<div
style={{ height: height * visibleRows, overflowY: "scroll" }}
onScroll={this.onScroll}
>
<div
style={{
height: height * numRows,
paddingTop: height * rowOffset,
}}
>
<table className="table" style={{ background: "white" }}>
<tbody>
{rows
.slice(rowOffset, rowOffset + visibleRows)
.map((row, i) => (
<tr key={i}>
<td>{rowOffset + i + 1}</td>
{row.map((cell, j) => (
<td
key={j}
style={{ height: height }}
>
{cell}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
}
@observer
class EditVariable extends React.Component<{
variable: EditableVariable
dataset: EditableDataset
}> {
render() {
const { variable, dataset } = this.props
return (
<li className="EditVariable">
<FieldsRow>
<BindString store={variable} field="name" label="" />
<select
onChange={(e) => {
variable.overwriteId = e.target.value
? parseInt(e.target.value)
: undefined
}}
value={variable.overwriteId || ""}
>
<option value="">Create new variable</option>
{dataset.existingVariables.map((v) => (
<option key={v.id} value={v.id}>
Overwrite {v.name}
</option>
))}
</select>
</FieldsRow>
</li>
)
}
}
@observer
class EditVariables extends React.Component<{ dataset: EditableDataset }> {
@computed get deletingVariables() {
const { dataset } = this.props
const deletingVariables: ExistingVariable[] = []
for (const variable of dataset.existingVariables) {
if (
!dataset.newVariables.some((v) => v.overwriteId === variable.id)
) {
deletingVariables.push(variable)
}
}
return deletingVariables
}
render() {
const { dataset } = this.props
return (
<section className="form-section variables-section">
<h3>Variables</h3>
<p className="form-section-desc">
These are the variables that will be stored for your
dataset.
</p>
<ol>
{dataset.newVariables.map((variable, i) => (
<EditVariable
key={i}
variable={variable}
dataset={dataset}
/>
))}
</ol>
{this.deletingVariables.length > 0 && (
<div className="alert alert-danger">
Some existing variables are not selected to overwrite
and will be deleted:{" "}
{this.deletingVariables.map((v) => v.name).join(",")}
</div>
)}
</section>
)
}
}
interface ValidationResults {
results: { class: string; message: string }[]
passed: boolean
}
class CSV {
static transformSingleLayout(rows: string[][], filename: string) {
const basename = (filename.match(/(.*?)(.csv)?$/) || [])[1]
const newRows = [["Entity", "Year", basename]]
for (let i = 1; i < rows.length; i++) {
const entity = rows[i][0]
for (let j = 1; j < rows[0].length; j++) {
const year = rows[0][j]
const value = rows[i][j]
newRows.push([entity, year, value])
}
}
return newRows
}
filename: string
rows: string[][]
existingEntities: string[]
@computed get basename() {
return (this.filename.match(/(.*?)(.csv)?$/) || [])[1]
}
@computed get data() {
const { rows } = this
const variables: EditableVariable[] = []
const entities = []
const years = []
const headingRow = rows[0]
for (const name of headingRow.slice(2)) {
const variable = new EditableVariable()
variable.name = name
variables.push(variable)
}
for (let i = 1; i < rows.length; i++) {
const row = rows[i]
const entity = row[0],
year = row[1]
entities.push(entity)
years.push(+year)
row.slice(2).forEach((value, j) => {
variables[j].values.push(value)
})
}
return {
variables: variables,
entities: entities,
years: years,
}
}
@computed get validation(): ValidationResults {
const validation: ValidationResults = { results: [], passed: false }
const { rows } = this
// Check we actually have enough data
if (rows[0].length < 3) {
validation.results.push({
class: "danger",
message: `No variables detected. CSV should have at least 3 columns.`,
})
}
// Make sure entities and years are valid
const invalidLines = []
for (let i = 1; i < rows.length; i++) {
const year = rows[i][1]
if ((+year).toString() !== year || isEmpty(rows[i][0])) {
invalidLines.push(i + 1)
}
}
if (invalidLines.length) {
validation.results.push({
class: "danger",
message: `Invalid or missing entity/year on lines: ${invalidLines.join(
", "
)}`,
})
}
// Check for duplicates
const uniqCheck: Record<string, number> = {}
for (let i = 1; i < rows.length; i++) {
const row = rows[i]
const entity = row[0],
year = row[1]
const key = entity + "-" + year
uniqCheck[key] = uniqCheck[key] || 0
uniqCheck[key] += 1
}
Object.keys(uniqCheck).forEach((key) => {
const count = uniqCheck[key]
if (count > 1) {
validation.results.push({
class: "danger",
message: `Duplicates detected: ${count} instances of ${key}.`,
})
}
})
// Warn about non-numeric data
const nonNumeric = []
for (let i = 1; i < rows.length; i++) {
const row = rows[i]
for (let j = 2; j < row.length; j++) {
if (
row[j] !== "" &&
(isNaN(parseFloat(row[j])) || !row[j].match(/^[0-9.-]+$/))
)
nonNumeric.push(`${i + 1} '${row[j]}'`)
}
}
if (nonNumeric.length)
validation.results.push({
class: "warning",
message:
"Non-numeric data detected on line " +
nonNumeric.join(", "),
})
// Warn if we're creating novel entities
const newEntities = difference(
uniq(this.data.entities),
this.existingEntities
)
if (newEntities.length >= 1) {
validation.results.push({
class: "warning",
message: `These entities were not found in the database and will be created: ${newEntities.join(
", "
)}`,
})
}
validation.passed = validation.results.every(
(result) => result.class !== "danger"
)
return validation
}
@computed get isValid() {
return this.validation.passed
}
constructor({ filename = "", rows = [], existingEntities = [] }) {
this.filename = filename
this.rows = rows
this.existingEntities = existingEntities
}
}
@observer
class ValidationView extends React.Component<{
validation: ValidationResults
}> {
render() {
const { validation } = this.props
return (
<section className="ValidationView">
{validation.results.map((v, index: number) => (
<div key={index} className={`alert alert-${v.class}`}>
{v.message}
</div>
))}
</section>
)
}
}
@observer
class CSVSelector extends React.Component<{
existingEntities: string[]
onCSV: (csv: CSV) => void
}> {
@observable csv?: CSV
fileInput?: HTMLInputElement
@action.bound onChooseCSV({ target }: { target: HTMLInputElement }) {
const { existingEntities } = this.props
const file = target.files && target.files[0]
if (!file) return
const reader = new FileReader()
reader.onload = (e) => {
const csv = e?.target?.result
if (csv && typeof csv === "string")
parse(
csv,
{
relax_column_count: true,
skip_empty_lines: true,
rtrim: true,
},
(_, rows) => {
// TODO error handling
//console.log("Error?", err)
if (rows[0][0].toLowerCase() === "year")
rows = CSV.transformSingleLayout(rows, file.name)
this.csv = new CSV({
filename: file.name,
rows,
existingEntities,
} as any)
this.props.onCSV(this.csv as any)
}
)
else console.error("CSV was falsy")
}
reader.readAsText(file)
}
render() {
const { csv } = this
return (
<section>
<input
type="file"
onChange={this.onChooseCSV}
ref={(e) => (this.fileInput = e as HTMLInputElement)}
/>
{csv && <DataPreview csv={csv} />}
{csv && <ValidationView validation={csv.validation} />}
</section>
)
}
componentDidMount() {
if (this.fileInput) this.fileInput.value = ""
}
}
@observer
class Importer extends React.Component<ImportPageData> {
static contextType = AdminAppContext
context!: AdminAppContextType
@observable csv?: CSV
@observable.ref dataset = new EditableDataset()
@observable existingDataset?: ExistingDataset
@observable postImportDatasetId?: number
// First step is user selecting a CSV file
@action.bound onCSV(csv: CSV) {
this.csv = csv
// Look for an existing dataset that matches this csv filename
const existingDataset = this.props.datasets.find(
(d) => d.name === csv.basename
)
if (existingDataset) {
this.getExistingDataset(existingDataset.id)
}
}
@action.bound onChooseDataset(datasetId: number) {
if (datasetId === -1) this.existingDataset = undefined
else this.getExistingDataset(datasetId)
}
// Grab existing dataset info to compare against what we are importing
async getExistingDataset(datasetId: number) {
const json = await this.context.admin.getJSON(
`/api/importData/datasets/${datasetId}.json`
)
runInAction(() => (this.existingDataset = json.dataset))
}
// When we have the csv and have matched against an existing dataset (or decided not to), we can
// then initialize the dataset model for user customization
@action.bound initializeDataset() {
const { csv, existingDataset } = this
if (!csv) return
const dataset = new EditableDataset()
if (existingDataset) {
dataset.name = existingDataset.name
dataset.description = existingDataset.description
dataset.existingVariables = existingDataset.variables
}
if (!dataset.name) dataset.name = csv.basename
dataset.newVariables = csv.data.variables.map(clone)
dataset.entities = csv.data.entities
dataset.years = csv.data.years
if (existingDataset) {
// Match new variables to existing variables
dataset.newVariables.forEach((variable) => {
const match = dataset.existingVariables.filter(
(v) => v.name === variable.name
)[0]
if (match) {
Object.keys(match).forEach((key) => {
if (key === "id") variable.overwriteId = match[key]
else (variable as any)[key] = (match as any)[key]
})
}
})
}
this.dataset = dataset
}
@action.bound onSubmit(e: React.FormEvent<HTMLFormElement>) {
e.preventDefault()
this.saveDataset()
}
// Commit the import!
saveDataset() {
const { newVariables, entities, years } = this.dataset
const requestData = {
dataset: {
id: this.existingDataset ? this.existingDataset.id : undefined,
name: this.dataset.name,
description: this.dataset.description,
},
years,
entities,
variables: newVariables,
}
this.context.admin
.requestJSON("/api/importDataset", requestData, "POST")
.then((json: any) => {
runInAction(() => {
this.postImportDatasetId = json.datasetId
})
})
}
disposers: IReactionDisposer[] = []
componentDidMount() {
this.disposers.push(
reaction(
() => [this.csv, this.existingDataset],
() => this.initializeDataset()
)
)
}
componentWillUnmount() {
for (const dispose of this.disposers) dispose()
}
render() {
const { csv, dataset, existingDataset } = this
const { datasets, existingEntities } = this.props
return (
<form className="Importer" onSubmit={this.onSubmit}>
<h2>Import CSV file</h2>
<p>
Examples of valid layouts:{" "}
<a href="http://ourworldindata.org/uploads/2016/02/ourworldindata_single-var.png">
single variable
</a>
,{" "}
<a href="http://ourworldindata.org/uploads/2016/02/ourworldindata_multi-var.png">
multiple variables
</a>
.{" "}
<span className="form-section-desc">
CSV files only:{" "}
<a href="https://ourworldindata.org/how-to-our-world-in-data-guide/#1-2-single-variable-datasets">
csv file format guide
</a>
. Maximum file size: 10MB{" "}
</span>
</p>
<CSVSelector
onCSV={this.onCSV}
existingEntities={existingEntities}
/>
{csv && csv.isValid && (
<section>
<p
style={{
opacity: dataset.id !== undefined ? 1 : 0,
}}
className="updateWarning"
>
Overwriting existing dataset
</p>
<NumericSelectField
value={existingDataset ? existingDataset.id : -1}
onValue={this.onChooseDataset}
options={[-1].concat(datasets.map((d) => d.id))}
optionLabels={["Create new dataset"].concat(
datasets.map((d) => d.name)
)}
/>
<hr />
<h3>
{existingDataset
? `Updating existing dataset`
: `Creating new dataset`}
</h3>
{!existingDataset && (
<p>
Your data will be validated and stored in the
database for visualization. After creating the
dataset, please fill out the metadata fields and
then mark the dataset as "publishable" if it
should be reused by others.
</p>
)}
<BindString
field="name"
store={dataset}
helpText={`Dataset name should include a basic description of the variables, followed by the source and year. For example: "Government Revenue Data – ICTD (2016)"`}
/>
{dataset.isLoading && (
<FontAwesomeIcon icon={faSpinner} spin />
)}
{!dataset.isLoading && [
<EditVariables
key="editVariables"
dataset={dataset}
/>,
<input
key="submit"
type="submit"
className="btn btn-success"
value={
existingDataset
? "Update dataset"
: "Create dataset"
}
/>,
]}
{this.postImportDatasetId && (
<Redirect
to={`/datasets/${this.postImportDatasetId}`}
/>
)}
</section>
)}
</form>
)
}
}
interface ImportPageData {
datasets: {
id: number
name: string
}[]
tags: {
id: number
name: string
parent: string
}[]
existingEntities: string[]
}
@observer
export class ImportPage extends React.Component {
static contextType = AdminAppContext
context!: AdminAppContextType
@observable importData?: ImportPageData
async getData() {
const json = await this.context.admin.getJSON("/api/importData.json")
runInAction(() => (this.importData = json as ImportPageData))
}
componentDidMount() {
this.getData()
}
render() {
return (
<AdminLayout>
<main className="ImportPage">
{this.importData && <Importer {...this.importData} />}
</main>
</AdminLayout>
)
}
} | the_stack |
import chalk from 'chalk';
import readline = require('readline');
import stream = require('stream');
import ora = require('ora');
import { isWindows } from './common';
let logging = true;
let logBuffer = '';
let errBuffer = '';
let logged = false;
class MutableStdout extends stream.Writable {
public muted:boolean = false;
_write (chunk, encoding, callback) {
if (!this.muted)
process.stdout.write(chunk, encoding);
callback();
}
}
const mutableStdout = new MutableStdout();
export enum LogType {
none,
err,
warn,
ok,
info,
debug,
status,
};
export let logLevel = LogType.info;
// if muting any logs, dump them on exit
let inputRedact;
process.on('exit', () => {
if (spinning && hiddenCnt === 0)
spinner.clear();
if (inputRedact) {
console.log('');
inputRedact();
}
if (logBuffer)
process.stdout.write(logBuffer);
if (errBuffer)
process.stderr.write(errBuffer);
});
// use the default option in all prompts
// throws an error for prompts that don't take a default
export let useDefaults = false;
export function setUseDefaults (_useDefaults: boolean) {
useDefaults = _useDefaults;
}
export function setLogLevel (level: LogType) {
logLevel = level;
};
const format = {
q (msg: string, opt?: string) {
return moduleMsg(msg + (opt ? ' [' + opt + ']' : '') + ': ');
},
[LogType.err] (msg: string) {
return chalk.red.bold('err ') + '(jspm) ' + moduleMsg(msg, false, false);
},
[LogType.info] (msg: string) {
return ' ' + moduleMsg(msg, true);
},
[LogType.warn] (msg: string) {
return chalk.yellow.bold('warn ') + '(jspm) ' + moduleMsg(msg, true);
},
[LogType.ok] (msg: string) {
return chalk.green.bold('ok ') + moduleMsg(msg, true);
},
[LogType.debug] (msg: string) {
return moduleMsg(msg, true);
}
};
const spinner = ora({
text: '',
color: 'yellow',
spinner: {
interval: 200,
frames: [
". ",
".. ",
"... ",
" ...",
" ..",
" .",
" "
]
}
});
let spinning = false;
export function startSpinner () {
spinning = true;
if (hiddenCnt === 0)
spinner.start();
}
export function stopSpinner () {
if (spinning && hiddenCnt === 0) {
spinner.clear();
spinner.stop();
frameIndex = 0;
}
spinning = false;
}
let hiddenCnt = 0;
let frameIndex = 0;
function hideSpinner () {
if (hiddenCnt++ === 0 && spinning && spinner.id) {
frameIndex = spinner.frameIndex;
spinner.clear();
spinner.stop();
}
}
function showSpinner () {
if ((hiddenCnt === 0 || --hiddenCnt === 0) && spinning && !spinner.id) {
spinner.frameIndex = frameIndex;
spinner.start();
}
}
export function logErr (msg: string) {
logged = true;
hideSpinner();
if (logging)
console.error(msg);
else
logBuffer += msg + '\n';
showSpinner();
}
export function ok (msg: string) {
log(msg, LogType.ok);
}
export function err (msg: string) {
log(msg, LogType.err);
}
export function warn (msg: string) {
log(msg, LogType.warn);
}
export function debug (msg: string) {
log(msg, LogType.debug);
}
export function info (msg: string) {
log(msg, LogType.info);
}
export function log (msg: string, type = LogType.info) {
if (<LogType>type === LogType.status) {
spinner.text = msg.substr(0, process.stdout.columns);
return;
}
logged = true;
if (type === undefined) {
hideSpinner();
if (logging)
console.log(msg);
else
logBuffer += msg + '\n';
showSpinner();
return;
}
msg = format[type](msg);
if (type <= logLevel) {
hideSpinner();
if (logging) {
if (<LogType>type !== LogType.err)
console.log(msg);
else
console.error(msg);
}
else {
if (<LogType>type !== LogType.err)
logBuffer += msg + '\n';
else
errBuffer += msg + '\n';
}
showSpinner();
}
};
const ansiControlCodeRegEx = /(\x9B|\x1B\[)[0-?]*[ -\/]*[@-~]/g;
function wordWrap (text: string, columns: number, leftIndent = 0, rightIndent = 0, skipFirstLineIndent = false) {
let leftSpaces = '';
let i;
for (i = 0; i < leftIndent; i++)
leftSpaces += ' ';
// simple word wrapping
columns = columns - leftIndent - rightIndent;
let output = [];
let lastBreak = 0;
let lastSpace = 0;
let skipLength = 0; // skip control characters
// carefully ensure underlines skip tab space added
let underline = false;
let underlineNext = false;
for (i = 0; i < text.length; i++) {
if (text[i] === '\x1b') {
ansiControlCodeRegEx.lastIndex = i - 1;
let controlCodeMatch = ansiControlCodeRegEx.exec(text);
if (!controlCodeMatch) {
skipLength = 1;
}
else {
skipLength = controlCodeMatch[0].length;
if (controlCodeMatch[0] === '\u001b[4m')
underline = true;
else if (controlCodeMatch[0] === '\u001b[24m')
underline = false;
}
continue;
}
if (text[i] === ' ')
lastSpace = i;
// existing newline adds buffer
if (text[i] === '\n') {
lastSpace = i;
output.push(
(output.length === 0 && skipFirstLineIndent ? '' : leftSpaces) +
(underlineNext ? '\x1b[4m' : '') +
text.substring(lastBreak, i) +
(underline ? ((underlineNext = true), '\x1b[24m') : ((underlineNext = false), '')) +
'\n');
lastSpace = i;
lastBreak = i + 1;
skipLength = 0;
}
// on expected breaking point
else if ((i - skipLength) !== lastBreak &&
(i - lastBreak - skipLength) % columns === 0 &&
lastSpace > lastBreak) {
output.push(
(output.length === 0 && skipFirstLineIndent ? '' : leftSpaces) +
(underlineNext ? '\x1b[4m' : '') +
text.substring(lastBreak, lastSpace) +
(underline ? ((underlineNext = true), '\x1b[24m') : ((underlineNext = false), '')) +
'\n');
lastBreak = lastSpace + 1;
skipLength = 0;
}
}
output.push(
(output.length === 0 && skipFirstLineIndent ? '' : leftSpaces) +
(underlineNext ? '\x1b[4m' : '') +
text.substr(lastBreak));
return output.join('');
}
function moduleMsg (msg: string, tab?, wrap?) {
if (tab)
msg = wordWrap(msg, process.stdout.columns + (isWindows ? -1 : 0), tab ? 5 : 0).substr(5);
else if (wrap)
msg = wordWrap(msg, process.stdout.columns + (isWindows ? -1 : 0));
else
msg.replace(/(\r?\n)/g, '$1 ');
// formatting
// msg.replace(/\t/g, ' ');
return msg;
}
export interface ConfirmOptions {
edit?: boolean,
info?: string,
silent?: boolean
};
let inputQueue = [];
export async function confirm (msg: string, def?: string | ConfirmOptions | boolean, options: ConfirmOptions = {}): Promise<boolean> {
if (typeof def === 'object' && def !== null) {
options = def;
def = undefined;
}
let defText;
if (def === true)
defText = 'Yes';
else if (def === false)
defText = 'No';
else
def = undefined;
if (useDefaults) {
if (def === undefined)
defText = 'Yes';
hideSpinner();
process.stdout.write(format.q(msg) + defText + '\n');
showSpinner();
return Promise.resolve(!!def);
}
let reply = await input(msg + (defText ? '' : ' [Yes/No]'), defText, {
edit: options.edit,
info: options.info,
silent: options.silent,
options: ['Yes', 'No']
});
if (reply == 'Yes')
return true;
if (reply == 'No')
return false;
return confirm(msg, def, options);
};
let inputFunc = _key => {};
process.stdin.on('keypress', (_chunk, key) => {
inputFunc(key);
});
export interface InputOptions extends ConfirmOptions {
options?: string[],
clearOnType?: boolean,
hideInfo?: boolean,
completer?: (partialLine: string) => [string[], string],
validate?: (input: string) => string | void,
validationError?: string,
optionalOptions?: boolean
}
export function input (msg: string, def: string | InputOptions, options: InputOptions = {}, queue: boolean = false): Promise<string> {
if (typeof def === 'object' && def !== null) {
options = def;
def = undefined;
}
const defValue: string = <string>def;
if (typeof options === 'boolean')
options = {
silent: true,
edit: false,
clearOnType: false,
info: undefined,
hideInfo: true,
completer: undefined,
validate: undefined,
validationError: undefined,
optionalOptions: false
};
options.completer = partialLine => {
if (!partialLine.length || !options.options)
return [[], partialLine];
partialLine = partialLine.toLowerCase().trim();
let hits = options.options.filter(c => c.toLowerCase().indexOf(partialLine) === 0);
// we only return one option, to avoid printing out completions
return [hits.length ? [hits[0]] : [], partialLine];
};
options = options || {};
if (useDefaults) {
process.stdout.write(format.q(msg) + (options.silent ? '' : defValue) + '\n');
return Promise.resolve(defValue);
}
hideSpinner();
return new Promise<string>((resolve, reject) => {
if (!logging && !queue)
return inputQueue.push({
args: [msg, defValue, options, true],
resolve: resolve,
reject: reject
});
// if there is info text for this question, first write out the hint text below
// then restore the cursor and write out the question
let infoLines = 1;
if (options.info || options.validationError) {
let infoText = '\n';
if (options.info)
infoText += wordWrap(options.info, process.stdout.columns, 5, 5) + '\n';
if (options.validationError)
infoText += format[LogType.warn](wordWrap(options.validationError, process.stdout.columns, 0, 5)) + '\n';
infoText += '\n';
process.stdout.write(infoText);
infoLines = infoText.split('\n').length;
}
if (!('hideInfo' in options))
options.hideInfo = true;
if (logging && logged)
process.stdout.write('\n');
logging = false;
let rl = readline.createInterface({
input: process.stdin,
output: mutableStdout,
terminal: true,
completer: options.completer
});
let questionMessage = format.q(msg, defValue && !options.edit ? defValue : '');
infoLines += questionMessage.split('\n').length - 1;
if (options.options)
var ctrlOpt = new CtrlOption(options.options, rl);
if (!options.edit)
inputFunc = key => {
if (!key)
return;
let i;
if (options.clearOnType && key.name !== 'return' && key.name !== 'backspace' && key.name !== 'left') {
// this actually works, which was rather unexpected
for (i = 0; i < (defValue || '').length; i++)
process.stdin.emit('keypress', '\b', { name: 'backspace' });
}
// allow scrolling through default options
if (ctrlOpt) {
if (key.name === 'up')
ctrlOpt.moveUp();
if (key.name === 'down')
ctrlOpt.moveDown();
}
// for no default options, allow backtracking to default
else if (key.name === 'up' || key.name === 'down') {
rl.write(null, { ctrl: true, name: 'u' });
for (i = 0; i < defValue.length; i++)
process.stdin.emit('keypress', defValue[i], { name: defValue[i] });
}
};
rl.question(questionMessage, inputVal => {
inputFunc = () => {};
if (mutableStdout.muted)
console.log('');
rl.close();
// run completions by default on enter when provided
if (options.options && !options.optionalOptions)
inputVal = options.completer(inputVal)[0][0] || '';
inputVal = inputVal.trim();
if (!options.edit)
inputVal = inputVal || defValue;
let retryErr;
if (options.validate)
retryErr = options.validate(inputVal);
inputRedact(inputVal, !!retryErr, options.silent);
inputRedact = null;
mutableStdout.muted = false;
if (retryErr)
return input(msg, defValue, {
info: options.info,
silent: options.silent,
edit: options.edit,
clearOnType: options.clearOnType,
completer: options.completer,
validate: options.validate,
validationError: retryErr.toString(),
optionalOptions: options.optionalOptions,
hideInfo: options.hideInfo
}, true).then(resolve, reject);
// bump the input queue
let next = inputQueue.shift();
if (next)
input.apply(null, next.args).then(next.resolve, next.reject);
else {
process.stdout.write(logBuffer);
process.stderr.write(errBuffer);
logBuffer = '';
errBuffer = '';
logging = true;
logged = false;
}
showSpinner();
resolve(inputVal);
});
inputRedact = (inputVal, retry, silent) => {
inputVal = inputVal || '';
let inputText = !retry ? format.q(msg, !options.edit && defValue || '') + (silent ? '' : inputVal) + '\n' : '';
// erase the help text, rewrite the question above, and begin the next question
process.stdout.write('\x1b[' + (options.hideInfo || retry ? infoLines : 0) + 'A\x1b[J' + inputText);
};
mutableStdout.muted = false;
if (options.silent)
mutableStdout.muted = true;
if (defValue && options.edit)
rl.write(defValue);
});
};
class CtrlOption {
rl: any;
options: string[];
constructor (options: string[], rl) {
this.options = options || [];
this.rl = rl;
}
cursol = 0;
moveUp () {
let next = this.cursol + 1;
this.cursol = (next >= this.options.length ) ? 0 : next;
this.move();
}
moveDown () {
let next = this.cursol - 1;
this.cursol = (next === -1 ) ? (this.options.length - 1) : next;
this.move();
}
move () {
this.rl.write(null, { ctrl: true, name: 'u' });
let input = this.options[this.cursol].split('');
for (let idx in input)
process.stdin.emit('keypress', input[idx], { name: input[idx] });
}
} | the_stack |
import React from 'react';
import moment from 'moment';
import {findDOMNode} from 'react-dom';
import cx from 'classnames';
import {Icon} from './icons';
import Overlay from './Overlay';
import Calendar from './calendar/Calendar';
import PopOver from './PopOver';
import {themeable, ThemeProps} from '../theme';
import {PlainObject} from '../types';
import {noop} from '../utils/helper';
import {LocaleProps, localeable} from '../locale';
import {DateRangePicker} from './DateRangePicker';
import capitalize from 'lodash/capitalize';
import {ShortCuts, ShortCutDateRange} from './DatePicker';
import {availableRanges} from './DateRangePicker';
export interface MonthRangePickerProps extends ThemeProps, LocaleProps {
className?: string;
popoverClassName?: string;
placeholder?: string;
theme?: any;
format: string;
utc?: boolean;
inputFormat?: string;
timeFormat?: string;
ranges?: string | Array<ShortCuts>;
clearable?: boolean;
minDate?: moment.Moment;
maxDate?: moment.Moment;
minDuration?: moment.Duration;
maxDuration?: moment.Duration;
joinValues: boolean;
delimiter: string;
value?: any;
onChange: (value: any) => void;
data?: any;
disabled?: boolean;
closeOnSelect?: boolean;
overlayPlacement: string;
resetValue?: any;
popOverContainer?: any;
embed?: boolean;
}
export interface MonthRangePickerState {
isOpened: boolean;
isFocused: boolean;
startDate?: moment.Moment;
endDate?: moment.Moment;
}
export class MonthRangePicker extends React.Component<
MonthRangePickerProps,
MonthRangePickerState
> {
static defaultProps = {
placeholder: 'MonthRange.placeholder',
format: 'YYYY-MM',
inputFormat: 'YYYY-MM',
joinValues: true,
clearable: true,
delimiter: ',',
resetValue: '',
closeOnSelect: true,
overlayPlacement: 'auto'
};
innerDom: any;
popover: any;
input?: HTMLInputElement;
dom: React.RefObject<HTMLDivElement>;
nextMonth = moment().add(1, 'year').startOf('month');
constructor(props: MonthRangePickerProps) {
super(props);
this.open = this.open.bind(this);
this.close = this.close.bind(this);
this.handleStartChange = this.handleStartChange.bind(this);
this.handleEndChange = this.handleEndChange.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.checkStartIsValidDate = this.checkStartIsValidDate.bind(this);
this.checkEndIsValidDate = this.checkEndIsValidDate.bind(this);
this.confirm = this.confirm.bind(this);
this.clearValue = this.clearValue.bind(this);
this.dom = React.createRef();
this.handleClick = this.handleClick.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
this.handlePopOverClick = this.handlePopOverClick.bind(this);
this.renderMonth = this.renderMonth.bind(this);
const {format, joinValues, delimiter, value} = this.props;
this.state = {
isOpened: false,
isFocused: false,
...DateRangePicker.unFormatValue(value, format, joinValues, delimiter)
};
}
componentDidUpdate(prevProps: MonthRangePickerProps) {
const props = this.props;
const {value, format, joinValues, delimiter} = props;
if (prevProps.value !== value) {
this.setState({
...DateRangePicker.unFormatValue(value, format, joinValues, delimiter)
});
}
}
focus() {
if (!this.dom.current || this.props.disabled) {
return;
}
this.dom.current.focus();
}
blur() {
if (!this.dom.current || this.props.disabled) {
return;
}
this.dom.current.blur();
}
handleFocus() {
this.setState({
isFocused: true
});
}
handleBlur() {
this.setState({
isFocused: false
});
}
open() {
if (this.props.disabled) {
return;
}
this.setState({
isOpened: true
});
}
close() {
this.setState(
{
isOpened: false
},
this.blur
);
}
handleClick() {
this.state.isOpened ? this.close() : this.open();
}
handlePopOverClick(e: React.MouseEvent<any>) {
e.stopPropagation();
e.preventDefault();
}
handleKeyPress(e: React.KeyboardEvent) {
if (e.key === ' ') {
this.handleClick();
e.preventDefault();
}
}
confirm() {
if (!this.state.startDate || !this.state.endDate) {
return;
} else if (this.state.startDate.isAfter(this.state.endDate)) {
return;
}
this.props.onChange(
DateRangePicker.formatValue(
{
startDate: this.state.startDate,
endDate: this.state.endDate
},
this.props.format,
this.props.joinValues,
this.props.delimiter,
this.props.utc
)
);
this.close();
}
filterDate(
date: moment.Moment,
originValue?: moment.Moment,
timeFormat?: string,
type: 'start' | 'end' = 'start'
): moment.Moment {
let value = date.clone();
value = value[type === 'start' ? 'startOf' : 'endOf']('month');
return value;
}
handleStartChange(newValue: moment.Moment) {
const {embed, minDuration, maxDuration} = this.props;
const {startDate, endDate} = this.state;
if (
startDate &&
!endDate &&
newValue.isSameOrAfter(startDate) &&
(!minDuration || newValue.isAfter(startDate.clone().add(minDuration))) &&
(!maxDuration || newValue.isBefore(startDate.clone().add(maxDuration)))
) {
return this.setState(
{
endDate: this.filterDate(newValue, endDate, '', 'end')
},
() => {
embed && this.confirm();
}
);
}
this.setState(
{
startDate: this.filterDate(newValue, startDate, '', 'start')
},
() => {
embed && this.confirm();
}
);
}
handleEndChange(newValue: moment.Moment) {
const {embed, minDuration, maxDuration} = this.props;
const {startDate, endDate} = this.state;
if (
endDate &&
!startDate &&
newValue.isSameOrBefore(endDate) &&
(!minDuration ||
newValue.isBefore(endDate.clone().subtract(minDuration))) &&
(!maxDuration || newValue.isAfter(endDate.clone().subtract(maxDuration)))
) {
return this.setState(
{
startDate: this.filterDate(newValue, startDate, '', 'start')
},
() => {
embed && this.confirm();
}
);
}
this.setState(
{
endDate: this.filterDate(newValue, endDate, '', 'end')
},
() => {
embed && this.confirm();
}
);
}
selectRannge(range: PlainObject) {
const {closeOnSelect, minDate, maxDate} = this.props;
this.setState(
{
startDate: minDate
? moment.max(range.startDate(moment()), minDate)
: range.startDate(moment()),
endDate: maxDate
? moment.min(maxDate, range.endDate(moment()))
: range.endDate(moment())
},
closeOnSelect ? this.confirm : noop
);
}
renderRanges(ranges: string | Array<ShortCuts> | undefined) {
if (!ranges) {
return null;
}
const {classPrefix: ns} = this.props;
let rangeArr: Array<string | ShortCuts>;
if (typeof ranges === 'string') {
rangeArr = ranges.split(',');
} else {
rangeArr = ranges;
}
const __ = this.props.translate;
return (
<ul className={`${ns}DateRangePicker-rangers`}>
{rangeArr.map(item => {
if (!item) {
return null;
}
let range: PlainObject = {};
if (typeof item === 'string') {
range = availableRanges[item];
range.key = item;
} else if (
(item as ShortCutDateRange).startDate &&
(item as ShortCutDateRange).endDate
) {
range = {
...item,
startDate: () => (item as ShortCutDateRange).startDate,
endDate: () => (item as ShortCutDateRange).endDate
};
}
return (
<li
className={`${ns}DateRangePicker-ranger`}
onClick={() => this.selectRannge(range)}
key={range.key || range.label}
>
<a>{__(range.label)}</a>
</li>
);
})}
</ul>
);
}
clearValue(e: React.MouseEvent<any>) {
e.preventDefault();
e.stopPropagation();
const {resetValue, onChange} = this.props;
onChange(resetValue);
}
checkStartIsValidDate(currentDate: moment.Moment) {
let {endDate, startDate} = this.state;
let {minDate, maxDate, minDuration, maxDuration} = this.props;
maxDate =
maxDate && endDate
? maxDate.isBefore(endDate)
? maxDate
: endDate
: maxDate || endDate;
if (minDate && currentDate.isBefore(minDate, 'day')) {
return false;
} else if (maxDate && currentDate.isAfter(maxDate, 'day')) {
return false;
} else if (
// 如果配置了 minDuration 那么 EndDate - minDuration 之后的天数也不能选
endDate &&
minDuration &&
currentDate.isAfter(endDate.clone().subtract(minDuration))
) {
return false;
} else if (
endDate &&
maxDuration &&
currentDate.isBefore(endDate.clone().subtract(maxDuration))
) {
return false;
}
return true;
}
checkEndIsValidDate(currentDate: moment.Moment) {
let {startDate} = this.state;
let {minDate, maxDate, minDuration, maxDuration} = this.props;
minDate =
minDate && startDate
? minDate.isAfter(startDate)
? minDate
: startDate
: minDate || startDate;
if (minDate && currentDate.isBefore(minDate, 'day')) {
return false;
} else if (maxDate && currentDate.isAfter(maxDate, 'day')) {
return false;
} else if (
startDate &&
minDuration &&
currentDate.isBefore(startDate.clone().add(minDuration))
) {
return false;
} else if (
startDate &&
maxDuration &&
currentDate.isAfter(startDate.clone().add(maxDuration))
) {
return false;
}
return true;
}
renderMonth(props: any, month: number, year: number) {
var currentDate = moment().year(year).month(month);
var monthStr = currentDate
.localeData()
.monthsShort(currentDate.month(month));
var strLength = 3;
var monthStrFixedLength = monthStr.substring(0, strLength);
const {startDate, endDate} = this.state;
if (
startDate &&
endDate &&
currentDate.isBetween(startDate, endDate, 'month', '[]')
) {
props.className += ' rdtBetween';
}
return (
<td {...props}>
<span>{capitalize(monthStrFixedLength)}</span>
</td>
);
}
renderCalendar() {
const {classPrefix: ns, classnames: cx, locale, embed, ranges, inputFormat, timeFormat} = this.props;
const __ = this.props.translate;
const viewMode: 'months' = 'months';
const dateFormat = 'YYYY-MM';
const {startDate, endDate} = this.state;
return (
<div className={`${ns}DateRangePicker-wrap`}>
{this.renderRanges(ranges)}
<Calendar
className={`${ns}DateRangePicker-start`}
value={startDate}
onChange={this.handleStartChange}
requiredConfirm={false}
dateFormat={dateFormat}
inputFormat={inputFormat}
timeFormat={timeFormat}
isValidDate={this.checkStartIsValidDate}
viewMode={viewMode}
input={false}
onClose={this.close}
renderMonth={this.renderMonth}
locale={locale}
/>
<Calendar
className={`${ns}DateRangePicker-end`}
value={
// 因为如果最后一天,切换月份的时候会切不了,有的月份有 31 号,有的没有。
endDate?.clone().startOf('month')
}
onChange={this.handleEndChange}
requiredConfirm={false}
dateFormat={dateFormat}
inputFormat={inputFormat}
timeFormat={timeFormat}
viewDate={this.nextMonth}
isEndDate
isValidDate={this.checkEndIsValidDate}
viewMode={viewMode}
input={false}
onClose={this.close}
renderMonth={this.renderMonth}
locale={locale}
/>
{embed ? null : (
<div key="button" className={cx('DateRangePicker-actions')}>
<a className={cx('Button', 'Button--default')} onClick={this.close}>
{__('cancel')}
</a>
<a
className={cx('Button', 'Button--primary', 'm-l-sm', {
'is-disabled': !this.state.startDate || !this.state.endDate
})}
onClick={this.confirm}
>
{__('confirm')}
</a>
</div>
)}
</div>
);
}
render() {
const {
className,
popoverClassName,
classPrefix: ns,
value,
placeholder,
popOverContainer,
inputFormat,
format,
joinValues,
delimiter,
clearable,
disabled,
embed,
overlayPlacement
} = this.props;
const {isOpened, isFocused} = this.state;
const selectedDate = DateRangePicker.unFormatValue(
value,
format,
joinValues,
delimiter
);
const startViewValue = selectedDate.startDate
? selectedDate.startDate.format(inputFormat)
: '';
const endViewValue = selectedDate.endDate
? selectedDate.endDate.format(inputFormat)
: '';
const arr = [];
startViewValue && arr.push(startViewValue);
endViewValue && arr.push(endViewValue);
const __ = this.props.translate;
if (embed) {
return (
<div
className={cx(
`${ns}DateRangeCalendar`,
{
'is-disabled': disabled
},
className
)}
>
{this.renderCalendar()}
</div>
);
}
return (
<div
tabIndex={0}
onKeyPress={this.handleKeyPress}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
className={cx(
`${ns}DateRangePicker`,
{
'is-disabled': disabled,
'is-focused': isFocused
},
className
)}
ref={this.dom}
onClick={this.handleClick}
>
{arr.length ? (
<span className={`${ns}DateRangePicker-value`}>
{arr.join(__('DateRange.valueConcat'))}
</span>
) : (
<span className={`${ns}DateRangePicker-placeholder`}>
{__(placeholder)}
</span>
)}
{clearable && !disabled && value ? (
<a className={`${ns}DateRangePicker-clear`} onClick={this.clearValue}>
<Icon icon="close" className="icon" />
</a>
) : null}
<a className={`${ns}DateRangePicker-toggler`}>
<Icon icon="calendar" className="icon" />
</a>
{isOpened ? (
<Overlay
target={() => this.dom.current}
onHide={this.close}
container={popOverContainer || (() => findDOMNode(this))}
rootClose={false}
placement={overlayPlacement}
show
>
<PopOver
classPrefix={ns}
className={cx(`${ns}DateRangePicker-popover`, popoverClassName)}
onHide={this.close}
onClick={this.handlePopOverClick}
overlay
>
{this.renderCalendar()}
</PopOver>
</Overlay>
) : null}
</div>
);
}
}
export default themeable(localeable(MonthRangePicker)); | the_stack |
import { DataPoint, RenderModel } from "../core/renderModel";
import { resolveColorRGBA, ResolvedCoreOptions, TimeChartSeriesOptions } from '../options';
import { domainSearch } from '../utils';
import { vec2 } from 'gl-matrix';
import { TimeChartPlugin } from '.';
import { LinkedWebGLProgram, throwIfFalsy } from './webGLUtils';
const enum VertexAttribLocations {
DATA_POINT = 0,
DIR = 1,
}
function vsSource(gl: WebGL2RenderingContext | WebGLRenderingContext) {
const body = `
uniform vec2 uModelScale;
uniform vec2 uModelTranslation;
uniform vec2 uProjectionScale;
uniform float uLineWidth;
void main() {
vec2 cssPose = uModelScale * aDataPoint + uModelTranslation;
vec2 dir = uModelScale * aDir;
dir = normalize(dir);
vec2 pos2d = uProjectionScale * (cssPose + vec2(-dir.y, dir.x) * uLineWidth);
gl_Position = vec4(pos2d, 0, 1);
}`;
if (gl instanceof WebGLRenderingContext) {
return `
attribute vec2 aDataPoint;
attribute vec2 aDir;
${body}`;
} else {
return `#version 300 es
layout (location = ${VertexAttribLocations.DATA_POINT}) in vec2 aDataPoint;
layout (location = ${VertexAttribLocations.DIR}) in vec2 aDir;
${body}`;
}
}
function fsSource(gl: WebGL2RenderingContext | WebGLRenderingContext) {
const body = `
`;
if (gl instanceof WebGLRenderingContext) {
return `
precision lowp float;
uniform vec4 uColor;
void main() {
gl_FragColor = uColor;
}`;
} else {
return `#version 300 es
precision lowp float;
uniform vec4 uColor;
out vec4 outColor;
void main() {
outColor = uColor;
}`;
}
}
class LineChartWebGLProgram extends LinkedWebGLProgram {
locations: {
uModelScale: WebGLUniformLocation;
uModelTranslation: WebGLUniformLocation;
uProjectionScale: WebGLUniformLocation;
uLineWidth: WebGLUniformLocation;
uColor: WebGLUniformLocation;
};
constructor(gl: WebGL2RenderingContext | WebGLRenderingContext, debug: boolean) {
super(gl, vsSource(gl), fsSource(gl), debug);
if (gl instanceof WebGLRenderingContext) {
gl.bindAttribLocation(this.program, VertexAttribLocations.DATA_POINT, 'aDataPoint');
gl.bindAttribLocation(this.program, VertexAttribLocations.DIR, 'aDir');
}
this.link();
const getLoc = (name: string) => throwIfFalsy(gl.getUniformLocation(this.program, name));
this.locations = {
uModelScale: getLoc('uModelScale'),
uModelTranslation: getLoc('uModelTranslation'),
uProjectionScale: getLoc('uProjectionScale'),
uLineWidth: getLoc('uLineWidth'),
uColor: getLoc('uColor'),
}
}
}
const INDEX_PER_POINT = 4;
const POINT_PER_DATAPOINT = 4;
const INDEX_PER_DATAPOINT = INDEX_PER_POINT * POINT_PER_DATAPOINT;
const BYTES_PER_POINT = INDEX_PER_POINT * Float32Array.BYTES_PER_ELEMENT;
const BUFFER_DATA_POINT_CAPACITY = 128 * 1024;
const BUFFER_CAPACITY = BUFFER_DATA_POINT_CAPACITY * INDEX_PER_DATAPOINT + 2 * POINT_PER_DATAPOINT;
interface IVAO {
bind(): void;
clear(): void;
}
class WebGL2VAO implements IVAO {
private vao: WebGLVertexArrayObject;
constructor(private gl: WebGL2RenderingContext) {
this.vao = throwIfFalsy(gl.createVertexArray());
this.bind();
}
bind() {
this.gl.bindVertexArray(this.vao);
}
clear() {
this.gl.deleteVertexArray(this.vao);
}
}
class OESVAO implements IVAO {
vao: WebGLVertexArrayObjectOES;
constructor(private vaoExt: OES_vertex_array_object) {
this.vao = throwIfFalsy(vaoExt.createVertexArrayOES());
this.bind();
}
bind() {
this.vaoExt.bindVertexArrayOES(this.vao);
}
clear() {
this.vaoExt.deleteVertexArrayOES(this.vao);
}
}
class WebGL1BufferInfo implements IVAO {
constructor(private bindFunc: () => void) {
}
bind() {
this.bindFunc();
}
clear() {
}
}
class SeriesSegmentVertexArray {
vao: IVAO;
dataBuffer: WebGLBuffer;
length = 0;
/**
* @param firstDataPointIndex At least 1, since datapoint 0 has no path to draw.
*/
constructor(
private gl: WebGL2RenderingContext | WebGLRenderingContext,
private dataPoints: ArrayLike<DataPoint>,
public readonly firstDataPointIndex: number,
) {
this.dataBuffer = throwIfFalsy(gl.createBuffer());
const bindFunc = () => {
gl.bindBuffer(gl.ARRAY_BUFFER, this.dataBuffer);
gl.enableVertexAttribArray(VertexAttribLocations.DATA_POINT);
gl.vertexAttribPointer(VertexAttribLocations.DATA_POINT, 2, gl.FLOAT, false, BYTES_PER_POINT, 0);
gl.enableVertexAttribArray(VertexAttribLocations.DIR);
gl.vertexAttribPointer(VertexAttribLocations.DIR, 2, gl.FLOAT, false, BYTES_PER_POINT, 2 * Float32Array.BYTES_PER_ELEMENT);
}
if (gl instanceof WebGLRenderingContext) {
const vaoExt = gl.getExtension('OES_vertex_array_object');
if (vaoExt) {
this.vao = new OESVAO(vaoExt);
} else {
this.vao = new WebGL1BufferInfo(bindFunc);
}
} else {
this.vao = new WebGL2VAO(gl);
}
bindFunc();
gl.bufferData(gl.ARRAY_BUFFER, BUFFER_CAPACITY * Float32Array.BYTES_PER_ELEMENT, gl.DYNAMIC_DRAW);
}
clear() {
this.length = 0;
}
delete() {
this.clear();
this.gl.deleteBuffer(this.dataBuffer);
this.vao.clear();
}
/**
* @returns Next data point index, or `dataPoints.length` if all data added.
*/
addDataPoints(): number {
const dataPoints = this.dataPoints;
const start = this.firstDataPointIndex + this.length;
const remainDPCapacity = BUFFER_DATA_POINT_CAPACITY - this.length;
const remainDPCount = dataPoints.length - start
const isOverflow = remainDPCapacity < remainDPCount;
const numDPtoAdd = isOverflow ? remainDPCapacity : remainDPCount;
let extraBufferLength = INDEX_PER_DATAPOINT * numDPtoAdd;
if (isOverflow) {
extraBufferLength += 2 * INDEX_PER_POINT;
}
const buffer = new Float32Array(extraBufferLength);
let bi = 0;
const vDP = vec2.create()
const vPreviousDP = vec2.create()
const dir1 = vec2.create();
const dir2 = vec2.create();
function calc(dp: DataPoint, previousDP: DataPoint) {
vDP[0] = dp.x;
vDP[1] = dp.y;
vPreviousDP[0] = previousDP.x;
vPreviousDP[1] = previousDP.y;
vec2.subtract(dir1, vDP, vPreviousDP);
vec2.normalize(dir1, dir1);
vec2.negate(dir2, dir1);
}
function put(v: vec2) {
buffer[bi] = v[0];
buffer[bi + 1] = v[1];
bi += 2;
}
let previousDP = dataPoints[start - 1];
for (let i = 0; i < numDPtoAdd; i++) {
const dp = dataPoints[start + i];
calc(dp, previousDP);
previousDP = dp;
for (const dp of [vPreviousDP, vDP]) {
for (const dir of [dir1, dir2]) {
put(dp);
put(dir);
}
}
}
if (isOverflow) {
calc(dataPoints[start + numDPtoAdd], previousDP);
for (const dir of [dir1, dir2]) {
put(vPreviousDP);
put(dir);
}
}
const gl = this.gl;
gl.bindBuffer(gl.ARRAY_BUFFER, this.dataBuffer);
gl.bufferSubData(gl.ARRAY_BUFFER, BYTES_PER_POINT * POINT_PER_DATAPOINT * this.length, buffer);
this.length += numDPtoAdd;
return start + numDPtoAdd;
}
draw(renderIndex: { min: number, max: number }) {
const first = Math.max(0, renderIndex.min - this.firstDataPointIndex);
const last = Math.min(this.length, renderIndex.max - this.firstDataPointIndex)
const count = last - first;
const gl = this.gl;
this.vao.bind();
gl.drawArrays(gl.TRIANGLE_STRIP, first * POINT_PER_DATAPOINT, count * POINT_PER_DATAPOINT);
}
}
/**
* An array of `SeriesSegmentVertexArray` to represent a series
*
* `series.data` index: 0 [1 ... C] [C+1 ... 2C] ... (C = `BUFFER_DATA_POINT_CAPACITY`)
* `vertexArrays` index: 0 1 ...
*/
class SeriesVertexArray {
private vertexArrays = [] as SeriesSegmentVertexArray[];
constructor(
private gl: WebGL2RenderingContext | WebGLRenderingContext,
private series: TimeChartSeriesOptions,
) {
}
syncBuffer() {
let activeArray: SeriesSegmentVertexArray;
let bufferedDataPointNum = 1;
const newArray = () => {
activeArray = new SeriesSegmentVertexArray(this.gl, this.series.data, bufferedDataPointNum);
this.vertexArrays.push(activeArray);
}
if (this.vertexArrays.length > 0) {
const lastVertexArray = this.vertexArrays[this.vertexArrays.length - 1];
bufferedDataPointNum = lastVertexArray.firstDataPointIndex + lastVertexArray.length;
if (bufferedDataPointNum > this.series.data.length) {
throw new Error('remove data unsupported.');
}
if (bufferedDataPointNum === this.series.data.length) {
return;
}
activeArray = lastVertexArray;
} else if (this.series.data.length >= 2) {
newArray();
activeArray = activeArray!;
} else {
return; // Not enough data
}
while (true) {
bufferedDataPointNum = activeArray.addDataPoints();
if (bufferedDataPointNum >= this.series.data.length) {
if (bufferedDataPointNum > this.series.data.length) { throw Error('Assertion failed.'); }
break;
}
newArray();
}
}
draw(renderDomain: { min: number, max: number }) {
const data = this.series.data;
if (this.vertexArrays.length === 0 || data[0].x > renderDomain.max || data[data.length - 1].x < renderDomain.min) {
return;
}
const key = (d: DataPoint) => d.x
const minIndex = domainSearch(data, 1, data.length, renderDomain.min, key);
const maxIndex = domainSearch(data, minIndex, data.length - 1, renderDomain.max, key) + 1;
const minArrayIndex = Math.floor((minIndex - 1) / BUFFER_DATA_POINT_CAPACITY);
const maxArrayIndex = Math.ceil((maxIndex - 1) / BUFFER_DATA_POINT_CAPACITY);
const renderIndex = { min: minIndex, max: maxIndex };
for (let i = minArrayIndex; i < maxArrayIndex; i++) {
this.vertexArrays[i].draw(renderIndex);
}
}
}
export class LineChartRenderer {
private program = new LineChartWebGLProgram(this.gl, this.options.debugWebGL);
private arrays = new Map<TimeChartSeriesOptions, SeriesVertexArray>();
private height = 0;
private width = 0;
constructor(
private model: RenderModel,
private gl: WebGL2RenderingContext | WebGLRenderingContext,
private options: ResolvedCoreOptions,
) {
this.program.use();
model.updated.on(() => this.drawFrame());
model.resized.on((w, h) => this.onResize(w, h));
}
syncBuffer() {
for (const s of this.options.series) {
let a = this.arrays.get(s);
if (!a) {
a = new SeriesVertexArray(this.gl, s);
this.arrays.set(s, a);
}
a.syncBuffer();
}
}
onResize(width: number, height: number) {
this.height = height;
this.width = width;
const scale = vec2.fromValues(width, height)
vec2.divide(scale, scale, [2, 2])
vec2.inverse(scale, scale)
const gl = this.gl;
gl.uniform2fv(this.program.locations.uProjectionScale, scale);
}
drawFrame() {
this.syncBuffer();
this.syncDomain();
const gl = this.gl;
for (const [ds, arr] of this.arrays) {
if (!ds.visible) {
continue;
}
const color = resolveColorRGBA(ds.color);
gl.uniform4fv(this.program.locations.uColor, color);
const lineWidth = ds.lineWidth ?? this.options.lineWidth;
gl.uniform1f(this.program.locations.uLineWidth, lineWidth / 2);
const renderDomain = {
min: this.model.xScale.invert(-lineWidth / 2),
max: this.model.xScale.invert(this.width + lineWidth / 2),
};
arr.draw(renderDomain);
}
if (this.options.debugWebGL) {
const err = gl.getError();
if (err != gl.NO_ERROR) {
throw new Error(`WebGL error ${err}`);
}
}
}
private ySvgToView(v: number) {
return -v + this.height / 2;
}
private xSvgToView(v: number) {
return v - this.width / 2;
}
syncDomain() {
const m = this.model;
const gl = this.gl;
const zero = [this.xSvgToView(m.xScale(0)!), this.ySvgToView(m.yScale(0)!)];
const one = [this.xSvgToView(m.xScale(1)!), this.ySvgToView(m.yScale(1)!)];
// Not using vec2 for precision
const scaling = [one[0] - zero[0], one[1] - zero[1]]
gl.uniform2fv(this.program.locations.uModelScale, scaling);
gl.uniform2fv(this.program.locations.uModelTranslation, zero);
}
}
export const lineChart: TimeChartPlugin<LineChartRenderer> = {
apply(chart) {
return new LineChartRenderer(chart.model, chart.canvasLayer.gl, chart.options);
}
} | the_stack |
import {
BuiltIns,
Schema,
DirectiveDefinition,
NonNullType,
NamedType,
Directive,
UnionType,
ObjectType,
ListType,
FieldDefinition,
CompositeType,
allSchemaRootKinds,
defaultRootName,
errorCauses,
ErrGraphQLValidationFailed,
SchemaElement,
baseType,
isInterfaceType,
isObjectType,
sourceASTs,
VariableDefinitions,
InterfaceType,
InputFieldDefinition,
isCompositeType
} from "./definitions";
import { assert, OrderedMap } from "./utils";
import { SDLValidationRule } from "graphql/validation/ValidationContext";
import { specifiedSDLRules } from "graphql/validation/specifiedRules";
import { ASTNode, DocumentNode, GraphQLError, KnownTypeNamesRule, parse, PossibleTypeExtensionsRule, Source } from "graphql";
import { defaultPrintOptions, printDirectiveDefinition } from "./print";
import { KnownTypeNamesInFederationRule } from "./validation/KnownTypeNamesInFederationRule";
import { buildSchema, buildSchemaFromAST } from "./buildSchema";
import { parseSelectionSet, SelectionSet } from './operations';
import { tagLocations, TAG_VERSIONS } from "./tagSpec";
import { error } from "./error";
export const entityTypeName = '_Entity';
export const serviceTypeName = '_Service';
export const anyTypeName = '_Any';
export const fieldSetTypeName = '_FieldSet';
export const keyDirectiveName = 'key';
export const extendsDirectiveName = 'extends';
export const externalDirectiveName = 'external';
export const requiresDirectiveName = 'requires';
export const providesDirectiveName = 'provides';
// TODO: so far, it seems we allow tag to appear without a corresponding definition, so we add it as a built-in.
// If we change our mind, we should change this.
export const tagDirectiveName = 'tag';
export const serviceFieldName = '_service';
export const entitiesFieldName = '_entities';
const tagSpec = TAG_VERSIONS.latest();
// We don't let user use this as a subgraph name. That allows us to use it in `query graphs` to name the source of roots
// in the "federated query graph" without worrying about conflict (see `FEDERATED_GRAPH_ROOT_SOURCE` in `querygraph.ts`).
// (note that we could deal with this in other ways, but having a graph named '_' feels like a terrible idea anyway, so
// disallowing it feels like more a good thing than a real restriction).
export const FEDERATION_RESERVED_SUBGRAPH_NAME = '_';
const FEDERATION_TYPES = [
entityTypeName,
serviceTypeName,
anyTypeName,
fieldSetTypeName
];
const FEDERATION_DIRECTIVES = [
keyDirectiveName,
extendsDirectiveName,
externalDirectiveName,
requiresDirectiveName,
providesDirectiveName,
tagDirectiveName
];
const FEDERATION_ROOT_FIELDS = [
serviceFieldName,
entitiesFieldName
];
const FEDERATION_OMITTED_VALIDATION_RULES = [
// We allow subgraphs to declare an extension even if the subgraph itself doesn't have a corresponding definition.
// The implication being that the definition is in another subgraph.
PossibleTypeExtensionsRule,
// The `KnownTypeNamesRule` of graphQL-js only looks at type definitions, so this goes against our previous
// desire to let a subgraph only have an extension for a type. Below, we add a replacement rules that looks
// at both type definitions _and_ extensions.
KnownTypeNamesRule
];
const FEDERATION_SPECIFIC_VALIDATION_RULES = [
KnownTypeNamesInFederationRule
];
const FEDERATION_VALIDATION_RULES = specifiedSDLRules.filter(rule => !FEDERATION_OMITTED_VALIDATION_RULES.includes(rule)).concat(FEDERATION_SPECIFIC_VALIDATION_RULES);
// Returns a list of the coordinate of all the fields in the selection that are marked external.
function validateFieldSetSelections(
directiveName: string,
selectionSet: SelectionSet,
hasExternalInParents: boolean,
externalTester: ExternalTester,
externalFieldCoordinatesCollector: string[],
allowOnNonExternalLeafFields: boolean,
): void {
for (const selection of selectionSet.selections()) {
if (selection.kind === 'FieldSelection') {
const field = selection.element().definition;
if (field.hasArguments()) {
throw new GraphQLError(`field ${field.coordinate} cannot be included because it has arguments (fields with argument are not allowed in @${directiveName})`, field.sourceAST);
}
// The field must be external if we don't allow non-external leaf fields, it's a leaf, and we haven't traversed an external field in parent chain leading here.
const mustBeExternal = !selection.selectionSet && !allowOnNonExternalLeafFields && !hasExternalInParents;
const isExternal = externalTester.isExternal(field);
if (isExternal) {
externalFieldCoordinatesCollector.push(field.coordinate);
} else if (mustBeExternal) {
if (externalTester.isFakeExternal(field)) {
throw new GraphQLError(
`field "${field.coordinate}" should not be part of a @${directiveName} since it is already "effectively" provided by this subgraph `
+ `(while it is marked @${externalDirectiveName}, it is a @${keyDirectiveName} field of an extension type, which are not internally considered external for historical/backward compatibility reasons)`,
field.sourceAST);
} else {
throw new GraphQLError(`field "${field.coordinate}" should not be part of a @${directiveName} since it is already provided by this subgraph (it is not marked @${externalDirectiveName})`, field.sourceAST);
}
}
if (selection.selectionSet) {
// When passing the 'hasExternalInParents', the field might be external himself, but we may also have
// the case where the field parent is an interface and some implementation of the field are external, in
// which case we should say we have an external on the path, because we may have one.
let newHasExternalInParents = hasExternalInParents || isExternal;
const parentType = field.parent;
if (!newHasExternalInParents && isInterfaceType(parentType)) {
for (const implem of parentType.possibleRuntimeTypes()) {
const fieldInImplem = implem.field(field.name);
if (fieldInImplem && externalTester.isExternal(fieldInImplem)) {
newHasExternalInParents = true;
break;
}
}
}
validateFieldSetSelections(directiveName, selection.selectionSet, newHasExternalInParents, externalTester, externalFieldCoordinatesCollector, allowOnNonExternalLeafFields);
}
} else {
validateFieldSetSelections(directiveName, selection.selectionSet, hasExternalInParents, externalTester, externalFieldCoordinatesCollector, allowOnNonExternalLeafFields);
}
}
}
function validateFieldSet(
type: CompositeType,
directive: Directive<any, {fields: any}>,
targetDescription: string,
externalTester: ExternalTester,
externalFieldCoordinatesCollector: string[],
allowOnNonExternalLeafFields: boolean,
): GraphQLError | undefined {
try {
const selectionSet = parseFieldSetArgument(type, directive);
selectionSet.validate();
validateFieldSetSelections(directive.name, selectionSet, false, externalTester, externalFieldCoordinatesCollector, allowOnNonExternalLeafFields);
return undefined;
} catch (e) {
if (!(e instanceof GraphQLError)) {
throw e;
}
const nodes = sourceASTs(directive);
if (e.nodes) {
nodes.push(...e.nodes);
}
let msg = e.message.trim();
// The rule for validating @requires in fed 1 was not properly recursive, so people upgrading
// may have a @require that selects some fields but without declaring those fields on the
// subgraph. As we fixed the validation, this will now fail, but we try here to provide some
// hint for those users for how to fix the problem.
// Note that this is a tad fragile to rely on the error message like that, but worth case, a
// future change make us not show the hint and that's not the end of the world.
if (msg.startsWith('Cannot query field')) {
if (msg.endsWith('.')) {
msg = msg.slice(0, msg.length - 1);
}
if (directive.name === keyDirectiveName) {
msg = msg + ' (the field should be either be added to this subgraph or, if it should not be resolved by this subgraph, you need to add it to this subgraph with @external).';
} else {
msg = msg + ' (if the field is defined in another subgraph, you need to add it to this subgraph with @external).';
}
}
return new GraphQLError(`On ${targetDescription}, for ${directive}: ${msg}`, nodes);
}
}
function validateAllFieldSet<TParent extends SchemaElement<any, any>>(
definition: DirectiveDefinition<{fields: any}>,
targetTypeExtractor: (element: TParent) => CompositeType,
targetDescriptionExtractor: (element: TParent) => string,
errorCollector: GraphQLError[],
externalTester: ExternalTester,
externalFieldCoordinatesCollector: string[],
isOnParentType: boolean,
allowOnNonExternalLeafFields: boolean,
): void {
for (const application of definition.applications()) {
const elt = application.parent as TParent;
const type = targetTypeExtractor(elt);
const targetDescription = targetDescriptionExtractor(elt);
const parentType = isOnParentType ? type : (elt.parent as NamedType);
if (isInterfaceType(parentType)) {
errorCollector.push(new GraphQLError(
isOnParentType
? `Cannot use ${definition.coordinate} on interface ${parentType.coordinate}: ${definition.coordinate} is not yet supported on interfaces`
: `Cannot use ${definition.coordinate} on ${targetDescription} of parent type ${parentType}: ${definition.coordinate} is not yet supported within interfaces`,
sourceASTs(application).concat(isOnParentType ? [] : sourceASTs(type))
));
}
const error = validateFieldSet(type, application, targetDescription, externalTester, externalFieldCoordinatesCollector, allowOnNonExternalLeafFields);
if (error) {
errorCollector.push(error);
}
}
}
/**
* Checks that all fields marked @external is used in a federation directive (@key, @provides or @requires) _or_ to satisfy an
* interface implementation. Otherwise, the field declaration is somewhat useless.
*/
function validateAllExternalFieldsUsed(
schema: Schema,
externalTester: ExternalTester,
allExternalFieldsUsedInFederationDirectivesCoordinates: string[],
errorCollector: GraphQLError[],
): void {
for (const type of schema.types()) {
if (!isObjectType(type) && !isInterfaceType(type)) {
continue;
}
for (const field of type.fields()) {
if (!externalTester.isExternal(field) || allExternalFieldsUsedInFederationDirectivesCoordinates.includes(field.coordinate)) {
continue;
}
if (!isFieldSatisfyingInterface(field)) {
errorCollector.push(new GraphQLError(
`Field ${field.coordinate} is marked @external but is not used in any federation directive (@key, @provides, @requires) or to satisfy an interface;`
+ ' the field declaration has no use and should be removed (or the field should not be @external).',
field.sourceAST
));
}
}
}
}
function isFieldSatisfyingInterface(field: FieldDefinition<ObjectType | InterfaceType>): boolean {
return field.parent.interfaces().some(itf => itf.field(field.name));
}
export class FederationBuiltIns extends BuiltIns {
addBuiltInTypes(schema: Schema) {
super.addBuiltInTypes(schema);
this.addBuiltInUnion(schema, entityTypeName);
this.addBuiltInObject(schema, serviceTypeName).addField('sdl', schema.stringType());
this.addBuiltInScalar(schema, anyTypeName);
this.addBuiltInScalar(schema, fieldSetTypeName);
}
addBuiltInDirectives(schema: Schema) {
super.addBuiltInDirectives(schema);
const fieldSetType = new NonNullType(schema.type(fieldSetTypeName)!);
// Note that we allow @key on interfaces in the definition to not break backward compatibility, because it has historically unfortunately be declared this way, but
// @key is actually not supported on interfaces at the moment, so if if is "used" then it is rejected.
const keyDirective = this.addBuiltInDirective(schema, keyDirectiveName)
.addLocations('OBJECT', 'INTERFACE');
// TODO: I believe fed 1 does not mark key repeatable and relax validation to accept repeating non-repeatable directive.
// Do we want to perpetuate this? (Obviously, this is for historical reason and some graphQL implementations still do
// not support 'repeatable'. But since this code does not kick in within users' code, not sure we have to accommodate
// for those implementations. Besides, we _do_ accept if people re-defined @key as non-repeatable).
keyDirective.repeatable = true;
keyDirective.addArgument('fields', fieldSetType);
this.addBuiltInDirective(schema, extendsDirectiveName)
.addLocations('OBJECT', 'INTERFACE');
this.addBuiltInDirective(schema, externalDirectiveName)
.addLocations('OBJECT', 'FIELD_DEFINITION');
for (const name of [requiresDirectiveName, providesDirectiveName]) {
this.addBuiltInDirective(schema, name)
.addLocations('FIELD_DEFINITION')
.addArgument('fields', fieldSetType);
}
const directive = this.addBuiltInDirective(schema, 'tag').addLocations(...tagLocations);
directive.addArgument("name", new NonNullType(schema.stringType()));
}
prepareValidation(schema: Schema) {
super.prepareValidation(schema);
// Populate the _Entity type union.
let entityType = schema.type(entityTypeName) as UnionType;
// Not that it's possible the _Entity type was provided in the schema. In that case, we don't really want to modify that
// instance, but rather the builtIn one.
if (!entityType.isBuiltIn) {
// And if it _was_ redefined, but the redefinition is empty, let's just remove it as we've historically allowed that
// (and it's a reasonable convenience). If the redefinition _has_ members, than we leave it but follow-up validation
// will bark if the redefinition is incorrect.
if (entityType.membersCount() === 0) {
entityType.remove();
}
entityType = schema.builtInTypes<UnionType>('UnionType', true).find(u => u.name === entityTypeName)!
}
entityType.clearTypes();
for (const objectType of schema.types<ObjectType>("ObjectType")) {
if (isEntityType(objectType)) {
entityType.addType(objectType);
}
}
const hasEntities = entityType.membersCount() > 0;
if (!hasEntities) {
entityType.remove();
}
// Adds the _entities and _service fields to the root query type.
const queryRoot = schema.schemaDefinition.root("query");
const queryType = queryRoot ? queryRoot.type : schema.addType(new ObjectType("Query"));
const entityField = queryType.field(entitiesFieldName);
if (hasEntities) {
const anyType = schema.type(anyTypeName);
assert(anyType, `The schema should have the _Any type`);
const entityFieldType = new NonNullType(new ListType(entityType));
if (!entityField) {
this.addBuiltInField(queryType, entitiesFieldName, entityFieldType)
.addArgument('representations', new NonNullType(new ListType(new NonNullType(anyType))));
} else if (!entityField.type) {
// This can happen when the schema had an empty redefinition of _Entity as we've removed it in
// that clear and that would have clear the type of the correspond field. Let's re-populate it
// in that case.
entityField.type = entityType;
}
} else if (entityField) {
entityField.remove();
}
if (!queryType.field(serviceFieldName)) {
this.addBuiltInField(queryType, serviceFieldName, schema.type(serviceTypeName) as ObjectType);
}
}
onValidation(schema: Schema): GraphQLError[] {
// We skip the validation on tagDirective to have a more targeted error message later below
const errors = super.onValidation(schema, [tagDirectiveName]);
// We rename all root type to their default names (we do here rather than in `prepareValidation` because
// that can actually fail).
for (const k of allSchemaRootKinds) {
const type = schema.schemaDefinition.root(k)?.type;
const defaultName = defaultRootName(k);
if (type && type.name !== defaultName) {
// We first ensure there is no other type using the default root name. If there is, this is a
// composition error.
const existing = schema.type(defaultName);
if (existing) {
errors.push(error(
`ROOT_${k.toUpperCase()}_USED`,
`The schema has a type named "${defaultName}" but it is not set as the ${k} root type ("${type.name}" is instead): `
+ 'this is not supported by federation. '
+ 'If a root type does not use its default name, there should be no other type with that default name.',
sourceASTs(type, existing)
));
}
type.rename(defaultName);
}
}
const externalTester = new ExternalTester(schema);
const externalFieldsInFedDirectivesCoordinates: string[] = [];
// We validate the @key, @requires and @provides.
const keyDirective = this.keyDirective(schema);
validateAllFieldSet<CompositeType>(
keyDirective,
type => type,
type => `type "${type}"`,
errors,
externalTester,
externalFieldsInFedDirectivesCoordinates,
true,
true
);
// Note that we currently reject @requires where a leaf field of the selection is not external,
// because if it's provided by the current subgraph, why "requires" it? That said, it's not 100%
// nonsensical if you wanted a local field to be part of the subgraph fetch even if it's not
// truly queried _for some reason_. But it's unclear such reasons exists, so for now we prefer
// rejecting it as it also make it less likely user misunderstand what @requires actually do.
// But we could consider lifting that limitation if users comes with a good rational for allowing
// it.
validateAllFieldSet<FieldDefinition<CompositeType>>(
this.requiresDirective(schema),
field => field.parent,
field => `field "${field.coordinate}"`,
errors,
externalTester,
externalFieldsInFedDirectivesCoordinates,
false,
false,
);
// Note that like for @requires above, we error out if a leaf field of the selection is not
// external in a @provides (we pass `false` for the `allowOnNonExternalLeafFields` parameter),
// but contrarily to @requires, there is probably no reason to ever change this, as a @provides
// of a field already provides is 100% nonsensical.
validateAllFieldSet<FieldDefinition<CompositeType>>(
this.providesDirective(schema),
field => {
if (externalTester.isExternal(field)) {
throw new GraphQLError(`Cannot have both @provides and @external on field "${field.coordinate}"`, field.sourceAST);
}
const type = baseType(field.type!);
if (!isCompositeType(type)) {
throw new GraphQLError(
`Invalid @provides directive on field "${field.coordinate}": field has type "${field.type}" which is not a Composite Type`,
field.sourceAST);
}
return type;
},
field => `field ${field.coordinate}`,
errors,
externalTester,
externalFieldsInFedDirectivesCoordinates,
false,
false,
);
validateAllExternalFieldsUsed(schema, externalTester, externalFieldsInFedDirectivesCoordinates, errors);
// If tag is redefined by the user, make sure the definition is compatible with what we expect
const tagDirective = this.tagDirective(schema);
if (!tagDirective.isBuiltIn) {
const error = tagSpec.checkCompatibleDirective(tagDirective);
if (error) {
errors.push(error);
}
}
return errors;
}
validationRules(): readonly SDLValidationRule[] {
return FEDERATION_VALIDATION_RULES;
}
keyDirective(schema: Schema): DirectiveDefinition<{fields: any}> {
return this.getTypedDirective(schema, keyDirectiveName);
}
extendsDirective(schema: Schema): DirectiveDefinition<Record<string, never>> {
return this.getTypedDirective(schema, extendsDirectiveName);
}
externalDirective(schema: Schema): DirectiveDefinition<Record<string, never>> {
return this.getTypedDirective(schema, externalDirectiveName);
}
requiresDirective(schema: Schema): DirectiveDefinition<{fields: any}> {
return this.getTypedDirective(schema, requiresDirectiveName);
}
providesDirective(schema: Schema): DirectiveDefinition<{fields: any}> {
return this.getTypedDirective(schema, providesDirectiveName);
}
tagDirective(schema: Schema): DirectiveDefinition<{name: string}> {
return this.getTypedDirective(schema, tagDirectiveName);
}
maybeUpdateSubgraphDocument(schema: Schema, document: DocumentNode): DocumentNode {
document = super.maybeUpdateSubgraphDocument(schema, document);
const definitions = document.definitions.concat();
for (const directiveName of FEDERATION_DIRECTIVES) {
const directive = schema.directive(directiveName);
assert(directive, 'This method should only have been called on a schema with federation built-ins')
// If the directive is _not_ marked built-in, that means it was manually defined
// in the document and we don't need to add it. Note that `onValidation` will
// ensure that re-definition is valid.
if (directive.isBuiltIn) {
definitions.push(parse(printDirectiveDefinition(directive, defaultPrintOptions)).definitions[0]);
}
}
return {
kind: 'Document',
loc: document.loc,
definitions
};
}
}
export const federationBuiltIns = new FederationBuiltIns();
export function isFederationSubgraphSchema(schema: Schema): boolean {
return schema.builtIns instanceof FederationBuiltIns;
}
export function isFederationType(type: NamedType): boolean {
return isFederationTypeName(type.name);
}
export function isFederationTypeName(typeName: string): boolean {
return FEDERATION_TYPES.includes(typeName);
}
export function isFederationField(field: FieldDefinition<CompositeType>): boolean {
if (field.parent === field.schema().schemaDefinition.root("query")?.type) {
return FEDERATION_ROOT_FIELDS.includes(field.name);
}
return false;
}
export function isFederationDirective(directive: DirectiveDefinition | Directive): boolean {
return FEDERATION_DIRECTIVES.includes(directive.name);
}
export function isEntityType(type: NamedType): boolean {
return type.kind == "ObjectType" && type.hasAppliedDirective(keyDirectiveName);
}
function buildSubgraph(name: string, source: DocumentNode | string): Schema {
try {
return typeof source === 'string'
? buildSchema(new Source(source, name), federationBuiltIns)
: buildSchemaFromAST(source, federationBuiltIns);
} catch (e) {
if (e instanceof GraphQLError) {
throw addSubgraphToError(e, name);
} else {
throw e;
}
}
}
export function parseFieldSetArgument(
parentType: CompositeType,
directive: Directive<NamedType | FieldDefinition<CompositeType>, {fields: any}>,
fieldAccessor: (type: CompositeType, fieldName: string) => FieldDefinition<any> | undefined = (type, name) => type.field(name)
): SelectionSet {
return parseSelectionSet(parentType, validateFieldSetValue(directive), new VariableDefinitions(), undefined, fieldAccessor);
}
function validateFieldSetValue(directive: Directive<NamedType | FieldDefinition<CompositeType>, {fields: any}>): string {
const fields = directive.arguments().fields;
if (typeof fields !== 'string') {
throw new GraphQLError(
`Invalid value for argument ${directive.definition!.argument('fields')!.coordinate} on ${directive.parent.coordinate}: must be a string.`,
directive.sourceAST
);
}
return fields;
}
export interface ServiceDefinition {
typeDefs: DocumentNode;
name: string;
url?: string;
}
export function subgraphsFromServiceList(serviceList: ServiceDefinition[]): Subgraphs | GraphQLError[] {
let errors: GraphQLError[] = [];
const subgraphs = new Subgraphs();
for (const service of serviceList) {
try {
subgraphs.add(service.name, service.url ?? '', service.typeDefs);
} catch (e) {
const causes = errorCauses(e);
if (causes) {
errors = errors.concat(causes);
} else {
throw e;
}
}
}
return errors.length === 0 ? subgraphs : errors;
}
// Simple wrapper around a Subgraph[] that ensures that 1) we never mistakenly get 2 subgraph with the same name,
// 2) keep the subgraphs sorted by name (makes iteration more predictable). It also allow convenient access to
// a subgraph by name so behave like a map<string, Subgraph> in most ways (but with the previously mentioned benefits).
export class Subgraphs {
private readonly subgraphs = new OrderedMap<string, Subgraph>();
add(subgraph: Subgraph): Subgraph;
add(name: string, url: string, schema: Schema | DocumentNode | string): Subgraph;
add(subgraphOrName: Subgraph | string, url?: string, schema?: Schema | DocumentNode | string): Subgraph {
const toAdd: Subgraph = typeof subgraphOrName === 'string'
? new Subgraph(subgraphOrName, url!, schema instanceof Schema ? schema! : buildSubgraph(subgraphOrName, schema!))
: subgraphOrName;
if (toAdd.name === FEDERATION_RESERVED_SUBGRAPH_NAME) {
throw new GraphQLError(`Invalid name ${FEDERATION_RESERVED_SUBGRAPH_NAME} for a subgraph: this name is reserved`);
}
if (this.subgraphs.has(toAdd.name)) {
throw new Error(`A subgraph named ${toAdd.name} already exists` + (toAdd.url ? ` (with url '${toAdd.url}')` : ''));
}
this.subgraphs.add(toAdd.name, toAdd);
return toAdd;
}
get(name: string): Subgraph | undefined {
return this.subgraphs.get(name);
}
size(): number {
return this.subgraphs.size;
}
names(): readonly string[] {
return this.subgraphs.keys();
}
values(): readonly Subgraph[] {
return this.subgraphs.values();
}
*[Symbol.iterator]() {
for (const subgraph of this.subgraphs) {
yield subgraph;
}
}
toString(): string {
return '[' + this.subgraphs.keys().join(', ') + ']'
}
}
export class Subgraph {
constructor(
readonly name: string,
readonly url: string,
readonly schema: Schema,
validateSchema: boolean = true
) {
if (validateSchema) {
schema.validate();
}
}
toString() {
return `${this.name} (${this.url})`
}
}
export type SubgraphASTNode = ASTNode & { subgraph: string };
export function addSubgraphToASTNode(node: ASTNode, subgraph: string): SubgraphASTNode {
return {
...node,
subgraph
};
}
export function addSubgraphToError(e: GraphQLError, subgraphName: string): GraphQLError {
const updatedCauses = errorCauses(e)!.map(cause => new GraphQLError(
`[${subgraphName}] ${cause.message}`,
cause.nodes ? cause.nodes.map(node => addSubgraphToASTNode(node, subgraphName)) : undefined,
cause.source,
cause.positions,
cause.path,
cause.originalError,
cause.extensions
));
return ErrGraphQLValidationFailed(updatedCauses);
}
export class ExternalTester {
private readonly fakeExternalFields = new Set<string>();
constructor(readonly schema: Schema) {
this.collectFakeExternals();
}
private collectFakeExternals() {
const keyDirective = federationBuiltIns.keyDirective(this.schema);
if (!keyDirective) {
return;
}
for (const key of keyDirective.applications()) {
const parent = key.parent as CompositeType;
if (!(key.ofExtension() || parent.hasAppliedDirective(extendsDirectiveName))) {
continue;
}
try {
parseFieldSetArgument(parent, key as Directive<any, {fields: any}>, (parentType, fieldName) => {
const field = parentType.field(fieldName);
if (field && field.hasAppliedDirective(externalDirectiveName)) {
this.fakeExternalFields.add(field.coordinate);
}
return field;
});
} catch (e) {
// This is not the right time to throw errors. If a directive is invalid, we'll throw
// an error later anyway, so just ignoring it for now.
}
}
}
isExternal(field: FieldDefinition<any> | InputFieldDefinition) {
return field.hasAppliedDirective(externalDirectiveName) && !this.isFakeExternal(field);
}
isFakeExternal(field: FieldDefinition<any> | InputFieldDefinition) {
return this.fakeExternalFields.has(field.coordinate);
}
} | the_stack |
/// <reference path="Prelude.Core.dsc"/>
/**
* Glob files; if pattern is undefined, then the default is "*".
* Returns the empty array if the globed directory does not exist.
*/
declare function glob(folder: Directory, pattern?: string): File[];
/**
* Glob folders; if pattern is undefined, then the default is "*".
* Returns the empty array if the globed directory does not exist.
*/
declare function globFolders(folder: Directory, pattern?: string, isRecursive?: Boolean): Directory[];
/**
* Glob files recursively; if pattern is undefined, then the default is "*"
* Returns the empty array if the globed directory does not exist.
*/
declare function globR(folder: Directory, pattern?: string): File[];
declare function globRecursively(folder: Directory, pattern?: string): File[];
/**
* Import require
* This function returns undefined if the first argument cannot be resolved.
*/
declare function importFrom(name: string, qualifier?: any): any;
declare function importFile(path: File, qualifier?: any): any;
/**
* This method is obsolete and will be removed soon.
* Use importFrom instead.
*/
declare function require(path: File | string, qualifier?: any): any;
/**
* Represents path atoms: path segments and extensions.
*/
interface PathAtom {
__brandPath: any;
/** Turns this path atom into a relative path. */
asRelativePath: () => RelativePath;
/**
* Changes the extension of a path atom and fails with an error if the extension is not a valid PathAtom.
* Use the empty string as an argument for removing the extension.
* If the path atom doesn't have an extension, the specified extension is appended.
*/
changeExtension: (extension: PathAtomOrString) => PathAtom;
/** Concats path atoms; fails with an error if the provided path atom is invalid. */
concat: (atom: PathAtomOrString) => PathAtom;
/**
* Checks if this path atom equals the argument. If ignoreCase argument is absent,
* then the check will be based on file name comparison rules of the current operating system.
*/
equals: (atom: PathAtomOrString, ignoreCase?: boolean) => boolean;
/** Gets the extension; returns undefined when the extension is missing. */
getExtension: () => PathAtom;
/** Gets the extension; returns undefined when the extension is missing. */
extension: PathAtom;
/** Checks if this path atom has an extension. */
hasExtension: () => boolean;
/* Returns a string representation of this path atom */
toString: () => string;
@@obsolete('Use "concat" method instead')
extend: (atom: PathAtomOrString) => Path;
}
/**
* This is a temporary workaround till we have a specific built-in syntax to build a PathAtom literal. E.g. '@literal' or |literal|
*/
namespace PathAtom {
/** Creates a path atom from a string. */
export declare function create(value: string): PathAtom;
/** Creates a path atom by interpolation. */
export declare function interpolate(value: PathAtomOrString, ...rest: PathAtomOrString[]);
}
/**
* Atom can be a string or a path atom.
* This type is a shorthand for writing signatures of methods of path atoms and absolute paths.
* TODO: this might be the indicator of the need of implicit conversion (string -> PathAtom) or function overloading
*/
type PathAtomOrString = PathAtom | string;
/**
* Represents relative paths.
*/
interface RelativePath {
/**
* Changes the extension of this relative path and fails with an error if the extension is not a valid PathAtom.
* Use the empty string as an argument for removing the extension.
* If the path atom doesn't have an extension, the specified extension is appended.
*/
changeExtension: (extension: PathAtomOrString) => RelativePath;
/**
* Extends this relative path with new path components.
* Example:
* RelativePath.create("a/b/c").combine("d/e/f") == RelativePath.create("a/b/c/d/e/f").
*/
combine: (fragment: PathFragment) => RelativePath;
/**
* Extends this relative path with a sequence of new path components.
* This method provides a convenient way to combine relative paths.
* Example:
* let fragments = ["d/e/f", "g/h/i"];
* RelativePath.create("a/b/c").combinePaths(...fragments) == RelativePath.create("a/b/c/d/e/f/g/h/i").
*/
combinePaths: (...fragments: PathFragment[]) => RelativePath;
/**
* Concatenates a path atom to the end of this relative path.
* Example:
* RelativePath.create("a/b/c").concat("xyz") == RelativePath.create("a/b/cxyz").
*/
concat: (atom: PathAtomOrString) => RelativePath;
/**
* Checks if this relative path equals the argument. If ignoreCase argument is absent,
* then the check will be based on file name comparison rules of the current operating system.
*/
equals: (fragment: RelativePath | string, ignoreCase?: boolean) => boolean;
/** Gets the extension; returns undefined when the extension is missing. */
getExtension: () => PathAtom;
/** Gets the extension; returns undefined when the extension is missing. */
extension: PathAtom;
/**
* Gets the parent of this relative path, i.e., removes the last segment of the relative path.
* Returns undefined if this relative path has no parent.
*/
parent: RelativePath;
/** Gets the last component of this relative path, and returns undefined if this relative path is empty. */
name: PathAtom;
/** Gets the last component of this relative path without extension, and returns undefined if this relative path is empty. */
getNameWithoutExtension: () => PathAtom;
/** Gets the last component of this relative path without extension, and returns undefined if this relative path is empty. */
nameWithoutExtension: PathAtom;
/** Checks if this relative path has an extension. */
hasExtension: () => boolean;
/** Checks if this relative path has a parent. */
hasParent: () => boolean;
/** Converts to an array of path atoms. */
toPathAtoms: () => PathAtom[];
/* Returns a string representation of this relative path. */
toString: () => string;
}
namespace RelativePath {
/**
* Creates a relative path from a string.
* Example:
* let x = RelativePath.create("a/b/c");
*/
export declare function create(value: string): RelativePath;
/**
* Creates a relative path from an array of path atoms.
* Example:
* RelativePath.fromPathAtoms(PathAtom.create("a"), "b", "c") == RelativePath.create("a/b/c").
*/
export declare function fromPathAtoms(...atoms: PathAtomOrString[]): RelativePath;
/** Creates a relative path by interpolation. */
export declare function interpolate(value: PathFragment, ...rest: PathFragment[]);
}
type PathFragment = PathAtom | RelativePath | string;
interface PathQueries {
/**
* Gets the path extension; returns undefined for invalid extension.
*/
extension: PathAtom;
/**
* Checks if this path has an extension.
*/
hasExtension: () => boolean;
/**
* Gets the parent of this path, i.e., removes the last segment of the path.
* Returns undefined if the path has no parent.
*/
parent: Path;
/**
* Checks if this path has a parent.
*/
hasParent: () => boolean;
/**
* Gets the last component of this path.
*/
name: PathAtom;
/**
* Gets the last component of this path without extension.
* This method is equal to .name.changeExtension("").
*/
nameWithoutExtension: PathAtom;
/**
* Checks if this path is within the specified container.
*/
isWithin: (container: Path | Directory | StaticDirectory) => boolean;
/**
* Gets the relative path of this path with respect to the argument.
* Returns undefined if the provided Path is not a descendant path of this path.
* */
getRelative: (relativeTo: Path) => RelativePath;
/**
* Returns this path.
* This method is useful so that paths can be used to denote source files.
*/
path: Path;
/**
* Gets the root of the path. On windows file systems this will be the drive letter for example: 'c:', on unix filesystems this will be '/'
*/
pathRoot: Path;
/**
* Helper method to get a file or path printed as a string for diagnostic purposes.
* The result will be OS specific.
*
* !!! WARNING !!!
* The result of this function should NEVER be used on a command-line, response file or file written to disk.
* This string should only be used for diagnostic purposes.
* If this string is used in a Pip, BuildXL loses the ability to:
* - Canonicalize the paths cross platform,
* - Normalize the paths for shared cache. i.e. c:\windows vs d:\windows on other machines, or folders with the current user
* - Compress the paths in all storage forms
* Doing this risks breaking caching, distribution and shared cache.
*/
toDiagnosticString: () => string;
/**
* Just for testing
* Returns the string representation of a path (without the factory methods)
*/
toProperString(): string;
/**
* Just for testing, same as getParent but internally flagged as obsolete
*/
getParentObsolete(): Path;
/**
* Just for testing, same as getParent but internally flagged as obsolete
*/
forTestObsolete(): Path;
}
interface PathCombineLike {
/**
* Extends this path with the specified path fragment.
* The string can represent either a path atom (e.g. "csc.exe") or a relative path (e.g. "a/b/csc.exe").
* Abandons if the provided atom can't be a valid relative path.
*/
combine: (fragment: PathFragment) => Path;
/**
* Extends this path with the specified list of path fragments.
* Each string can represent either a path atom (e.g. "csc.exe") or a relative path (e.g. "a/b/csc.exe").
* Abandons if any of the provided atoms can't be a valid path atom.
* This method provides a convenient way to combine path fragments.
* Example:
* let fragments = ["a/b", "c/d", "e/f"];
* let outDir = 'bin/debug';
* let fullOutPath = outDir.combinePaths(...fragments);
* Of course you can also do it as
* let fullOutPath = outDir.combine(fragments.join("/"));
* but if fragments is an array of path atoms or relative paths, then array join cannot be used.
*/
combinePaths: (...fragments: PathFragment[]) => Path;
}
/**
* Represents an absolute path.
*
* To create a Path from a string, use call the 'p' function:
*
* p`my_path_as_string`
*/
interface Path extends PathQueries, PathCombineLike {
__brandPath: any;
/**
* Changes extension of a path and abandons if the extension is not a valid PathAtom.
* Use the empty string as an argument for removing the extension.
*/
changeExtension: (extension: PathAtomOrString) => Path;
/**
* Relocates this path from its container (source container) to a new target container, possibly giving a new extension.
* Abandons if the new extension is provided and it can't be a valid path atom.
* Returns undefined if the path is not within the specified container.
* */
relocate: (sourceContainer: Directory | StaticDirectory, targetContainer: Directory | StaticDirectory, newExt?: PathAtomOrString) => Path;
/**
* Extends path by a string or path atom at the, e.g., 'a/b/Foo'.concat("Bar") === 'a/b/FooBar'.
*/
concat: (atom: PathAtomOrString) => Path;
/**
* Extends path by a string or path atom at the, e.g., 'a/b/Foo'.extend("Bar") === 'a/b/FooBar'.
* This method is obsolete, use concat.
*/
@@obsolete('use concat')
extend: (atom: PathAtomOrString) => Path;
/**
* Returns a string representation of this path.
* The string representation has an invalid path character. This character is a mechanism
* to prevents users (although not bullet-proof) from using paths and strings interchangeably.
*/
toString: () => string;
}
namespace Path {
export declare function interpolate(root: Path | Directory | StaticDirectory, ...rest: PathFragment[]): Path;
/**
* A helper for when you dynamically read paths from a file and you need to create absolute paths.withQualifier
* For all other path construction cases. Please use the p`...` patterns to maintain good readability.
**/
export declare function createFromAbsolutePathString(absPath: string) : Path;
}
/**
* Represents a source directory artifact.
*
* To create a Directory from a string, call the 'd' function, i.e.:
*
* d`my_path_as_string`
*/
interface Directory extends PathQueries, PathCombineLike {
__directoryBrand: any;
/**
* Returns a string representation of this directory.
* The string representation has an invalid path character. This character is a mechanism
* to prevents users (although not bullet-proof) from using paths and strings interchangeably.
*/
toString: () => string;
}
/** Files are either source or ss. */
interface File extends PathQueries {
/**
* Returns a string representation of this derived file.
* The string representation has an invalid path character. This character is a mechanism
* to prevents users (although not bullet-proof) from using paths and strings interchangeably.
* Moreover, the string representation includes the rewrite count of this file.
*/
toString: () => string;
}
/** Derived files represent artifacts generated during a build. */
interface DerivedFile extends File {
__derivedFileBrand: any;
}
/**
* SourceFile represents a file that is not an artifact generated during a build.
*
* To create a SourceFile from a string, call the 'f' function, i.e.:
*
* f`my_path_as_string`
*/
interface SourceFile extends File {
__sourceFileBrand: any;
}
/** All the available flavors of static directories */
type StaticDirectoryKind = "shared" | "exclusive" | "sourceAllDirectories" | "sourceTopDirectories" | "full" | "partial";
/**
* Represents a sealed Directory that has statically-known contents.
*/
interface StaticDirectory extends PathQueries {
__staticDirectoryBrand: any;
/** Gets the root directory. */
root: Directory;
/** The kind of a static directory */
kind: StaticDirectoryKind;
/** Gets the sealed directory. */
/** This method will be deprecated in favour of root property. */
getSealedDirectory: () => Directory;
/** Gets the file given its path; returns undefined if no such a file exists in this static directory. */
getFile: (path: Path | PathFragment) => File;
/** Gets an array of files given its paths; returns undefined in the result array if no such a file exists in this static directory. */
getFiles: (path: (Path | PathFragment)[]) => File[];
/**
* Asserts that a given file is part of the directory.
* For opaque directories, the check is delayed to runtime execution. Otherwise, this is equivalent to getFile()
*/
assertExistence: (path: Path | PathFragment) => File;
/** ensures the subFolder exists in the sealed directory and will return a new sealed directory scoped to that subdirectory */
ensureContents: (args: {subFolder: RelativePath}) => StaticDirectory;
/** Checks whether the sealed directory has the given file. */
hasFile: (path: Path | PathFragment) => boolean;
/** Gets the contents of this static directory. */
contents: File[];
/** Gets the content of this static directory. */
/** This method will be deprecated in favour of contents property. */
getContent: () => File[];
/**
* Returns a string representation of this static directory.
* The string representation has an invalid path character. This character is a mechanism
* to prevents users (although not bullet-proof) from using paths and strings interchangeably.
*/
toString: () => string;
}
/** A shared opaque directory. Its static content is always empty. */
interface SharedOpaqueDirectory extends StaticDirectory {
kind: "shared"
}
/** An exclusive opaque directory. Its static content is always empty. */
interface ExclusiveOpaqueDirectory extends StaticDirectory {
kind: "exclusive"
}
/** A source sealed directory where only the top directory is sealed. Its static content is always empty. */
interface SourceTopDirectory extends StaticDirectory {
kind: "sourceTopDirectories"
}
/** A source sealed directory where all directories, recursively, are sealed. Its static content is always empty. */
interface SourceAllDirectory extends StaticDirectory {
kind: "sourceAllDirectories"
}
/** A fully sealed directory. Its content is known statically and can be retrieved. */
interface FullStaticContentDirectory extends StaticDirectory {
kind: "full"
}
/** A partial sealed directory. Its content is known statically and can be retrieved. */
interface PartialStaticContentDirectory extends StaticDirectory {
kind: "partial"
}
/**
* Directory-related types that group semantically related directories, mainly for convenience
*/
type StaticContentDirectory = FullStaticContentDirectory | PartialStaticContentDirectory;
type SourceDirectory = SourceTopDirectory | SourceAllDirectory;
type OpaqueDirectory = SharedOpaqueDirectory | ExclusiveOpaqueDirectory;
// -----------------------------------------------------------
// Factory functions for creating path-related artifacts.
// -----------------------------------------------------------
/** Text encoding. */
const enum TextEncoding {
ascii = 0,
bigEndianUnicode,
unicode,
utf32,
utf7,
utf8
}
namespace File {
/** Returns a file artifact located at a given path (no actual file is created on disk!) */
export declare function fromPath(p: Path): File;
/**
* Read a source file as text.
* The source file will be tracked by the input tracker of BuildXL's engine, in the same way as spec files.
* Note that since it takes a source file as an input, this function cannot be used to read a derived file,
* or a file produced by a pip.
*/
export declare function readAllText(file: SourceFile, encoding?: TextEncoding): string;
/** Returns true if a given file exists on disk. */
export declare function exists(path: SourceFile): boolean;
}
namespace Directory {
/** Returns a directory artifact located at a given path (no actual directory is created on disk!) */
export declare function fromPath(p: Path): Directory;
/** Returns true if a given directory exists on disk. */
export declare function exists(path: Directory): boolean;
}
namespace Path {
export declare function interpolate(root: Path | Directory | StaticDirectory, ...rest: PathFragment[]): Path;
}
/** Creates an absolute path from a string. */
declare function p(format: string, ...args: any[]): Path;
/** Creates a directory artifact (doesn't create a physical directory in the file system). */
declare function d(format: string, ...args: any[]): Directory;
/** Creates a file artifact (doesn't create a physical file in the file system). */
declare function f(format: string, ...args: any[]): SourceFile;
/** Creates a relative path from a string. */
declare function r(format: string, ...args: any[]): RelativePath;
/** Creates a path atom from a string. */
declare function a(format: string, ...args: any[]): PathAtom; | the_stack |
import { testStartup } from '../testMain';
import {expect} from 'chai';
import { runQuery } from '../../server/vulcan-lib';
import { createDummyUser, createDummyPost, createDummyComment, userUpdateFieldSucceeds, userUpdateFieldFails, catchGraphQLErrors, assertIsPermissionsFlavoredError } from '../utils'
testStartup();
import Users from '../../lib/collections/users/collection';
import { userIsBannedFromPost, userIsBannedFromAllPosts, userIsAllowedToComment, userCanModeratePost, userCanEditUsersBannedUserIds } from '../../lib/collections/users/helpers';
describe('userIsBannedFromPost --', () => {
it('returns false if post.bannedUserIds does not contain exist', async () => {
const user = await createDummyUser()
const author = await createDummyUser({groups:['trustLevel1']})
const post = await createDummyPost(author)
expect(userIsBannedFromPost(user, post, author)).to.equal(false)
})
it('returns false if post.bannedUserIds does not contain user._id', async () => {
const user = await createDummyUser()
const author = await createDummyUser({groups:['trustLevel1']})
const post = await createDummyPost(author, {bannedUserIds:['notUserId']})
expect(userIsBannedFromPost(user, post, author)).to.equal(false)
})
it('returns true if post.bannedUserIds contain user._id but post.user is NOT in trustLevel1', async () => {
const user = await createDummyUser()
const author = await createDummyUser()
const post = await createDummyPost(author, {bannedUserIds:[user._id]})
expect(userIsBannedFromPost(user, post, author)).to.equal(true)
})
it('returns true if post.bannedUserIds contain user._id AND post.user is in trustLevel1', async () => {
const user = await createDummyUser()
const author = await createDummyUser({groups:['trustLevel1']})
const post = await createDummyPost(author, {bannedUserIds:[user._id]})
expect(userIsBannedFromPost(user, post, author)).to.equal(true)
})
})
describe('userIsBannedFromAllPosts --', () => {
it('returns false if post.user.bannedUserIds does not contain exist', async () => {
const user = await createDummyUser()
const author = await createDummyUser({groups:['trustLevel1']})
const post = await createDummyPost(author)
expect(userIsBannedFromAllPosts(user, post, author)).to.equal(false)
})
it('returns false if post.bannedUserIds does not contain user._id', async () => {
const user = await createDummyUser()
const author = await createDummyUser({groups:['trustLevel1'], bannedUserIds:['notUserId']})
const post = await createDummyPost(author)
expect(userIsBannedFromAllPosts(user, post, author)).to.equal(false)
})
it('returns false if post.bannedUserIds contain user._id but post.user is NOT in trustLevel1', async () => {
const user = await createDummyUser()
const author = await createDummyUser({bannedUserIds:[user._id]})
const post = await createDummyPost(author)
expect(userIsBannedFromAllPosts(user, post, author)).to.equal(false)
})
it('returns true if post.bannedUserIds contain user._id AND post.user is in trustLevel1', async () => {
const user = await createDummyUser()
const author = await createDummyUser({groups:['trustLevel1'], bannedUserIds:[user._id]})
const post = await createDummyPost(author)
expect(userIsBannedFromAllPosts(user, post, author)).to.equal(true)
})
})
describe('userIsAllowedToComment --', () => {
it('returns false if there is no user', async () => {
const author = await createDummyUser();
const post = await createDummyPost(author);
expect(userIsAllowedToComment(null, post, author)).to.equal(false)
})
//it('returns true if passed a user but NOT post', async () => {
// //Unit test removed because post is now a required argument (enforced by type signature)
// const user = await createDummyUser()
// expect(userIsAllowedToComment(user, null, null)).to.equal(true)
//})
it('returns true if passed a user AND post does NOT contain bannedUserIds OR user', async () => {
const user = await createDummyUser()
const post = await createDummyPost()
expect(userIsAllowedToComment(user, post, null)).to.equal(true)
})
it('returns true if passed a user AND post contains bannedUserIds but NOT user', async () => {
const user = await createDummyUser()
const post = await createDummyPost(null, {bannedUserIds:[user._id]})
expect(userIsAllowedToComment(user, post, null)).to.equal(true)
})
it('returns false if passed a user AND post contains bannedUserIds BUT post-user is NOT in trustLevel1', async () => {
const user = await createDummyUser()
const author = await createDummyUser()
const post = await createDummyPost(author, {bannedUserIds:[user._id]})
expect(userIsAllowedToComment(user, post, author)).to.equal(false)
})
it('returns false if passed a user AND post contains bannedUserIds AND post-user is in trustLevel1', async () => {
const user = await createDummyUser()
const author = await createDummyUser({groups:['trustLevel1']})
const post = await createDummyPost(author, {bannedUserIds:[user._id]})
expect(userIsAllowedToComment(user, post, author)).to.equal(false)
})
})
describe('Posts Moderation --', function() {
let graphQLerrors = catchGraphQLErrors();
it('CommentsNew should succeed if user is not in bannedUserIds list', async function() {
const user = await createDummyUser()
const post = await createDummyPost()
const query = `
mutation CommentsNew {
createComment(data:{postId: "${post._id}", contents: {originalContents: {type: "markdown", data: "test"}}}){
data {
postId
contents {
markdown
}
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { createComment: {data: { postId: post._id, contents: { markdown:"test" } } } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
});
it('new comment on a post should fail if user in Post.bannedUserIds list', async () => {
const user = await createDummyUser({groups:['trustLevel1']})
const post = await createDummyPost(user, {bannedUserIds:[user._id]})
const query = `
mutation CommentsNew {
createComment(data:{postId: "${post._id}", contents: { originalContents: { type: "markdown", data: "test" } } }){
data {
contents {
markdown
}
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
await (response as any).should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
});
it('new comment on a post should fail if user in User.bannedUserIds list and post.user is in trustLevel1', async () => {
const secondUser = await createDummyUser()
const user = await createDummyUser({groups:['trustLevel1'], bannedUserIds:[secondUser._id]})
const post = await createDummyPost(user)
const query = `
mutation CommentsNew {
createComment(data:{postId:"${post._id}", contents: {originalContents: { type: "markdown", data: "test" } } }){
data {
contents {
markdown
}
userId
}
}
}
`;
const response = runQuery(query, {}, {currentUser:secondUser})
await (response as any).should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
});
it('new comment on a post should succeed if user in User.bannedUserIds list but post.user is NOT in trustLevel1', async () => {
const secondUser = await createDummyUser()
const user = await createDummyUser({bannedUserIds:[secondUser._id]})
const post = await createDummyPost(user)
const query = `
mutation CommentsNew {
createComment(data:{postId:"${post._id}", contents: { originalContents: {type: "markdown", data: "test" } } }){
data {
contents {
markdown
}
postId
}
}
}
`;
const response = runQuery(query, {}, {currentUser:secondUser})
const expectedOutput = { data: { createComment: { data: {postId: post._id, contents: {markdown: "test"} } } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
});
});
describe('User moderation fields --', () => {
let graphQLerrors = catchGraphQLErrors();
it("new trusted users do not have a moderationStyle", async () => {
const user = await createDummyUser({groups:["trustLevel1"]})
expect(user.moderationStyle).to.equal(undefined)
});
it("non-trusted users can set their moderationStyle", async () => {
const user = await createDummyUser()
const query = `
mutation UsersUpdate {
updateUser(selector: {_id: "${user._id}"}, data: {moderationStyle:"easy-going"}) {
data {
moderationStyle
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { updateUser: {data: { moderationStyle: "easy-going" } } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
});
it("non-trusted users can set their moderationGuidelines", async () => {
const user = await createDummyUser()
const query = `
mutation UsersUpdate {
updateUser(selector: {_id: "${user._id}"}, data: {moderationGuidelines: {originalContents: {type: "markdown", data: "blah"}}}) {
data {
moderationGuidelines {
markdown
}
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { updateUser: { data: {moderationGuidelines: {markdown: "blah"} } } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
});
it("non-trusted users can set their moderatorAssistance", async () => {
const user = await createDummyUser()
const query = `
mutation UsersUpdate {
updateUser(selector: {_id: "${user._id}"}, data: {moderatorAssistance: true}) {
data {
moderatorAssistance
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { updateUser: { data: {moderatorAssistance: true} } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
});
it("trusted users can set their moderationStyle", async () => {
const user = await createDummyUser({groups:["trustLevel1"]})
const query = `
mutation UsersUpdate {
updateUser(selector: {_id: "${user._id}"}, data: {moderationStyle:"easy-going"}) {
data {
moderationStyle
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { updateUser: {data: { moderationStyle: "easy-going" } } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
});
it("trusted users can set their moderationGuidelines", async () => {
const user = await createDummyUser({groups:["trustLevel1"]})
const query = `
mutation UsersUpdate {
updateUser(selector: {_id: "${user._id}"}, data: {moderationGuidelines: {originalContents: {type: "markdown", data: "blah"}}}) {
data {
moderationGuidelines {
markdown
}
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { updateUser: { data: {moderationGuidelines: {markdown: "blah"}} } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
});
it("trusted users can set their moderatorAssistance", async () => {
const user = await createDummyUser({groups:["trustLevel1"]})
const query = `
mutation UsersUpdate {
updateUser(selector: {_id: "${user._id}"}, data: {moderatorAssistance: true}) {
data {
moderatorAssistance
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { updateUser: { data: {moderatorAssistance: true} } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
});
it("trusted users can NOT set other user's moderationGuidelines", async () => {
const user = await createDummyUser({groups:["trustLevel1"]})
const user2 = await createDummyUser({groups:["trustLevel1"]})
const query = `
mutation UsersUpdate {
updateUser(selector: {_id: "${user._id}"}, data: {moderationGuidelines: {originalContents: {data:"assad", type: "markdown"}}}) {
data {
moderationGuidelines {
markdown
}
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user2})
await (response as any).should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
});
})
/*describe('PostsEdit bannedUserIds permissions --', ()=> {
let graphQLerrors = catchGraphQLErrors(beforeEach, afterEach);
it("PostsEdit bannedUserIds should succeed if user in trustLevel1, owns post and has moderationGuidelines set on the post", async () => {
const user = await createDummyUser({moderationStyle:"easy-going", groups:["trustLevel1"]})
const post = await createDummyPost(user, {moderationGuidelines: {originalContents: {type: "html", data: "beware"}}})
const testBannedUserIds = "test"
const query = `
mutation PostsEdit {
updatePost(selector: {_id :"${post._id}"},data: {bannedUserIds:["${testBannedUserIds}"]}) {
data {
bannedUserIds
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { updatePost: { data: {bannedUserIds: [testBannedUserIds]} } } }
return response.should.eventually.deep.equal(expectedOutput);
})
it("PostsEdit bannedUserIds should fail if user owns post, has set moderationStyle, and is NOT in trustLevel1", async () => {
const user = await createDummyUser({moderationStyle:"easy-going"})
const post = await createDummyPost(user)
const testBannedUserIds = "test"
const query = `
mutation PostsEdit {
updatePost(selector: {_id :"${post._id}"},data: {bannedUserIds:["${testBannedUserIds}"]}) {
data {
bannedUserIds
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
await response.should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
it("PostsEdit bannedUserIds should fail if user in TrustLevel1, has set moderationStyle, and does NOT own post", async () => {
const user = await createDummyUser({moderationStyle:"easy-going", groups:["trustLevel1"]})
const otherUser = await createDummyUser()
const post = await createDummyPost(otherUser)
const testBannedUserIds = "test"
const query = `
mutation PostsEdit {
updatePost(selector: {_id :"${post._id}"},data: {bannedUserIds:["${testBannedUserIds}"]}) {
data {
bannedUserIds
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
await response.should.be.rejected
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
it("PostsEdit bannedUserIds should fail if user in trustLevel1, owns post, but has NOT set moderationStyle", async () => {
const user = await createDummyUser({groups:["trustLevel1"]})
const post = await createDummyPost(user)
const testBannedUserIds = "test"
const query = `
mutation PostsEdit {
updatePost(selector: {_id :"${post._id}"},data: {bannedUserIds:["${testBannedUserIds}"]}) {
data {
bannedUserIds
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
await response.should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
})*/
describe('UsersEdit bannedUserIds permissions --', ()=> {
let graphQLerrors = catchGraphQLErrors(beforeEach, afterEach);
it("usersEdit bannedUserIds should succeed if user in trustLevel1", async () => {
const user = await createDummyUser({groups:["trustLevel1"]})
const testBannedUserIds = "test"
const query = `
mutation UsersEdit {
updateUser(selector: {_id :"${user._id}"},data: {bannedUserIds:["${testBannedUserIds}"]}) {
data {
bannedUserIds
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { updateUser: { data: {bannedUserIds: ["test"] } } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
})
it("usersEdit bannedUserIds should fail if user has set moderationStyle and in trustLevel1 but is NOT the target user ", async () => {
const user = await createDummyUser({groups:["trustLevel1"], moderationStyle:"easy"})
const user2 = await createDummyUser({groups:["trustLevel1"], moderationStyle:"easy"})
const testBannedUserIds = "test"
const query = `
mutation UsersEdit {
updateUser(selector: {_id :"${user._id}"},data: {bannedUserIds:["${testBannedUserIds}"]}) {
data {
bannedUserIds
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user2})
await (response as any).should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
})
describe('userCanModeratePost --', ()=> {
// TODO - rewrite this to pass in user data based on fragments where this function is called
it("returns false if user is undefined", async () => {
const author = await createDummyUser({groups:['trustLevel1']})
const post = await createDummyPost(author)
expect(userCanModeratePost(null, post)).to.be.false;
})
it("returns false if post is undefined", async () => {
const author = await createDummyUser({groups:['trustLevel1']})
expect(userCanModeratePost(author, null)).to.be.false;
})
it("returns false if user not in trustLevel1, sunshineRegiment or admins", async () => {
const author = await createDummyUser()
const post = await createDummyPost(author)
expect(userCanModeratePost(author, post)).to.be.false;
})
it("returns false if user in trustLevel1 but does NOT own post", async () => {
const author = await createDummyUser({groups:['trustLevel1']})
const post = await createDummyPost()
expect(userCanModeratePost(author, post)).to.be.false;
})
it("returns false if user in trustLevel1 AND owns post but has NOT set user.moderationStyle", async () => {
const author = await createDummyUser({groups:['trustLevel1']})
const post = await createDummyPost(author)
expect(userCanModeratePost(author, post)).to.be.false;
})
it("returns true if user in trustLevel1 AND owns post AND has moderationGuidelines", async () => {
const author = await createDummyUser({groups:['trustLevel1'], moderationStyle:"1"})
const post = await createDummyPost(author, {moderationGuidelines: {originalContents: {type: "html", data: "beware"}}})
expect(userCanModeratePost(author, post)).to.be.true;
})
it("returns true if user in sunshineRegiment", async () => {
const moderator = await createDummyUser({groups:['sunshineRegiment']})
const post = await createDummyPost()
expect(userCanModeratePost(moderator, post)).to.be.true;
})
})
describe('userCanEditUsersBannedUserIds --', ()=> {
// TODO - rewrite this to pass in user data based on fragments where this function is called
it("returns false if currentUser is undefined", async () => {
const user = await Users.findOneArbitrary()
if (!user) throw Error("Can't find any user")
expect(userCanEditUsersBannedUserIds(null, user)).to.be.false;
})
it("returns false if user not in trustLevel1", async () => {
const user = await createDummyUser()
expect(userCanEditUsersBannedUserIds(user, user)).to.be.false;
})
it("returns false if user in trustLevel1 but does has NOT set user.moderationStyle", async () => {
const user = await createDummyUser({groups:['trustLevel1']})
expect(userCanEditUsersBannedUserIds(user, user)).to.be.false;
})
it("returns true if user in trustLevel1 AND has set user.moderationStyle", async () => {
const user = await createDummyUser({groups:['trustLevel1'], moderationStyle:"1"})
expect(userCanEditUsersBannedUserIds(user, user)).to.be.true;
})
it("returns true if user in sunshineRegiment", async () => {
const user = await createDummyUser({groups:['sunshineRegiment']})
expect(userCanEditUsersBannedUserIds(user, user)).to.be.true;
})
})
describe('Comments deleted permissions --', function() {
let graphQLerrors = catchGraphQLErrors(beforeEach, afterEach);
it("updateComment – Deleted should succeed if user in sunshineRegiment", async function() {
const user = await createDummyUser({groups:["sunshineRegiment"]})
const commentAuthor = await createDummyUser()
const post = await createDummyPost(user)
const comment = await createDummyComment(commentAuthor, {postId: post._id})
return userUpdateFieldSucceeds({ user:user, document:comment,
fieldName:'deleted', newValue: true, collectionType: "Comment"
})
})
it("CommentsEdit set Deleted should fail if user is trustLevel1 and has set moderationStyle", async () => {
const user = await createDummyUser({groups:["trustLevel1"], moderationStyle:"easy"})
const commentAuthor = await createDummyUser()
const post = await createDummyPost(user)
const comment = await createDummyComment(commentAuthor, {postId:post._id})
await userUpdateFieldFails({ user:user, document:comment,
fieldName:'deleted', newValue: true, collectionType: "Comment"
})
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
it("CommentsEdit set Deleted should fail if user is alignmentForum", async () => {
const user = await createDummyUser({groups:["alignmentForum"]})
const commentAuthor = await createDummyUser()
const post = await createDummyPost(user)
const comment = await createDummyComment(commentAuthor, {postId:post._id})
await userUpdateFieldFails({ user:user, document:comment, fieldName:'deleted', newValue: true, collectionType: "Comment"})
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
it("moderateComment set deleted should succeed if user in sunshineRegiment", async () => {
const user = await createDummyUser({groups:["sunshineRegiment"]})
const commentAuthor = await createDummyUser()
const post = await createDummyPost(user)
const comment = await createDummyComment(commentAuthor, {postId:post._id})
const query = `
mutation {
moderateComment(commentId:"${comment._id}",deleted:true) {
deleted
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { moderateComment: { deleted: true } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
})
it("set deleted should succeed if user in trustLevel1, has set moderationGuidelines and owns post", async () => {
const user = await createDummyUser({groups:["trustLevel1"], moderationStyle:"easy"})
const commentAuthor = await createDummyUser()
const post = await createDummyPost(user, {moderationGuidelines: {originalContents: {type: "html", data: "beware"}}})
const comment = await createDummyComment(commentAuthor, {postId:post._id})
const query = `
mutation {
moderateComment(commentId:"${comment._id}",deleted:true) {
deleted
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { moderateComment: { deleted: true } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
})
it("set deleted should fail if user in trustLevel1, owns post but NOT set moderationGuidelines", async () => {
const user = await createDummyUser({groups:["trustLevel1"]})
const commentAuthor = await createDummyUser()
const post = await createDummyPost(user)
const comment = await createDummyComment(commentAuthor, {postId:post._id})
const query = `
mutation {
moderateComment(commentId:"${comment._id}",deleted:true) {
deleted
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
await (response as any).should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
it("set deleted should fail if user in trustLevel1, has set moderationStyle but does NOT own post", async () => {
const user = await createDummyUser({groups:["trustLevel1"], moderationStyle:"easy"})
const commentAuthor = await createDummyUser()
const post = await createDummyPost(commentAuthor)
const comment = await createDummyComment(commentAuthor, {postId:post._id})
const query = `
mutation {
moderateComment(commentId:"${comment._id}",deleted:true) {
deleted
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
await (response as any).should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
it("set deleted should fail if user has set moderationStyle, owns post but is NOT in trustLevel1", async () => {
const user = await createDummyUser({moderationStyle:"easy"})
const commentAuthor = await createDummyUser()
const post = await createDummyPost(user)
const comment = await createDummyComment(commentAuthor, {postId:post._id})
const query = `
mutation {
moderateComment(commentId:"${comment._id}",deleted:true) {
deleted
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
await (response as any).should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
})
describe('CommentLock permissions --', ()=> {
let graphQLerrors = catchGraphQLErrors(beforeEach, afterEach);
it("PostsEdit.commentLock should succeed if user in sunshineRegiment", async () => {
const user = await createDummyUser({groups:["sunshineRegiment"]})
const author = await createDummyUser()
const post = await createDummyPost(author)
const query = `
mutation PostsEdit {
updatePost(selector: {_id:"${post._id}"},data:{commentsLocked:true}) {
data {
commentsLocked
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
const expectedOutput = { data: { updatePost: { data: {commentsLocked: true} } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
})
it("PostsEdit.commentLock should fail if user is rando", async () => {
const user = await createDummyUser()
const author = await createDummyUser()
const post = await createDummyPost(author)
const query = `
mutation PostsEdit {
updatePost(selector: {_id:"${post._id}"},data:{commentsLocked:true}) {
data {
commentsLocked
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
await (response as any).should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
it("PostsEdit.commentLock should fail if author not in canCommentLock", async () => {
const author = await createDummyUser()
const post = await createDummyPost(author)
const query = `
mutation PostsEdit {
updatePost(selector: {_id:"${post._id}"},data:{commentsLocked:true}) {
data {
commentsLocked
}
}
}
`;
const response = runQuery(query, {}, {currentUser:author})
await (response as any).should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
})
it("PostsEdit.commentLock should fail if author in canCommentLock", async () => {
// FIXME: Description says "should fail", but test body says it succeeds?
const author = await createDummyUser({groups:["canCommentLock"]})
const post = await createDummyPost(author)
const query = `
mutation PostsEdit {
updatePost(selector: {_id:"${post._id}"},data:{commentsLocked:true}) {
data {
commentsLocked
}
}
}
`;
const response = runQuery(query, {}, {currentUser:author})
const expectedOutput = { data: { updatePost: { data: {commentsLocked: true} } } }
return (response as any).should.eventually.deep.equal(expectedOutput);
})
it("CommentsNew should fail if post is commentLocked", async () => {
const user = await createDummyUser()
const post = await createDummyPost(undefined, {commentsLocked:true})
const query = `
mutation CommentsNew {
createComment(data:{postId:"${post._id}", contents: { originalContents: { type: "markdown", data: "test" } } }){
data {
postId
}
}
}
`;
const response = runQuery(query, {}, {currentUser:user})
await (response as any).should.be.rejected;
assertIsPermissionsFlavoredError(graphQLerrors.getErrors());
});
}) | the_stack |
// This is legacy code that we are not maintaining for Typescript 4
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-nocheck
import { ATN } from 'antlr4ts/atn/ATN';
import { ATNDeserializer } from 'antlr4ts/atn/ATNDeserializer';
import { LexerATNSimulator } from 'antlr4ts/atn/LexerATNSimulator';
import { CharStream } from 'antlr4ts/CharStream';
import { NotNull, Override } from 'antlr4ts/Decorators';
import { Lexer } from 'antlr4ts/Lexer';
import * as Utils from 'antlr4ts/misc/Utils';
import { RuleContext } from 'antlr4ts/RuleContext';
import { Vocabulary } from 'antlr4ts/Vocabulary';
import { VocabularyImpl } from 'antlr4ts/VocabularyImpl';
export class mongoLexer extends Lexer {
public static readonly T__0 = 1;
public static readonly T__1 = 2;
public static readonly T__2 = 3;
public static readonly T__3 = 4;
public static readonly T__4 = 5;
public static readonly T__5 = 6;
public static readonly T__6 = 7;
public static readonly T__7 = 8;
public static readonly RegexLiteral = 9;
public static readonly SingleLineComment = 10;
public static readonly MultiLineComment = 11;
public static readonly StringLiteral = 12;
public static readonly NullLiteral = 13;
public static readonly BooleanLiteral = 14;
public static readonly NumericLiteral = 15;
public static readonly DecimalLiteral = 16;
public static readonly LineTerminator = 17;
public static readonly SEMICOLON = 18;
public static readonly DOT = 19;
public static readonly DB = 20;
public static readonly IDENTIFIER = 21;
public static readonly DOUBLE_QUOTED_STRING_LITERAL = 22;
public static readonly SINGLE_QUOTED_STRING_LITERAL = 23;
public static readonly WHITESPACE = 24;
public static readonly modeNames: string[] = [
"DEFAULT_MODE"
];
public static readonly ruleNames: string[] = [
"T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "RegexLiteral",
"RegexFlag", "SingleLineComment", "MultiLineComment", "StringLiteral",
"NullLiteral", "BooleanLiteral", "NumericLiteral", "DecimalLiteral", "LineTerminator",
"SEMICOLON", "DOT", "DB", "IDENTIFIER", "DOUBLE_QUOTED_STRING_LITERAL",
"SINGLE_QUOTED_STRING_LITERAL", "STRING_ESCAPE", "DecimalIntegerLiteral",
"ExponentPart", "DecimalDigit", "WHITESPACE"
];
private static readonly _LITERAL_NAMES: (string | undefined)[] = [
undefined, "'('", "','", "')'", "'{'", "'}'", "'['", "']'", "':'", undefined,
undefined, undefined, undefined, "'null'", undefined, undefined, undefined,
undefined, "';'", "'.'", "'db'"
];
private static readonly _SYMBOLIC_NAMES: (string | undefined)[] = [
undefined, undefined, undefined, undefined, undefined, undefined, undefined,
undefined, undefined, "RegexLiteral", "SingleLineComment", "MultiLineComment",
"StringLiteral", "NullLiteral", "BooleanLiteral", "NumericLiteral", "DecimalLiteral",
"LineTerminator", "SEMICOLON", "DOT", "DB", "IDENTIFIER", "DOUBLE_QUOTED_STRING_LITERAL",
"SINGLE_QUOTED_STRING_LITERAL", "WHITESPACE"
];
public static readonly VOCABULARY: Vocabulary = new VocabularyImpl(mongoLexer._LITERAL_NAMES, mongoLexer._SYMBOLIC_NAMES, []);
@Override
@NotNull
public get vocabulary(): Vocabulary {
return mongoLexer.VOCABULARY;
}
private isExternalIdentifierText(text) {
return text === 'db';
}
constructor(input: CharStream) {
super(input);
this._interp = new LexerATNSimulator(mongoLexer._ATN, this);
}
@Override
public get grammarFileName(): string { return "mongo.g4"; }
@Override
public get ruleNames(): string[] { return mongoLexer.ruleNames; }
@Override
public get serializedATN(): string { return mongoLexer._serializedATN; }
@Override
public get modeNames(): string[] { return mongoLexer.modeNames; }
@Override
public sempred(_localctx: RuleContext, ruleIndex: number, predIndex: number): boolean {
switch (ruleIndex) {
case 21:
return this.IDENTIFIER_sempred(_localctx, predIndex);
}
return true;
}
private IDENTIFIER_sempred(_localctx: RuleContext, predIndex: number): boolean {
switch (predIndex) {
case 0:
return !this.isExternalIdentifierText(this.text)
;
}
return true;
}
public static readonly _serializedATN: string =
"\x03\uAF6F\u8320\u479D\uB75C\u4880\u1605\u191C\uAB37\x02\x1A\xF2\b\x01" +
"\x04\x02\t\x02\x04\x03\t\x03\x04\x04\t\x04\x04\x05\t\x05\x04\x06\t\x06" +
"\x04\x07\t\x07\x04\b\t\b\x04\t\t\t\x04\n\t\n\x04\v\t\v\x04\f\t\f\x04\r" +
"\t\r\x04\x0E\t\x0E\x04\x0F\t\x0F\x04\x10\t\x10\x04\x11\t\x11\x04\x12\t" +
"\x12\x04\x13\t\x13\x04\x14\t\x14\x04\x15\t\x15\x04\x16\t\x16\x04\x17\t" +
"\x17\x04\x18\t\x18\x04\x19\t\x19\x04\x1A\t\x1A\x04\x1B\t\x1B\x04\x1C\t" +
"\x1C\x04\x1D\t\x1D\x04\x1E\t\x1E\x03\x02\x03\x02\x03\x03\x03\x03\x03\x04" +
"\x03\x04\x03\x05\x03\x05\x03\x06\x03\x06\x03\x07\x03\x07\x03\b\x03\b\x03" +
"\t\x03\t\x03\n\x03\n\x03\n\x03\n\x05\nR\n\n\x03\n\x03\n\x03\n\x07\nW\n" +
"\n\f\n\x0E\nZ\v\n\x03\n\x03\n\x07\n^\n\n\f\n\x0E\na\v\n\x03\v\x03\v\x03" +
"\f\x03\f\x03\f\x03\f\x07\fi\n\f\f\f\x0E\fl\v\f\x03\f\x03\f\x03\r\x03\r" +
"\x03\r\x03\r\x07\rt\n\r\f\r\x0E\rw\v\r\x03\r\x03\r\x03\r\x03\r\x03\r\x03" +
"\x0E\x03\x0E\x05\x0E\x80\n\x0E\x03\x0F\x03\x0F\x03\x0F\x03\x0F\x03\x0F" +
"\x03\x10\x03\x10\x03\x10\x03\x10\x03\x10\x03\x10\x03\x10\x03\x10\x03\x10" +
"\x05\x10\x90\n\x10\x03\x11\x05\x11\x93\n\x11\x03\x11\x03\x11\x03\x12\x03" +
"\x12\x03\x12\x06\x12\x9A\n\x12\r\x12\x0E\x12\x9B\x03\x12\x05\x12\x9F\n" +
"\x12\x03\x12\x03\x12\x06\x12\xA3\n\x12\r\x12\x0E\x12\xA4\x03\x12\x05\x12" +
"\xA8\n\x12\x03\x12\x03\x12\x05\x12\xAC\n\x12\x05\x12\xAE\n\x12\x03\x13" +
"\x03\x13\x03\x13\x03\x13\x03\x14\x03\x14\x03\x15\x03\x15\x03\x16\x03\x16" +
"\x03\x16\x03\x17\x03\x17\x06\x17\xBD\n\x17\r\x17\x0E\x17\xBE\x03\x17\x03" +
"\x17\x03\x18\x03\x18\x03\x18\x07\x18\xC6\n\x18\f\x18\x0E\x18\xC9\v\x18" +
"\x03\x18\x03\x18\x03\x19\x03\x19\x03\x19\x07\x19\xD0\n\x19\f\x19\x0E\x19" +
"\xD3\v\x19\x03\x19\x03\x19\x03\x1A\x03\x1A\x03\x1A\x03\x1B\x03\x1B\x03" +
"\x1B\x07\x1B\xDD\n\x1B\f\x1B\x0E\x1B\xE0\v\x1B\x05\x1B\xE2\n\x1B\x03\x1C" +
"\x03\x1C\x05\x1C\xE6\n\x1C\x03\x1C\x06\x1C\xE9\n\x1C\r\x1C\x0E\x1C\xEA" +
"\x03\x1D\x03\x1D\x03\x1E\x03\x1E\x03\x1E\x03\x1E\x03u\x02\x02\x1F\x03" +
"\x02\x03\x05\x02\x04\x07\x02\x05\t\x02\x06\v\x02\x07\r\x02\b\x0F\x02\t" +
"\x11\x02\n\x13\x02\v\x15\x02\x02\x17\x02\f\x19\x02\r\x1B\x02\x0E\x1D\x02" +
"\x0F\x1F\x02\x10!\x02\x11#\x02\x12%\x02\x13\'\x02\x14)\x02\x15+\x02\x16" +
"-\x02\x17/\x02\x181\x02\x193\x02\x025\x02\x027\x02\x029\x02\x02;\x02\x1A" +
"\x03\x02\x0F\x06\x02\f\f\x0F\x0F,,11\x05\x02\f\f\x0F\x0F11\x07\x02iik" +
"kooww{{\x05\x02\f\f\x0F\x0F\u202A\u202B\f\x02\v\f\x0F\x0F\"\"$$)+.0<=" +
"]_}}\x7F\x7F\x04\x02$$^^\x04\x02))^^\x05\x02$$))^^\x03\x023;\x04\x02G" +
"Ggg\x04\x02--//\x03\x022;\x04\x02\v\v\"\"\u0106\x02\x03\x03\x02\x02\x02" +
"\x02\x05\x03\x02\x02\x02\x02\x07\x03\x02\x02\x02\x02\t\x03\x02\x02\x02" +
"\x02\v\x03\x02\x02\x02\x02\r\x03\x02\x02\x02\x02\x0F\x03\x02\x02\x02\x02" +
"\x11\x03\x02\x02\x02\x02\x13\x03\x02\x02\x02\x02\x17\x03\x02\x02\x02\x02" +
"\x19\x03\x02\x02\x02\x02\x1B\x03\x02\x02\x02\x02\x1D\x03\x02\x02\x02\x02" +
"\x1F\x03\x02\x02\x02\x02!\x03\x02\x02\x02\x02#\x03\x02\x02\x02\x02%\x03" +
"\x02\x02\x02\x02\'\x03\x02\x02\x02\x02)\x03\x02\x02\x02\x02+\x03\x02\x02" +
"\x02\x02-\x03\x02\x02\x02\x02/\x03\x02\x02\x02\x021\x03\x02\x02\x02\x02" +
";\x03\x02\x02\x02\x03=\x03\x02\x02\x02\x05?\x03\x02\x02\x02\x07A\x03\x02" +
"\x02\x02\tC\x03\x02\x02\x02\vE\x03\x02\x02\x02\rG\x03\x02\x02\x02\x0F" +
"I\x03\x02\x02\x02\x11K\x03\x02\x02\x02\x13M\x03\x02\x02\x02\x15b\x03\x02" +
"\x02\x02\x17d\x03\x02\x02\x02\x19o\x03\x02\x02\x02\x1B\x7F\x03\x02\x02" +
"\x02\x1D\x81\x03\x02\x02\x02\x1F\x8F\x03\x02\x02\x02!\x92\x03\x02\x02" +
"\x02#\xAD\x03\x02\x02\x02%\xAF\x03\x02\x02\x02\'\xB3\x03\x02\x02\x02)" +
"\xB5\x03\x02\x02\x02+\xB7\x03\x02\x02\x02-\xBC\x03\x02\x02\x02/\xC2\x03" +
"\x02\x02\x021\xCC\x03\x02\x02\x023\xD6\x03\x02\x02\x025\xE1\x03\x02\x02" +
"\x027\xE3\x03\x02\x02\x029\xEC\x03\x02\x02\x02;\xEE\x03\x02\x02\x02=>" +
"\x07*\x02\x02>\x04\x03\x02\x02\x02?@\x07.\x02\x02@\x06\x03\x02\x02\x02" +
"AB\x07+\x02\x02B\b\x03\x02\x02\x02CD\x07}\x02\x02D\n\x03\x02\x02\x02E" +
"F\x07\x7F\x02\x02F\f\x03\x02\x02\x02GH\x07]\x02\x02H\x0E\x03\x02\x02\x02" +
"IJ\x07_\x02\x02J\x10\x03\x02\x02\x02KL\x07<\x02\x02L\x12\x03\x02\x02\x02" +
"MQ\x071\x02\x02NR\n\x02\x02\x02OP\x07^\x02\x02PR\x071\x02\x02QN\x03\x02" +
"\x02\x02QO\x03\x02\x02\x02RX\x03\x02\x02\x02SW\n\x03\x02\x02TU\x07^\x02" +
"\x02UW\x071\x02\x02VS\x03\x02\x02\x02VT\x03\x02\x02\x02WZ\x03\x02\x02" +
"\x02XV\x03\x02\x02\x02XY\x03\x02\x02\x02Y[\x03\x02\x02\x02ZX\x03\x02\x02" +
"\x02[_\x071\x02\x02\\^\x05\x15\v\x02]\\\x03\x02\x02\x02^a\x03\x02\x02" +
"\x02_]\x03\x02\x02\x02_`\x03\x02\x02\x02`\x14\x03\x02\x02\x02a_\x03\x02" +
"\x02\x02bc\t\x04\x02\x02c\x16\x03\x02\x02\x02de\x071\x02\x02ef\x071\x02" +
"\x02fj\x03\x02\x02\x02gi\n\x05\x02\x02hg\x03\x02\x02\x02il\x03\x02\x02" +
"\x02jh\x03\x02\x02\x02jk\x03\x02\x02\x02km\x03\x02\x02\x02lj\x03\x02\x02" +
"\x02mn\b\f\x02\x02n\x18\x03\x02\x02\x02op\x071\x02\x02pq\x07,\x02\x02" +
"qu\x03\x02\x02\x02rt\v\x02\x02\x02sr\x03\x02\x02\x02tw\x03\x02\x02\x02" +
"uv\x03\x02\x02\x02us\x03\x02\x02\x02vx\x03\x02\x02\x02wu\x03\x02\x02\x02" +
"xy\x07,\x02\x02yz\x071\x02\x02z{\x03\x02\x02\x02{|\b\r\x02\x02|\x1A\x03" +
"\x02\x02\x02}\x80\x051\x19\x02~\x80\x05/\x18\x02\x7F}\x03\x02\x02\x02" +
"\x7F~\x03\x02\x02\x02\x80\x1C\x03\x02\x02\x02\x81\x82\x07p\x02\x02\x82" +
"\x83\x07w\x02\x02\x83\x84\x07n\x02\x02\x84\x85\x07n\x02\x02\x85\x1E\x03" +
"\x02\x02\x02\x86\x87\x07v\x02\x02\x87\x88\x07t\x02\x02\x88\x89\x07w\x02" +
"\x02\x89\x90\x07g\x02\x02\x8A\x8B\x07h\x02\x02\x8B\x8C\x07c\x02\x02\x8C" +
"\x8D\x07n\x02\x02\x8D\x8E\x07u\x02\x02\x8E\x90\x07g\x02\x02\x8F\x86\x03" +
"\x02\x02\x02\x8F\x8A\x03\x02\x02\x02\x90 \x03\x02\x02\x02\x91\x93\x07" +
"/\x02\x02\x92\x91\x03\x02\x02\x02\x92\x93\x03\x02\x02\x02\x93\x94\x03" +
"\x02\x02\x02\x94\x95\x05#\x12\x02\x95\"\x03\x02\x02\x02\x96\x97\x055\x1B" +
"\x02\x97\x99\x070\x02\x02\x98\x9A\x059\x1D\x02\x99\x98\x03\x02\x02\x02" +
"\x9A\x9B\x03\x02\x02\x02\x9B\x99\x03\x02\x02\x02\x9B\x9C\x03\x02\x02\x02" +
"\x9C\x9E\x03\x02\x02\x02\x9D\x9F\x057\x1C\x02\x9E\x9D\x03\x02\x02\x02" +
"\x9E\x9F\x03\x02\x02\x02\x9F\xAE\x03\x02\x02\x02\xA0\xA2\x070\x02\x02" +
"\xA1\xA3\x059\x1D\x02\xA2\xA1\x03\x02\x02\x02\xA3\xA4\x03\x02\x02\x02" +
"\xA4\xA2\x03\x02\x02\x02\xA4\xA5\x03\x02\x02\x02\xA5\xA7\x03\x02\x02\x02" +
"\xA6\xA8\x057\x1C\x02\xA7\xA6\x03\x02\x02\x02\xA7\xA8\x03\x02\x02\x02" +
"\xA8\xAE\x03\x02\x02\x02\xA9\xAB\x055\x1B\x02\xAA\xAC\x057\x1C\x02\xAB" +
"\xAA\x03\x02\x02\x02\xAB\xAC\x03\x02\x02\x02\xAC\xAE\x03\x02\x02\x02\xAD" +
"\x96\x03\x02\x02\x02\xAD\xA0\x03\x02\x02\x02\xAD\xA9\x03\x02\x02\x02\xAE" +
"$\x03\x02\x02\x02\xAF\xB0\t\x05\x02\x02\xB0\xB1\x03\x02\x02\x02\xB1\xB2" +
"\b\x13\x02\x02\xB2&\x03\x02\x02\x02\xB3\xB4\x07=\x02\x02\xB4(\x03\x02" +
"\x02\x02\xB5\xB6\x070\x02\x02\xB6*\x03\x02\x02\x02\xB7\xB8\x07f\x02\x02" +
"\xB8\xB9\x07d\x02\x02\xB9,\x03\x02\x02\x02\xBA\xBD\n\x06\x02\x02\xBB\xBD" +
"\x053\x1A\x02\xBC\xBA\x03\x02\x02\x02\xBC\xBB\x03\x02\x02\x02\xBD\xBE" +
"\x03\x02\x02\x02\xBE\xBC\x03\x02\x02\x02\xBE\xBF\x03\x02\x02\x02\xBF\xC0" +
"\x03\x02\x02\x02\xC0\xC1\x06\x17\x02\x02\xC1.\x03\x02\x02\x02\xC2\xC7" +
"\x07$\x02\x02\xC3\xC6\n\x07\x02\x02\xC4\xC6\x053\x1A\x02\xC5\xC3\x03\x02" +
"\x02\x02\xC5\xC4\x03\x02\x02\x02\xC6\xC9\x03\x02\x02\x02\xC7\xC5\x03\x02" +
"\x02\x02\xC7\xC8\x03\x02\x02\x02\xC8\xCA\x03\x02\x02\x02\xC9\xC7\x03\x02" +
"\x02\x02\xCA\xCB\x07$\x02\x02\xCB0\x03\x02\x02\x02\xCC\xD1\x07)\x02\x02" +
"\xCD\xD0\n\b\x02\x02\xCE\xD0\x053\x1A\x02\xCF\xCD\x03\x02\x02\x02\xCF" +
"\xCE\x03\x02\x02\x02\xD0\xD3\x03\x02\x02\x02\xD1\xCF\x03\x02\x02\x02\xD1" +
"\xD2\x03\x02\x02\x02\xD2\xD4\x03\x02\x02\x02\xD3\xD1\x03\x02\x02\x02\xD4" +
"\xD5\x07)\x02\x02\xD52\x03\x02\x02\x02\xD6\xD7\x07^\x02\x02\xD7\xD8\t" +
"\t\x02\x02\xD84\x03\x02\x02\x02\xD9\xE2\x072\x02\x02\xDA\xDE\t\n\x02\x02" +
"\xDB\xDD\x059\x1D\x02\xDC\xDB\x03\x02\x02\x02\xDD\xE0\x03\x02\x02\x02" +
"\xDE\xDC\x03\x02\x02\x02\xDE\xDF\x03\x02\x02\x02\xDF\xE2\x03\x02\x02\x02" +
"\xE0\xDE\x03\x02\x02\x02\xE1\xD9\x03\x02\x02\x02\xE1\xDA\x03\x02\x02\x02" +
"\xE26\x03\x02\x02\x02\xE3\xE5\t\v\x02\x02\xE4\xE6\t\f\x02\x02\xE5\xE4" +
"\x03\x02\x02\x02\xE5\xE6\x03\x02\x02\x02\xE6\xE8\x03\x02\x02\x02\xE7\xE9" +
"\x059\x1D\x02\xE8\xE7\x03\x02\x02\x02\xE9\xEA\x03\x02\x02\x02\xEA\xE8" +
"\x03\x02\x02\x02\xEA\xEB\x03\x02\x02\x02\xEB8\x03\x02\x02\x02\xEC\xED" +
"\t\r\x02\x02\xED:\x03\x02\x02\x02\xEE\xEF\t\x0E\x02\x02\xEF\xF0\x03\x02" +
"\x02\x02\xF0\xF1\b\x1E\x03\x02\xF1<\x03\x02\x02\x02\x1C\x02QVX_ju\x7F" +
"\x8F\x92\x9B\x9E\xA4\xA7\xAB\xAD\xBC\xBE\xC5\xC7\xCF\xD1\xDE\xE1\xE5\xEA" +
"\x04\x02\x03\x02\b\x02\x02";
public static __ATN: ATN;
public static get _ATN(): ATN {
if (!mongoLexer.__ATN) {
mongoLexer.__ATN = new ATNDeserializer().deserialize(Utils.toCharArray(mongoLexer._serializedATN));
}
return mongoLexer.__ATN;
}
} | the_stack |
import React from 'react';
import * as POOL from 'types/generated/trader_pb';
import { fireEvent, waitFor } from '@testing-library/react';
import { injectIntoGrpcUnary, renderWithProviders } from 'util/tests';
import { createStore, Store } from 'store';
import OrderFormSection from 'components/pool/OrderFormSection';
describe('OrderFormSection', () => {
let store: Store;
beforeEach(async () => {
store = createStore();
await store.accountStore.fetchAccounts();
await store.orderStore.fetchOrders();
await store.batchStore.fetchLeaseDurations();
});
const render = () => {
return renderWithProviders(<OrderFormSection />, store);
};
it('should display the Bid form fields', () => {
const { getByText } = render();
fireEvent.click(getByText('Bid'));
expect(getByText('Desired Inbound Liquidity')).toBeInTheDocument();
expect(getByText('Bid Premium')).toBeInTheDocument();
expect(getByText('Minimum Channel Size')).toBeInTheDocument();
expect(getByText('Max Batch Fee Rate')).toBeInTheDocument();
expect(getByText('Min Node Tier')).toBeInTheDocument();
expect(getByText('Place Bid Order')).toBeInTheDocument();
});
it('should display the Ask form fields', () => {
const { getByText } = render();
fireEvent.click(getByText('Ask'));
expect(getByText('Offered Outbound Liquidity')).toBeInTheDocument();
expect(getByText('Ask Premium')).toBeInTheDocument();
expect(getByText('Minimum Channel Size')).toBeInTheDocument();
expect(getByText('Max Batch Fee Rate')).toBeInTheDocument();
expect(getByText('Place Ask Order')).toBeInTheDocument();
});
it('should toggle the additional options', () => {
const { getByText, store } = render();
expect(store.orderFormView.addlOptionsVisible).toBe(false);
fireEvent.click(getByText('View Additional Options'));
expect(store.orderFormView.addlOptionsVisible).toBe(true);
fireEvent.click(getByText('Hide Additional Options'));
expect(store.orderFormView.addlOptionsVisible).toBe(false);
});
it('should submit a bid order', async () => {
const { getByText, changeInput, changeSelect } = render();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '10000');
changeInput('Minimum Channel Size', '100000');
changeInput('Max Batch Fee Rate', '1');
await changeSelect('Min Node Tier', 'T0 - All Nodes');
let bid: Required<POOL.Bid.AsObject>;
// capture the rate that is sent to the API
injectIntoGrpcUnary((_, props) => {
bid = (props.request.toObject() as any).bid;
});
fireEvent.click(getByText('Place Bid Order'));
expect(bid!.details.amt).toBe('1000000');
expect(bid!.details.rateFixed).toBe(4960);
expect(bid!.details.minUnitsMatch).toBe(1);
expect(bid!.leaseDurationBlocks).toBe(2016);
expect(bid!.minNodeTier).toBe(1);
expect(bid!.details.maxBatchFeeRateSatPerKw).toBe('253');
});
it('should submit an ask order', async () => {
const { getByText, changeInput } = render();
fireEvent.click(getByText('Ask'));
changeInput('Offered Outbound Liquidity', '1000000');
changeInput('Ask Premium', '10000');
changeInput('Minimum Channel Size', '100000');
changeInput('Max Batch Fee Rate', '1');
let ask: Required<POOL.Ask.AsObject>;
// capture the rate that is sent to the API
injectIntoGrpcUnary((_, props) => {
ask = (props.request.toObject() as any).ask;
});
fireEvent.click(getByText('Place Ask Order'));
expect(ask!.details.amt).toBe('1000000');
expect(ask!.details.rateFixed).toBe(4960);
expect(ask!.details.minUnitsMatch).toBe(1);
expect(ask!.leaseDurationBlocks).toBe(2016);
expect(ask!.details.maxBatchFeeRateSatPerKw).toBe('253');
});
it('should submit an order with a different lease duration', async () => {
const { getByText, changeInput, changeSelect } = render();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '10000');
changeInput('Minimum Channel Size', '100000');
changeInput('Max Batch Fee Rate', '1');
await changeSelect('Channel Duration', '4032 (open)');
await changeSelect('Min Node Tier', 'T0 - All Nodes');
let bid: Required<POOL.Bid.AsObject>;
// capture the rate that is sent to the API
injectIntoGrpcUnary((_, props) => {
bid = (props.request.toObject() as any).bid;
});
fireEvent.click(getByText('Place Bid Order'));
expect(bid!.details.amt).toBe('1000000');
expect(bid!.details.rateFixed).toBe(2480);
expect(bid!.details.minUnitsMatch).toBe(1);
expect(bid!.leaseDurationBlocks).toBe(4032);
expect(bid!.minNodeTier).toBe(1);
expect(bid!.details.maxBatchFeeRateSatPerKw).toBe('253');
});
it('should reset the form after placing an order', async () => {
const { getByText, getByLabelText, changeInput } = render();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '10000');
changeInput('Minimum Channel Size', '500000');
changeInput('Max Batch Fee Rate', '1');
fireEvent.click(getByText('Place Bid Order'));
await waitFor(() => {
expect(getByLabelText('Desired Inbound Liquidity')).toHaveValue('');
expect(getByLabelText('Bid Premium')).toHaveValue('');
expect(getByLabelText('Minimum Channel Size')).toHaveValue(`500,000`);
expect(getByLabelText('Max Batch Fee Rate')).toHaveValue(`1`);
});
});
it('should display an error if order submission fails', async () => {
const { getByText, findByText, changeInput } = render();
fireEvent.click(getByText('Ask'));
changeInput('Offered Outbound Liquidity', '1000000');
changeInput('Ask Premium', '10000');
changeInput('Minimum Channel Size', '100000');
changeInput('Max Batch Fee Rate', '1');
injectIntoGrpcUnary(() => {
throw new Error('test-error');
});
fireEvent.click(getByText('Place Ask Order'));
expect(await findByText('Unable to submit the order')).toBeInTheDocument();
expect(await findByText('test-error')).toBeInTheDocument();
});
it('should display an error for amount field', () => {
const { getByText, changeInput } = render();
changeInput('Desired Inbound Liquidity', '1');
expect(getByText('must be a multiple of 100,000')).toBeInTheDocument();
});
it('should display an error for premium field', () => {
const { getByText, changeInput } = render();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '1');
expect(getByText('per block fixed rate is too small')).toBeInTheDocument();
});
it('should suggest the correct premium', async () => {
const { getByText, getByLabelText, changeInput } = render();
await store.batchStore.fetchBatches();
store.batchStore.sortedBatches[0].clearingPriceRate = 496;
changeInput('Desired Inbound Liquidity', '1000000');
fireEvent.click(getByText('Suggested'));
expect(getByLabelText('Bid Premium')).toHaveValue('1,000');
store.batchStore.sortedBatches[0].clearingPriceRate = 1884;
changeInput('Desired Inbound Liquidity', '1000000');
fireEvent.click(getByText('Suggested'));
expect(getByLabelText('Bid Premium')).toHaveValue('3,800');
store.batchStore.sortedBatches[0].clearingPriceRate = 2480;
changeInput('Desired Inbound Liquidity', '1000000');
fireEvent.click(getByText('Suggested'));
expect(getByLabelText('Bid Premium')).toHaveValue('5,000');
});
it('should display an error for suggested premium', async () => {
const { getByText, findByText, changeInput } = render();
fireEvent.click(getByText('Suggested'));
expect(await findByText('Unable to suggest premium')).toBeInTheDocument();
expect(await findByText('Must specify amount first')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
fireEvent.click(getByText('Suggested'));
expect(await findByText('Unable to suggest premium')).toBeInTheDocument();
expect(await findByText('Previous batch not found')).toBeInTheDocument();
});
it('should display an error for min chan size field', () => {
const { getByText, changeInput } = render();
changeInput('Minimum Channel Size', '1');
expect(getByText('must be a multiple of 100,000')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Minimum Channel Size', '1100000');
expect(getByText('must be less than liquidity amount')).toBeInTheDocument();
});
it('should display an error for batch fee rate field', () => {
const { getByText, changeInput } = render();
changeInput('Max Batch Fee Rate', '0.11');
expect(getByText('minimum 1 sats/vByte')).toBeInTheDocument();
});
it('should display the channel duration', () => {
const { getByText, getAllByText } = render();
expect(getAllByText('Channel Duration')).toHaveLength(2);
expect(getByText('2016 blocks')).toBeInTheDocument();
expect(getByText('(~2 weeks)')).toBeInTheDocument();
});
it('should calculate the per block rate', () => {
const { getByText, changeInput } = render();
expect(getByText('Per Block Fixed Rate')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '1000');
expect(getByText('496')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '5000000');
changeInput('Bid Premium', '1000');
expect(getByText('99')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '50000000');
changeInput('Bid Premium', '100');
expect(getByText('< 1')).toBeInTheDocument();
});
it('should calculate the interest rate percent correctly', () => {
const { getByText, changeInput } = render();
expect(getByText('Interest Rate')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '1000');
expect(getByText('10 bps')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '500');
expect(getByText('5 bps')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '1234');
expect(getByText('12 bps')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '');
expect(getByText('0 bps')).toBeInTheDocument();
});
it('should calculate the APR correctly', () => {
const { getByText, changeInput } = render();
expect(getByText('Annual Rate (APR)')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '1000');
expect(getByText('2.61%')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '500');
expect(getByText('1.3%')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '1234');
expect(getByText('3.22%')).toBeInTheDocument();
changeInput('Desired Inbound Liquidity', '1000000');
changeInput('Bid Premium', '');
expect(getByText('0%')).toBeInTheDocument();
});
}); | the_stack |
import { RotationCorrection } from '../../input/OcrExtractor';
import {
Barcode,
BoundingBox,
Character,
Document,
Drawing,
Element,
Font,
Heading,
Image,
JsonBox,
JsonElement,
JsonExport,
JsonFont,
JsonMetadata,
JsonPage,
JsonPageRotation,
List,
Page,
SpannedTableCell,
Table,
TableCell,
TableRow,
Text,
Word,
} from '../../types/DocumentRepresentation';
import { SvgLine } from '../../types/DocumentRepresentation/SvgLine';
import { SvgShape } from '../../types/DocumentRepresentation/SvgShape';
import { TableOfContents } from '../../types/DocumentRepresentation/TableOfContents';
import { TableOfContentsItem } from '../../types/DocumentRepresentation/TableOfContentsItem';
import { ComplexMetadata, Metadata, NumberMetadata } from '../../types/Metadata';
import * as utils from '../../utils';
import logger from '../../utils/Logger';
import { Exporter } from '../Exporter';
import { existsSync, readFileSync } from 'fs';
import { json2document } from '../../utils/json2document';
export class JsonExporter extends Exporter {
private granularity: string;
private includeDrawings: boolean;
private currentMetadataId: number = 1;
private currentFontId: number = 0;
private json: JsonExport = {} as JsonExport;
private fontCatalog: Map<Font, number> = new Map<Font, number>();
private metadataCatalog: Map<Metadata, number> = new Map<Metadata, number>();
constructor(doc: Document, granularity: string, includeDrawings: boolean = false) {
super(doc);
this.granularity = granularity;
this.includeDrawings = includeDrawings;
}
public export(outputPath: string): Promise<void> {
logger.info('Exporting json...');
return this.writeFile(outputPath, JSON.stringify(this.getJson()));
}
public getJson(): JsonExport {
this.json.metadata = [];
this.buildMetadataCatalog();
this.metadataToJson();
let drawingsDoc = null;
if (this.includeDrawings && this.doc.drawingsFile && existsSync(this.doc.drawingsFile)) {
drawingsDoc = json2document(JSON.parse(readFileSync(this.doc.drawingsFile, { encoding: 'utf8' })));
}
this.json.pages = this.doc.pages.map((page: Page) => {
const elements = page.elements
.sort(utils.sortElementsByOrder)
.map(e => this.elementToJsonElement(e));
if (drawingsDoc) {
const drawingsPage = drawingsDoc.pages.find(p => p.pageNumber === page.pageNumber);
if (drawingsPage) {
elements.push(
...drawingsPage.elements
.filter(e => e instanceof Drawing)
.map(e => this.elementToJsonElement(e)),
);
}
}
const jsonPage: JsonPage = {
margins: this.doc.margins,
box: this.boxToJsonBox(page.box),
rotation: this.rotationToJsonRotation(page.pageRotation),
pageNumber: page.pageNumber,
elements,
};
return jsonPage;
});
this.json.fonts = [];
this.fontCatalog.forEach((fontId, font) => {
const name = font.name;
const size = font.size;
const url = font.url;
const scaling = font.scaling;
let weight = font.weight;
let isItalic = font.isItalic;
let isUnderline = font.isUnderline;
let sizeUnit = 'px';
let color = font.color;
if (font.color !== 'black' && font.color !== '#000000' && font.color !== '000000') {
color = font.color;
}
if (font.weight !== 'medium') {
weight = font.weight;
}
if (font.isItalic) {
isItalic = font.isItalic;
}
if (font.isUnderline) {
isUnderline = font.isUnderline;
}
if (font.sizeUnit) {
sizeUnit = font.sizeUnit;
}
const jsonFont: JsonFont = {
id: fontId,
name,
size,
weight,
isItalic,
isUnderline,
color,
url,
scaling,
sizeUnit,
};
this.json.fonts.push(jsonFont);
});
return this.json;
}
private buildMetadataCatalog() {
// Build the catalog, avoiding duplicates thanks to the Map
this.doc.pages.forEach(page => {
page.elements.forEach(elem => {
this.findMetadata(elem);
});
});
}
private findMetadata(element: Element) {
element.metadata.forEach(m => {
if (!this.metadataCatalog.has(m)) {
this.metadataCatalog.set(m, this.currentMetadataId++);
}
});
if (element.content instanceof Array) {
element.content.forEach(elem => this.findMetadata(elem));
}
}
private metadataToJson() {
this.metadataCatalog.forEach((id: number, metadata: Metadata) => {
const jsonMetadata: JsonMetadata = {
id,
elements: metadata.elements.map(e => e.id).sort((a, b) => a - b),
type: utils.toKebabCase(metadata.constructor.name).replace(/-metadata$/, ''),
};
if (metadata instanceof NumberMetadata) {
jsonMetadata.value = metadata.value;
}
if (metadata instanceof ComplexMetadata) {
Object.keys(metadata.data).forEach(k => {
metadata.data[k] = this.convertElementValue(metadata.data[k]);
});
jsonMetadata.data = metadata.data;
}
this.json.metadata.push(jsonMetadata);
});
}
private elementToJsonElement(element: Element) {
const id: number = element.id;
const type: string = utils.toKebabCase(element.constructor.name);
const jsonElement: JsonElement = {
id,
type,
};
if (element.properties) {
jsonElement.properties = element.properties;
}
jsonElement.metadata = element.metadata.map(metadata => this.metadataCatalog.get(metadata));
if (Element.hasBoundingBox(element)) {
jsonElement.box = this.boxToJsonBox(element.box);
}
if (element instanceof Text) {
jsonElement.conf = element.confidence;
if (typeof element.content === 'string') {
jsonElement.content = element.content;
} else if (
this.granularity === 'word' &&
element.content instanceof Array &&
element.content.length > 0 &&
element.content[0] instanceof Character
) {
jsonElement.content = element.toString();
} else {
jsonElement.content = element.content
.sort(utils.sortElementsByOrder)
.map(elem => this.elementToJsonElement(elem));
}
if (element instanceof Word || element instanceof Character) {
if (typeof element.font !== 'undefined') {
const allFonts = Array.from(this.fontCatalog.keys());
const wordFont = allFonts.filter(font => font.isEqual(element.font));
if (wordFont.length === 0) {
this.currentFontId++;
this.fontCatalog.set(element.font, this.currentFontId);
jsonElement.font = this.currentFontId;
jsonElement.fontSize = element.font.size;
} else {
jsonElement.font = this.fontCatalog.get(wordFont[0]);
jsonElement.fontSize = element.font.size;
}
}
} else if (element instanceof Heading) {
jsonElement.level = element.level;
}
} else if (element instanceof List) {
jsonElement.isOrdered = element.isOrdered;
jsonElement.firstItemNumber = element.firstItemNumber;
jsonElement.content = element.content.map(elem => this.elementToJsonElement(elem));
} else if (element instanceof Table) {
jsonElement.content = element.content.map(elem => this.elementToJsonElement(elem));
} else if (element instanceof TableRow) {
jsonElement.content = element.content.map(elem => this.elementToJsonElement(elem));
} else if (element instanceof SpannedTableCell) {
jsonElement.spanDirection = element.spanDirection;
jsonElement.colspan = element.colspan;
jsonElement.rowspan = element.rowspan;
jsonElement.content = [];
} else if (element instanceof TableCell) {
jsonElement.rowspan = element.rowspan;
jsonElement.colspan = element.colspan;
jsonElement.content = element.content
.sort(utils.sortElementsByOrder)
.map(elem => this.elementToJsonElement(elem));
} else if (element instanceof SvgShape) {
if (element instanceof SvgLine) {
jsonElement.fromX = element.fromX;
jsonElement.fromY = element.fromY;
jsonElement.toX = element.toX;
jsonElement.toY = element.toY;
jsonElement.thickness = element.thickness;
jsonElement.color = element.color;
jsonElement.fillOpacity = element.fillOpacity;
jsonElement.strokeOpacity = element.strokeOpacity;
}
} else if (element instanceof Drawing) {
jsonElement.content = element.content.map(elem => this.elementToJsonElement(elem));
} else if (element instanceof Barcode) {
jsonElement.codeType = element.type;
jsonElement.codeValue = element.content;
} else if (element instanceof Image) {
if (!element.enabled) {
// If image detection module is not executed in pipe all images have enabled = false
return null;
}
jsonElement.src = element.src; // TODO replace this with a location based on an API access point
jsonElement.refId = element.refId;
jsonElement.xObjId = element.xObjId;
jsonElement.xObjExt = element.xObjExt;
} else if (element instanceof Heading) {
jsonElement.level = element.level;
} else if (element instanceof TableOfContents) {
jsonElement.content = element.content.map(elem => this.elementToJsonElement(elem));
} else if (element instanceof TableOfContentsItem) {
jsonElement.content = element.toString();
}
return jsonElement;
}
private boxToJsonBox(box: BoundingBox): JsonBox {
const jsonBox: JsonBox = {
l: utils.round(box.left),
t: utils.round(box.top),
w: utils.round(box.width),
h: utils.round(box.height),
};
return jsonBox;
}
private rotationToJsonRotation(rotation: RotationCorrection): JsonPageRotation {
if (rotation != null) {
const jsonRotation: JsonPageRotation = {
degrees: rotation.degrees,
origin: rotation.origin,
translation: rotation.translation,
};
return jsonRotation;
}
const noRotation: JsonPageRotation = {
degrees: 0,
origin: { x: 0, y: 0 },
translation: { x: 0, y: 0 },
};
return noRotation;
}
private convertElementValue(value: any): any {
if (value instanceof Element) {
return value.id;
} else if (value instanceof Array) {
return value.map(v => this.convertElementValue(v));
} else {
return value;
}
}
} | the_stack |
namespace dragonBones {
const {
ccclass,
} = cc._decorator;
@ccclass
class ClockHandler extends cc.Component {
update(passedTime: number) {
CocosFactory.factory.dragonBones.advanceTime(passedTime);
}
}
/**
* - The Cocos factory.
* @version DragonBones 3.0
* @language en_US
*/
/**
* - Cocos 工厂。
* @version DragonBones 3.0
* @language zh_CN
*/
export class CocosFactory extends BaseFactory {
private static _dragonBonesInstance: DragonBones = null as any;
private static _factory: CocosFactory | null = null;
/**
* - A global factory instance that can be used directly.
* @version DragonBones 4.7
* @language en_US
*/
/**
* - 一个可以直接使用的全局工厂实例。
* @version DragonBones 4.7
* @language zh_CN
*/
public static get factory(): CocosFactory {
if (this._factory === null) {
this._factory = new CocosFactory();
}
return this._factory;
}
protected _node: cc.Node | null = null;
protected _armatureNode: cc.Node | null = null;
public constructor(dataParser: DataParser | null = null) {
super(dataParser);
if (!CC_EDITOR) { // Is playing.
if (this._node === null) {
const nodeName = "DragonBones Node";
this._node = cc.find(nodeName);
if (this._node === null) {
this._node = new cc.Node(nodeName);
cc.game.addPersistRootNode(this._node);
}
}
if (!this._node.getComponent(ClockHandler)) {
this._node.addComponent(ClockHandler);
}
const eventManager = this._node.getComponent(CocosArmatureComponent) || this._node.addComponent(CocosArmatureComponent);
if (CocosFactory._dragonBonesInstance === null) {
CocosFactory._dragonBonesInstance = new DragonBones(eventManager);
//
DragonBones.yDown = false;
}
}
else {
if (CocosFactory._dragonBonesInstance === null) {
CocosFactory._dragonBonesInstance = new DragonBones(null as any);
//
DragonBones.yDown = false;
}
}
this._dragonBones = CocosFactory._dragonBonesInstance;
}
protected _isSupportMesh(): boolean {
if ((cc as any)._renderType !== (cc.game as any).RENDER_TYPE_WEBGL) { // creator.d.ts error.
console.warn("Only webgl mode can support mesh.");
return false;
}
return true;
}
protected _buildTextureAtlasData(textureAtlasData: CocosTextureAtlasData | null, textureAtlas: cc.Texture2D | null): CocosTextureAtlasData {
if (textureAtlasData !== null) {
textureAtlasData.renderTexture = textureAtlas;
}
else {
textureAtlasData = BaseObject.borrowObject(CocosTextureAtlasData);
}
return textureAtlasData;
}
protected _buildArmature(dataPackage: BuildArmaturePackage): Armature {
const armature = BaseObject.borrowObject(Armature);
const armatureDisplay = this._armatureNode === null ? new cc.Node(dataPackage.armature.name) : this._armatureNode;
const armatureComponent = armatureDisplay.getComponent(CocosArmatureComponent) || armatureDisplay.addComponent(CocosArmatureComponent);
armatureDisplay.setOpacityModifyRGB(false);
armatureDisplay.setCascadeOpacityEnabled(true);
(armatureDisplay as any)._sgNode.setCascadeColorEnabled(true); // creator.d.ts error.
this._armatureNode = null;
armatureComponent._armature = armature;
armature.init(
dataPackage.armature,
armatureComponent, armatureDisplay, this._dragonBones
);
return armature;
}
protected _buildChildArmature(dataPackage: BuildArmaturePackage | null, slot: Slot, displayData: ArmatureDisplayData): Armature | null {
const childDisplayName = slot.slotData.name + " (" + displayData.path.replace("/", "_") + ")"; //
const proxy = slot.armature.proxy as CocosArmatureComponent;
let childNode = cc.find(childDisplayName, proxy.node);
let childArmature: Armature | null = null;
if (!childNode) {
if (dataPackage !== null) {
childArmature = this.buildArmature(displayData.path, dataPackage.dataName);
}
else {
childArmature = this.buildArmature(displayData.path, displayData.parent.parent.parent.name);
}
}
else {
let childArmatureComponent: CocosArmatureComponent | null = childNode.getComponent(CocosArmatureComponent) || null;
if (childArmatureComponent === null) {
if (dataPackage !== null) {
childArmatureComponent = this.buildArmatureComponent(displayData.path, dataPackage !== null ? dataPackage.dataName : "", "", dataPackage.textureAtlasName, childNode);
}
else {
childArmatureComponent = this.buildArmatureComponent(displayData.path, "", "", "", childNode);
}
}
if (childArmatureComponent !== null) {
childArmature = childArmatureComponent.armature;
}
}
if (childArmature === null) {
return null;
}
const childArmatureDisplay = childArmature.display as cc.Node;
childArmatureDisplay.name = childDisplayName;
if (childArmatureDisplay.parent !== proxy.node) {
proxy.node.addChild(childArmatureDisplay, slot._zOrder);
}
childArmatureDisplay.active = false;
return childArmature;
}
protected _buildSlot(_dataPackage: BuildArmaturePackage, slotData: SlotData, armature: Armature): Slot {
const slot = BaseObject.borrowObject(CocosSlot);
const armatureDisplay = armature.display as cc.Node;
const rawSlotDisplay = cc.find(slotData.name, armatureDisplay) || new cc.Node(slotData.name);
rawSlotDisplay.addComponent(cc.Sprite);
rawSlotDisplay.setAnchorPoint(0.0, 0.0);
rawSlotDisplay.setOpacityModifyRGB(false);
rawSlotDisplay.setCascadeOpacityEnabled(true);
(rawSlotDisplay as any)._sgNode.setCascadeColorEnabled(true); // creator.d.ts error.
slot.init(
slotData, armature,
rawSlotDisplay, rawSlotDisplay
);
return slot;
}
/**
* - Create a armature component from cached DragonBonesData instances and TextureAtlasData instances, then use the {@link #clock} to update it.
* - The difference is that the armature created by {@link #buildArmature} is not WorldClock instance update.
* - Note that when the created armature proxy that is no longer in use, you need to explicitly dispose {@link #dragonBones.IArmatureProxy#dispose()}.
* @param armatureName - The armature data name.
* @param dragonBonesName - The cached name of the DragonBonesData instance. (If not set, all DragonBonesData instances are retrieved, and when multiple DragonBonesData instances contain a the same name armature data, it may not be possible to accurately create a specific armature)
* @param skinName - The skin name, you can set a different ArmatureData name to share it's skin data. (If not set, use the default skin data)
* @returns The armature component.
* @see dragonBones.IArmatureProxy
* @see dragonBones.BaseFactory#buildArmature
* @version DragonBones 4.5
* @example
*
* <pre>
* let armatureComponent = factory.buildArmatureComponent("armatureName", "dragonBonesName");
* </pre>
* @language en_US
*/
/**
* - 通过缓存的 DragonBonesData 实例和 TextureAtlasData 实例创建一个骨架组件,并用 {@link #clock} 更新该骨架。
* - 区别在于由 {@link #buildArmature} 创建的骨架没有 WorldClock 实例驱动。
* - 注意,创建的骨架代理不再使用时,需要显式释放 {@link #dragonBones.IArmatureProxy#dispose()}。
* @param armatureName - 骨架数据名称。
* @param dragonBonesName - DragonBonesData 实例的缓存名称。 (如果未设置,将检索所有的 DragonBonesData 实例,当多个 DragonBonesData 实例中包含同名的骨架数据时,可能无法准确的创建出特定的骨架)
* @param skinName - 皮肤名称,可以设置一个其他骨架数据名称来共享其皮肤数据。(如果未设置,则使用默认的皮肤数据)
* @returns 骨架组件。
* @see dragonBones.IArmatureProxy
* @see dragonBones.BaseFactory#buildArmature
* @version DragonBones 4.5
* @example
*
* <pre>
* let armatureComponent = factory.buildArmatureComponent("armatureName", "dragonBonesName");
* </pre>
* @language zh_CN
*/
public buildArmatureComponent(armatureName: string, dragonBonesName: string = "", skinName: string = "", textureAtlasName: string = "", node: cc.Node | null = null): CocosArmatureComponent | null {
this._armatureNode = node;
const armature = this.buildArmature(armatureName, dragonBonesName || "", skinName || "", textureAtlasName || "");
if (armature !== null) {
this._dragonBones.clock.add(armature);
return armature.proxy as CocosArmatureComponent;
}
return null;
}
/**
* - Create the display object with the specified texture.
* @param textureName - The texture data name.
* @param textureAtlasName - The texture atlas data name. (Of not set, all texture atlas data will be searched)
* @version DragonBones 3.0
* @language en_US
*/
/**
* - 创建带有指定贴图的显示对象。
* @param textureName - 贴图数据名称。
* @param textureAtlasName - 贴图集数据名称。 (如果未设置,将检索所有的贴图集数据)
* @version DragonBones 3.0
* @language zh_CN
*/
public getTextureDisplay(textureName: string, textureAtlasName: string | null = null): cc.Sprite | null {
const textureData = this._getTextureData(textureAtlasName !== null ? textureAtlasName : "", textureName) as CocosTextureData;
if (textureData !== null && textureData.renderTexture !== null) {
const texture = textureData.renderTexture;
const sprite = new cc.Sprite();
sprite.spriteFrame = texture;
return sprite;
}
return null;
}
/**
* - A global sound event manager.
* Sound events can be listened to uniformly from the manager.
* @version DragonBones 4.5
* @language en_US
*/
/**
* - 全局声音事件管理器。
* 声音事件可以从该管理器统一侦听。
* @version DragonBones 4.5
* @language zh_CN
*/
public get soundEventManager(): cc.Node {
return (this._dragonBones.eventManager as CocosArmatureComponent).node;
}
}
} | the_stack |
import { Component, Property, Event, EmitType, EventHandler, L10n, setValue, getValue, isNullOrUndefined } from '@syncfusion/ej2-base';
import { NotifyPropertyChanges, INotifyPropertyChanged, detach, Internationalization, getUniqueID, closest } from '@syncfusion/ej2-base';
import { addClass, removeClass } from '@syncfusion/ej2-base';
import { FloatLabelType, Input, InputObject } from '../input/input';
import { TextBoxModel} from './textbox-model';
const HIDE_CLEAR: string = 'e-clear-icon-hide';
const TEXTBOX_FOCUS: string = 'e-input-focus';
const containerAttr: string[] = ['title', 'style', 'class'];
export interface FocusInEventArgs {
/** Returns the TextBox container element */
container?: HTMLElement
/** Returns the event parameters from TextBox. */
event?: Event
/** Returns the entered value of the TextBox. */
value?: string
}
export interface FocusOutEventArgs {
/** Returns the TextBox container element */
container?: HTMLElement
/** Returns the event parameters from TextBox. */
event?: Event
/** Returns the entered value of the TextBox. */
value?: string
}
export interface ChangedEventArgs extends FocusInEventArgs {
/** Returns the previously entered value of the TextBox. */
previousValue?: string
/** DEPRECATED-Returns the original event. */
isInteraction?: boolean
/** Returns the original event. */
isInteracted?: boolean
}
export interface InputEventArgs extends FocusInEventArgs {
/** Returns the previously updated value of the TextBox. */
previousValue?: string
}
/**
* Represents the TextBox component that allows the user to enter the values based on it's type.
* ```html
* <input name='images' id='textbox'/>
* ```
* ```typescript
* <script>
* var textboxObj = new TextBox();
* textboxObj.appendTo('#textbox');
* </script>
* ```
*/
@NotifyPropertyChanges
export class TextBox extends Component<HTMLInputElement | HTMLTextAreaElement> implements INotifyPropertyChanged {
private textboxWrapper: InputObject;
private l10n: L10n;
private previousValue: string = null;
private cloneElement: HTMLInputElement;
private globalize: Internationalization;
private preventChange: boolean;
private isAngular: boolean = false;
private isHiddenInput: boolean = false;
private textarea: HTMLTextAreaElement;
private respectiveElement: HTMLInputElement | HTMLTextAreaElement;
private isForm: boolean = false;
private formElement: HTMLElement;
private initialValue: string;
private textboxOptions: TextBoxModel;
private inputPreviousValue: string = null;
private isVue: boolean = false;
/**
* Specifies the behavior of the TextBox such as text, password, email, etc.
*
* @default 'text'
*/
@Property('text')
public type: string;
/**
* Specifies the boolean value whether the TextBox allows user to change the text.
*
* @default false
*/
@Property(false)
public readonly: boolean;
/**
* Sets the content of the TextBox.
*
* @default null
*/
@Property(null)
public value: string;
/**
* Specifies the floating label behavior of the TextBox that the placeholder text floats above the TextBox based on the below values.
* Possible values are:
* * `Never` - The placeholder text should not be float ever.
* * `Always` - The placeholder text floats above the TextBox always.
* * `Auto` - The placeholder text floats above the TextBox while focusing or enter a value in Textbox.
*
* @default Never
*/
@Property('Never')
public floatLabelType: FloatLabelType;
/**
* Specifies the CSS class value that is appended to wrapper of Textbox.
*
* @default ''
*/
@Property('')
public cssClass: string;
/**
* Specifies the text that is shown as a hint/placeholder until the user focus or enter a value in Textbox.
* The property is depending on the floatLabelType property.
*
* @default null
*/
@Property(null)
public placeholder: string;
/**
* Specifies whether the browser is allow to automatically enter or select a value for the textbox.
* By default, autocomplete is enabled for textbox.
* Possible values are:
* `on` - Specifies that autocomplete is enabled.
* `off` - Specifies that autocomplete is disabled.
*
* @default 'on'
*/
@Property('on')
public autocomplete: string;
/**
* You can add the additional html attributes such as disabled, value etc., to the element.
* If you configured both property and equivalent html attribute then the component considers the property value.
* {% codeBlock src='textbox/htmlAttributes/index.md' %}{% endcodeBlock %}
*
* @default {}
*/
@Property({})
public htmlAttributes: { [key: string]: string };
/**
* Specifies a boolean value that enable or disable the multiline on the TextBox.
* The TextBox changes from single line to multiline when enable this multiline mode.
*
* @default false
*/
@Property(false)
public multiline: boolean;
/**
* Specifies a Boolean value that indicates whether the TextBox allow user to interact with it.
*
* @default true
*/
@Property(true)
public enabled: boolean;
/**
* Specifies a Boolean value that indicates whether the clear button is displayed in Textbox.
*
* @default false
*/
@Property(false)
public showClearButton: boolean;
/**
* Enable or disable persisting TextBox state between page reloads. If enabled, the `value` state will be persisted.
*
* @default false
*/
@Property(false)
public enablePersistence: boolean;
/**
* Specifies the width of the Textbox component.
*
* @default null
*/
@Property(null)
public width: number | string;
/**
* Triggers when the TextBox component is created.
*
* @event created
*/
@Event()
public created: EmitType<Object>;
/**
* Triggers when the TextBox component is destroyed.
*
* @event destroyed
*/
@Event()
public destroyed: EmitType<Object>;
/**
* Triggers when the content of TextBox has changed and gets focus-out.
*
* @event change
*/
@Event()
public change: EmitType<ChangedEventArgs>;
/**
* Triggers when the TextBox has focus-out.
*
* @event blur
*/
@Event()
public blur: EmitType<FocusOutEventArgs>;
/**
* Triggers when the TextBox gets focus.
*
* @event focus
*/
@Event()
public focus: EmitType<FocusInEventArgs>;
/**
* Triggers each time when the value of TextBox has changed.
*
* @event input
*/
@Event()
public input: EmitType<InputEventArgs>;
/**
*
* @param {TextBoxModel} options - Specifies the TextBox model.
* @param {string | HTMLInputElement | HTMLTextAreaElement} element - Specifies the element to render as component.
* @private
*/
public constructor(options?: TextBoxModel, element?: string | HTMLInputElement | HTMLTextAreaElement ) {
super(options, <string | HTMLInputElement | HTMLTextAreaElement> element);
this.textboxOptions = options;
}
/**
* Calls internally if any of the property value is changed.
*
* @param {TextBoxModel} newProp - Returns the dynamic property value of the component.
* @param {TextBoxModel} oldProp - Returns the previous property value of the component.
* @returns {void}
* @private
*/
public onPropertyChanged(newProp: TextBoxModel, oldProp: TextBoxModel): void {
for (const prop of Object.keys(newProp)) {
switch (prop) {
case 'floatLabelType':
Input.removeFloating(this.textboxWrapper);
Input.addFloating(this.respectiveElement, this.floatLabelType, this.placeholder);
break;
case 'enabled':
Input.setEnabled(this.enabled, this.respectiveElement, this.floatLabelType, this.textboxWrapper.container);
this.bindClearEvent();
break;
case 'width':
Input.setWidth(newProp.width, this.textboxWrapper.container);
break;
case 'value': {
const prevOnChange: boolean = this.isProtectedOnChange;
this.isProtectedOnChange = true;
if (!this.isBlank(this.value)) {
this.value = this.value.toString();
}
this.isProtectedOnChange = prevOnChange;
Input.setValue(this.value, this.respectiveElement, this.floatLabelType, this.showClearButton);
if (this.isHiddenInput) {
this.element.value = this.respectiveElement.value;
}
this.inputPreviousValue = this.respectiveElement.value;
/* istanbul ignore next */
if ((this.isAngular || this.isVue) && this.preventChange === true) {
this.previousValue = this.isAngular ? this.value : this.previousValue;
this.preventChange = false;
} else if (isNullOrUndefined(this.isAngular) || !this.isAngular
|| (this.isAngular && !this.preventChange) || (this.isAngular && isNullOrUndefined(this.preventChange))) {
this.raiseChangeEvent();
}
}
break;
case 'htmlAttributes': {
this.updateHTMLAttrToElement();
this.updateHTMLAttrToWrapper();
this.checkAttributes(true);
Input.validateInputType(this.textboxWrapper.container, this.element);
}
break;
case 'readonly':
Input.setReadonly(this.readonly, this.respectiveElement);
break;
case 'type':
if (this.respectiveElement.tagName !== 'TEXTAREA') {
this.respectiveElement.setAttribute('type', this.type);
Input.validateInputType(this.textboxWrapper.container, this.element);
this.raiseChangeEvent();
}
break;
case 'showClearButton':
if (this.respectiveElement.tagName !== 'TEXTAREA') {
Input.setClearButton(this.showClearButton, this.respectiveElement, this.textboxWrapper);
this.bindClearEvent();
}
break;
case 'enableRtl':
Input.setEnableRtl(this.enableRtl, [this.textboxWrapper.container]);
break;
case 'placeholder':
Input.setPlaceholder(this.placeholder, this.respectiveElement);
break;
case 'autocomplete':
if ( this.autocomplete !== 'on' && this.autocomplete !== '') {
this.respectiveElement.autocomplete = this.autocomplete;
} else {
this.removeAttributes(['autocomplete']);
}
break;
case 'cssClass':
this.updateCssClass(newProp.cssClass, oldProp.cssClass);
break;
case 'locale':
this.globalize = new Internationalization(this.locale);
this.l10n.setLocale(this.locale);
this.setProperties({ placeholder: this.l10n.getConstant('placeholder') }, true);
Input.setPlaceholder(this.placeholder, this.respectiveElement);
break;
}
}
}
/**
* Gets the component name
*
* @returns {string} Returns the component name.
* @private
*/
public getModuleName(): string {
return 'textbox';
}
private isBlank(str: string): boolean {
return (!str || /^\s*$/.test(str));
}
protected preRender(): void {
this.cloneElement = <HTMLInputElement>this.element.cloneNode(true);
this.formElement = closest(this.element, 'form') as HTMLFormElement;
if (!isNullOrUndefined(this.formElement)) {
this.isForm = true;
}
/* istanbul ignore next */
if (this.element.tagName === 'EJS-TEXTBOX') {
const ejInstance: Object = getValue('ej2_instances', this.element);
const inputElement: string | HTMLInputElement | HTMLTextAreaElement = this.multiline ?
<HTMLTextAreaElement>this.createElement('textarea') :
<HTMLInputElement>this.createElement('input');
let index: number = 0;
for (index; index < this.element.attributes.length; index++) {
const attributeName: string = this.element.attributes[index].nodeName;
if (attributeName !== 'id') {
inputElement.setAttribute(attributeName, this.element.attributes[index].nodeValue);
inputElement.innerHTML = this.element.innerHTML;
if (attributeName === 'name') {
this.element.removeAttribute('name');
}
}
}
this.element.appendChild(inputElement);
this.element = inputElement;
setValue('ej2_instances', ejInstance, this.element);
}
this.updateHTMLAttrToElement();
this.checkAttributes(false);
if (this.element.tagName !== 'TEXTAREA') {
this.element.setAttribute('type', this.type);
}
this.element.setAttribute('role', 'textbox');
this.globalize = new Internationalization(this.locale);
const localeText: { placeholder: string } = { placeholder: this.placeholder };
this.l10n = new L10n('textbox', localeText, this.locale);
if (this.l10n.getConstant('placeholder') !== '') {
this.setProperties({ placeholder: this.placeholder || this.l10n.getConstant('placeholder') }, true);
}
if (!this.element.hasAttribute('id')) {
this.element.setAttribute('id', getUniqueID('textbox'));
}
if (!this.element.hasAttribute('name')) {
this.element.setAttribute('name', this.element.getAttribute('id'));
}
if (this.element.tagName === 'INPUT' && this.multiline) {
this.isHiddenInput = true;
this.textarea = <HTMLTextAreaElement>this.createElement('textarea');
this.element.parentNode.insertBefore(this.textarea, this.element);
this.element.setAttribute('type', 'hidden');
this.textarea.setAttribute('name', this.element.getAttribute('name'));
this.element.removeAttribute('name');
this.textarea.setAttribute('role', this.element.getAttribute('role'));
this.element.removeAttribute('role');
this.textarea.setAttribute('id', getUniqueID('textarea'));
const apiAttributes : string[] = ['placeholder', 'disabled', 'value', 'readonly', 'type', 'autocomplete'];
for (let index: number = 0; index < this.element.attributes.length; index++) {
const attributeName: string = this.element.attributes[index].nodeName;
if (this.element.hasAttribute(attributeName) && containerAttr.indexOf(attributeName) < 0 &&
!(attributeName === 'id' || attributeName === 'type' || attributeName === 'e-mappinguid')) {
// e-mappinguid attribute is handled for Grid component.
this.textarea.setAttribute(attributeName, this.element.attributes[index].nodeValue);
if (apiAttributes.indexOf(attributeName) < 0) {
this.element.removeAttribute(attributeName);
index--;
}
}
}
}
}
private checkAttributes(isDynamic: boolean): void {
const attrs: string[] = isDynamic ? isNullOrUndefined(this.htmlAttributes) ? [] : Object.keys(this.htmlAttributes) :
['placeholder', 'disabled', 'value', 'readonly', 'type', 'autocomplete'];
for (const key of attrs) {
if (!isNullOrUndefined(this.element.getAttribute(key))) {
switch (key) {
case 'disabled':
if (( isNullOrUndefined(this.textboxOptions) || (this.textboxOptions['enabled'] === undefined)) || isDynamic) {
const enabled: boolean = this.element.getAttribute(key) === 'disabled' || this.element.getAttribute(key) === '' ||
this.element.getAttribute(key) === 'true' ? false : true;
this.setProperties({enabled: enabled}, !isDynamic);
}
break;
case 'readonly':
if (( isNullOrUndefined(this.textboxOptions) || (this.textboxOptions['readonly'] === undefined)) || isDynamic) {
const readonly: boolean = this.element.getAttribute(key) === 'readonly' || this.element.getAttribute(key) === ''
|| this.element.getAttribute(key) === 'true' ? true : false;
this.setProperties({readonly: readonly}, !isDynamic);
}
break;
case 'placeholder':
if (( isNullOrUndefined(this.textboxOptions) || (this.textboxOptions['placeholder'] === undefined)) || isDynamic) {
this.setProperties({placeholder: this.element.placeholder}, !isDynamic);
}
break;
case 'autocomplete':
if (( isNullOrUndefined(this.textboxOptions) || (this.textboxOptions['autocomplete'] === undefined)) || isDynamic) {
const autoCompleteTxt: string = this.element.autocomplete === 'off' ? 'off' : 'on';
this.setProperties({ autocomplete: autoCompleteTxt }, !isDynamic);
}
break;
case 'value':
if (( isNullOrUndefined(this.textboxOptions) || (this.textboxOptions['value'] === undefined)) || isDynamic) {
this.setProperties({value: this.element.value}, !isDynamic);
}
break;
case 'type':
if (( isNullOrUndefined(this.textboxOptions) || (this.textboxOptions['type'] === undefined)) || isDynamic) {
this.setProperties({type: this.element.type}, !isDynamic);
}
break;
}
}
}
}
/**
* To Initialize the control rendering
*
* @returns {void}
* @private
*/
public render(): void {
let updatedCssClassValue: string = this.cssClass;
if (!isNullOrUndefined(this.cssClass) && this.cssClass !== '') {
updatedCssClassValue = this.getInputValidClassList(this.cssClass);
}
this.respectiveElement = (this.isHiddenInput) ? this.textarea : this.element;
this.textboxWrapper = Input.createInput({
element: this.respectiveElement,
floatLabelType: this.floatLabelType,
properties: {
enabled: this.enabled,
enableRtl: this.enableRtl,
cssClass: updatedCssClassValue,
readonly: this.readonly,
placeholder: this.placeholder,
showClearButton: this.showClearButton
}
});
this.updateHTMLAttrToWrapper();
if (this.isHiddenInput) {
this.respectiveElement.parentNode.insertBefore(this.element, this.respectiveElement);
}
this.wireEvents();
if (!isNullOrUndefined(this.value)) {
Input.setValue(this.value, this.respectiveElement, this.floatLabelType, this.showClearButton);
if (this.isHiddenInput) {
this.element.value = this.respectiveElement.value;
}
}
if (!isNullOrUndefined(this.value)) {
this.initialValue = this.value;
this.setInitialValue();
}
if (this.autocomplete !== 'on' && this.autocomplete !== '') {
this.respectiveElement.autocomplete = this.autocomplete;
} else if (!isNullOrUndefined(this.textboxOptions) && (this.textboxOptions['autocomplete'] !== undefined)) {
this.removeAttributes(['autocomplete']);
}
this.previousValue = this.value;
this.inputPreviousValue = this.value;
this.respectiveElement.defaultValue = this.respectiveElement.value;
Input.setWidth(this.width, this.textboxWrapper.container);
this.renderComplete();
}
private updateHTMLAttrToWrapper(): void {
if ( !isNullOrUndefined(this.htmlAttributes)) {
for (const key of Object.keys(this.htmlAttributes)) {
if (containerAttr.indexOf(key) > -1 ) {
if (key === 'class') {
const updatedClassValues : string = this.getInputValidClassList(this.htmlAttributes[key]);
if (updatedClassValues !== '') {
addClass([this.textboxWrapper.container], updatedClassValues.split(' '));
}
} else if (key === 'style') {
let setStyle: string = this.textboxWrapper.container.getAttribute(key);
setStyle = !isNullOrUndefined(setStyle) ? (setStyle + this.htmlAttributes[key]) :
this.htmlAttributes[key];
this.textboxWrapper.container.setAttribute(key, setStyle);
} else {
this.textboxWrapper.container.setAttribute(key, this.htmlAttributes[key]);
}
}
}
}
}
private updateHTMLAttrToElement(): void {
if ( !isNullOrUndefined(this.htmlAttributes)) {
for (const key of Object.keys(this.htmlAttributes)) {
if (containerAttr.indexOf(key) < 0 ) {
this.element.setAttribute(key, this.htmlAttributes[key]);
}
}
}
}
private updateCssClass(newClass : string, oldClass : string) : void {
Input.setCssClass(this.getInputValidClassList(newClass), [this.textboxWrapper.container], this.getInputValidClassList(oldClass));
}
private getInputValidClassList(inputClassName: string): string {
let result: string = inputClassName;
if (!isNullOrUndefined(inputClassName) && inputClassName !== '') {
result = (inputClassName.replace(/\s+/g, ' ')).trim();
}
return result;
}
private setInitialValue() : void {
if (!this.isAngular) {
this.respectiveElement.setAttribute('value', this.initialValue);
}
}
private wireEvents(): void {
EventHandler.add(this.respectiveElement, 'focus', this.focusHandler, this);
EventHandler.add(this.respectiveElement, 'blur', this.focusOutHandler, this);
EventHandler.add(this.respectiveElement, 'input', this.inputHandler, this);
EventHandler.add(this.respectiveElement, 'change', this.changeHandler, this);
if (this.isForm) {
EventHandler.add(this.formElement, 'reset', this.resetForm, this);
}
this.bindClearEvent();
if (!isNullOrUndefined(this.textboxWrapper.container.querySelector('.e-float-text')) && this.floatLabelType === 'Auto'
&& this.textboxWrapper.container.classList.contains('e-autofill') &&
this.textboxWrapper.container.classList.contains('e-outline')) {
EventHandler.add((this.textboxWrapper.container.querySelector('.e-float-text')), 'animationstart', this.animationHandler, this);
}
}
private animationHandler() : void {
this.textboxWrapper.container.classList.add('e-valid-input');
const label: HTMLElement = this.textboxWrapper.container.querySelector('.e-float-text');
if (!isNullOrUndefined(label)) {
label.classList.add('e-label-top');
if (label.classList.contains('e-label-bottom')) {
label.classList.remove('e-label-bottom');
}
}
}
private resetValue(value: string) : void {
const prevOnChange: boolean = this.isProtectedOnChange;
this.isProtectedOnChange = true;
this.value = value;
this.isProtectedOnChange = prevOnChange;
}
private resetForm() : void {
if (this.isAngular) {
this.resetValue('');
} else {
this.resetValue(this.initialValue);
}
if (!isNullOrUndefined(this.textboxWrapper)) {
const label: HTMLElement = this.textboxWrapper.container.querySelector('.e-float-text');
if (!isNullOrUndefined(label)) {
if ((isNullOrUndefined(this.initialValue) || this.initialValue === '')) {
label.classList.add('e-label-bottom');
label.classList.remove('e-label-top');
} else if (this.initialValue !== '') {
label.classList.add('e-label-top');
label.classList.remove('e-label-bottom');
}
}
}
}
private focusHandler(args: MouseEvent | TouchEvent | KeyboardEvent): void {
const eventArgs: FocusInEventArgs = {
container: this.textboxWrapper.container,
event: args,
value: this.value
};
this.trigger('focus', eventArgs);
}
private focusOutHandler(args: MouseEvent | TouchEvent | KeyboardEvent): void {
if (!(this.previousValue === null && this.value === null && this.respectiveElement.value === '') &&
(this.previousValue !== this.respectiveElement.value)) {
this.raiseChangeEvent(args, true);
}
const eventArgs: FocusOutEventArgs = {
container: this.textboxWrapper.container,
event: args,
value: this.value
};
this.trigger('blur', eventArgs);
}
private inputHandler(args: KeyboardEvent): void {
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-this-alias
const textboxObj: any = this;
const eventArgs: InputEventArgs = {
event: args,
value: this.respectiveElement.value,
previousValue: this.inputPreviousValue,
container: this.textboxWrapper.container
};
this.inputPreviousValue = this.respectiveElement.value;
/* istanbul ignore next */
if (this.isAngular) {
textboxObj.localChange({ value: this.respectiveElement.value });
this.preventChange = true;
}
if (this.isVue) {
this.preventChange = true;
}
this.trigger('input', eventArgs);
args.stopPropagation();
}
private changeHandler(args: Event): void {
this.setProperties({value: this.respectiveElement.value}, true);
this.raiseChangeEvent(args, true);
args.stopPropagation();
}
private raiseChangeEvent(event?: Event, interaction?: boolean): void {
const eventArgs: ChangedEventArgs = {
event: event,
value: this.value,
previousValue: this.previousValue,
container: this.textboxWrapper.container,
isInteraction: interaction ? interaction : false,
isInteracted: interaction ? interaction : false
};
this.preventChange = false;
this.trigger('change', eventArgs);
this.previousValue = this.value;
}
private bindClearEvent(): void {
if (this.showClearButton && this.respectiveElement.tagName !== 'TEXTAREA') {
if (this.enabled) {
EventHandler.add(this.textboxWrapper.clearButton, 'mousedown touchstart', this.resetInputHandler, this);
} else {
EventHandler.remove(this.textboxWrapper.clearButton, 'mousedown touchstart', this.resetInputHandler);
}
}
}
private resetInputHandler(event?: MouseEvent): void {
event.preventDefault();
if (!(this.textboxWrapper.clearButton.classList.contains(HIDE_CLEAR))) {
Input.setValue('', this.respectiveElement, this.floatLabelType, this.showClearButton);
if (this.isHiddenInput) {
this.element.value = this.respectiveElement.value;
}
this.setProperties({value: this.respectiveElement.value}, true);
const eventArgs: InputEventArgs = {
event: event,
value: this.respectiveElement.value,
previousValue: this.inputPreviousValue,
container: this.textboxWrapper.container
};
this.trigger('input', eventArgs);
this.inputPreviousValue = this.respectiveElement.value;
this.raiseChangeEvent(event, true);
}
}
private unWireEvents(): void {
EventHandler.remove(this.respectiveElement, 'focus', this.focusHandler);
EventHandler.remove(this.respectiveElement, 'blur', this.focusOutHandler);
EventHandler.remove(this.respectiveElement, 'input', this.inputHandler);
EventHandler.remove(this.respectiveElement, 'change', this.changeHandler);
if (this.isForm) {
EventHandler.remove(this.formElement, 'reset', this.resetForm);
}
if (!isNullOrUndefined(this.textboxWrapper.container.querySelector('.e-float-text')) && this.floatLabelType === 'Auto'
&& this.textboxWrapper.container.classList.contains('e-outline') &&
this.textboxWrapper.container.classList.contains('e-autofill')) {
EventHandler.remove((this.textboxWrapper.container.querySelector('.e-float-text')), 'animationstart', this.animationHandler);
}
}
/**
* Removes the component from the DOM and detaches all its related event handlers.
* Also, it maintains the initial TextBox element from the DOM.
*
* @method destroy
* @returns {void}
*/
public destroy(): void {
this.unWireEvents();
if (this.element.tagName === 'INPUT' && this.multiline) {
detach(this.textboxWrapper.container.getElementsByTagName('textarea')[0]);
this.respectiveElement = this.element;
this.element.removeAttribute('type');
}
this.respectiveElement.value = this.respectiveElement.defaultValue;
this.respectiveElement.classList.remove('e-input');
this.removeAttributes(['aria-placeholder', 'aria-disabled', 'aria-readonly', 'aria-labelledby']);
if (!isNullOrUndefined(this.textboxWrapper)) {
this.textboxWrapper.container.insertAdjacentElement('afterend', this.respectiveElement);
detach(this.textboxWrapper.container);
}
this.textboxWrapper = null;
super.destroy();
}
/**
* Adding the icons to the TextBox component.
*
* @param { string } position - Specify the icon placement on the TextBox. Possible values are append and prepend.
* @param { string | string[] } icons - Icon classes which are need to add to the span element which is going to created.
* Span element acts as icon or button element for TextBox.
* @returns {void}
*/
public addIcon(position: string, icons: string | string[]): void {
Input.addIcon(position, icons, this.textboxWrapper.container, this.respectiveElement, this.createElement);
}
/* eslint-disable valid-jsdoc, jsdoc/require-returns */
/**
* Gets the properties to be maintained in the persisted state.
*
*/
public getPersistData(): string {
const keyEntity: string[] = ['value'];
return this.addOnPersist(keyEntity);
}
/* eslint-enable valid-jsdoc, jsdoc/require-returns */
/**
* Adding the multiple attributes as key-value pair to the TextBox element.
*
* @param {string} attributes - Specifies the attributes to be add to TextBox element.
* @returns {void}
*/
public addAttributes(attributes: { [key: string]: string }): void {
for (const key of Object.keys(attributes)) {
if (key === 'disabled') {
this.setProperties({ enabled: false }, true);
Input.setEnabled(this.enabled, this.respectiveElement, this.floatLabelType, this.textboxWrapper.container);
} else if (key === 'readonly') {
this.setProperties({ readonly: true }, true);
Input.setReadonly(this.readonly, this.respectiveElement);
} else if (key === 'class') {
this.respectiveElement.classList.add(attributes[key]);
} else if (key === 'placeholder') {
this.setProperties({ placeholder: attributes[key] }, true);
Input.setPlaceholder(this.placeholder, this.respectiveElement);
} else if (key === 'rows' && this.respectiveElement.tagName === 'TEXTAREA') {
this.respectiveElement.setAttribute(key, attributes[key]);
} else {
this.respectiveElement.setAttribute(key, attributes[key]);
}
}
}
/**
* Removing the multiple attributes as key-value pair to the TextBox element.
*
* @param { string[] } attributes - Specifies the attributes name to be removed from TextBox element.
* @returns {void}
*/
public removeAttributes(attributes: string[]): void {
for (const key of attributes) {
if (key === 'disabled') {
this.setProperties({ enabled: true }, true);
Input.setEnabled(this.enabled, this.respectiveElement, this.floatLabelType, this.textboxWrapper.container);
} else if (key === 'readonly') {
this.setProperties({ readonly: false }, true);
Input.setReadonly(this.readonly, this.respectiveElement);
} else if (key === 'placeholder') {
this.setProperties({ placeholder: null }, true);
Input.setPlaceholder(this.placeholder, this.respectiveElement);
} else {
this.respectiveElement.removeAttribute(key);
}
}
}
/**
* Sets the focus to widget for interaction.
*
* @returns {void}
*/
public focusIn(): void {
if (document.activeElement !== this.respectiveElement && this.enabled) {
this.respectiveElement.focus();
if (this.textboxWrapper.container.classList.contains('e-input-group')
|| this.textboxWrapper.container.classList.contains('e-outline')
|| this.textboxWrapper.container.classList.contains('e-filled')) {
addClass([this.textboxWrapper.container], [TEXTBOX_FOCUS]);
}
}
}
/**
* Remove the focus from widget, if the widget is in focus state.
*
* @returns {void}
*/
public focusOut(): void {
if (document.activeElement === this.respectiveElement && this.enabled) {
this.respectiveElement.blur();
if (this.textboxWrapper.container.classList.contains('e-input-group')
|| this.textboxWrapper.container.classList.contains('e-outline')
|| this.textboxWrapper.container.classList.contains('e-filled')) {
removeClass([this.textboxWrapper.container], [TEXTBOX_FOCUS]);
}
}
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { WCFRelays } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { RelayAPI } from "../relayAPI";
import {
WcfRelay,
WCFRelaysListByNamespaceNextOptionalParams,
WCFRelaysListByNamespaceOptionalParams,
AuthorizationRule,
WCFRelaysListAuthorizationRulesNextOptionalParams,
WCFRelaysListAuthorizationRulesOptionalParams,
WCFRelaysListByNamespaceResponse,
WCFRelaysCreateOrUpdateOptionalParams,
WCFRelaysCreateOrUpdateResponse,
WCFRelaysDeleteOptionalParams,
WCFRelaysGetOptionalParams,
WCFRelaysGetResponse,
WCFRelaysListAuthorizationRulesResponse,
WCFRelaysCreateOrUpdateAuthorizationRuleOptionalParams,
WCFRelaysCreateOrUpdateAuthorizationRuleResponse,
WCFRelaysDeleteAuthorizationRuleOptionalParams,
WCFRelaysGetAuthorizationRuleOptionalParams,
WCFRelaysGetAuthorizationRuleResponse,
WCFRelaysListKeysOptionalParams,
WCFRelaysListKeysResponse,
RegenerateAccessKeyParameters,
WCFRelaysRegenerateKeysOptionalParams,
WCFRelaysRegenerateKeysResponse,
WCFRelaysListByNamespaceNextResponse,
WCFRelaysListAuthorizationRulesNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing WCFRelays operations. */
export class WCFRelaysImpl implements WCFRelays {
private readonly client: RelayAPI;
/**
* Initialize a new instance of the class WCFRelays class.
* @param client Reference to the service client
*/
constructor(client: RelayAPI) {
this.client = client;
}
/**
* Lists the WCF relays within the namespace.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param options The options parameters.
*/
public listByNamespace(
resourceGroupName: string,
namespaceName: string,
options?: WCFRelaysListByNamespaceOptionalParams
): PagedAsyncIterableIterator<WcfRelay> {
const iter = this.listByNamespacePagingAll(
resourceGroupName,
namespaceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByNamespacePagingPage(
resourceGroupName,
namespaceName,
options
);
}
};
}
private async *listByNamespacePagingPage(
resourceGroupName: string,
namespaceName: string,
options?: WCFRelaysListByNamespaceOptionalParams
): AsyncIterableIterator<WcfRelay[]> {
let result = await this._listByNamespace(
resourceGroupName,
namespaceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByNamespaceNext(
resourceGroupName,
namespaceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByNamespacePagingAll(
resourceGroupName: string,
namespaceName: string,
options?: WCFRelaysListByNamespaceOptionalParams
): AsyncIterableIterator<WcfRelay> {
for await (const page of this.listByNamespacePagingPage(
resourceGroupName,
namespaceName,
options
)) {
yield* page;
}
}
/**
* Authorization rules for a WCF relay.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param options The options parameters.
*/
public listAuthorizationRules(
resourceGroupName: string,
namespaceName: string,
relayName: string,
options?: WCFRelaysListAuthorizationRulesOptionalParams
): PagedAsyncIterableIterator<AuthorizationRule> {
const iter = this.listAuthorizationRulesPagingAll(
resourceGroupName,
namespaceName,
relayName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listAuthorizationRulesPagingPage(
resourceGroupName,
namespaceName,
relayName,
options
);
}
};
}
private async *listAuthorizationRulesPagingPage(
resourceGroupName: string,
namespaceName: string,
relayName: string,
options?: WCFRelaysListAuthorizationRulesOptionalParams
): AsyncIterableIterator<AuthorizationRule[]> {
let result = await this._listAuthorizationRules(
resourceGroupName,
namespaceName,
relayName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listAuthorizationRulesNext(
resourceGroupName,
namespaceName,
relayName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listAuthorizationRulesPagingAll(
resourceGroupName: string,
namespaceName: string,
relayName: string,
options?: WCFRelaysListAuthorizationRulesOptionalParams
): AsyncIterableIterator<AuthorizationRule> {
for await (const page of this.listAuthorizationRulesPagingPage(
resourceGroupName,
namespaceName,
relayName,
options
)) {
yield* page;
}
}
/**
* Lists the WCF relays within the namespace.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param options The options parameters.
*/
private _listByNamespace(
resourceGroupName: string,
namespaceName: string,
options?: WCFRelaysListByNamespaceOptionalParams
): Promise<WCFRelaysListByNamespaceResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, namespaceName, options },
listByNamespaceOperationSpec
);
}
/**
* Creates or updates a WCF relay. This operation is idempotent.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param parameters Parameters supplied to create a WCF relay.
* @param options The options parameters.
*/
createOrUpdate(
resourceGroupName: string,
namespaceName: string,
relayName: string,
parameters: WcfRelay,
options?: WCFRelaysCreateOrUpdateOptionalParams
): Promise<WCFRelaysCreateOrUpdateResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, namespaceName, relayName, parameters, options },
createOrUpdateOperationSpec
);
}
/**
* Deletes a WCF relay.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param options The options parameters.
*/
delete(
resourceGroupName: string,
namespaceName: string,
relayName: string,
options?: WCFRelaysDeleteOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, namespaceName, relayName, options },
deleteOperationSpec
);
}
/**
* Returns the description for the specified WCF relay.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
namespaceName: string,
relayName: string,
options?: WCFRelaysGetOptionalParams
): Promise<WCFRelaysGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, namespaceName, relayName, options },
getOperationSpec
);
}
/**
* Authorization rules for a WCF relay.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param options The options parameters.
*/
private _listAuthorizationRules(
resourceGroupName: string,
namespaceName: string,
relayName: string,
options?: WCFRelaysListAuthorizationRulesOptionalParams
): Promise<WCFRelaysListAuthorizationRulesResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, namespaceName, relayName, options },
listAuthorizationRulesOperationSpec
);
}
/**
* Creates or updates an authorization rule for a WCF relay.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param authorizationRuleName The authorization rule name.
* @param parameters The authorization rule parameters.
* @param options The options parameters.
*/
createOrUpdateAuthorizationRule(
resourceGroupName: string,
namespaceName: string,
relayName: string,
authorizationRuleName: string,
parameters: AuthorizationRule,
options?: WCFRelaysCreateOrUpdateAuthorizationRuleOptionalParams
): Promise<WCFRelaysCreateOrUpdateAuthorizationRuleResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
namespaceName,
relayName,
authorizationRuleName,
parameters,
options
},
createOrUpdateAuthorizationRuleOperationSpec
);
}
/**
* Deletes a WCF relay authorization rule.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param authorizationRuleName The authorization rule name.
* @param options The options parameters.
*/
deleteAuthorizationRule(
resourceGroupName: string,
namespaceName: string,
relayName: string,
authorizationRuleName: string,
options?: WCFRelaysDeleteAuthorizationRuleOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{
resourceGroupName,
namespaceName,
relayName,
authorizationRuleName,
options
},
deleteAuthorizationRuleOperationSpec
);
}
/**
* Get authorizationRule for a WCF relay by name.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param authorizationRuleName The authorization rule name.
* @param options The options parameters.
*/
getAuthorizationRule(
resourceGroupName: string,
namespaceName: string,
relayName: string,
authorizationRuleName: string,
options?: WCFRelaysGetAuthorizationRuleOptionalParams
): Promise<WCFRelaysGetAuthorizationRuleResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
namespaceName,
relayName,
authorizationRuleName,
options
},
getAuthorizationRuleOperationSpec
);
}
/**
* Primary and secondary connection strings to the WCF relay.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param authorizationRuleName The authorization rule name.
* @param options The options parameters.
*/
listKeys(
resourceGroupName: string,
namespaceName: string,
relayName: string,
authorizationRuleName: string,
options?: WCFRelaysListKeysOptionalParams
): Promise<WCFRelaysListKeysResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
namespaceName,
relayName,
authorizationRuleName,
options
},
listKeysOperationSpec
);
}
/**
* Regenerates the primary or secondary connection strings to the WCF relay.
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param authorizationRuleName The authorization rule name.
* @param parameters Parameters supplied to regenerate authorization rule.
* @param options The options parameters.
*/
regenerateKeys(
resourceGroupName: string,
namespaceName: string,
relayName: string,
authorizationRuleName: string,
parameters: RegenerateAccessKeyParameters,
options?: WCFRelaysRegenerateKeysOptionalParams
): Promise<WCFRelaysRegenerateKeysResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
namespaceName,
relayName,
authorizationRuleName,
parameters,
options
},
regenerateKeysOperationSpec
);
}
/**
* ListByNamespaceNext
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param nextLink The nextLink from the previous successful call to the ListByNamespace method.
* @param options The options parameters.
*/
private _listByNamespaceNext(
resourceGroupName: string,
namespaceName: string,
nextLink: string,
options?: WCFRelaysListByNamespaceNextOptionalParams
): Promise<WCFRelaysListByNamespaceNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, namespaceName, nextLink, options },
listByNamespaceNextOperationSpec
);
}
/**
* ListAuthorizationRulesNext
* @param resourceGroupName Name of the Resource group within the Azure subscription.
* @param namespaceName The namespace name
* @param relayName The relay name.
* @param nextLink The nextLink from the previous successful call to the ListAuthorizationRules method.
* @param options The options parameters.
*/
private _listAuthorizationRulesNext(
resourceGroupName: string,
namespaceName: string,
relayName: string,
nextLink: string,
options?: WCFRelaysListAuthorizationRulesNextOptionalParams
): Promise<WCFRelaysListAuthorizationRulesNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, namespaceName, relayName, nextLink, options },
listAuthorizationRulesNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByNamespaceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.WcfRelaysListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.WcfRelay
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters6,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.relayName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.relayName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.WcfRelay
},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.relayName
],
headerParameters: [Parameters.accept],
serializer
};
const listAuthorizationRulesOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AuthorizationRuleListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.relayName
],
headerParameters: [Parameters.accept],
serializer
};
const createOrUpdateAuthorizationRuleOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.AuthorizationRule
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters3,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.authorizationRuleName,
Parameters.relayName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const deleteAuthorizationRuleOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}",
httpMethod: "DELETE",
responses: {
200: {},
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.authorizationRuleName,
Parameters.relayName
],
headerParameters: [Parameters.accept],
serializer
};
const getAuthorizationRuleOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AuthorizationRule
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.authorizationRuleName,
Parameters.relayName
],
headerParameters: [Parameters.accept],
serializer
};
const listKeysOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/listKeys",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.AccessKeys
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.authorizationRuleName,
Parameters.relayName
],
headerParameters: [Parameters.accept],
serializer
};
const regenerateKeysOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/regenerateKeys",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.AccessKeys
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters4,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.authorizationRuleName,
Parameters.relayName
],
headerParameters: [Parameters.accept, Parameters.contentType],
mediaType: "json",
serializer
};
const listByNamespaceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.WcfRelaysListResult
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName
],
headerParameters: [Parameters.accept],
serializer
};
const listAuthorizationRulesNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AuthorizationRuleListResult
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.nextLink,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.namespaceName,
Parameters.relayName
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import type vscode from 'vscode';
import { Autowired, Injector, INJECTOR_TOKEN } from '@opensumi/di';
import { WSChannelHandler } from '@opensumi/ide-connection/lib/browser';
import {
EDITOR_COMMANDS,
UriComponents,
ClientAppContribution,
CommandContribution,
CommandRegistry,
CommandService,
Domain,
electronEnv,
FILE_COMMANDS,
formatLocalize,
getIcon,
IAsyncResult,
IClientApp,
IContextKeyService,
IEventBus,
IPreferenceSettingsService,
localize,
QuickOpenItem,
QuickOpenService,
replaceLocalizePlaceholder,
URI,
ILogger,
AppConfig,
} from '@opensumi/ide-core-browser';
import {
IStatusBarService,
StatusBarAlignment,
StatusBarEntryAccessor,
} from '@opensumi/ide-core-browser/lib/services/status-bar-service';
import { IResourceOpenOptions, WorkbenchEditorService, EditorGroupColumn } from '@opensumi/ide-editor';
import { IWindowDialogService } from '@opensumi/ide-overlay';
import { IWebviewService } from '@opensumi/ide-webview';
import type { ITextEditorOptions } from '@opensumi/monaco-editor-core/esm/vs/platform/editor/common/editor';
import {
ExtensionNodeServiceServerPath,
IExtensionNodeClientService,
EMIT_EXT_HOST_EVENT,
ExtensionHostProfilerServicePath,
ExtensionService,
IExtensionHostProfilerService,
ExtensionHostTypeUpperCase,
} from '../common';
import { ActivatedExtension } from '../common/activator';
import { TextDocumentShowOptions, ViewColumn, CUSTOM_EDITOR_SCHEME } from '../common/vscode';
import { fromRange, isLikelyVscodeRange, viewColumnToResourceOpenOptions } from '../common/vscode/converter';
import {
AbstractExtInstanceManagementService,
ExtensionApiReadyEvent,
ExtHostEvent,
IActivationEventService,
Serializable,
} from './types';
import * as VSCodeBuiltinCommands from './vscode/builtin-commands';
export const getClientId = (injector: Injector) => {
let clientId: string;
const appConfig: AppConfig = injector.get(AppConfig);
// Electron 环境下,未指定 isRemote 时默认使用本地连接
// 否则使用 WebSocket 连接
if (appConfig.isElectronRenderer && !appConfig.isRemote) {
clientId = electronEnv.metadata.windowClientId;
} else {
const channelHandler = injector.get(WSChannelHandler);
clientId = channelHandler.clientId;
}
return clientId;
};
@Domain(ClientAppContribution)
export class ExtensionClientAppContribution implements ClientAppContribution {
@Autowired(IPreferenceSettingsService)
private readonly preferenceSettingsService: IPreferenceSettingsService;
@Autowired(INJECTOR_TOKEN)
private readonly injector: Injector;
@Autowired(ExtensionNodeServiceServerPath)
private readonly extensionNodeClient: IExtensionNodeClientService;
@Autowired(QuickOpenService)
protected readonly quickOpenService: QuickOpenService;
@Autowired(IStatusBarService)
protected readonly statusBar: IStatusBarService;
@Autowired(IEventBus)
private readonly eventBus: IEventBus;
@Autowired(IWebviewService)
webviewService: IWebviewService;
@Autowired(ExtensionService)
private readonly extensionService: ExtensionService;
@Autowired(ILogger)
private readonly logger: ILogger;
initialize() {
/**
* 这里不需要阻塞 initialize 流程
* 因为其他 contribution 唯一依赖
* 的是主题信息,目前主题注册成功以
* 后会发送对应事件
*/
this.extensionService
.activate()
.catch((err) => {
this.logger.error(err);
})
.finally(() => {
const disposer = this.webviewService.registerWebviewReviver({
handles: () => 0,
revive: async (id: string) =>
new Promise<void>((resolve) => {
this.eventBus.on(ExtensionApiReadyEvent, () => {
disposer.dispose();
resolve(this.webviewService.tryReviveWebviewComponent(id));
});
}),
});
});
}
async onStart() {
this.preferenceSettingsService.registerSettingGroup({
id: 'extension',
title: localize('settings.group.extension'),
iconClass: getIcon('extension'),
});
}
onDisposeSideEffects() {
/**
* IDE 关闭或者刷新时销毁插件进程
* 最好在这里直接关掉插件进程,调用链路太长可能导致请求调不到后端
*/
this.extensionNodeClient.disposeClientExtProcess(this.clientId, false);
}
/**
* 当前客户端 id
*/
private get clientId() {
return getClientId(this.injector);
}
}
@Domain(CommandContribution)
export class ExtensionCommandContribution implements CommandContribution {
@Autowired(INJECTOR_TOKEN)
private readonly injector: Injector;
@Autowired(WorkbenchEditorService)
private readonly workbenchEditorService: WorkbenchEditorService;
@Autowired(IActivationEventService)
private readonly activationEventService: IActivationEventService;
@Autowired(QuickOpenService)
protected readonly quickOpenService: QuickOpenService;
@Autowired(ExtensionHostProfilerServicePath)
private readonly extensionProfiler: IExtensionHostProfilerService;
@Autowired(IStatusBarService)
protected readonly statusBar: IStatusBarService;
@Autowired(IWindowDialogService)
private readonly dialogService: IWindowDialogService;
@Autowired(IClientApp)
private readonly clientApp: IClientApp;
@Autowired(IEventBus)
private readonly eventBus: IEventBus;
@Autowired(CommandService)
private readonly commandService: CommandService;
@Autowired(IContextKeyService)
private readonly contextKeyService: IContextKeyService;
@Autowired(IWebviewService)
webviewService: IWebviewService;
@Autowired(ExtensionService)
private readonly extensionService: ExtensionService;
@Autowired(AbstractExtInstanceManagementService)
private readonly extensionInstanceManageService: AbstractExtInstanceManagementService;
@Autowired(ILogger)
private readonly logger: ILogger;
private cpuProfileStatus: StatusBarEntryAccessor | null;
registerCommands(registry: CommandRegistry) {
registry.registerCommand(
{
id: 'ext.restart',
label: '重启进程',
},
{
execute: async () => {
this.logger.log('插件进程开始重启');
await this.extensionService.restartExtProcess();
this.logger.log('插件进程重启结束');
},
},
);
this.registerVSCBuiltinCommands(registry);
}
private registerVSCBuiltinCommands(registry: CommandRegistry) {
// vscode `setContext` for extensions
// only works for global scoped context
registry.registerCommand(VSCodeBuiltinCommands.SET_CONTEXT, {
execute: (contextKey: any, contextValue: any) => {
this.contextKeyService.createKey(String(contextKey), contextValue);
},
});
registry.registerCommand(VSCodeBuiltinCommands.RELOAD_WINDOW_COMMAND, {
execute: () => {
this.clientApp.fireOnReload();
},
});
registry.registerCommand(EMIT_EXT_HOST_EVENT, {
execute: async (eventName: string, ...eventArgs: Serializable[]) => {
// activationEvent 添加 onEvent:xxx
await this.activationEventService.fireEvent('onEvent:' + eventName);
const results = await this.eventBus.fireAndAwait<any[]>(
new ExtHostEvent({
eventName,
eventArgs,
}),
);
const mergedResults: IAsyncResult<any[]>[] = [];
results.forEach((r) => {
if (r.err) {
mergedResults.push(r);
} else {
mergedResults.push(...(r.result! || []));
}
});
return mergedResults;
},
});
registry.registerCommand(VSCodeBuiltinCommands.SHOW_RUN_TIME_EXTENSION, {
execute: async () => {
const activated = await this.extensionService.getActivatedExtensions();
this.quickOpenService.open(
{
onType: (_: string, acceptor) => acceptor(this.asQuickOpenItems(activated)),
},
{
placeholder: '运行中的插件',
fuzzyMatchLabel: {
enableSeparateSubstringMatching: true,
},
},
);
},
});
registry.registerCommand(VSCodeBuiltinCommands.START_EXTENSION_HOST_PROFILER, {
execute: async () => {
if (!this.cpuProfileStatus) {
this.cpuProfileStatus = this.statusBar.addElement('ExtensionHostProfile', {
tooltip: formatLocalize('extension.profiling.clickStop', 'Click to stop profiling.'),
text: `$(sync~spin) ${formatLocalize('extension.profilingExtensionHost', 'Profiling Extension Host')}`,
alignment: StatusBarAlignment.RIGHT,
command: VSCodeBuiltinCommands.STOP_EXTENSION_HOST_PROFILER.id,
});
}
await this.extensionProfiler.$startProfile(this.clientId);
},
isPermitted: () => false,
});
registry.registerCommand(VSCodeBuiltinCommands.STOP_EXTENSION_HOST_PROFILER, {
execute: async () => {
const successful = await this.extensionProfiler.$stopProfile(this.clientId);
if (this.cpuProfileStatus) {
this.cpuProfileStatus.dispose();
this.cpuProfileStatus = null;
}
if (successful) {
const saveUri = await this.dialogService.showSaveDialog({
saveLabel: formatLocalize('extension.profile.save', 'Save Extension Host Profile'),
showNameInput: true,
defaultFileName: `CPU-${new Date().toISOString().replace(/[\-:]/g, '')}.cpuprofile`,
});
if (saveUri?.codeUri) {
await this.extensionProfiler.$saveLastProfile(saveUri?.codeUri.fsPath);
}
}
},
isPermitted: () => false,
});
registry.registerCommand(VSCodeBuiltinCommands.COPY_FILE_PATH, {
execute: async (uri: vscode.Uri) => {
await this.commandService.executeCommand(FILE_COMMANDS.COPY_PATH.id, URI.from(uri));
},
});
registry.registerCommand(VSCodeBuiltinCommands.COPY_RELATIVE_FILE_PATH, {
execute: async (uri: vscode.Uri) => {
await this.commandService.executeCommand(FILE_COMMANDS.COPY_RELATIVE_PATH.id, URI.from(uri));
},
});
registry.registerCommand(VSCodeBuiltinCommands.OPEN, {
execute: (
uriComponents: UriComponents,
columnOrOptions?: ViewColumn | TextDocumentShowOptions,
label?: string,
) => {
const uri = URI.from(uriComponents);
const options: IResourceOpenOptions = {};
if (columnOrOptions) {
if (typeof columnOrOptions === 'number') {
options.groupIndex = columnOrOptions;
} else {
options.groupIndex = columnOrOptions.viewColumn;
options.focus = options.preserveFocus = columnOrOptions.preserveFocus;
// 这个range 可能是 vscode.range, 因为不会经过args转换
if (columnOrOptions.selection && isLikelyVscodeRange(columnOrOptions.selection)) {
columnOrOptions.selection = fromRange(columnOrOptions.selection);
}
if (Array.isArray(columnOrOptions.selection) && columnOrOptions.selection.length === 2) {
const [start, end] = columnOrOptions.selection;
options.range = {
startLineNumber: start.line + 1,
startColumn: start.character + 1,
endLineNumber: end.line + 1,
endColumn: end.character + 1,
};
} else {
options.range = columnOrOptions.selection;
}
options.preview = columnOrOptions.preview;
}
}
if (label) {
options.label = label;
}
return this.workbenchEditorService.open(uri, options);
},
});
registry.registerCommand(VSCodeBuiltinCommands.OPEN_WITH, {
execute: (resource: UriComponents, id: string, columnAndOptions?: [EditorGroupColumn?, ITextEditorOptions?]) => {
const uri = URI.from(resource);
const options: IResourceOpenOptions = {};
const [columnArg] = columnAndOptions ?? [];
if (id !== 'default') {
options.forceOpenType = {
type: 'component',
componentId: `${CUSTOM_EDITOR_SCHEME}-${id}`,
};
}
if (typeof columnArg === 'number') {
options.groupIndex = columnArg;
}
return this.workbenchEditorService.open(uri, options);
},
});
registry.registerCommand(VSCodeBuiltinCommands.DIFF, {
execute: (left: UriComponents, right: UriComponents, title: string, options?: any) => {
const openOptions: IResourceOpenOptions = {
...viewColumnToResourceOpenOptions(options?.viewColumn),
revealFirstDiff: true,
...options,
};
return this.commandService.executeCommand(
EDITOR_COMMANDS.COMPARE.id,
{
original: URI.from(left),
modified: URI.from(right),
name: title,
},
openOptions,
);
},
});
[
// editor builtin commands
VSCodeBuiltinCommands.WORKBENCH_CLOSE_ACTIVE_EDITOR,
VSCodeBuiltinCommands.REVERT_AND_CLOSE_ACTIVE_EDITOR,
VSCodeBuiltinCommands.SPLIT_EDITOR_RIGHT,
VSCodeBuiltinCommands.SPLIT_EDITOR_DOWN,
VSCodeBuiltinCommands.EDITOR_NAVIGATE_BACK,
VSCodeBuiltinCommands.EDITOR_NAVIGATE_FORWARD,
VSCodeBuiltinCommands.EDITOR_SAVE_ALL,
VSCodeBuiltinCommands.CLOSE_ALL_EDITORS,
VSCodeBuiltinCommands.PREVIOUS_EDITOR,
VSCodeBuiltinCommands.PREVIOUS_EDITOR_IN_GROUP,
VSCodeBuiltinCommands.NEXT_EDITOR,
VSCodeBuiltinCommands.NEXT_EDITOR_IN_GROUP,
VSCodeBuiltinCommands.EVEN_EDITOR_WIDTH,
VSCodeBuiltinCommands.CLOSE_OTHER_GROUPS,
VSCodeBuiltinCommands.LAST_EDITOR_IN_GROUP,
VSCodeBuiltinCommands.OPEN_EDITOR_AT_INDEX,
VSCodeBuiltinCommands.CLOSE_OTHER_EDITORS,
VSCodeBuiltinCommands.NEW_UNTITLED_FILE,
VSCodeBuiltinCommands.FILE_SAVE,
VSCodeBuiltinCommands.SPLIT_EDITOR,
VSCodeBuiltinCommands.SPLIT_EDITOR_ORTHOGONAL,
VSCodeBuiltinCommands.NAVIGATE_LEFT,
VSCodeBuiltinCommands.NAVIGATE_RIGHT,
VSCodeBuiltinCommands.NAVIGATE_UP,
VSCodeBuiltinCommands.NAVIGATE_DOWN,
VSCodeBuiltinCommands.NAVIGATE_NEXT,
VSCodeBuiltinCommands.REVERT_FILES,
VSCodeBuiltinCommands.WORKBENCH_FOCUS_FILES_EXPLORER,
VSCodeBuiltinCommands.WORKBENCH_FOCUS_ACTIVE_EDITOR_GROUP,
VSCodeBuiltinCommands.API_OPEN_EDITOR_COMMAND_ID,
VSCodeBuiltinCommands.API_OPEN_DIFF_EDITOR_COMMAND_ID,
VSCodeBuiltinCommands.API_OPEN_WITH_EDITOR_COMMAND_ID,
// debug builtin commands
VSCodeBuiltinCommands.DEBUG_COMMAND_STEP_INTO,
VSCodeBuiltinCommands.DEBUG_COMMAND_STEP_OVER,
VSCodeBuiltinCommands.DEBUG_COMMAND_STEP_OUT,
VSCodeBuiltinCommands.DEBUG_COMMAND_CONTINUE,
VSCodeBuiltinCommands.DEBUG_COMMAND_RUN,
VSCodeBuiltinCommands.DEBUG_COMMAND_START,
VSCodeBuiltinCommands.DEBUG_COMMAND_PAUSE,
VSCodeBuiltinCommands.DEBUG_COMMAND_RESTART,
VSCodeBuiltinCommands.DEBUG_COMMAND_STOP,
VSCodeBuiltinCommands.EDITOR_SHOW_ALL_SYMBOLS,
// explorer builtin commands
VSCodeBuiltinCommands.REVEAL_IN_EXPLORER,
VSCodeBuiltinCommands.OPEN_FOLDER,
// terminal builtin commands
VSCodeBuiltinCommands.CLEAR_TERMINAL,
VSCodeBuiltinCommands.TOGGLE_WORKBENCH_VIEW_TERMINAL,
VSCodeBuiltinCommands.NEW_WORKBENCH_VIEW_TERMINAL,
// others
VSCodeBuiltinCommands.RELOAD_WINDOW,
VSCodeBuiltinCommands.SETTINGS_COMMAND_OPEN_SETTINGS,
VSCodeBuiltinCommands.SETTINGS_COMMAND_OPEN_SETTINGS_JSON,
].forEach((command) => {
registry.registerCommand(command);
});
}
private asQuickOpenItems(activated: {
node?: ActivatedExtension[] | undefined;
worker?: ActivatedExtension[] | undefined;
}): QuickOpenItem[] {
const nodes = activated.node ? activated.node.map((e, i) => this.toQuickOpenItem(e, 'Node.js', i === 0)) : [];
const workers = activated.worker
? activated.worker.map((e, i) => this.toQuickOpenItem(e, 'Web Worker', i === 0))
: [];
return [...nodes, ...workers];
}
private toQuickOpenItem(e: ActivatedExtension, host: ExtensionHostTypeUpperCase, firstItem: boolean): QuickOpenItem {
const extension = this.extensionInstanceManageService.getExtensionInstanceByExtId(e.id);
return new QuickOpenItem({
groupLabel: firstItem ? host : undefined,
showBorder: !!firstItem,
label: replaceLocalizePlaceholder(e.displayName, e.id),
description: replaceLocalizePlaceholder(e.description, e.id),
detail: extension?.realPath,
});
}
/**
* 当前客户端 id
*/
private get clientId() {
return getClientId(this.injector);
}
} | the_stack |
import {
AfterContentInit,
AfterViewInit,
ChangeDetectorRef,
Component,
ContentChildren,
ElementRef,
EventEmitter,
forwardRef,
HostBinding,
HostListener,
Input,
Output,
Provider,
QueryList,
ViewChild,
ViewEncapsulation,
} from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { MdlPopoverComponent } from "@angular-mdl/popover";
import { MdlOptionComponent } from "./option";
import { isCharacterKey, isKey, keyboardEventKey, KEYS } from "./keyboard";
import { stringifyValue } from "./util";
const uniq = (array: string[]) => Array.from(new Set(array));
const isEqual = (a: unknown, b: unknown) =>
JSON.stringify(a) === JSON.stringify(b);
const toBoolean = (value: unknown): boolean =>
value != null && `${value}` !== "false";
const randomId = () => {
// eslint-disable-next-line
const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
return S4() + S4();
};
export const MDL_SELECT_VALUE_ACCESSOR: Provider = {
provide: NG_VALUE_ACCESSOR,
// eslint-disable-next-line
useExisting: forwardRef(() => MdlSelectComponent),
multi: true,
};
export class SearchableComponent {
public searchQuery = "";
private clearTimeout: unknown = null;
// short search query will be cleared after 300 ms
protected updateShortSearchQuery($event: KeyboardEvent): void {
if (this.clearTimeout) {
clearTimeout(this.clearTimeout as number);
}
this.clearTimeout = setTimeout(() => {
this.searchQuery = "";
}, 300);
this.searchQuery += keyboardEventKey($event).toLowerCase();
}
}
@Component({
selector: "mdl-select",
templateUrl: "select.component.html",
encapsulation: ViewEncapsulation.None,
providers: [MDL_SELECT_VALUE_ACCESSOR],
})
export class MdlSelectComponent
extends SearchableComponent
implements ControlValueAccessor, AfterContentInit, AfterViewInit {
@Input() ngModel: string[] | string;
@Input() disabled = false;
@Input() autocomplete = false;
@Input() public label = "";
@Input() placeholder = "";
@Input() multiple = false;
// eslint-disable-next-line
@Output() change: EventEmitter<any> = new EventEmitter(true);
// eslint-disable-next-line
@Output() blur: EventEmitter<any> = new EventEmitter(true);
@Output() inputChange: EventEmitter<string> = new EventEmitter(true);
@ViewChild("selectInput", { static: true }) selectInput: ElementRef;
@ViewChild(MdlPopoverComponent, { static: true })
public popoverComponent: MdlPopoverComponent;
@ContentChildren(MdlOptionComponent)
public optionComponents: QueryList<MdlOptionComponent>;
@HostBinding("class.mdl-select") isMdlSelect = true;
directionUp = false;
textfieldId: string;
text = "";
focused = false;
private selectElement: HTMLElement;
private popoverElement: HTMLElement;
private textByValue: { [property: string]: string } = {};
private onChange = Function.prototype;
private onTouched = Function.prototype;
private misFloatingLabel = false;
constructor(
private changeDetectionRef: ChangeDetectorRef,
private elementRef: ElementRef
) {
super();
this.textfieldId = `mdl-textfield-${randomId()}`;
}
@HostBinding("class.has-placeholder") get isPlaceholder(): boolean {
return !!this.placeholder;
}
get isFloatingLabel(): boolean {
return this.misFloatingLabel;
}
// eslint-disable-next-line @angular-eslint/no-input-rename
@HostBinding("class.mdl-select--floating-label")
@Input("floating-label")
set isFloatingLabel(value: boolean) {
this.misFloatingLabel = toBoolean(value);
}
@HostListener("keydown", ["$event"])
public onKeyDown($event: KeyboardEvent): void {
if (!this.disabled && this.popoverComponent.isVisible && !this.multiple) {
if (isKey($event, KEYS.upArrow)) {
this.onArrow($event, -1);
} else if (isKey($event, KEYS.downArrow)) {
this.onArrow($event, 1);
} else if (!this.autocomplete && isCharacterKey($event)) {
this.onCharacterKeydown($event);
}
}
}
@HostListener("keyup", ["$event"])
public onKeyUp($event: KeyboardEvent): void {
const inputField = $event.target as HTMLInputElement;
const inputValue = inputField.value;
if (!this.multiple && isKey($event, KEYS.enter, KEYS.escape, KEYS.tab)) {
this.searchQuery = "";
if (isKey($event, KEYS.enter)) {
this.setCurrentOptionValue();
} else {
inputField.value = this.text;
}
inputField.blur();
this.popoverComponent.hide();
} else if (
this.autocomplete &&
!isKey($event, KEYS.downArrow, KEYS.upArrow)
) {
this.inputChange.emit(inputValue);
this.searchQuery = inputValue;
}
$event.preventDefault();
}
ngAfterContentInit(): void {
this.bindOptions();
this.renderValue(this.ngModel);
this.optionComponents.changes.subscribe(() => {
this.bindOptions();
this.renderValue(this.ngModel);
});
this.popoverComponent.onShow.subscribe(() => this.onOpen());
this.popoverComponent.onHide.subscribe(() => this.onClose());
}
ngAfterViewInit(): void {
this.selectElement = this.elementRef.nativeElement as HTMLElement;
this.popoverElement = this.popoverComponent.elementRef
.nativeElement as HTMLElement;
}
public isDirty(): boolean {
return Boolean(this.selectInput.nativeElement.value);
}
// rebind options and reset value in connected select
reset(resetValue: boolean = true): void {
if (resetValue && !this.isEmpty()) {
this.ngModel = this.multiple ? [] : "";
this.onChange(this.ngModel);
this.change.emit(this.ngModel);
this.renderValue(this.ngModel);
}
}
toggle($event: Event): void {
if (!this.disabled) {
$event.stopPropagation();
this.popoverComponent.toggle($event);
}
}
onFocus($event: Event): void {
if (!this.popoverComponent.isVisible) {
setTimeout(() => {
this.popoverComponent.show($event);
this.selectInput.nativeElement.focus();
}, 200);
}
}
onInputFocus(): void {
if (this.autocomplete) {
this.selectInput.nativeElement.select();
}
}
public writeValue(value: string | string[]): void {
if (this.multiple) {
this.ngModel = this.ngModel || [];
if (!value || this.ngModel === value) {
// skip ngModel update when undefined value or multiple selects initialized with same array
} else if (Array.isArray(value)) {
this.ngModel = uniq((this.ngModel as string[]).concat(value));
} else if (
(this.ngModel as string[])
.map((v: string) => stringifyValue(v))
.indexOf(stringifyValue(value)) !== -1
) {
this.ngModel = [
...(this.ngModel as string[]).filter(
(v: string) => stringifyValue(v) !== stringifyValue(value)
),
];
} else if (!!value) {
this.ngModel = [...(this.ngModel as string[]), value];
}
} else {
this.ngModel = value;
}
this.onChange(this.ngModel);
this.renderValue(this.ngModel);
}
registerOnChange(fn: (value: unknown) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => unknown): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.disabled = isDisabled;
}
private setCurrentOptionValue() {
const currentOption = this.getCurrentOption();
const autoSelectedValue = this.getAutoSelection();
const value =
autoSelectedValue || (currentOption ? currentOption.value : this.ngModel);
this.resetText();
if (!isEqual(this.ngModel, value)) {
this.writeValue(value);
this.change.emit(value);
}
}
private resetText() {
this.text = this.selectInput.nativeElement.value;
this.changeDetectionRef.detectChanges();
}
private getCurrentOption() {
return this.optionComponents
? this.optionComponents.find((option) => option.selected)
: null;
}
private onCharacterKeydown($event: KeyboardEvent): void {
this.updateShortSearchQuery($event);
const autoSelectedValue = this.getAutoSelection();
if (autoSelectedValue) {
this.onSelect(autoSelectedValue);
}
$event.preventDefault();
}
private getAutoSelection(): string {
const filteredOptions = this.optionComponents
.filter(({ disabled }) => !disabled)
.filter((option) =>
option.text.toLowerCase().startsWith(this.searchQuery)
);
const selectedOption = this.optionComponents.find(
(option) => option.selected
);
if (filteredOptions.length > 0) {
const selectedOptionInFiltered =
filteredOptions.indexOf(selectedOption) !== -1;
if (!selectedOptionInFiltered && !filteredOptions[0].selected) {
return filteredOptions[0].value;
}
}
return null;
}
private onArrow($event: KeyboardEvent, offset: number) {
const arr = this.optionComponents
.toArray()
.filter(({ disabled }) => !disabled);
const selectedOption = arr.find((option) => option.selected);
const selectedOptionIndex = arr.indexOf(selectedOption);
const optionForSelection =
selectedOption !== null
? arr[selectedOptionIndex + offset]
: arr[offset > 0 ? -1 : 0];
if (optionForSelection) {
const value = optionForSelection.value;
this.selectValue(value);
}
$event.preventDefault();
}
private selectValue(value: string | string[]) {
this.scrollToValue(value);
if (this.optionComponents) {
this.optionComponents.forEach((selectOptionComponent) => {
selectOptionComponent.updateSelected(value);
});
}
}
private isEmpty() {
return this.multiple ? !this.ngModel.length : !this.ngModel;
}
private bindOptions() {
this.optionComponents.forEach(
(selectOptionComponent: MdlOptionComponent) => {
selectOptionComponent.setMultiple(this.multiple);
selectOptionComponent.onSelect = this.onSelect.bind(this);
if (selectOptionComponent.value != null) {
this.textByValue[
stringifyValue(selectOptionComponent.value)
] = selectOptionComponent.contentWrapper.nativeElement.textContent.trim();
}
}
);
}
private renderValue(value: string | string[]) {
if (this.multiple) {
this.text = ((value as string[]) || [])
.map((valueItem: string) => this.textByValue[stringifyValue(valueItem)])
.join(", ");
} else {
this.text = this.textByValue[stringifyValue(value)] || "";
}
this.changeDetectionRef.detectChanges();
if (this.optionComponents) {
const mvalue =
!this.multiple && this.optionComponents.length === 1
? this.optionComponents.first.value
: value;
this.optionComponents.forEach((selectOptionComponent) => {
selectOptionComponent.updateSelected(mvalue);
});
}
}
private onOpen() {
if (!this.disabled) {
this.popoverElement.style.visibility = "hidden";
setTimeout(() => {
this.focused = true;
this.selectValue(this.ngModel);
this.tryToUpdateDirection();
this.popoverElement.style.visibility = "visible";
});
}
}
private tryToUpdateDirection() {
const targetRect = this.selectElement.getBoundingClientRect();
const viewHeight = window.innerHeight;
const height = this.popoverElement.offsetHeight;
if (height) {
const bottomSpaceAvailable = viewHeight - targetRect.bottom;
this.directionUp = bottomSpaceAvailable < height;
this.changeDetectionRef.markForCheck();
}
}
private onClose() {
if (!this.disabled) {
this.focused = false;
this.selectValue(this.ngModel);
this.selectInput.nativeElement.value = this.text;
this.popoverElement.style.visibility = "hidden";
this.blur.emit(this.ngModel);
}
}
private onSelect(value: string | string[]) {
if (!this.multiple) {
this.scrollToValue(value);
}
if (!isEqual(this.ngModel, value)) {
this.writeValue(value);
this.change.emit(value);
}
}
private scrollToValue(value: string | string[]) {
const popover: HTMLElement = this.popoverComponent.elementRef.nativeElement;
const list: HTMLElement = popover.querySelector(".mdl-list");
const optionComponent = this.optionComponents.find(
(o) => o.value === value
);
const optionElement: HTMLElement = optionComponent
? optionComponent.contentWrapper.nativeElement
: null;
if (optionElement) {
const selectedItemElem = optionElement.parentElement;
const computedScrollTop =
selectedItemElem.offsetTop -
list.clientHeight / 2 +
selectedItemElem.clientHeight / 2;
list.scrollTop = Math.max(computedScrollTop, 0);
}
}
} | the_stack |
import { Literal, Quad_Object, NamedNode } from "@rdfjs/types";
import { Time } from "../datatypes";
import {
Thing,
ThingLocal,
ThingPersisted,
Url,
UrlString,
} from "../interfaces";
import {
addBoolean,
addDate,
addDatetime,
addTime,
addDecimal,
addInteger,
addIri,
addLiteral,
addNamedNode,
AddOfType,
addStringEnglish,
addStringNoLocale,
addStringWithLocale,
addTerm,
addUrl,
} from "./add";
import {
removeAll,
removeBoolean,
removeDate,
removeDatetime,
removeTime,
removeDecimal,
removeInteger,
removeIri,
removeLiteral,
removeNamedNode,
RemoveOfType,
removeStringNoLocale,
removeStringEnglish,
removeStringWithLocale,
removeUrl,
} from "./remove";
import {
setBoolean,
setDate,
setDatetime,
setTime,
setDecimal,
setInteger,
setIri,
setLiteral,
setNamedNode,
SetOfType,
setStringEnglish,
setStringNoLocale,
setStringWithLocale,
setTerm,
setUrl,
} from "./set";
import {
createThing,
CreateThingLocalOptions,
CreateThingOptions,
CreateThingPersistedOptions,
isThing,
} from "./thing";
type Adder<Type, T extends Thing> = (
property: Parameters<AddOfType<Type>>[1],
value: Parameters<AddOfType<Type>>[2]
) => ThingBuilder<T>;
type Setter<Type, T extends Thing> = (
property: Parameters<SetOfType<Type>>[1],
value: Parameters<SetOfType<Type>>[2]
) => ThingBuilder<T>;
type Remover<Type, T extends Thing> = (
property: Parameters<RemoveOfType<Type>>[1],
value: Parameters<RemoveOfType<Type>>[2]
) => ThingBuilder<T>;
// Unfortunately this interface has too many properties for TypeScript to infer,
// hence the duplication between the interface and the implementation method names.
/**
* A Fluent interface to build a [[Thing]].
*
* Add, replace or remove property values using consecutive calls to `.add*()`,
* `.set*()` and `.remove*()`, then finally generate a [[Thing]] with the given
* properties using `.build()`.
* @since 1.9.0
*/
export type ThingBuilder<T extends Thing> = {
build: () => T;
addUrl: Adder<Url | UrlString | Thing, T>;
addIri: Adder<Url | UrlString | Thing, T>;
addBoolean: Adder<boolean, T>;
addDatetime: Adder<Date, T>;
addDate: Adder<Date, T>;
addTime: Adder<Time, T>;
addDecimal: Adder<number, T>;
addInteger: Adder<number, T>;
addStringNoLocale: Adder<string, T>;
addStringEnglish: Adder<string, T>;
addStringWithLocale: (
property: Parameters<typeof addStringWithLocale>[1],
value: Parameters<typeof addStringWithLocale>[2],
locale: Parameters<typeof addStringWithLocale>[3]
) => ThingBuilder<T>;
addNamedNode: Adder<NamedNode, T>;
addLiteral: Adder<Literal, T>;
addTerm: Adder<Quad_Object, T>;
setUrl: Setter<Url | UrlString | Thing, T>;
setIri: Setter<Url | UrlString | Thing, T>;
setBoolean: Setter<boolean, T>;
setDatetime: Setter<Date, T>;
setDate: Setter<Date, T>;
setTime: Setter<Time, T>;
setDecimal: Setter<number, T>;
setInteger: Setter<number, T>;
setStringNoLocale: Setter<string, T>;
setStringEnglish: Setter<string, T>;
setStringWithLocale: (
property: Parameters<typeof setStringWithLocale>[1],
value: Parameters<typeof setStringWithLocale>[2],
locale: Parameters<typeof setStringWithLocale>[3]
) => ThingBuilder<T>;
setNamedNode: Setter<NamedNode, T>;
setLiteral: Setter<Literal, T>;
setTerm: Setter<Quad_Object, T>;
removeAll: (property: Parameters<typeof removeLiteral>[1]) => ThingBuilder<T>;
removeUrl: Remover<Url | UrlString | Thing, T>;
removeIri: Remover<Url | UrlString | Thing, T>;
removeBoolean: Remover<boolean, T>;
removeDatetime: Remover<Date, T>;
removeDate: Remover<Date, T>;
removeTime: Remover<Time, T>;
removeDecimal: Remover<number, T>;
removeInteger: Remover<number, T>;
removeStringNoLocale: Remover<string, T>;
removeStringEnglish: Remover<string, T>;
removeStringWithLocale: (
property: Parameters<typeof removeStringWithLocale>[1],
value: Parameters<typeof removeStringWithLocale>[2],
locale: Parameters<typeof removeStringWithLocale>[3]
) => ThingBuilder<T>;
removeNamedNode: Remover<NamedNode, T>;
removeLiteral: Remover<Literal, T>;
};
/**
* Modify a [[Thing]], setting multiple properties in a single expresssion.
*
* For example, you can initialise several properties of a given Thing as follows:
*
* const me = buildThing(createThing({ name: "profile-vincent" }))
* .addUrl(rdf.type, schema.Person)
* .addStringNoLocale(schema.givenName, "Vincent")
* .build();
*
* Take note of the final call to `.build()` to obtain the actual Thing.
*
* @param init A Thing to modify.
* @returns a [[ThingBuilder]], a Fluent API that allows you to set multiple properties in a single expression.
* @since 1.9.0
*/
export function buildThing(init: ThingLocal): ThingBuilder<ThingLocal>;
/**
* Modify a [[Thing]], setting multiple properties in a single expresssion.
*
* For example, you can initialise several properties of a given Thing as follows:
*
* const me = buildThing(createThing({ url: "https://example.pod/profile#vincent" }))
* .addUrl(rdf.type, schema.Person)
* .addStringNoLocale(schema.givenName, "Vincent")
* .build();
*
* Take note of the final call to `.build()` to obtain the actual Thing.
*
* @param init A Thing to modify.
* @returns a [[ThingBuilder]], a Fluent API that allows you to set multiple properties in a single expression.
* @since 1.9.0
*/
export function buildThing(init: ThingPersisted): ThingBuilder<ThingPersisted>;
/**
* Create a [[Thing]], setting multiple properties in a single expresssion.
*
* For example, you can create a new Thing and initialise several properties as follows:
*
* const me = buildThing({ name: "profile-vincent" })
* .addUrl(rdf.type, schema.Person)
* .addStringNoLocale(schema.givenName, "Vincent")
* .build();
*
* Take note of the final call to `.build()` to obtain the actual Thing.
*
* @param init Options used to initialise a new Thing.
* @returns a [[ThingBuilder]], a Fluent API that allows you to set multiple properties in a single expression.
* @since 1.9.0
*/
export function buildThing(
init: CreateThingLocalOptions
): ThingBuilder<ThingLocal>;
/**
* Create a [[Thing]], setting multiple properties in a single expresssion.
*
* For example, you can create a new Thing and initialise several properties as follows:
*
* const me = buildThing({ url: "https://example.pod/profile#vincent" })
* .addUrl(rdf.type, schema.Person)
* .addStringNoLocale(schema.givenName, "Vincent")
* .build();
*
* Take note of the final call to `.build()` to obtain the actual Thing.
*
* @param init Optionally pass an existing [[Thing]] to modify the properties of. If left empty, `buildThing` will initialise a new Thing.
* @returns a [[ThingBuilder]], a Fluent API that allows you to set multiple properties in a single expression.
* @since 1.9.0
*/
export function buildThing(
init: CreateThingPersistedOptions
): ThingBuilder<ThingPersisted>;
/**
* Create a [[Thing]], setting multiple properties in a single expresssion.
*
* For example, you can create a new Thing and initialise several properties as follows:
*
* const me = buildThing()
* .addUrl(rdf.type, schema.Person)
* .addStringNoLocale(schema.givenName, "Vincent")
* .build();
*
* Take note of the final call to `.build()` to obtain the actual Thing.
*
* @returns a [[ThingBuilder]], a Fluent API that allows you to set multiple properties in a single expression.
* @since 1.9.0
*/
export function buildThing(): ThingBuilder<ThingLocal>;
/**
* Create or modify a [[Thing]], setting multiple properties in a single expresssion.
*
* For example, you can create a new Thing and initialise several properties as follows:
*
* const me = buildThing()
* .addUrl(rdf.type, schema.Person)
* .addStringNoLocale(schema.givenName, "Vincent")
* .build();
*
* Take note of the final call to `.build()` to obtain the actual Thing.
*
* @param init Optionally pass an existing [[Thing]] to modify the properties of. If left empty, `buildThing` will initialise a new Thing.
* @returns a [[ThingBuilder]], a Fluent API that allows you to set multiple properties in a single expression.
* @since 1.9.0
*/
export function buildThing(
init: Thing | CreateThingOptions = createThing()
): ThingBuilder<Thing> {
let thing = isThing(init) ? init : createThing(init);
function getAdder<Type>(adder: AddOfType<Type>) {
return (
property: Parameters<typeof adder>[1],
value: Parameters<typeof adder>[2]
) => {
thing = adder(thing, property, value);
return builder;
};
}
function getSetter<Type>(setter: SetOfType<Type>) {
return (
property: Parameters<typeof setter>[1],
value: Parameters<typeof setter>[2]
) => {
thing = setter(thing, property, value);
return builder;
};
}
function getRemover<Type>(remover: RemoveOfType<Type>) {
return (
property: Parameters<typeof remover>[1],
value: Parameters<typeof remover>[2]
) => {
thing = remover(thing, property, value);
return builder;
};
}
const builder: ThingBuilder<Thing> = {
build: () => thing,
addUrl: getAdder(addUrl),
addIri: getAdder(addIri),
addBoolean: getAdder(addBoolean),
addDatetime: getAdder(addDatetime),
addDate: getAdder(addDate),
addTime: getAdder(addTime),
addDecimal: getAdder(addDecimal),
addInteger: getAdder(addInteger),
addStringNoLocale: getAdder(addStringNoLocale),
addStringEnglish: (
property: Parameters<typeof addStringWithLocale>[1],
value: Parameters<typeof addStringWithLocale>[2]
) => {
thing = addStringWithLocale(thing, property, value, "en");
return builder;
},
addStringWithLocale: (
property: Parameters<typeof addStringWithLocale>[1],
value: Parameters<typeof addStringWithLocale>[2],
locale: Parameters<typeof addStringWithLocale>[3]
) => {
thing = addStringWithLocale(thing, property, value, locale);
return builder;
},
addNamedNode: getAdder(addNamedNode),
addLiteral: getAdder(addLiteral),
addTerm: getAdder(addTerm),
setUrl: getSetter(setUrl),
setIri: getSetter(setIri),
setBoolean: getSetter(setBoolean),
setDatetime: getSetter(setDatetime),
setDate: getSetter(setDate),
setTime: getSetter(setTime),
setDecimal: getSetter(setDecimal),
setInteger: getSetter(setInteger),
setStringNoLocale: getSetter(setStringNoLocale),
setStringEnglish: (
property: Parameters<typeof setStringWithLocale>[1],
value: Parameters<typeof setStringWithLocale>[2]
) => {
thing = setStringWithLocale(thing, property, value, "en");
return builder;
},
setStringWithLocale: (
property: Parameters<typeof setStringWithLocale>[1],
value: Parameters<typeof setStringWithLocale>[2],
locale: Parameters<typeof setStringWithLocale>[3]
) => {
thing = setStringWithLocale(thing, property, value, locale);
return builder;
},
setNamedNode: getSetter(setNamedNode),
setLiteral: getSetter(setLiteral),
setTerm: getSetter(setTerm),
removeAll: (property: Parameters<typeof removeAll>[1]) => {
thing = removeAll(thing, property);
return builder;
},
removeUrl: getRemover(removeUrl),
removeIri: getRemover(removeIri),
removeBoolean: getRemover(removeBoolean),
removeDatetime: getRemover(removeDatetime),
removeDate: getRemover(removeDate),
removeTime: getRemover(removeTime),
removeDecimal: getRemover(removeDecimal),
removeInteger: getRemover(removeInteger),
removeStringNoLocale: getRemover(removeStringNoLocale),
removeStringEnglish: (
property: Parameters<typeof removeStringWithLocale>[1],
value: Parameters<typeof removeStringWithLocale>[2]
) => buildThing(removeStringWithLocale(thing, property, value, "en")),
removeStringWithLocale: (
property: Parameters<typeof removeStringWithLocale>[1],
value: Parameters<typeof removeStringWithLocale>[2],
locale: Parameters<typeof removeStringWithLocale>[3]
) => buildThing(removeStringWithLocale(thing, property, value, locale)),
removeNamedNode: getRemover(removeNamedNode),
removeLiteral: getRemover(removeLiteral),
};
return builder;
} | the_stack |
import '@types/node'
import * as http from 'http'
import * as https from 'https'
import * as stream from 'stream'
// ----------------------------------------------------------------------------
/**
* Node core HTTP request options
* | [docs](https://nodejs.org/dist/latest-v14.x/docs/api/http.html#http_http_request_options_callback)
*/
interface NodeCoreHttpOptions {
/**
* Agent
*/
agent?: boolean | https.Agent | http.Agent
/**
* Basic authentication
*/
auth?: string
/**
* A function that produces a socket/stream to use for the request
*/
createConnection?: Function
/**
* Default port for the protocol
*/
defaultPort?: number
/**
* IP address family to use when resolving host or hostname
*/
family?: number
/**
* Request headers
*/
headers?: object
/**
* Hostname
*/
host?: string
/**
* Hostname
*/
hostname?: string
/**
* Use an insecure HTTP parser that accepts invalid HTTP headers
*/
insecureHTTPParser?: boolean
/**
* Local interface to bind for network connections
*/
localAddress?: string
/**
* Custom lookup function
*/
lookup?: Function
/**
* Maximum length of response headers in bytes
*/
maxHeaderSize?: number
/**
* HTTP request method
*/
method?: string
/**
* Request path
*/
path?: string
/**
* Port of remote server
*/
port?: number
/**
* Protocol to use
*/
protocol?: string
/**
* Specifies whether or not to automatically add the Host header
*/
setHost?: boolean
/**
* Unix Domain Socket
*/
socketPath?: string
/**
* Socket timeout in milliseconds
*/
timeout?: number
}
/**
* Node core HTTPS request options
* | [docs](https://nodejs.org/dist/latest-v14.x/docs/api/https.html#https_https_request_options_callback)
* | [docs](https://nodejs.org/dist/latest-v14.x/docs/api/tls.html#tls_tls_connect_options_callback)
* | [docs](https://nodejs.org/dist/latest-v14.x/docs/api/tls.html#tls_tls_createsecurecontext_options)
*/
interface NodeCoreHttpsOptions {
/**
* Override the trusted CA certificates
*/
ca?: string | string[] | Buffer | Buffer[]
/**
* Cert chains in PEM format
*/
cert?: string | string[] | Buffer | Buffer[]
/**
* Cipher suite specification
*/
ciphers?: string
/**
* Name of an OpenSSL engine which can provide the client certificate
*/
clientCertEngine?: string
/**
* PEM formatted CRLs (Certificate Revocation Lists)
*/
crl?: string | string[] | Buffer | Buffer[]
/**
* Diffie-Hellman parameters
*/
dhparam?: string | Buffer
/**
* A string describing a named curve or a colon separated list of curve NIDs or names
*/
ecdhCurve?: string
/**
* Attempt to use the server's cipher suite preferences instead of the client's
*/
honorCipherOrder?: boolean
/**
* Private keys in PEM format
*/
key?: string | string[] | Buffer | Buffer[] | object[]
/**
* Shared passphrase used for a single private key and/or a PFX
*/
passphrase?: string
/**
* PFX or PKCS12 encoded private key and certificate chain
*/
pfx?: string | string[] | Buffer | Buffer[] | object[]
/**
* If not false a server automatically reject clients with invalid certificates
*/
rejectUnauthorized?: boolean
/**
* Optionally affect the OpenSSL protocol behavior
*/
secureOptions?: number
/**
* Legacy mechanism to select the TLS protocol version to use
*/
secureProtocol?: string
/**
* Server name for the SNI (Server Name Indication) TLS extension
*/
servername?: string
/**
* Opaque identifier used by servers to ensure session state is not shared between applications
*/
sessionIdContext?: string
/**
* Consistent with the readable stream highWaterMark parameter
*/
highWaterMark?: number
}
/**
* Request compose options
* | [docs](https://github.com/simov/request-compose#options)
*/
interface RequestComposeOptions {
/**
* Absolute URL
*/
url?: string
/**
* Proxy URL; for HTTPS use Agent instead
*/
proxy?: string
/**
* URL querystring
*/
qs?: object | string
/**
* application/x-www-form-urlencoded request body
*/
form?: object | string
/**
* JSON encoded request body
*/
json?: object | string
/**
* Raw request body
*/
body?: string | Buffer | stream.Readable
/**
* multipart/form-data as object or multipart/related as array
* | [docs](https://github.com/simov/request-multipart#request-multipart)
*/
multipart?: object | []
/**
* Basic authentication
*/
auth?: AuthOptions
/**
* OAuth 1.0a authentication
* | [docs](https://github.com/simov/request-oauth#request-oauth)
*/
oauth?: OAuthOptions
/**
* Response encoding
*/
encoding?: string
/**
* Cookie store
*/
cookie?: object
/**
* Redirect options
*/
redirect?: RedirectOptions
}
/**
* Request compose default options
*/
interface RequestComposeDefaults {
/**
* Request headers
* @default {}
*/
headers?: object
/**
* Hostname
* @default localhost
*/
hostname?: string
/**
* HTTP request method
* @default 'GET'
*/
method?: string
/**
* Request path
* @default '/'
*/
path?: string
/**
* Port of remote server
* @default 80
*/
port?: number
/**
* Protocol to use
* @default 'http:'
*/
protocol?: string
/**
* Socket timeout in milliseconds
* @default 3000
*/
timeout?: number
}
/**
* Basic authentication
*/
export interface AuthOptions {
/**
* User name
*/
user?: string
/**
* Password
*/
pass?: string
}
/**
* OAuth 1.0a
* | [docs](https://github.com/simov/request-oauth#options)
*/
export interface OAuthOptions {
/**
* Consumer key
*/
consumer_key: string
/**
* Consumer secret
*/
consumer_secret?: string
/**
* Private key
*/
private_key?: string
/**
* Access token
*/
token: string
/**
* Access secret
*/
token_secret: string
/**
* OAuth version
* @default 1.0
*/
version?: string
/**
* Signature method
* @default HMAC-SHA1
*/
signature_method?: 'HMAC-SHA1' | 'RSA-SHA1' | 'PLAINTEXT'
/**
* Transport method
* @default header
*/
transport_method?: 'header' | 'query' | 'form'
/**
* Timestamp
*/
timestamp?: string
/**
* Nonce
*/
nonce?: string
/**
* Realm
*/
realm?: string
/**
* Body hash string or true to generate one
*/
body_hash?: string | boolean
}
/**
* Redirect options
* | [docs](https://github.com/simov/request-compose#redirect)
*/
export interface RedirectOptions {
/**
* Maximum number of redirects to follow
* @default 3
*/
max?: number
/**
* Follow non-GET HTTP 3xx responses as redirects
* @default false
*/
all?: boolean
/**
* Follow original HTTP method, otherwise convert all redirects to GET
* @default true
*/
method?: boolean
/**
* Keep authorization header when changing hostnames
* @default true
*/
auth?: boolean
/**
* Add referer header
* @default false
*/
referer?: boolean
}
/**
* Node core request options
*/
type NodeCoreRequestOptions = NodeCoreHttpOptions & NodeCoreHttpsOptions
/**
* Request options
* | [docs](https://github.com/simov/request-compose#options)
*/
export type RequestOptions = NodeCoreRequestOptions & RequestComposeOptions & RequestComposeDefaults
// ----------------------------------------------------------------------------
/**
* Request compose default options
*/
type RequestMiddlewareDefaults = NodeCoreRequestOptions & Required<RequestComposeDefaults>
/**
* Request middleware options
*/
interface RequestMiddlewareOptions {
/**
* Node core request options
*/
options: RequestMiddlewareDefaults
/**
* Request body
*/
body?: string | object | Buffer | stream.Readable
}
/**
* Response middleware options
*/
interface ResponseMiddlewareOptions {
/**
* Node core request options
*/
options: RequestMiddlewareDefaults
/**
* Response object
*/
res: http.IncomingMessage
/**
* Response body
*/
body?: string | object | Buffer
/**
* Raw response body
*/
raw?: Buffer | string
}
/**
* Defaults middleware
*/
export type DefaultsMiddleware = (options?: any) => () => RequestMiddlewareOptions
/**
* Request middleware
*/
export type RequestMiddleware = (options?: any) => (options: RequestMiddlewareOptions) => RequestMiddlewareOptions
/**
* Response middleware
*/
export type ResponseMiddleware = (options?: any) => (options: ResponseMiddlewareOptions) => ResponseMiddlewareOptions
/**
* Request middlewares
*/
interface RequestMiddlewares {
/**
* Request defaults
*/
defaults: DefaultsMiddleware
/**
* Absolute URL
*/
url: RequestMiddleware
/**
* Proxy URL
*/
proxy: RequestMiddleware
/**
* URL querystring
*/
qs: RequestMiddleware
/**
* Cookie store
*/
cookie?: RequestMiddleware
/**
* application/x-www-form-urlencoded request body
*/
form: RequestMiddleware
/**
* JSON encoded request body
*/
json: RequestMiddleware
/**
* Multipart encoded request body
*/
multipart?: RequestMiddleware
/**
* Raw request body
*/
body: RequestMiddleware
/**
* Basic authentication
*/
auth: RequestMiddleware
/**
* OAuth 1.0a
*/
oauth?: RequestMiddleware
/**
* Request body length
*/
length: RequestMiddleware
/**
* Request
*/
send: RequestMiddleware
}
/**
* Response middlewares
*/
interface ResponseMiddlewares {
/**
* Buffer response body
*/
buffer: ResponseMiddleware
/**
* Decode gzip/deflate encoded response body
*/
gzip: ResponseMiddleware
/**
* String response body
*/
string: ResponseMiddleware
/**
* Parse JSON or application/x-www-form-urlencoded encoded response body
*/
parse: ResponseMiddleware
/**
* Throw on non successful status codes
*/
status: ResponseMiddleware
/**
* HTTP redirect
*/
redirect: ResponseMiddleware
}
/**
* Extend middlewares
*/
interface ExtendMiddlewares {
/**
* Request middlewares
*/
Request?: Partial<RequestMiddlewares>
/**
* Response middlewares
*/
Response?: Partial<ResponseMiddlewares>
}
// ----------------------------------------------------------------------------
/**
* Client response
*/
export interface ClientResponse {
/**
* Response object
*/
res: http.IncomingMessage
/**
* Response body
*/
body: string | object
}
/**
* Buffer response
*/
export interface BufferResponse {
/**
* Response object
*/
res: http.IncomingMessage
/**
* Response body
*/
body: Buffer
}
/**
* Stream response
*/
export interface StreamResponse {
/**
* Response object
*/
res: http.IncomingMessage
}
// ----------------------------------------------------------------------------
/**
* Functional composition
*/
declare function compose(...functions: any): (options?: any) => Promise<any>
/**
* Functional composition
*/
declare namespace compose {
/**
* Request middlewares
*/
const Request: RequestMiddlewares
/**
* Response middlewares
*/
const Response: ResponseMiddlewares
/**
* Client composition
*/
function client(options: RequestOptions): Promise<ClientResponse>
/**
* Buffer composition
*/
function buffer(options: RequestOptions): Promise<BufferResponse>
/**
* Stream composition
*/
function stream(options: RequestOptions): Promise<StreamResponse>
/**
* Extend instance
*/
function extend(options: ExtendMiddlewares): typeof compose
}
export default compose | the_stack |
import React, {
ReactNode,
useState,
useRef,
useEffect,
useMemo,
Fragment,
forwardRef,
} from 'react'
import cn from 'classnames'
import { usePopper } from 'react-popper'
import * as timelineStyles from './Timeline.css'
import * as eventStyles from './Event.css'
import ReactDOM from 'react-dom'
import {
Box,
Icon,
Button,
Stack,
Tag,
Text,
Inline,
} from '@island.is/island-ui/core'
import Link from 'next/link'
const formatNumber = (value: number) =>
value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.')
export type TimelineEvent = {
date: Date
title: string
value?: number
maxValue?: number
valueLabel?: string
data?: {
labels: string[]
text: ReactNode
link: string
}
}
export interface TimelineProps {
events: TimelineEvent[]
getMonthByIndex: (idx: number) => string
}
function setDefault<K, V>(map: Map<K, V>, key: K, value: V): V {
if (!map.has(key)) map.set(key, value)
return map.get(key) as V
}
const mapEvents = (
events: TimelineEvent[],
): Map<number, Map<number, TimelineEvent[]>> => {
events = events.slice().sort((a, b) => b.date.getTime() - a.date.getTime())
const byYear = new Map()
for (const event of events) {
const byMonth = setDefault(byYear, event.date.getFullYear(), new Map())
setDefault(byMonth, event.date.getMonth(), [] as TimelineEvent[]).push(
event,
)
}
return byYear
}
export const Timeline = ({ events, getMonthByIndex }: TimelineProps) => {
const frameRef = useRef<HTMLDivElement>(null)
const entriesParentRef = useRef<HTMLDivElement>(null)
const [currentIndex, setCurrentIndex] = useState(0)
const [prevButtonDisabled, setPrevButtonDisabled] = useState(false)
const [nextButtonDisabled, setNextButtonDisabled] = useState(false)
const [visibleModal, setVisibleModal] = useState<string | null>('')
const eventMap = useMemo(() => mapEvents(events), [events])
const getPrevIndex = () => (currentIndex <= 0 ? 0 : currentIndex - 1)
const getNextIndex = () =>
currentIndex >= entriesParentRef.current.children.length - 1
? currentIndex
: currentIndex + 1
/**
* Move timeline to DOM node index (years and months)
* @param index DOM index
* @param behavior type of scroll behavior
*/
const moveTimeline = (
index: number,
behavior: 'smooth' | 'auto' = 'smooth',
) => {
const child = entriesParentRef.current.children[index] as HTMLElement
frameRef.current.scrollTo({
top: child.offsetTop,
behavior,
})
const scrollReachedTop = child.offsetTop <= 0
const scrollReachedBottom =
frameRef.current.scrollHeight - child.offsetTop <=
frameRef.current.clientHeight
setPrevButtonDisabled(scrollReachedTop)
setNextButtonDisabled(scrollReachedBottom)
setCurrentIndex(index)
}
useEffect(() => {
if (frameRef.current && entriesParentRef.current?.children?.length > 0) {
/**
* Scroll to current month vertical and horizontal
*/
const today = new Date()
const year = today.getFullYear()
const month = today.getMonth()
// find current month
const months = Array.from(
entriesParentRef.current.children,
) as Array<HTMLElement>
const { currentMonthIndex, currentMonth } = months.reduce<{
currentMonthIndex: number
currentMonth: HTMLElement | null
}>(
(acc, current, index) => {
if (current.dataset.date === `${year}/${month}`) {
acc.currentMonthIndex = index
acc.currentMonth = current
}
return acc
},
{
currentMonthIndex: 0,
currentMonth: null,
},
)
// padding based on mobile gutter
const leftPadding = 24
frameRef.current.scrollLeft =
currentMonth && currentMonth.offsetLeft
? currentMonth.offsetLeft - leftPadding
: undefined
moveTimeline(currentMonthIndex)
}
}, [])
return (
<div className={timelineStyles.container}>
<ArrowButton
type="prev"
disabled={prevButtonDisabled}
onClick={() => {
moveTimeline(getPrevIndex())
}}
/>
<ArrowButton
type="next"
disabled={nextButtonDisabled}
onClick={() => {
moveTimeline(getNextIndex())
}}
/>
<div ref={frameRef} className={timelineStyles.frame}>
<div className={timelineStyles.innerContainer}>
<div ref={entriesParentRef} className={timelineStyles.yearContainer}>
{Array.from(eventMap.entries(), ([year, eventsByMonth]) => (
<Fragment key={year}>
<div className={timelineStyles.section}>
<div className={timelineStyles.left}>
<span
className={cn(
timelineStyles.year,
timelineStyles.leftLabel,
)}
>
{year}
</span>
</div>
<div className={timelineStyles.right}> </div>
</div>
{Array.from(eventsByMonth.entries(), ([month, monthEvents]) => (
<div
key={month}
className={timelineStyles.monthContainer}
data-date={`${year}/${month}`}
>
<div className={timelineStyles.section}>
<div className={timelineStyles.left}>
<span
className={cn(
timelineStyles.month,
timelineStyles.leftLabel,
)}
>
{getMonthByIndex(month)}
</span>
</div>
<div className={timelineStyles.right}> </div>
</div>
<div className={timelineStyles.section}>
<div className={timelineStyles.left}> </div>
<div className={timelineStyles.right}>
<div className={timelineStyles.eventsContainer}>
{monthEvents.map((event, eventIndex) => {
const larger = Boolean(event.data)
const modalKey = `modal-${year}-${month}-${eventIndex}`
const isVisible = visibleModal === modalKey
const bulletLineClass = cn(
timelineStyles.bulletLine,
{
[timelineStyles.bulletLineLarger]: larger,
},
)
return (
<div
key={eventIndex}
className={timelineStyles.eventWrapper}
>
<div className={timelineStyles.event}>
{larger ? (
<Event
event={event}
visibleModal={visibleModal}
modalKey={modalKey}
setVisibleModal={setVisibleModal}
/>
) : (
<span
className={timelineStyles.eventSimple}
>
{event.title}
</span>
)}
</div>
<span className={bulletLineClass}>
<BulletLine selected={isVisible} />
</span>
</div>
)
})}
</div>
</div>
</div>
</div>
))}
</Fragment>
))}
</div>
</div>
</div>
</div>
)
}
const Event = ({ event, setVisibleModal, visibleModal, modalKey }) => {
const portalRef = useRef()
const [referenceElement, setReferenceElement] = useState(null)
const [popperElement, setPopperElement] = useState(null)
const [mounted, setMounted] = useState(false)
const { styles, attributes } = usePopper(referenceElement, popperElement, {
placement: 'top-start',
modifiers: [
{
name: 'flip',
options: {
rootBoundary: 'document',
flipVariations: false,
allowedAutoPlacements: ['top-start'],
},
},
],
})
const isVisible = visibleModal === modalKey
useEffect(() => {
portalRef.current = document.querySelector('#__next')
setMounted(true)
}, [])
return (
<>
<EventBar
ref={setReferenceElement}
onClick={() => {
setVisibleModal(isVisible ? null : modalKey)
}}
event={event}
/>
{mounted &&
isVisible &&
ReactDOM.createPortal(
<Fragment>
<Box
display={['none', 'none', 'none', 'block']}
ref={setPopperElement}
style={styles.popper}
{...attributes.popper}
>
<EventModal event={event} onClose={() => setVisibleModal(null)} />
</Box>
<Box
display={['flex', 'flex', 'flex', 'none']}
position="fixed"
top={0}
bottom={0}
left={0}
right={0}
overflow="auto"
padding={3}
className={eventStyles.mobileModalContainer}
>
<EventModal event={event} onClose={() => setVisibleModal(null)} />
</Box>
</Fragment>,
portalRef.current,
)}
</>
)
}
interface EventBarProps {
event: TimelineEvent
onClick: () => void
}
const EventBar = forwardRef(
(
{ event, onClick }: EventBarProps,
ref: React.LegacyRef<HTMLButtonElement>,
) => {
return (
<button onClick={onClick} className={eventStyles.eventBar} ref={ref}>
<Box
component="span"
className={eventStyles.eventBarTitle}
background="purple100"
display="flex"
>
<Box component="span" className={eventStyles.eventBarIcon}>
<Icon type="filled" icon="person" color="purple400" size="medium" />
</Box>
<Box component="span" paddingLeft={2} paddingRight={3}>
<Text as="span" variant="h5" color="purple400">
{event.title}
</Text>
</Box>
</Box>
{!!event.value && (
<span className={eventStyles.eventBarStats}>
<span className={eventStyles.valueWrapper}>
<span className={eventStyles.value}>
{formatNumber(event.value)}
</span>
{!!event.maxValue && (
<span className={eventStyles.maxValue}>
/{formatNumber(event.maxValue)}
</span>
)}
</span>
<span className={eventStyles.valueLabel}>
{event.valueLabel?.split(/[\r\n]+/).map((line, i) => (
<Fragment key={i}>
{line}
<br />
</Fragment>
))}
</span>
</span>
)}
</button>
)
},
)
interface EventModalProps {
event: TimelineEvent
onClose: () => void
}
const EventModal = forwardRef(
(
{ event, onClose }: EventModalProps,
ref: React.LegacyRef<HTMLDivElement>,
) => {
if (!event) {
return null
}
return (
<div ref={ref} className={eventStyles.eventModal}>
<Box
className={eventStyles.eventBarTitle}
background="white"
display="inlineFlex"
>
<Box className={eventStyles.eventBarIcon}>
<Icon type="filled" icon="person" color="purple400" size="medium" />
</Box>
{!!event.value && (
<Box
display="inlineFlex"
alignItems="center"
className={eventStyles.nowrap}
paddingLeft={2}
paddingRight={4}
>
<Text variant="h2" color="purple400" as="span">
{formatNumber(event.value)}
</Text>
{!!event.maxValue && (
<Text
variant="h2"
color="purple400"
as="span"
fontWeight="light"
>
/{formatNumber(event.maxValue)}
</Text>
)}
<Box marginLeft={1}>
<Text variant="eyebrow" color="purple400" fontWeight="semiBold">
{event.valueLabel?.split(/[\r\n]+/).map((line, i) => (
<Fragment key={i}>
{line}
<br />
</Fragment>
))}
</Text>
</Box>
</Box>
)}
</Box>
<Box padding={6}>
<Box className={eventStyles.eventModalClose}>
<Button
circle
colorScheme="negative"
icon="close"
onClick={onClose}
/>
</Box>
<Stack space={2}>
<Text variant="h2" as="h3" color="purple400">
{event.title}
</Text>
{event.data?.labels && (
<Inline space={2}>
{event.data.labels.map((label, index) => (
<Tag key={index} variant="purple" outlined>
{label}
</Tag>
))}
</Inline>
)}
{Boolean(event.data?.text) && event.data.text}
{event.data?.link && (
<Link href={event.data.link}>
<Button variant="text" icon="arrowForward">
Lesa meira
</Button>
</Link>
)}
</Stack>
</Box>
</div>
)
},
)
const BulletLine = ({ selected = false }: { selected?: boolean }) => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="126"
height="24"
fill="none"
viewBox="0 0 126 24"
>
<path
fill={selected ? '#ff0050' : '#99c0ff'}
fillRule="evenodd"
d="M118.126 13A4.002 4.002 0 00126 12a4 4 0 00-8 0H24c0-6.627-5.373-12-12-12S0 5.373 0 12s5.373 12 12 12c6.29 0 11.45-4.84 11.959-11h94.167zM8 12a4 4 0 108 0 4 4 0 00-8 0z"
clipRule="evenodd"
></path>
</svg>
)
}
interface ArrowButtonProps {
type: 'prev' | 'next'
onClick: () => void
disabled: boolean
}
const ArrowButton = ({
type = 'prev',
onClick,
disabled,
}: ArrowButtonProps) => {
return (
<Box
className={cn(
timelineStyles.arrowButton,
timelineStyles.arrowButtonTypes[type],
)}
>
<Button
colorScheme="negative"
circle
icon="arrowBack"
onClick={onClick}
/>
</Box>
)
}
export default Timeline | the_stack |
import { AccessControl } from '../';
import { IAccessInfo, AccessControlError } from '../core';
import { Action, Possession, actions, possessions } from '../enums';
import { utils } from '../utils';
/**
* Represents the inner `Access` class that helps build an access information
* to be granted or denied; and finally commits it to the underlying grants
* model. You can get a first instance of this class by calling
* `AccessControl#grant()` or `AccessControl#deny()` methods.
* @class
* @inner
* @memberof AccessControl
*/
class Access {
/**
* Inner `IAccessInfo` object.
* @protected
* @type {IAccessInfo}
*/
protected _: IAccessInfo = {};
/**
* Main grants object.
* @protected
* @type {AccessControl}
*/
protected _ac: AccessControl;
/**
* Main grants object.
* @protected
* @type {Any}
*/
protected _grants: any;
/**
* Initializes a new instance of `Access`.
* @private
*
* @param {AccessControl} ac
* AccessControl instance.
* @param {String|Array<String>|IAccessInfo} [roleOrInfo]
* Either an `IAccessInfo` object, a single or an array of
* roles. If an object is passed, possession and attributes
* properties are optional. CAUTION: if attributes is omitted,
* and access is not denied, it will default to `["*"]` which means
* "all attributes allowed". If possession is omitted, it will
* default to `"any"`.
* @param {Boolean} denied
* Specifies whether this `Access` is denied.
*/
constructor(ac: AccessControl, roleOrInfo?: string | string[] | IAccessInfo, denied: boolean = false) {
this._ac = ac;
this._grants = (ac as any)._grants;
this._.denied = denied;
if (typeof roleOrInfo === 'string' || Array.isArray(roleOrInfo)) {
this.role(roleOrInfo);
} else if (utils.type(roleOrInfo) === 'object') {
if (Object.keys(roleOrInfo).length === 0) {
throw new AccessControlError('Invalid IAccessInfo: {}');
}
// if an IAccessInfo instance is passed and it has 'action' defined, we
// should directly commit it to grants.
roleOrInfo.denied = denied;
this._ = utils.resetAttributes(roleOrInfo);
if (utils.isInfoFulfilled(this._)) utils.commitToGrants(this._grants, this._, true);
} else if (roleOrInfo !== undefined) {
// undefined is allowed (`roleOrInfo` can be omitted) but throw if
// some other type is passed.
throw new AccessControlError('Invalid role(s), expected a valid string, string[] or IAccessInfo.');
}
}
// -------------------------------
// PUBLIC PROPERTIES
// -------------------------------
/**
* Specifies whether this access is initally denied.
* @name AccessControl~Access#denied
* @type {Boolean}
* @readonly
*/
get denied(): boolean {
return this._.denied;
}
// -------------------------------
// PUBLIC METHODS
// -------------------------------
/**
* A chainer method that sets the role(s) for this `Access` instance.
* @param {String|Array<String>} value
* A single or array of roles.
* @returns {Access}
* Self instance of `Access`.
*/
role(value: string | string[]): Access {
// in case chain is not terminated (e.g. `ac.grant('user')`) we'll
// create/commit the roles to grants with an empty object.
utils.preCreateRoles(this._grants, value);
this._.role = value;
return this;
}
/**
* A chainer method that sets the resource for this `Access` instance.
* @param {String|Array<String>} value
* Target resource for this `Access` instance.
* @returns {Access}
* Self instance of `Access`.
*/
resource(value: string | string[]): Access {
// this will throw if any item fails
utils.hasValidNames(value, true);
this._.resource = value;
return this;
}
/**
* Sets the array of allowed attributes for this `Access` instance.
* @param {String|Array<String>} value
* Attributes to be set.
* @returns {Access}
* Self instance of `Access`.
*/
attributes(value: string | string[]): Access {
this._.attributes = value;
return this;
}
/**
* Sets the roles to be extended for this `Access` instance.
* @alias Access#inherit
* @name AccessControl~Access#extend
* @function
*
* @param {String|Array<String>} roles
* A single or array of roles.
* @returns {Access}
* Self instance of `Access`.
*
* @example
* ac.grant('user').createAny('video')
* .grant('admin').extend('user');
* const permission = ac.can('admin').createAny('video');
* console.log(permission.granted); // true
*/
extend(roles: string | string[]): Access {
utils.extendRole(this._grants, this._.role, roles);
return this;
}
/**
* Alias of `extend`.
* @private
*/
inherit(roles: string | string[]): Access {
this.extend(roles);
return this;
}
/**
* Shorthand to switch to a new `Access` instance with a different role
* within the method chain.
*
* @param {String|Array<String>|IAccessInfo} [roleOrInfo]
* Either a single or an array of roles or an
* {@link ?api=ac#AccessControl~IAccessInfo|`IAccessInfo` object}.
*
* @returns {Access}
* A new `Access` instance.
*
* @example
* ac.grant('user').createOwn('video')
* .grant('admin').updateAny('video');
*/
grant(roleOrInfo?: string | string[] | IAccessInfo): Access {
return (new Access(this._ac, roleOrInfo, false)).attributes(['*']);
}
/**
* Shorthand to switch to a new `Access` instance with a different
* (or same) role within the method chain.
*
* @param {String|Array<String>|IAccessInfo} [roleOrInfo]
* Either a single or an array of roles or an
* {@link ?api=ac#AccessControl~IAccessInfo|`IAccessInfo` object}.
*
* @returns {Access}
* A new `Access` instance.
*
* @example
* ac.grant('admin').createAny('video')
* .deny('user').deleteAny('video');
*/
deny(roleOrInfo?: string | string[] | IAccessInfo): Access {
return (new Access(this._ac, roleOrInfo, true)).attributes([]);
}
/**
* Chainable, convenience shortcut for {@link ?api=ac#AccessControl#lock|`AccessControl#lock()`}.
* @returns {Access}
*/
lock(): Access {
utils.lockAC(this._ac);
return this;
}
/**
* Sets the action to `"create"` and possession to `"own"` and commits the
* current access instance to the underlying grant model.
*
* @param {String|Array<String>} [resource]
* Defines the target resource this access is granted or denied for.
* This is only optional if the resource is previously defined.
* If not defined and omitted, this will throw.
* @param {String|Array<String>} [attributes]
* Defines the resource attributes for which the access is granted
* for. If access is denied previously by calling `.deny()` this
* will default to an empty array (which means no attributes allowed).
* Otherwise (if granted before via `.grant()`) this will default
* to `["*"]` (which means all attributes allowed.)
*
* @throws {AccessControlError}
* If the access instance to be committed has any invalid
* data.
*
* @returns {Access}
* Self instance of `Access` so that you can chain and define
* another access instance to be committed.
*/
createOwn(resource?: string | string[], attributes?: string | string[]): Access {
return this._prepareAndCommit(Action.CREATE, Possession.OWN, resource, attributes);
}
/**
* Sets the action to `"create"` and possession to `"any"` and commits the
* current access instance to the underlying grant model.
* @alias Access#create
* @name AccessControl~Access#createAny
* @function
*
* @param {String|Array<String>} [resource]
* Defines the target resource this access is granted or denied for.
* This is only optional if the resource is previously defined.
* If not defined and omitted, this will throw.
* @param {String|Array<String>} [attributes]
* Defines the resource attributes for which the access is granted
* for. If access is denied previously by calling `.deny()` this
* will default to an empty array (which means no attributes allowed).
* Otherwise (if granted before via `.grant()`) this will default
* to `["*"]` (which means all attributes allowed.)
*
* @throws {AccessControlError}
* If the access instance to be committed has any invalid data.
*
* @returns {Access}
* Self instance of `Access` so that you can chain and define
* another access instance to be committed.
*/
createAny(resource?: string | string[], attributes?: string | string[]): Access {
return this._prepareAndCommit(Action.CREATE, Possession.ANY, resource, attributes);
}
/**
* Alias of `createAny`
* @private
*/
create(resource?: string | string[], attributes?: string | string[]): Access {
return this.createAny(resource, attributes);
}
/**
* Sets the action to `"read"` and possession to `"own"` and commits the
* current access instance to the underlying grant model.
*
* @param {String|Array<String>} [resource]
* Defines the target resource this access is granted or denied for.
* This is only optional if the resource is previously defined.
* If not defined and omitted, this will throw.
* @param {String|Array<String>} [attributes]
* Defines the resource attributes for which the access is granted
* for. If access is denied previously by calling `.deny()` this
* will default to an empty array (which means no attributes allowed).
* Otherwise (if granted before via `.grant()`) this will default
* to `["*"]` (which means all attributes allowed.)
*
* @throws {AccessControlError}
* If the access instance to be committed has any invalid data.
*
* @returns {Access}
* Self instance of `Access` so that you can chain and define
* another access instance to be committed.
*/
readOwn(resource?: string | string[], attributes?: string | string[]): Access {
return this._prepareAndCommit(Action.READ, Possession.OWN, resource, attributes);
}
/**
* Sets the action to `"read"` and possession to `"any"` and commits the
* current access instance to the underlying grant model.
* @alias Access#read
* @name AccessControl~Access#readAny
* @function
*
* @param {String|Array<String>} [resource]
* Defines the target resource this access is granted or denied for.
* This is only optional if the resource is previously defined.
* If not defined and omitted, this will throw.
* @param {String|Array<String>} [attributes]
* Defines the resource attributes for which the access is granted
* for. If access is denied previously by calling `.deny()` this
* will default to an empty array (which means no attributes allowed).
* Otherwise (if granted before via `.grant()`) this will default
* to `["*"]` (which means all attributes allowed.)
*
* @throws {AccessControlError}
* If the access instance to be committed has any invalid data.
*
* @returns {Access}
* Self instance of `Access` so that you can chain and define
* another access instance to be committed.
*/
readAny(resource?: string | string[], attributes?: string | string[]): Access {
return this._prepareAndCommit(Action.READ, Possession.ANY, resource, attributes);
}
/**
* Alias of `readAny`
* @private
*/
read(resource?: string | string[], attributes?: string | string[]): Access {
return this.readAny(resource, attributes);
}
/**
* Sets the action to `"update"` and possession to `"own"` and commits the
* current access instance to the underlying grant model.
*
* @param {String|Array<String>} [resource]
* Defines the target resource this access is granted or denied for.
* This is only optional if the resource is previously defined.
* If not defined and omitted, this will throw.
* @param {String|Array<String>} [attributes]
* Defines the resource attributes for which the access is granted
* for. If access is denied previously by calling `.deny()` this
* will default to an empty array (which means no attributes allowed).
* Otherwise (if granted before via `.grant()`) this will default
* to `["*"]` (which means all attributes allowed.)
*
* @throws {AccessControlError}
* If the access instance to be committed has any invalid data.
*
* @returns {Access}
* Self instance of `Access` so that you can chain and define
* another access instance to be committed.
*/
updateOwn(resource?: string | string[], attributes?: string | string[]): Access {
return this._prepareAndCommit(Action.UPDATE, Possession.OWN, resource, attributes);
}
/**
* Sets the action to `"update"` and possession to `"any"` and commits the
* current access instance to the underlying grant model.
* @alias Access#update
* @name AccessControl~Access#updateAny
* @function
*
* @param {String|Array<String>} [resource]
* Defines the target resource this access is granted or denied for.
* This is only optional if the resource is previously defined.
* If not defined and omitted, this will throw.
* @param {String|Array<String>} [attributes]
* Defines the resource attributes for which the access is granted
* for. If access is denied previously by calling `.deny()` this
* will default to an empty array (which means no attributes allowed).
* Otherwise (if granted before via `.grant()`) this will default
* to `["*"]` (which means all attributes allowed.)
*
* @throws {AccessControlError}
* If the access instance to be committed has any invalid data.
*
* @returns {Access}
* Self instance of `Access` so that you can chain and define
* another access instance to be committed.
*/
updateAny(resource?: string | string[], attributes?: string | string[]): Access {
return this._prepareAndCommit(Action.UPDATE, Possession.ANY, resource, attributes);
}
/**
* Alias of `updateAny`
* @private
*/
update(resource?: string | string[], attributes?: string | string[]): Access {
return this.updateAny(resource, attributes);
}
/**
* Sets the action to `"delete"` and possession to `"own"` and commits the
* current access instance to the underlying grant model.
*
* @param {String|Array<String>} [resource]
* Defines the target resource this access is granted or denied for.
* This is only optional if the resource is previously defined.
* If not defined and omitted, this will throw.
* @param {String|Array<String>} [attributes]
* Defines the resource attributes for which the access is granted
* for. If access is denied previously by calling `.deny()` this
* will default to an empty array (which means no attributes allowed).
* Otherwise (if granted before via `.grant()`) this will default
* to `["*"]` (which means all attributes allowed.)
*
* @throws {AccessControlError}
* If the access instance to be committed has any invalid data.
*
* @returns {Access}
* Self instance of `Access` so that you can chain and define
* another access instance to be committed.
*/
deleteOwn(resource?: string | string[], attributes?: string | string[]): Access {
return this._prepareAndCommit(Action.DELETE, Possession.OWN, resource, attributes);
}
/**
* Sets the action to `"delete"` and possession to `"any"` and commits the
* current access instance to the underlying grant model.
* @alias Access#delete
* @name AccessControl~Access#deleteAny
* @function
*
* @param {String|Array<String>} [resource]
* Defines the target resource this access is granted or denied for.
* This is only optional if the resource is previously defined.
* If not defined and omitted, this will throw.
* @param {String|Array<String>} [attributes]
* Defines the resource attributes for which the access is granted
* for. If access is denied previously by calling `.deny()` this
* will default to an empty array (which means no attributes allowed).
* Otherwise (if granted before via `.grant()`) this will default
* to `["*"]` (which means all attributes allowed.)
*
* @throws {AccessControlError}
* If the access instance to be committed has any invalid data.
*
* @returns {Access}
* Self instance of `Access` so that you can chain and define
* another access instance to be committed.
*/
deleteAny(resource?: string | string[], attributes?: string | string[]): Access {
return this._prepareAndCommit(Action.DELETE, Possession.ANY, resource, attributes);
}
/**
* Alias of `deleteAny`
* @private
*/
delete(resource?: string | string[], attributes?: string | string[]): Access {
return this.deleteAny(resource, attributes);
}
// -------------------------------
// PRIVATE METHODS
// -------------------------------
/**
* @private
* @param {String} action [description]
* @param {String} possession [description]
* @param {String|Array<String>} resource [description]
* @param {String|Array<String>} attributes [description]
* @returns {Access}
* Self instance of `Access`.
*/
private _prepareAndCommit(action: string, possession: string, resource?: string | string[], attributes?: string | string[]): Access {
this._.action = action;
this._.possession = possession;
if (resource) this._.resource = resource;
if (this._.denied) {
this._.attributes = [];
} else {
// if omitted and not denied, all attributes are allowed
this._.attributes = attributes ? utils.toStringArray(attributes) : ['*'];
}
utils.commitToGrants(this._grants, this._, false);
// important: reset attributes for chained methods
this._.attributes = undefined;
return this;
}
}
export { Access }; | the_stack |
import {Watcher, Program, RawMap, RawValue, RawEAVC} from "./watcher";
import {UIWatcher} from "../watchers/ui";
interface Attrs extends RawMap<RawValue> {}
function t(tag:string) {
return `tag-browser/${tag}`;
}
function collapse<T extends any[]>(...args:T[]):T {
let all:T = [] as any;
for(let sublist of args) {
for(let item of sublist) {
all.push(item);
}
}
return all;
}
export class TagBrowserWatcher extends Watcher {
browser:Program = this.createTagBrowser();
setup() {
this.program
.watch("Export all tags", ({find, record}) => {
let rec = find();
return [
record("child-tag", {"child-tag": rec.tag})
];
})
.asDiffs((diffs) => {
let eavs:RawEAVC[] = [];
for(let [e, a, v] of diffs.removes) {
eavs.push([e, a, v, -1]);
}
for(let [e, a, v] of diffs.adds) {
eavs.push([e, a, v, 1]);
}
if(eavs.length) {
this.browser.inputEAVs(eavs);
}
})
// .watch("Export records with active tags", ({find, lookup, record}) => {
// let {"active-tag": activeTag} = find("tag-browser/active-tag");
// let rec = find({tag: activeTag});
// let {attribute, value} = lookup(rec);
// return [
// rec.add("tag", "child-record").add(attribute, value)
// ];
// })
.watch("Export all records", ({find, lookup, choose, record}) => {
let rec = find();
let {attribute, value} = lookup(rec);
// let [attrName] = choose(
// () => { attribute == "tag"; return "child-tag"; },
// () => attribute
// );
return [
rec.add("tag", "child-record").add(attribute, value)
];
})
.asDiffs((diffs) => {
let eavs:RawEAVC[] = [];
for(let [e, a, v] of diffs.removes) {
// @NOTE: this breaks tag-browser inspecting tag-browser
if(a === "tag" && v !== "child-record") a = "child-tag";
eavs.push([e, a, v, -1]);
}
for(let [e, a, v] of diffs.adds) {
// @NOTE: this breaks tag-browser inspecting tag-browser
if(a === "tag" && v !== "child-record") a = "child-tag";
eavs.push([e, a, v, 1]);
}
if(eavs.length) {
this.browser.inputEAVs(eavs);
}
})
}
createTagBrowser() {
let prog = new Program("Tag Browser");
prog.attach("ui");
let {$style, $row, $column, $text, $elem} = UIWatcher.helpers;
//--------------------------------------------------------------------
// Custom UI Components
//--------------------------------------------------------------------
// Tag Button
prog
.bind("Tag button component", ({find, record}) => {
let tagButton = find("tag-browser/tag");
let tag = tagButton.target;
return [
tagButton.add({tag: "ui/button", class: "inset", text: tag, sort: tag})
];
})
.commit("When a tag button is clicked, update the view target.", ({find, record}) => {
let click = find("html/event/click");
let {element} = click;
element.tag == "tag-browser/tag";
let view = find("tag-browser/view");
return [
view.remove("target").add("target", element.target)
];
})
// @FIXME: Work around for a bug that occurs when leaving a record open and then letting it be retracted and reasserted
// .commit("When a tag button is clicked, clear any open child records", ({find, record}) => {
// let click = find("html/event/click");
// let {element} = click;
// element.tag == "tag-browser/tag";
// //let view = find("tag-browser/view");
// //view.target != element.target;
// let openChildren = find("tag-browser/record");
// openChildren.open;
// return [
// openChildren.remove("open")
// ];
// });
// Record
prog
.bind("Record component (closed)", ({find, record}) => {
let childRecord = find("tag-browser/record");
return [
childRecord.add({
tag: "ui/column",
style: record({border: "1px solid gray", margin: 10, padding: 10}),
rec: childRecord.target,
children: [
record("ui/row", "tag-browser/record-header", {sort: 0, rec: childRecord.target}).add("children", [
record("html/element", {tagname: "div", class: "hexagon"}),
record("ui/text", {rec: childRecord.target, text: childRecord.target.displayName})
])
]
})
];
})
.bind("Record component (open)", ({find, lookup, record}) => {
let childRecord = find("tag-browser/record", {open: "true"});
let {attribute, value} = lookup(childRecord.target);
attribute != "tag";
return [
childRecord.add({
children: [
record("tag-browser/record-attribute", {rec: childRecord.target, attr: attribute}).add("val", value)
]
})
];
})
.commit("Clicking a record toggles it open/closed", ({find, choose}) => {
let recordHeader = find("tag-browser/record-header");
let record = find("tag-browser/record", {children: recordHeader});
find("html/event/click", {element: recordHeader});
let [open] = choose(
() => { record.open == "true"; return "false"; },
() => "true"
)
return [
record.remove("open").add("open", open)
];
});
// Record Attribute
prog
.bind("Record attribute component", ({find, choose, record}) => {
let recordAttribute = find("tag-browser/record-attribute");
let {target} = find("tag-browser/view")
let [attrName] = choose(
() => { recordAttribute.attr == "child-tag"; return "tag"; },
() => recordAttribute.attr
);
let {rec, val} = recordAttribute;
return [
recordAttribute.add({tag: "ui/row",
children: [
record("ui/text", {sort: 0, text: `${attrName}:`, rec, style: record({"margin-right": 10})}),
record("ui/column", {sort: 1, rec, attrName}) // @FIXME: These attrs from the parent shouldn't need to be on the children.
.add("children", record("tag-browser/record-value", {rec, attr: attrName, val, "active-input":"foo"}))
]
})
];
});
// Record Value
prog
.bind("Record value component (as tag)", ({find, record}) => {
let recordValue = find("tag-browser/record-value");
let {val} = recordValue;
let childTag = find("child-tag", {"child-tag": val});
return [
recordValue.add({tag: "tag-browser/tag", target: val})
];
})
.bind("Record value component (as record)", ({find, record}) => {
let recordValue = find("tag-browser/record-value");
let childRecord = find("child-record");
childRecord == recordValue.val;
return [
recordValue.add({tag: "tag-browser/record", target: childRecord})
];
})
.bind("Record value component (as raw value)", ({find, not, record}) => {
let recordValue = find("tag-browser/record-value");
// @FIXME: Not is *still* busted
not(() => recordValue.tag == "tag-browser/tag");
not(() => recordValue.tag == "tag-browser/record");
let {val} = recordValue;
return [
recordValue.add({tag: "ui/text", sort: val, text: val})
];
})
// Tag Cloud
prog.bind("List all tags in the tag cloud.", ({find, not, record}) => {
let cloud = find("tag-browser/cloud");
let rec = find("child-tag");
let tag = rec["child-tag"];
return [
cloud.add("children", record("tag-browser/tag", {target: tag}))
];
});
// Tag View
prog
.bind("Show the targeted tag", ({find, record}) => {
let view = find("tag-browser/view");
let target = view.target;
return [
view.add("children", record("ui/text", {text: `Current tag: ${target}`, sort: 0}))
]
})
.bind("Show records with the targeted tag", ({find, not, record}) => {
let view = find("tag-browser/view");
let targetedRecord = find("child-record", {"child-tag": view.target});
return [
view.add("children", record("ui/row", {
sort: 1,
style: record({"flex-wrap": "wrap", "align-items": "flex-start"}),
}).add("children", record("tag-browser/record", {target: targetedRecord, "active-tag": view.target})))
];
})
.watch("When the view target changes, mark it as the active tag in the child program", ({find, record}) => {
let view = find("tag-browser/view");
return [
record("tag-browser/active-tag", {"active-tag": view.target})
];
})
.asDiffs((diffs) => {
let eavs:RawEAVC[] = [];
for(let [e, a, v] of diffs.removes) {
eavs.push([e, a, v, -1]);
}
for(let [e, a, v] of diffs.adds) {
eavs.push([e, a, v, 1]);
}
if(eavs.length) {
this.program.inputEAVs(eavs);
}
});
// Display Name aliasing
prog
.bind("Alias display names", ({find, choose}) => {
let record = find("child-record");
let [name] = choose(
//() => record.displayName,
() => record.name,
() => "???"
);
return [
record.add("displayName", name)
];
})
// Create root UI
let changes = collapse(
$column({tag: t("root")}, [
$row({tag: t("cloud"), style: $style({"flex-wrap": "wrap"})}, []),
$column({tag: t("view")}, [])
]),
$elem("html/element", {
tagname: "style",
text: `
.hexagon {
width: 22px;
height: 22px;
margin-right: 5px;
vertical-align: middle;
border-radius: 100px;
border: 2px solid #AAA;
}
`
})
);
prog.inputEAVs(changes);
return prog;
}
}
Watcher.register("tag browser", TagBrowserWatcher); | the_stack |
import {Program} from "../src/runtime/dsl2";
import * as Runtime from "../src/runtime/runtime";
import * as test from "tape";
// You can specify changes as either [e,a,v] or [e,a,v,round,count];
export type EAVTuple = [Runtime.RawValue, Runtime.RawValue, Runtime.RawValue];
export type EAVRCTuple = [Runtime.RawValue, Runtime.RawValue, Runtime.RawValue, number, number];
export type TestChange = EAVTuple | EAVRCTuple;
let {GlobalInterner} = Runtime;
let TEST_INPUT_NODE = "test-input-node";
export function pprint(obj:any):string {
if(typeof obj === "object" && obj instanceof Array) {
return "[" + obj.map((v) => pprint(v)).join(", ") + "]";
} else if(typeof obj === "string") {
return `"${obj}"`;
}
return ""+obj;
}
export class EntityId {
constructor(public id:Runtime.ID) {}
toString() {
return "$" + this.id;
}
}
export function o_o(val:Runtime.ID):EntityId|Runtime.RawValue|undefined {
let raw = GlobalInterner.reverse(val);
if(typeof raw === "string" && raw.indexOf("|") !== -1) {
return new EntityId(val);
}
return raw;
}
export function createChanges(transaction:number,eavns:TestChange[]) {
let changes:Runtime.Change[] = [];
for(let [e, a, v, round = 0, count = 1] of eavns as EAVRCTuple[]) {
changes.push(Runtime.Change.fromValues(e, a, v, TEST_INPUT_NODE, transaction, round, count));
}
return changes;
}
export function verify(assert:test.Test, program:Program, input:any[], output:any[], transaction = 1) {
let ins = createChanges(transaction, input);
let outs = createChanges(transaction, output);
let all:(Runtime.Change|undefined)[] = outs;
let {changes, context} = program.input(ins)!;
let inputNode = GlobalInterner.get(TEST_INPUT_NODE);
changes = changes.filter((v) => v.n !== inputNode);
let msg = "Fewer changes than expected";
if(changes.length > all.length) {
msg = "More changes than expected";
}
if(changes.length !== all.length) {
assert.comment(". Actual: " + pprint(changes.map((change) => {
let {e, a, v, round, count} = change;
return [o_o(e), o_o(a), o_o(v), round, count];
})));
}
assert.equal(changes.length, all.length, msg);
try {
context.distinctIndex.sanityCheck();
} catch(e) {
assert.fail("Distinct sanity check failed");
}
// Because the changes handed to us in expected aren't going to have the same
// e's as what the program itself is going to generate, we're going to have to do
// some fancy matching to map from generated e's to expected e's. We'll need to
// store that mapping somewhere, so we have eMap:
let eMap:any = {};
let fullyResolved:any = {};
if(changes.length === all.length) {
// As we check all of the changes we got from running the input on the program,
// we need to update our eMap based on the expected changes that *could* match.
// Most of the time, the hope is that there's only one potential match, but when
// you're looking at something like tag, it's easy for there to be many records
// that get generated with the same tag, so we're going to do a decent amount of
// work here.
for(let actual of changes) {
let found = false;
// console.log("\n\nACTUAL");
// console.log(" ", actual.toString());
// console.log(" ", actual);
let expectedIx = 0;
// check if we've found any potential matches for this e yet
let matches = eMap[actual.e];
// if we haven't found any matches yet, we need to collect some initial ones.
if(!matches) {
let potentials = [];
for(let expected of all) {
if(!expected) {
expectedIx++;
continue;
}
// if this expected *could* match ignoring e and n, then we'll store this as
// a potential mapping from the actual.e to the expected.e. We're also going
// to store this expected's index so that once we know for sure that this
// actual.e === expected.e we can clean out the expecteds that no one can claim
// anymore.
if(actual.equal(expected, true /*ignore the node*/, true /*ignore the e*/)) {
found = true;
potentials.push({e: expected.e, relatedChanges: [expectedIx]});
}
expectedIx++;
}
// if there was only one match, no one can ever have this expected - we've claimed it.
// As such, we need to remove it from the list;
if(potentials.length === 1) {
// We need to check that we haven't already resolved this match to some other actual value.
let e = potentials[0].e;
if(fullyResolved[e] !== undefined) {
assert.fail(`\`${GlobalInterner.reverse(e)}\` has already been resolved to \`${GlobalInterner.reverse(fullyResolved[e])}\`,` +
` but we are trying to resolve it to \`${GlobalInterner.reverse(actual.e)}\``);
break;
}
fullyResolved[e] = actual.e;
for(let ix of potentials[0].relatedChanges) {
all[ix] = undefined;
}
}
eMap[actual.e] = potentials;
} else if(matches.length === 1) {
// in the case where we've mapped our actual.e to our expected.e, we just check this
// current fact for a match where the expected.e is what we're looking for
for(let expected of all) {
if(!expected) {
expectedIx++;
continue;
}
if(expected.e === matches[0].e && actual.equal(expected, true, true)) {
found = true;
all[expectedIx] = undefined;
}
expectedIx++;
}
} else {
// since we have multiple potential matches, we need to see if this actual might reduce
// the set down for us. For each expected that's left, we'll check if expected.e matches
// one of our potentials, and if this expected would equal our actual if we ignored the
// e. If so, we keep this potential in the running. Any potentials the don't end up with
// a match get removed on account of us recreating the potential array from scratch here.
let potentials = [];
for(let expected of all) {
if(!expected) {
expectedIx++;
continue;
}
for(let match of matches) {
if(match.e === expected.e && !fullyResolved[match.e] && actual.equal(expected, true, true)) {
found = true;
potentials.push(match);
match.relatedChanges.push(expectedIx);
}
}
expectedIx++;
}
// If we only have one potential, we need to clean up after ourselves again. This time
// however, we could have had many relatedChanges that we need to clean up, so we'll loop
// through them and remove them from the list. They're our's now.
if(potentials.length === 1) {
// We need to check that we haven't already resolved this match to some other actual value.
let e = potentials[0].e;
if(fullyResolved[e] !== undefined) {
assert.fail(`\`${GlobalInterner.reverse(e)}\` has already been resolved to \`${GlobalInterner.reverse(fullyResolved[e])}\`,` +
` but we are trying to resolve it to \`${GlobalInterner.reverse(actual.e)}\``);
break;
}
fullyResolved[e] = actual.e;
let related = potentials[0].relatedChanges;
related.sort((a:number, b:number) => b - a);
for(let relatedIx of related) {
all[relatedIx] = undefined;
}
potentials[0].relatedChanges = []
}
eMap[actual.e] = potentials;
}
// console.log(" ", actual.e, ":", eMap[actual.e]);
// console.log(" [")
// for(let thing of all) {
// console.log(" ", thing);
// }
// console.log(" ]")
if(!found) assert.fail("No match found for: " + actual.toString());
else assert.pass("Found match for: " + actual.toString());
}
}
}
export function time(start?:any): number | number[] | string {
if ( !start ) return process.hrtime();
let end = process.hrtime(start);
return ((end[0]*1000) + (end[1]/1000000)).toFixed(3);
}
export function createInputs(inputString:string) {
let transactionInputs:EAVRCTuple[][] = [];
let transactions = inputString.split(";");
for(let transaction of transactions) {
let eavrcs:EAVRCTuple[] = [];
let roundNumber = 0;
for(let round of transaction.split(",")) {
for(let input of round.split(" ")) {
if(!input) continue;
let count;
if(input[0] === "+") count = 1;
else if(input[0] === "-") count = -1;
else throw new Error(`Malformed input: ${input}`);
let args = input.slice(1).split(":");
let id = args.shift();
if(!id) throw new Error(`Malformed input: '${input}'`);
eavrcs.push([id, "tag", "input", roundNumber, count]);
let argIx = 0;
for(let arg of args) {
eavrcs.push([id, `arg${argIx}`, (isNaN(arg as any) ? arg : +arg), roundNumber, count]);
argIx++;
}
}
roundNumber += 1;
}
transactionInputs.push(eavrcs);
}
return transactionInputs;
}
export function createVerifier<T extends {[name:string]: () => Program}>(programs:T) {
return function verifyInput(assert:test.Test, progName:(keyof T), inputString:string, expecteds:EAVRCTuple[][]) {
let prog = programs[progName]();
let inputs = createInputs(inputString);
if(expecteds.length !== inputs.length) {
assert.fail("Malformed test case");
throw new Error(`Incorrect number of expecteds given the inputString Got ${expecteds.length}, needed: ${inputs.length}`);
}
let transactionNumber = 0;
for(let input of inputs) {
let expected = expecteds[transactionNumber];
assert.comment(". Verifying: " + pprint(input) + " -> " + pprint(expected));
verify(assert, prog, input, expected);
transactionNumber++;
}
assert.end();
return prog;
};
} | the_stack |
import {
Data,
Filter,
Partial,
ThisTask,
ThisWatcher,
ThisListener,
Listener,
Component,
ComponentCallback,
ComponentLoader,
PropTypeFunction,
PropValueFunction,
PropRule,
} from 'yox-type/src/type'
import {
VNode,
} from 'yox-type/src/vnode'
import {
DirectiveHooks,
TransitionHooks,
} from 'yox-type/src/hooks'
import {
EmitterEvent,
EmitterOptions,
ListenerOptions,
ComponentOptions,
ThisWatcherOptions,
ThisListenerOptions,
} from 'yox-type/src/options'
import {
YoxInterface,
} from 'yox-type/src/yox'
import {
IsApi,
DomApi,
ArrayApi,
ObjectApi,
StringApi,
LoggerApi,
} from 'yox-type/src/api'
import {
HOOK_BEFORE_CREATE,
HOOK_AFTER_CREATE,
HOOK_BEFORE_MOUNT,
HOOK_AFTER_MOUNT,
HOOK_BEFORE_UPDATE,
HOOK_AFTER_UPDATE,
HOOK_BEFORE_DESTROY,
HOOK_AFTER_DESTROY,
HOOK_BEFORE_PROPS_UPDATE,
MODEL_PROP_DEFAULT,
SLOT_DATA_PREFIX,
MODIFER_NATIVE,
} from 'yox-config/src/config'
import Emitter from 'yox-common/src/util/Emitter'
import NextTask from 'yox-common/src/util/NextTask'
import CustomEvent from 'yox-common/src/util/CustomEvent'
import * as is from 'yox-common/src/util/is'
import * as cache from 'yox-common/src/util/cache'
import * as array from 'yox-common/src/util/array'
import * as string from 'yox-common/src/util/string'
import * as object from 'yox-common/src/util/object'
import * as logger from 'yox-common/src/util/logger'
import * as constant from 'yox-common/src/util/constant'
import * as snabbdom from 'yox-snabbdom/src/snabbdom'
import * as templateCompiler from 'yox-template-compiler/src/compiler'
import * as templateGenerator from 'yox-template-compiler/src/generator'
import * as templateRender from 'yox-template-compiler/src/renderer'
import * as domApi from 'yox-dom/src/dom'
import Observer from 'yox-observer/src/Observer'
class LifeCycle {
private $emitter: Emitter
constructor() {
this.$emitter = new Emitter()
}
fire(component: YoxInterface, type: string, data?: Data) {
this.$emitter.fire(
type,
[
component,
data,
]
)
}
on(type: string, listener: Function) {
this.$emitter.on(type, listener)
return this
}
off(type: string, listener: Function) {
this.$emitter.off(type, listener)
return this
}
}
const globalDirectives = { },
globalTransitions = { },
globalComponents = { },
globalPartials = { },
globalFilters = { },
selectorPattern = /^[#.][-\w+]+$/,
lifeCycle = new LifeCycle(),
compileTemplate = cache.createOneKeyCache(
function (template: string) {
const nodes = templateCompiler.compile(template)
if (process.env.NODE_ENV === 'development') {
if (nodes.length !== 1) {
logger.fatal(`The "template" option should have just one root element.`)
}
}
return templateGenerator.generate(nodes[0])
}
),
markDirty = function () {
this.$isDirty = constant.TRUE
}
export default class Yox implements YoxInterface {
$options: ComponentOptions
$observer: Observer
$emitter: Emitter
$el?: HTMLElement
$template?: Function
$refs?: Record<string, YoxInterface | HTMLElement>
$model?: string
$root?: YoxInterface
$parent?: YoxInterface
$context?: YoxInterface
$children?: YoxInterface[]
$vnode: VNode | undefined
private $nextTask: NextTask
private $directives?: Record<string, DirectiveHooks>
private $components?: Record<string, ComponentOptions>
private $transitions?: Record<string, TransitionHooks>
private $partials?: Record<string, Function>
private $filters?: Record<string, Filter>
private $dependencies?: Record<string, boolean>
private $isDirty?: boolean
/**
* core 版本
*/
public static version = process.env.NODE_VERSION
/**
* 方便外部共用的通用逻辑,特别是写插件,减少重复代码
*/
public static is: IsApi = is
public static dom: DomApi = domApi
public static array: ArrayApi = array
public static object: ObjectApi = object
public static string: StringApi = string
public static logger: LoggerApi = logger
public static Event = CustomEvent
public static Emitter = Emitter
public static lifeCycle = lifeCycle
/**
* 外部可配置的对象
*/
public static config = constant.PUBLIC_CONFIG
/**
* 定义组件对象
*/
public static define<Computed, Watchers, Events, Methods>(
options: ComponentOptions<Computed, Watchers, Events, Methods> & ThisType<Methods & YoxInterface>
) {
return options
}
/**
* 安装插件
*
* 插件必须暴露 install 方法
*/
public static use(
plugin: {
install(Y: typeof Yox): void
}
): void {
plugin.install(Yox)
}
/**
* 因为组件采用的是异步更新机制,为了在更新之后进行一些操作,可使用 nextTick
*/
public static nextTick(task: Function, context?: any): void {
NextTask.shared().append(task, context)
}
/**
* 编译模板,暴露出来是为了打包阶段的模板预编译
*/
public static compile(template: string | Function, stringify?: boolean): string | Function {
if (process.env.NODE_ENV !== 'pure' && process.env.NODE_ENV !== 'runtime') {
// 需要编译的都是模板源文件,一旦经过预编译,就成了 render 函数
if (is.func(template)) {
return template as Function
}
template = compileTemplate(template as string)
return stringify
? template
: new Function(`return ${template}`)()
}
else {
return template
}
}
/**
* 注册全局指令
*/
public static directive(
name: string | Record<string, DirectiveHooks>,
directive?: DirectiveHooks
): DirectiveHooks | void {
if (process.env.NODE_ENV !== 'pure') {
if (is.string(name) && !directive) {
return getResource(globalDirectives, name as string)
}
setResource(globalDirectives, name, directive)
}
}
/**
* 注册全局过渡动画
*/
public static transition(
name: string | Record<string, TransitionHooks>,
transition?: TransitionHooks
): TransitionHooks | void {
if (process.env.NODE_ENV !== 'pure') {
if (is.string(name) && !transition) {
return getResource(globalTransitions, name as string)
}
setResource(globalTransitions, name, transition)
}
}
/**
* 注册全局组件
*/
public static component(
name: string | Record<string, Component>,
component?: Component
): Component | void {
if (process.env.NODE_ENV !== 'pure') {
if (is.string(name) && !component) {
return getResource(globalComponents, name as string)
}
setResource(globalComponents, name, component)
}
}
/**
* 注册全局子模板
*/
public static partial(
name: string | Record<string, Partial>,
partial?: Partial
): Function | void {
if (process.env.NODE_ENV !== 'pure') {
if (is.string(name) && !partial) {
return getResource(globalPartials, name as string)
}
setResource(globalPartials, name, partial, Yox.compile)
}
}
/**
* 注册全局过滤器
*/
public static filter(
name: string | Record<string, Filter>,
filter?: Filter
): Filter | void {
if (process.env.NODE_ENV !== 'pure') {
if (is.string(name) && !filter) {
return getResource(globalFilters, name as string)
}
setResource(globalFilters, name, filter)
}
}
constructor(options?: ComponentOptions) {
const instance = this, $options: ComponentOptions = options || constant.EMPTY_OBJECT
// 为了冒泡 HOOK_BEFORE_CREATE 事件,必须第一时间创建 emitter
// 监听各种事件
// 支持命名空间
instance.$emitter = new Emitter(constant.TRUE)
if ($options.events) {
instance.on($options.events)
}
if (process.env.NODE_ENV !== 'pure') {
// 当前组件的直接父组件
if ($options.parent) {
instance.$parent = $options.parent
}
// 建立好父子连接后,立即触发钩子
const beforeCreateHook = $options[HOOK_BEFORE_CREATE]
if (beforeCreateHook) {
beforeCreateHook.call(instance, $options)
}
lifeCycle.fire(
instance,
HOOK_BEFORE_CREATE,
{
options: $options,
}
)
}
let {
data,
props,
vnode,
propTypes,
computed,
methods,
watchers,
extensions,
} = $options
instance.$options = $options
if (extensions) {
object.extend(instance, extensions)
}
// 数据源,默认值仅在创建组件时启用
const source = props ? object.copy(props) : {}
if (process.env.NODE_ENV !== 'pure') {
if (propTypes) {
object.each(
propTypes,
function (rule: PropRule, key: string) {
let value = source[key]
if (process.env.NODE_ENV === 'development') {
checkProp($options.name, key, value, rule)
}
if (value === constant.UNDEFINED) {
value = rule.value
if (value !== constant.UNDEFINED) {
source[key] = rule.type === constant.RAW_FUNCTION
? value
: is.func(value)
? (value as PropValueFunction)()
: value
}
}
}
)
}
}
// 先放 props
// 当 data 是函数时,可以通过 this.get() 获取到外部数据
const observer = instance.$observer = new Observer(
source,
instance,
instance.$nextTask = new NextTask({
afterTask() {
if (instance.$isDirty) {
instance.$isDirty = constant.UNDEFINED
instance.update(
instance.render() as VNode,
instance.$vnode as VNode
)
}
}
})
)
if (computed) {
object.each(
computed,
function (options, keypath) {
observer.addComputed(keypath, options)
}
)
}
// 后放 data
if (process.env.NODE_ENV === 'development') {
if (vnode && is.object(data)) {
logger.warn(`The "data" option of child component should be a function which return an object.`)
}
}
const extend = is.func(data) ? (data as Function).call(instance, options) : data
if (is.object(extend)) {
object.each(
extend,
function (value, key) {
if (process.env.NODE_ENV === 'development') {
if (object.has(source, key)) {
logger.warn(`The data "${key}" is already used as a prop.`)
}
}
source[key] = value
}
)
}
if (methods) {
object.each(
methods,
function (method: Function, name: string) {
if (process.env.NODE_ENV === 'development') {
if (instance[name]) {
logger.fatal(`The method "${name}" is conflicted with built-in methods.`)
}
}
instance[name] = method
}
)
}
if (process.env.NODE_ENV !== 'pure') {
let placeholder: Node | void = constant.UNDEFINED,
{
el,
root,
model,
context,
replace,
template,
transitions,
components,
directives,
partials,
filters,
slots,
} = $options
if (model) {
instance.$model = model
}
// 把 slots 放进数据里,方便 get
if (slots) {
object.extend(source, slots)
}
// 检查 template
if (is.string(template)) {
// 传了选择器,则取对应元素的 html
if (selectorPattern.test(template as string)) {
placeholder = domApi.find(template as string)
if (placeholder) {
template = domApi.getHtml(placeholder as Element) as string
placeholder = constant.UNDEFINED
}
else if (process.env.NODE_ENV === 'development') {
logger.fatal(`The selector "${template}" can't match an element.`)
}
}
}
// 检查 el
if (el) {
if (is.string(el)) {
const selector = el as string
if (selectorPattern.test(selector)) {
placeholder = domApi.find(selector)
if (process.env.NODE_ENV === 'development') {
if (!placeholder) {
logger.fatal(`The selector "${selector}" can't match an element.`)
}
}
}
else if (process.env.NODE_ENV === 'development') {
logger.fatal(`The "el" option should be a selector.`)
}
}
else {
placeholder = el as Node
}
if (!replace) {
domApi.append(
placeholder as Node,
placeholder = domApi.createComment(constant.EMPTY_STRING)
)
}
}
// 根组件
if (root) {
instance.$root = root
}
// 当前组件是被哪个组件渲染出来的
// 因为有 slot 机制,$context 不一定等于 $parent
if (context) {
instance.$context = context
}
setFlexibleOptions(instance, constant.RAW_TRANSITION, transitions)
setFlexibleOptions(instance, constant.RAW_COMPONENT, components)
setFlexibleOptions(instance, constant.RAW_DIRECTIVE, directives)
setFlexibleOptions(instance, constant.RAW_PARTIAL, partials)
setFlexibleOptions(instance, constant.RAW_FILTER, filters)
if (template) {
if (watchers) {
observer.watch(watchers)
}
if (process.env.NODE_ENV !== 'pure') {
const afterCreateHook = $options[HOOK_AFTER_CREATE]
if (afterCreateHook) {
afterCreateHook.call(instance)
}
lifeCycle.fire(
instance,
HOOK_AFTER_CREATE
)
}
// 编译模板
// 在开发阶段,template 是原始的 html 模板
// 在产品阶段,template 是编译后的渲染函数
// 当然,具体是什么需要外部自己控制
instance.$template = is.string(template)
? Yox.compile(template as string) as Function
: template as Function
if (!vnode) {
if (process.env.NODE_ENV === 'development') {
if (!placeholder) {
logger.fatal('The "el" option is required for root component.')
}
}
vnode = snabbdom.create(
domApi,
placeholder as Node,
instance
)
}
instance.update(
instance.render() as VNode,
vnode
)
return
}
else if (process.env.NODE_ENV === 'development') {
if (placeholder || vnode) {
logger.fatal('The "template" option is required.')
}
}
}
if (watchers) {
observer.watch(watchers)
}
if (process.env.NODE_ENV !== 'pure') {
const afterCreateHook = $options[HOOK_AFTER_CREATE]
if (afterCreateHook) {
afterCreateHook.call(instance)
}
lifeCycle.fire(
instance,
HOOK_AFTER_CREATE
)
}
}
/**
* 取值
*/
get(
keypath: string,
defaultValue?: any
): any {
return this.$observer.get(keypath, defaultValue)
}
/**
* 设值
*/
set(
keypath: string | Data,
value?: any
): void {
// 组件经常有各种异步改值,为了避免组件销毁后依然调用 set
// 这里判断一下,至于其他方法的异步调用就算了,业务自己控制吧
const { $observer } = this
if ($observer) {
$observer.set(keypath, value)
}
}
/**
* 监听事件,支持链式调用
*/
on(
type: string | Record<string, ThisListener<this> | ThisListenerOptions>,
listener?: ThisListener<this> | ThisListenerOptions
): this {
addEvents(this, type, listener)
return this
}
/**
* 监听一次事件,支持链式调用
*/
once(
type: string | Record<string, ThisListener<this> | ThisListenerOptions>,
listener?: ThisListener<this> | ThisListenerOptions
): this {
addEvents(this, type, listener, constant.TRUE)
return this
}
/**
* 取消监听事件,支持链式调用
*/
off(
type?: string,
listener?: ThisListener<this> | ThisListenerOptions
): this {
this.$emitter.off(type, listener)
return this
}
/**
* 发射事件
*/
fire(
type: string | EmitterEvent | CustomEvent,
data?: Data | boolean,
downward?: boolean
): boolean {
// 外部为了使用方便,fire(type) 或 fire(type, data) 就行了
// 内部为了保持格式统一
// 需要转成 Event,这样还能知道 target 是哪个组件
const instance = this,
{ $emitter, $parent, $children } = instance
// 生成事件对象
let event: CustomEvent
if (CustomEvent.is(type)) {
event = type as CustomEvent
}
else if (is.string(type)) {
event = new CustomEvent(type as string)
}
else {
const emitterEvent = type as EmitterEvent
event = new CustomEvent(emitterEvent.type)
event.ns = emitterEvent.ns
}
// 先解析出命名空间,避免每次 fire 都要解析
if (event.ns === constant.UNDEFINED) {
const emitterEvent = $emitter.toEvent(event.type)
event.type = emitterEvent.type
event.ns = emitterEvent.ns
}
// 如果手动 fire 带上了事件命名空间
// 则命名空间不能是 native,因为 native 有特殊用处
if (process.env.NODE_ENV === 'development') {
if (event.ns === MODIFER_NATIVE) {
logger.error(`The namespace "${MODIFER_NATIVE}" is not permitted.`)
}
}
// 告诉外部是谁发出的事件
if (!event.target) {
event.target = instance
}
// 事件参数列表
let args: any[] = [event],
// 事件是否正常结束(未被停止冒泡)
isComplete: boolean
// 比如 fire('name', true) 直接向下发事件
if (is.object(data)) {
array.push(args, data as Data)
}
else if (data === constant.TRUE) {
downward = constant.TRUE
}
// 向上发事件会经过自己
// 如果向下发事件再经过自己,就产生了一次重叠
// 这是没有必要的,而且会导致向下发事件时,外部能接收到该事件,但我们的本意只是想让子组件接收到事件
isComplete = downward && event.target === instance
? constant.TRUE
: $emitter.fire(event, args)
if (isComplete) {
if (downward) {
if ($children) {
event.phase = CustomEvent.PHASE_DOWNWARD
array.each(
$children,
function (child) {
return isComplete = child.fire(event, data, constant.TRUE)
}
)
}
}
else if ($parent) {
event.phase = CustomEvent.PHASE_UPWARD
isComplete = $parent.fire(event, data)
}
}
return isComplete
}
/**
* 监听数据变化,支持链式调用
*/
watch(
keypath: string | Record<string, ThisWatcher<this> | ThisWatcherOptions<this>>,
watcher?: ThisWatcher<this> | ThisWatcherOptions<this>,
immediate?: boolean
): this {
this.$observer.watch(keypath, watcher, immediate)
return this
}
/**
* 取消监听数据变化,支持链式调用
*/
unwatch(
keypath?: string,
watcher?: ThisWatcher<this>
): this {
this.$observer.unwatch(keypath, watcher)
return this
}
/**
* 加载组件,组件可以是同步或异步,最后会调用 callback
*
* @param name 组件名称
* @param callback 组件加载成功后的回调
*/
loadComponent(name: string, callback: ComponentCallback): void {
if (process.env.NODE_ENV !== 'pure') {
if (!loadComponent(this.$components, name, callback)) {
if (process.env.NODE_ENV === 'development') {
if (!loadComponent(globalComponents, name, callback)) {
logger.error(`The component "${name}" is not found.`)
}
}
else {
loadComponent(globalComponents, name, callback)
}
}
}
}
/**
* 创建子组件
*
* @param options 组件配置
* @param vnode 虚拟节点
*/
createComponent(options: ComponentOptions, vnode: VNode): YoxInterface {
if (process.env.NODE_ENV !== 'pure') {
const instance = this
options = object.copy(options)
options.root = instance.$root || instance
options.parent = instance
options.context = vnode.context
options.vnode = vnode
options.replace = constant.TRUE
let { props, slots, model } = vnode
if (model) {
if (!props) {
props = {}
}
const key = options.model || MODEL_PROP_DEFAULT
props[key] = model.value
options.model = key
}
if (props) {
options.props = props
}
if (slots) {
options.slots = slots
}
const child = new Yox(options)
array.push(
instance.$children || (instance.$children = []),
child
)
const node = child.$el
if (node) {
vnode.node = node
}
else if (process.env.NODE_ENV === 'development') {
logger.fatal(`The root element of component "${vnode.tag}" is not found.`)
}
return child
}
else {
return this
}
}
/**
* 注册当前组件级别的指令
*/
directive(
name: string | Record<string, DirectiveHooks>,
directive?: DirectiveHooks
): DirectiveHooks | void {
if (process.env.NODE_ENV !== 'pure') {
const instance = this, { $directives } = instance
if (is.string(name) && !directive) {
return getResource($directives, name as string, Yox.directive)
}
setResource(
$directives || (instance.$directives = {}),
name,
directive
)
}
}
/**
* 注册当前组件级别的过渡动画
*/
transition(
name: string | Record<string, TransitionHooks>,
transition?: TransitionHooks
): TransitionHooks | void {
if (process.env.NODE_ENV !== 'pure') {
const instance = this, { $transitions } = instance
if (is.string(name) && !transition) {
return getResource($transitions, name as string, Yox.transition)
}
setResource(
$transitions || (instance.$transitions = {}),
name,
transition
)
}
}
/**
* 注册当前组件级别的组件
*/
component(
name: string | Record<string, Component>,
component?: Component
): Component | void {
if (process.env.NODE_ENV !== 'pure') {
const instance = this, { $components } = instance
if (is.string(name) && !component) {
return getResource($components, name as string, Yox.component)
}
setResource(
$components || (instance.$components = {}),
name,
component
)
}
}
/**
* 注册当前组件级别的子模板
*/
partial(
name: string | Record<string, Partial>,
partial?: Partial
): Function | void {
if (process.env.NODE_ENV !== 'pure') {
const instance = this, { $partials } = instance
if (is.string(name) && !partial) {
return getResource($partials, name as string, Yox.partial)
}
setResource(
$partials || (instance.$partials = {}),
name,
partial,
Yox.compile
)
}
}
/**
* 注册当前组件级别的过滤器
*/
filter(
name: string | Record<string, Filter>,
filter?: Filter
): Filter | void {
if (process.env.NODE_ENV !== 'pure') {
const instance = this, { $filters } = instance
if (is.string(name) && !filter) {
return getResource($filters, name as string, Yox.filter)
}
setResource(
$filters || (instance.$filters = {}),
name,
filter
)
}
}
/**
* 对于某些特殊场景,修改了数据,但是模板的依赖中并没有这一项
* 而你非常确定需要更新模板,强制刷新正是你需要的
*/
forceUpdate(props?: Data): void {
if (process.env.NODE_ENV !== 'pure') {
const instance = this,
{ $options, $vnode, $nextTask } = instance
if ($vnode) {
if (props) {
const beforePropsUpdateHook = $options[HOOK_BEFORE_PROPS_UPDATE]
if (beforePropsUpdateHook) {
beforePropsUpdateHook.call(instance, props)
}
instance.set(props)
}
// 当前可能正在进行下一轮更新
$nextTask.run()
// 没有更新模板,强制刷新
if (!props && $vnode === instance.$vnode) {
instance.update(
instance.render() as VNode,
$vnode
)
}
}
}
}
/**
* 把模板抽象语法树渲染成 virtual dom
*/
render() {
if (process.env.NODE_ENV !== 'pure') {
const instance = this,
{ $observer, $dependencies } = instance,
oldDependencies = $dependencies || constant.EMPTY_OBJECT,
dependencies = { },
vnode = templateRender.render(
instance,
instance.$template as Function,
dependencies,
$observer.data,
$observer.computed,
instance.$filters,
globalFilters,
instance.$partials,
globalPartials,
instance.$directives,
globalDirectives,
instance.$transitions,
globalTransitions
)
for (let key in dependencies) {
if (!(key in oldDependencies)) {
$observer.watch(key, markDirty)
}
}
if ($dependencies) {
for (let key in $dependencies) {
if (!(key in dependencies)) {
$observer.unwatch(key, markDirty)
}
}
}
instance.$dependencies = dependencies
return vnode
}
}
/**
* 更新 virtual dom
*
* @param vnode
* @param oldVNode
*/
update(vnode: VNode, oldVNode: VNode) {
if (process.env.NODE_ENV !== 'pure') {
let instance = this,
{ $vnode, $options } = instance,
afterHookName: string
if ($vnode) {
const beforeUpdateHook = $options[HOOK_BEFORE_UPDATE]
if (beforeUpdateHook) {
beforeUpdateHook.call(instance)
}
lifeCycle.fire(
instance,
HOOK_BEFORE_UPDATE
)
snabbdom.patch(domApi, vnode, oldVNode)
afterHookName = HOOK_AFTER_UPDATE
}
else {
const beforeMountHook = $options[HOOK_BEFORE_MOUNT]
if (beforeMountHook) {
beforeMountHook.call(instance)
}
lifeCycle.fire(
instance,
HOOK_BEFORE_MOUNT
)
snabbdom.patch(domApi, vnode, oldVNode)
instance.$el = vnode.node as HTMLElement
afterHookName = HOOK_AFTER_MOUNT
}
instance.$vnode = vnode
// 跟 nextTask 保持一个节奏
// 这样可以预留一些优化的余地
Yox.nextTick(
function () {
if (instance.$vnode) {
const afterHook = $options[afterHookName]
if (afterHook) {
afterHook.call(instance)
}
lifeCycle.fire(
instance,
afterHookName
)
}
}
)
}
}
/**
* 校验组件参数
*
* @param props
*/
checkProp(key: string, value: any): void {
if (process.env.NODE_ENV === 'development') {
const { name, propTypes } = this.$options
if (propTypes) {
const rule = propTypes[key]
if (rule) {
checkProp(name, key, value, rule)
}
}
}
}
/**
* 销毁组件
*/
destroy(): void {
const instance = this,
{ $parent, $options, $emitter, $observer } = instance
if (process.env.NODE_ENV !== 'pure') {
const beforeDestroyHook = $options[HOOK_BEFORE_DESTROY]
if (beforeDestroyHook) {
beforeDestroyHook.call(instance)
}
lifeCycle.fire(
instance,
HOOK_BEFORE_DESTROY
)
const { $vnode } = instance
if ($parent && $parent.$children) {
array.remove($parent.$children, instance)
}
if ($vnode) {
snabbdom.destroy(domApi, $vnode, !$parent)
}
}
$observer.destroy()
if (process.env.NODE_ENV !== 'pure') {
const afterDestroyHook = $options[HOOK_AFTER_DESTROY]
if (afterDestroyHook) {
afterDestroyHook.call(instance)
}
lifeCycle.fire(
instance,
HOOK_AFTER_DESTROY
)
}
// 发完 after destroy 事件再解绑所有事件
$emitter.off()
instance.$el = constant.UNDEFINED
}
/**
* 因为组件采用的是异步更新机制,为了在更新之后进行一些操作,可使用 nextTick
*/
nextTick(task: ThisTask<this>): void {
this.$nextTask.append(task, this)
}
/**
* 取反 keypath 对应的数据
*
* 不管 keypath 对应的数据是什么类型,操作后都是布尔型
*/
toggle(keypath: string): boolean {
return this.$observer.toggle(keypath)
}
/**
* 递增 keypath 对应的数据
*
* 注意,最好是整型的加法,如果涉及浮点型,不保证计算正确
*
* @param keypath 值必须能转型成数字,如果不能,则默认从 0 开始递增
* @param step 步进值,默认是 1
* @param max 可以递增到的最大值,默认不限制
*/
increase(keypath: string, step?: number, max?: number): number | void {
return this.$observer.increase(keypath, step, max)
}
/**
* 递减 keypath 对应的数据
*
* 注意,最好是整型的减法,如果涉及浮点型,不保证计算正确
*
* @param keypath 值必须能转型成数字,如果不能,则默认从 0 开始递减
* @param step 步进值,默认是 1
* @param min 可以递减到的最小值,默认不限制
*/
decrease(keypath: string, step?: number, min?: number): number | void {
return this.$observer.decrease(keypath, step, min)
}
/**
* 在数组指定位置插入元素
*
* @param keypath
* @param item
* @param index
*/
insert(keypath: string, item: any, index: number | boolean): true | void {
return this.$observer.insert(keypath, item, index)
}
/**
* 在数组尾部添加元素
*
* @param keypath
* @param item
*/
append(keypath: string, item: any): true | void {
return this.$observer.append(keypath, item)
}
/**
* 在数组首部添加元素
*
* @param keypath
* @param item
*/
prepend(keypath: string, item: any): true | void {
return this.$observer.prepend(keypath, item)
}
/**
* 通过索引移除数组中的元素
*
* @param keypath
* @param index
*/
removeAt(keypath: string, index: number): true | void {
return this.$observer.removeAt(keypath, index)
}
/**
* 直接移除数组中的元素
*
* @param keypath
* @param item
*/
remove(keypath: string, item: any): true | void {
return this.$observer.remove(keypath, item)
}
/**
* 拷贝任意数据,支持深拷贝
*
* @param data
* @param deep
*/
copy<T>(data: T, deep?: boolean): T {
return this.$observer.copy(data, deep)
}
}
const toString = Object.prototype.toString
function matchType(value: any, type: string) {
return type === 'numeric'
? is.numeric(value)
: string.lower(toString.call(value)) === `[object ${type}]`
}
function checkProp(componentName: string | undefined, key: string, value: any, rule: PropRule) {
// 传了数据
if (value !== constant.UNDEFINED) {
const type = rule.type
// 如果不写 type 或 type 不是 字符串 或 数组
// 就当做此规则无效,和没写一样
if (type) {
// 自定义函数判断是否匹配类型
// 自己打印警告信息吧
if (is.func(type)) {
(type as PropTypeFunction)(key, value, componentName)
}
else {
let matched = constant.FALSE
// type: 'string'
if (!string.falsy(type)) {
matched = matchType(value, type as string)
}
// type: ['string', 'number']
else if (!array.falsy(type)) {
array.each(
type as string[],
function (item) {
if (matchType(value, item)) {
matched = constant.TRUE
return constant.FALSE
}
}
)
}
if (!matched) {
logger.warn(`The type of prop "${key}" expected to be "${type}", but is "${value}".`, componentName)
}
}
}
else {
logger.warn(`The prop "${key}" in propTypes has no type.`, componentName)
}
}
// 没传值但此项是必传项
else if (rule.required) {
logger.warn(`The prop "${key}" is marked as required, but its value is undefined.`, componentName)
}
}
function setFlexibleOptions(instance: YoxInterface, key: string, value: Function | Data | void) {
if (is.func(value)) {
instance[key](
(value as Function).call(instance)
)
}
else if (is.object(value)) {
instance[key](value)
}
}
function addEvent(instance: Yox, type: string, listener?: Listener | ListenerOptions, once?: true) {
const { $emitter } = instance, filter = $emitter.toFilter(type, listener)
const options: EmitterOptions = {
listener: filter.listener as Function,
ns: filter.ns,
ctx: instance,
}
if (once) {
options.max = 1
}
$emitter.on(filter.type as string, options)
}
function addEvents(
instance: Yox,
type: string | Record<string, Listener | ListenerOptions>,
listener?: Listener | ListenerOptions,
once?: true
) {
if (is.string(type)) {
addEvent(instance, type as string, listener, once)
}
else {
object.each(
type as Record<string, Listener | ListenerOptions>,
function (value: Listener | ListenerOptions, key: string) {
addEvent(instance, key, value, once)
}
)
}
}
function loadComponent(
registry: Record<string, Component | ComponentCallback[]> | void,
name: string,
callback: ComponentCallback
): true | void {
if (registry && registry[name]) {
const component = registry[name]
// 注册的是异步加载函数
if (is.func(component)) {
registry[name] = [callback]
const componentCallback = function (result: ComponentOptions) {
const queue = registry[name], options = result['default'] || result
registry[name] = options
array.each(
queue as ComponentCallback[],
function (callback) {
callback(options)
}
)
},
promise = (component as ComponentLoader)(componentCallback)
if (promise) {
promise.then(componentCallback)
}
}
// 正在加载中
else if (is.array(component)) {
array.push(
component as ComponentCallback[],
callback
)
}
// 不是异步加载函数,直接同步返回
else {
callback(component as ComponentOptions)
}
return constant.TRUE
}
}
function getResource(registry: Data | void, name: string, lookup?: Function) {
if (registry && registry[name]) {
return registry[name]
}
else if (lookup) {
return lookup(name)
}
}
function setResource(registry: Data, name: string | Data, value?: any, formatValue?: (value: any) => any) {
if (is.string(name)) {
registry[name as string] = formatValue ? formatValue(value) : value
}
else {
object.each(
name as Data,
function (value, key) {
registry[key] = formatValue ? formatValue(value) : value
}
)
}
}
if (process.env.NODE_ENV !== 'pure') {
// 全局注册内置过滤器
Yox.filter({
hasSlot(name: string): boolean {
// 不鼓励在过滤器使用 this
// 因此过滤器没有 this 的类型声明
// 这个内置过滤器是不得不用 this
return (this as YoxInterface).get(SLOT_DATA_PREFIX + name) !== constant.UNDEFINED
}
})
} | the_stack |
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { EChartOption } from 'echarts';
import * as echarts from 'echarts';
import { WidgetsGQL } from '@graphql/graphql.service';
import { RealtimeWeather, Coords, WeatherForcast, Sales } from './weather.interface';
import { environment } from '@env';
@Injectable()
export class AnalysisService {
private widgetsExtend: any;
private caiyunApiUrl = environment.caiyunApi.url;
private caiyunApiKey = environment.caiyunApi.key;
private weatherReport = {
weathericon: 'wi-day-cloudy',
today: {
temperature: 0,
wind: {
direction: 0,
speed: 0
},
humidity: 0,
pm25: 0,
cloudrate: 0,
precipitation: {
local: {
intensity: 0
}
}
},
future: [],
day: {
date: Date.now(),
xingqi: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][new Date().getDay()],
}
};
constructor(
private widgets: WidgetsGQL,
private http: HttpClient
) {
this.widgetsExtend = {
user: {
title: '用户',
titleIcon: 'person',
chartTheme: '#7986cb'
},
clicks: {
title: '点击量',
titleIcon: 'flash_on',
chartTheme: '#ffd54f'
},
views: {
title: '浏览量',
titleIcon: 'equalizer',
chartTheme: '#4dd0e1'
},
follows: {
title: '关注度',
titleIcon: 'storage',
chartTheme: '#81c784'
}
};
}
private getWidgetChartOptions(color: string, data: { date: Array<string>, amount: Array<number> }): EChartOption {
return {
grid: {
top: '8%',
left: '1%',
right: '1%',
bottom: '8%',
containLabel: true,
},
xAxis: [{
type: 'category',
boundaryGap: false,
axisLine: { // 坐标轴轴线相关设置。数学上的x轴
show: false
},
axisTick: {
show: false,
},
axisLabel: {
show: false
},
data: data.date,
}],
yAxis: [{
type: 'value',
min: 0,
max: 50,
splitLine: {
show: false
},
axisLine: {
show: false,
},
axisLabel: {
show: false
},
axisTick: {
show: false,
}
}],
series: [{
type: 'line',
smooth: true, // 是否平滑曲线显示
symbolSize: 0,
lineStyle: {
width: 0
},
areaStyle: { // 区域填充样式
normal: {
// 线性渐变,前4个参数分别是x0,y0,x2,y2(范围0~1);相当于图形包围盒中的百分比。如果最后一个参数是‘true’,则该四个值是绝对像素位置。
/*color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
{
offset: 0,
color: '#7986cb'
},
{
offset: 0.8,
color: '#7986cb'
}
], false),*/
color,
shadowColor: 'rgba(53,142,215, 0.9)', // 阴影颜色
shadowBlur: 0 // shadowBlur设图形阴影的模糊大小。配合shadowColor,shadowOffsetX/Y, 设置图形的阴影效果。
}
},
data: data.amount
}]
};
}
getWidgets(): Observable<Array<any>> {
return this.widgets
.watch()
.valueChanges
.pipe(
map(result => result.data.widgets),
map(widgets => {
const results = [];
widgets.map(widget => {
const { date, amount } = widget.chartData,
widgetExtend = this.widgetsExtend[widget.type];
const obj = Object.assign({}, widget, {
...widgetExtend,
chartOption: this.getWidgetChartOptions(widgetExtend.chartTheme, { date, amount })
});
results.push(obj);
});
return results;
})
);
}
private getRealtimeWeather(coords: Coords): Observable<RealtimeWeather> {
return this.http.get<RealtimeWeather>(this.caiyunApiUrl + `v2/${this.caiyunApiKey}/${coords.longitude},${coords.latitude}/realtime.json`);
}
private getWeatherForecast(coords: Coords): Observable<WeatherForcast> {
return this.http.get<WeatherForcast>(this.caiyunApiUrl + `v2/${this.caiyunApiKey}/${coords.longitude},${coords.latitude}/forecast.json`);
}
getWeatherReportData(): any {
if (!navigator.geolocation) {
// 当前浏览器不支持 geolocation时 默认为北京
const coords: Coords = { latitude: 39.90923, longitude: 116.397428 };
this.updateWeather(coords);
} else {
navigator.geolocation.getCurrentPosition(({ coords }) => {
this.updateWeather(coords);
}, err => {
// 获取不到位置信息时 默认为北京
const coords: Coords = { latitude: 39.90923, longitude: 116.397428 };
this.updateWeather(coords);
});
}
return this.weatherReport;
}
private updateWeather(coords: Coords) {
// 实时天气
this.getRealtimeWeather(coords)
.subscribe(data => {
if (data.result.status === 'ok') {
this.weatherReport.today = data.result;
this.weatherReport.weathericon = this.weatherIcon(data.result.skycon);
}
});
// 天气预报,5日内天气
this.getWeatherForecast(coords)
.subscribe(data => {
if (data.status === 'ok') {
this.weatherReport.future = data.result.daily.temperature;
data.result.daily.skycon.forEach((obj: any, index: number) => {
this.weatherReport.future[index].weathericon = this.weatherIcon(obj.value);
});
}
});
}
private weatherIcon(skycon) {
return {
CLEAR_DAY: 'wi-day-sunny',
CLEAR_NIGHT: 'wi-night-clear',
PARTLY_CLOUDY_DAY: 'wi-day-cloudy',
PARTLY_CLOUDY_NIGHT: 'wi-night-alt-cloudy',
CLOUDY: 'wi-day-cloudy-high',
RAIN: 'wi-day-rain',
SNOW: 'wi-day-snow',
WIND: 'wi-day-windy',
HAZE: 'wi-day-haze'
}[skycon];
}
getScatterMapOption(): Observable<EChartOption> {
return this.http.get('assets/data/world.json')
.pipe(
map(worldJson => {
// register map:
echarts.registerMap('world', worldJson);
}),
map(_ => {
// scatter map options:
const scatterMapOption = {
geo: {
map: 'world',
itemStyle: { // 定义样式
normal: { // 普通状态下的样式
areaColor: '#c5cae9',
borderColor: '#fff'
},
emphasis: { // 高亮状态下的样式
areaColor: '#b3bbef'
}
},
label: {
emphasis: {
show: false
}
},
roam: true, // 开启鼠标缩放和平移漫游
zoom: 1,
scaleLimit: {
min: 2,
max: 13
},
center: [21.148055, 27.939372]
},
backgroundColor: '#fff',
tooltip: {
trigger: 'item',
formatter: (params: any) => {
return params.name + ' : ' + params.value[2] + ' ' + params.seriesName;
}
},
visualMap: [{
show: false,
min: 0,
max: 2500,
left: 'left',
top: 'bottom',
text: ['高', '低'], // 文本,默认为数值文本
calculable: true
}],
toolbox: {
show: true,
orient: 'vertical',
left: '0',
top: 'center',
feature: {
mark: { show: true },
dataView: {
show: true,
readOnly: false,
emphasis: {
iconStyle: {
textPosition: 'right',
textAlign: 'left'
}
}
},
restore: {
show: true,
emphasis: {
iconStyle: {
textPosition: 'right',
textAlign: 'left'
}
}
},
saveAsImage: {
show: true,
emphasis: {
iconStyle: {
textPosition: 'right',
textAlign: 'left'
}
}
}
}
},
series: [
{
name: 'Visits', // series名称
type: 'scatter', // series图标类型
coordinateSystem: 'geo', // series坐标系类型
data: [
{
name: 'China', // 数据项名称,在这里指地区名称
value: [ // 数据项值
116.46, // 地理坐标,经度
39.92, // 地理坐标,纬度
340 // 北京地区的数值
]
},
{
name: 'Russia',
value: [
103.41, 66.42,
1500
]
},
{
name: 'US',
value: [
-74.13, 42.37,
3000
]
}
]
}
]
};
return scatterMapOption;
})
);
}
getTrendBarOption(): EChartOption {
const trendBarOption = {
title: {
text: 'Visits Trend',
left: '3%',
top: '20px',
textStyle: {
color: '#fff',
fontSize: 20,
marginBottom: '20px'
}
},
color: ['#fff'],
backgroundColor: '#1d88e5',
tooltip: {},
grid: {
top: '30%',
left: '3%',
right: '4%',
bottom: '15%',
containLabel: true
},
xAxis: [
{
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
axisTick: { show: false },
axisLine: { show: false },
axisLabel: {
color: '#fff',
fontSize: 14,
fontWeight: 'bold'
}
}
],
yAxis: [
{
type: 'value',
splitLine: { show: false },
axisTick: { show: false },
axisLine: { show: false },
axisLabel: {
color: '#fff',
fontSize: 14,
fontWeight: 'bold'
}
}
],
series: [
{ // For shadow
type: 'bar',
silent: true,
itemStyle: {
normal: {
color: '#57a8ef'
}
},
barGap: '-100%',
barCategoryGap: '60%',
data: [500, 500, 500, 500, 500, 500, 500],
animation: false
},
{
name: 'Visits',
type: 'bar',
z: 3,
label: {
normal: {
position: 'top',
show: true
}
},
barWidth: '20%',
data: [74, 52, 200, 334, 390, 330, 220]
}
]
};
return trendBarOption;
}
getSalesOption(): Sales {
const salesOption = {
prediction: {
title: 'Sales Prediction',
profit: 3528,
amount: {
min: 150,
max: 165
},
chartOption: {
series: [{
name: 'Sales Prediction',
type: 'gauge',
radius: '100%',
startAngle: 180,
endAngle: 0,
min: 0,
max: 100,
grid: {
bottom: '-45%'
},
axisLine: { // 坐标轴线
lineStyle: {
color: [[0.5, '#049efb'], [1, '#9098ac']],
width: 15
}
},
axisLabel: { // 坐标轴小标记
show: false
},
axisTick: {
show: false
},
splitLine: {
show: false
},
title: { show: false },
detail: {
show: false
},
data: [{ value: 50, name: 'Sales Prediction', color: '#049efb' }]
}]
}
},
difference: {
title: 'Sales Difference',
profit: 4316,
amount: {
min: 150,
max: 165
},
chartOption: {
series: [{
name: 'Sales Difference',
type: 'gauge',
radius: '100%',
startAngle: 180,
endAngle: 0,
min: 0,
max: 100,
axisLine: { // 坐标轴线
lineStyle: {
color: [[0.3, '#f44337'], [1, '#9098ac']],
width: 15
}
},
axisLabel: { // 坐标轴小标记
show: false
},
axisTick: {
show: false
},
splitLine: {
show: false
},
title: { show: false },
detail: {
show: false
},
data: [{ value: 30, name: 'Sales Difference', color: '#049efb' }]
}]
}
}
};
return salesOption;
}
} | the_stack |
import { ActiveInterface, AvComposedEntity, AvEntityChild, AvGadget, AvGrabButton, AvInterfaceEntity, InterfaceProp, AvModel, AvModelTransform, AvOrigin, AvPrimitive, AvTransform, AvHeadFacingTransform, GrabPose, GrabRequest, GrabRequestType, k_MenuInterface, MenuEvent, MenuEventType, PanelRequest, PanelRequestType, PrimitiveType, PrimitiveYOrigin, SimpleContainerComponent, InterfaceRole, AvWeightedTransform } from '@aardvarkxr/aardvark-react';
import { InputProcessor, AvNodeTransform, AvQuaternion, AvVolume, g_builtinAnims, EHand, emptyVolume, EndpointAddr, endpointAddrsMatch, endpointAddrToString, EVolumeContext, EVolumeType, g_builtinModelMenuIntro, g_builtinModelGear, handToDevice, InterfaceLockResult, multiplyTransforms, rayVolume, g_builtinModelSkinnedHandLeft, g_builtinModelSkinnedHandRight, Av, g_anim_Left_ThumbsUp, nodeTransformToMat4, InteractionProfile } from '@aardvarkxr/aardvark-shared';
import { vec3 } from '@tlaukkan/tsm';
import bind from 'bind-decorator';
import { initSentryForBrowser } from 'common/sentry_utils';
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { k_actionSets } from './default_hands_input';
import {gestureVolumes, volumeDictionary} from './default_hands_gesture_volumes'
initSentryForBrowser();
const k_gadgetRegistryUI = "aardvark-gadget-registry@1";
interface DefaultHandProps
{
hand: EHand;
}
enum GrabberState
{
Idle,
Highlight,
Grabbing,
GrabReleased,
WaitingForDropComplete,
WaitingForRegrab,
WaitingForRegrabDropComplete,
WaitingForRegrabNewMoveable,
GrabFailed,
Menu,
}
interface DefaultHandState
{
activeGrab: ActiveInterface;
activePanel1: ActiveInterface;
activePanel2: ActiveInterface;
activeMenu: ActiveInterface;
grabberFromGrabbableOverride?: AvNodeTransform | GrabPose;
grabberFromGrabbableOrigin?: vec3,
grabberFromGrabbableDirection?: vec3;
grabberFromGrabbableRange?: number;
grabberFromGrabbableRotation?: AvQuaternion;
state: GrabberState;
regrabTarget?: EndpointAddr;
grabberFromRegrabTarget?: AvNodeTransform;
rayButtonDown?: boolean;
wasShowingRay?: boolean;
hasRayIntersect?: boolean;
}
enum ButtonState
{
Idle, // not pressed
Pressed, // pressed and active
Suppressed, // pressed, but we're ignoring this press for whatever reason
}
let inputProcessor = new InputProcessor( k_actionSets );
class DefaultHand extends React.Component< DefaultHandProps, DefaultHandState >
{
private grabListenerHandle = 0;
private menuListenerHandle = 0;
private containerComponent = new SimpleContainerComponent();
private grabPressed = ButtonState.Idle;
private menuPressed = ButtonState.Idle;
private grabRayHandler = 0;
private grabMoveHandler = 0;
private lastMoveTime = 0;
private rawGrabCount = 0;
constructor( props: any )
{
super( props );
this.state =
{
activeGrab: null,
activePanel1: null,
activePanel2: null,
activeMenu: null,
state: GrabberState.Idle,
};
this.grabListenerHandle = inputProcessor.registerBooleanCallbacks( "interact", "grab",
handToDevice( this.props.hand ),
this.onRawGrabPressed, this.onRawGrabReleased );
this.grabListenerHandle = inputProcessor.registerBooleanCallbacks( "interact", "grab_secondary",
handToDevice( this.props.hand ),
this.onRawGrabPressed, this.onRawGrabReleased );
this.menuListenerHandle = inputProcessor.registerBooleanCallbacks( "interact", "menu",
handToDevice( this.props.hand ),
this.onMenuPressed, this.onMenuReleased );
this.grabRayHandler = inputProcessor.registerBooleanCallbacks( "default", "showRay",
handToDevice( this.props.hand ),
this.onGrabShowRay, this.onGrabHideRay );
this.grabMoveHandler = inputProcessor.registerVector2Callback( "grabbed", "move",
handToDevice( this.props.hand ), this.onGrabMove );
this.containerComponent.onItemChanged( () => this.forceUpdate() );
inputProcessor.activateActionSet( "default", handToDevice( this.props.hand ) );
Av().registerSceneApplicationNotification( this.onSceneAppChanged );
}
componentWillUnmount()
{
inputProcessor.unregisterCallback( this.grabListenerHandle );
inputProcessor.unregisterCallback( this.menuListenerHandle );
inputProcessor.unregisterCallback( this.grabRayHandler );
inputProcessor.unregisterCallback( this.grabMoveHandler );
}
componentDidUpdate( prevProps: DefaultHandProps, prevState: DefaultHandState )
{
if( this.state.activeGrab || this.state.activePanel1 || this.state.activeMenu
|| this.state.state == GrabberState.WaitingForRegrabNewMoveable
|| this.state.state == GrabberState.WaitingForRegrabDropComplete
|| this.state.state == GrabberState.WaitingForRegrab
|| this.state.state == GrabberState.Grabbing )
{
console.log( `${ EHand[ this.props.hand ] } interact activated` );
inputProcessor.activateActionSet( "interact", handToDevice( this.props.hand ) );
}
else
{
console.log( `${ EHand[ this.props.hand ] } interact deactivated` );
inputProcessor.deactivateActionSet( "interact", handToDevice( this.props.hand ) );
}
if( this.state.state != prevState.state )
{
console.log( `${ EHand[ this.props.hand ] } transitioned to ${ GrabberState[ this.state.state ] }` );
}
}
@bind
private onSceneAppChanged()
{
this.forceUpdate();
}
@bind
private onGrabMove( newValue: [ number, number ] )
{
const k_moveSpeed = 2.0; // meters per second
let now = performance.now();
let elapsedSeconds = Math.max( 0, ( now - this.lastMoveTime ) / 1000 );
this.lastMoveTime = now;
this.setState( (prevState: DefaultHandState ) =>
{
return { grabberFromGrabbableRange: prevState.grabberFromGrabbableRange
+ elapsedSeconds * k_moveSpeed * newValue[ 1 ] };
} );
}
private startGrabMove()
{
inputProcessor.activateActionSet( "grabbed", handToDevice( this.props.hand ) );
this.lastMoveTime = performance.now();
}
private stopGrabMove()
{
inputProcessor.deactivateActionSet( "grabbed", handToDevice( this.props.hand ) );
}
@bind
private onGrabShowRay()
{
// skip the ray when we already have something interesting going on.
if( this.state.state != GrabberState.Idle
|| this.state.activePanel1 || this.state.activePanel2 )
return;
this.setState(
{
rayButtonDown: true
} );
}
@bind
private onGrabHideRay()
{
this.setState(
{
rayButtonDown: false
} );
}
@bind
private onRawGrabPressed()
{
this.rawGrabCount = Math.min( 2, this.rawGrabCount + 1 );
if( this.rawGrabCount == 1 )
{
this.onGrabPressed();
}
}
@bind
private onRawGrabReleased()
{
this.rawGrabCount = Math.max( 0, this.rawGrabCount - 1 );
if( this.rawGrabCount == 0 )
{
this.onGrabReleased();
}
}
private async onGrabPressed()
{
console.log( `${ EHand[ this.props.hand ] } grab pressed` );
switch( this.grabPressed )
{
case ButtonState.Idle:
if( this.menuPressed == ButtonState.Pressed )
{
console.log( "Menu pressed before grab. Ignoring the grab" );
this.grabPressed = ButtonState.Suppressed;
}
else
{
this.grabPressed = ButtonState.Pressed;
if( this.state.activeGrab )
{
this.setState( { state: GrabberState.Grabbing } );
let res = await this.state.activeGrab.lock();
if( res != InterfaceLockResult.Success )
{
console.log( `Fail to lock when grabbing ${ InterfaceLockResult[ res ] }` );
}
// check active interface again again because we might have lost it while awaiting
if( this.state.activeGrab )
{
this.state.activeGrab.sendEvent( { type: GrabRequestType.SetGrabber } as GrabRequest );
let grabberFromGrabbable = this.state.activeGrab.selfFromPeer;
this.setGrabberFromGrabbable( grabberFromGrabbable );
this.startGrabMove();
}
}
else if( this.state.activePanel1 )
{
await this.state.activePanel1.lock();
this.state.activePanel1?.sendEvent( { type: PanelRequestType.Down } as PanelRequest );
}
}
break;
case ButtonState.Pressed:
case ButtonState.Suppressed:
console.log( "DUPLICATE GRAB PRESSED!" );
break;
}
}
private async onGrabReleased()
{
console.log( `${ EHand[ this.props.hand ] } grab released with `
+ `${ ButtonState[ this.grabPressed ] }, `
+ `activeGrab=${ endpointAddrToString( this.state.activeGrab?.peer ) }, `
+ `state=${ GrabberState[ this.state.state ] }`);
switch( this.grabPressed )
{
case ButtonState.Suppressed:
this.grabPressed = ButtonState.Idle;
break;
case ButtonState.Idle:
console.log( "DUPLICATE GRAB RELEASED!" );
// FALL THROUGH (just in case we need to clean up)
case ButtonState.Pressed:
this.grabPressed = ButtonState.Idle;
this.stopGrabMove();
if( this.state.activeGrab )
{
switch( this.state.state )
{
case GrabberState.GrabFailed:
if( this.state.activeGrab )
{
this.setState( { state: GrabberState.Highlight } );
}
else
{
this.setState( { state: GrabberState.Idle } );
}
break;
case GrabberState.Grabbing:
// we need to wait here to make sure the moveable on the other
// end has a good transform relative to its new container when
// we unlock below.
await this.state.activeGrab.sendEvent( { type: GrabRequestType.DropYourself } as GrabRequest );
this.setState( { state: GrabberState.WaitingForDropComplete } );
break;
case GrabberState.WaitingForRegrab:
// The user let the grab go mid-regrab. We'll just drop when the new moveable comes in
break;
case GrabberState.GrabReleased:
this.state.activeGrab.unlock();
this.setState( { state: GrabberState.Highlight } );
break;
default:
// other states shouldn't get here
console.log( `Unexpected grabber state ${ GrabberState[ this.state.state ] } on grab release` );
}
}
else if( this.state.activePanel1 )
{
this.state.activePanel1.sendEvent( { type: PanelRequestType.Up } as PanelRequest );
this.state.activePanel1.unlock();
}
break;
}
}
@bind
private async onMenuPressed()
{
switch( this.menuPressed )
{
case ButtonState.Pressed:
case ButtonState.Suppressed:
console.log( "DUPLICATE MENU PRESS" );
break;
case ButtonState.Idle:
if( this.grabPressed == ButtonState.Pressed )
{
console.log( "Ignoring menu because grab was pressed" );
this.menuPressed = ButtonState.Suppressed;
}
else
{
console.log( "Menu button pressed" );
this.menuPressed = ButtonState.Pressed;
if( this.state.activeGrab )
{
this.setState( { state: GrabberState.Menu } );
let res = await this.state.activeGrab.lock();
if( res != InterfaceLockResult.Success )
{
console.log( `Fail to lock when grabbing ${ InterfaceLockResult[ res ] }` );
}
// check active interface again again because we might have lost it while awaiting
if( this.state.activeGrab )
{
let evt: GrabRequest = { type: GrabRequestType.ShowMenu };
this.state.activeGrab.sendEvent( evt );
}
}
}
break;
}
}
@bind
private async onMenuReleased()
{
switch( this.menuPressed )
{
case ButtonState.Suppressed:
this.menuPressed = ButtonState.Idle;
break;
case ButtonState.Idle:
console.log( "DUPLICATE MENU RELEASE" );
break;
case ButtonState.Pressed:
console.log( "Menu button released" );
if( this.state.activeMenu )
{
let evt: MenuEvent = { type: MenuEventType.Activate };
this.state.activeMenu.sendEvent( evt );
}
if( this.state.activeGrab )
{
let evt: GrabRequest = { type: GrabRequestType.HideMenu };
this.state.activeGrab.sendEvent( evt );
this.state.activeGrab.unlock();
this.setState( { state: GrabberState.Highlight } );
}
else
{
this.setState( { state: GrabberState.Idle } );
}
this.menuPressed = ButtonState.Idle;
break;
}
}
private shouldShowRay() : boolean
{
return this.state.hasRayIntersect && this.state.rayButtonDown;
}
@bind
private async onRayStart( activeInterface: ActiveInterface )
{
this.setState( { hasRayIntersect : true } );
activeInterface.onEnded( () =>
{
this.setState( { hasRayIntersect: false } );
} );
}
@bind
private async onGrabStart( activeInterface: ActiveInterface )
{
if( this.state.state == GrabberState.WaitingForRegrabNewMoveable )
{
if( !endpointAddrsMatch( activeInterface.peer, this.state.regrabTarget ) )
{
console.log( `Regrab target mismatch. Expected: ${ endpointAddrToString( this.state.regrabTarget )} `
+ `Received: ${ endpointAddrToString( activeInterface.peer ) }` );
}
let grabberFromGrabbable = this.state.grabberFromRegrabTarget ?? activeInterface.selfFromPeer;
this.setGrabberFromGrabbable( grabberFromGrabbable );
this.setState(
{
grabberFromRegrabTarget: null,
regrabTarget: null,
} );
this.startGrabMove();
let res = await activeInterface.lock();
if( res != InterfaceLockResult.AlreadyLocked )
{
console.log( "How did we get here without having the new thing locked?" );
}
activeInterface.sendEvent( { type: GrabRequestType.SetGrabber } as GrabRequest );
if( !this.grabPressed )
{
console.log( "Grab was released while regrabbing. Dropping right away")
// the user released the grab while we were acquiring our new moveable. So we need to
// drop it immediately.
await activeInterface.sendEvent( { type: GrabRequestType.DropYourself } as GrabRequest );
this.setState( { state: GrabberState.WaitingForDropComplete } );
}
}
else
{
AvGadget.instance().sendHapticEvent(activeInterface.self, 0.7, 1, 0 );
this.setState( { state: GrabberState.Highlight } );
}
console.log( `setting activeInterface to ${ endpointAddrToString( activeInterface.peer ) }`)
this.setState( { activeGrab: activeInterface, wasShowingRay: this.shouldShowRay() } );
activeInterface.onEvent(
async ( event: GrabRequest ) =>
{
console.log( `GRAB EVENT from ${ endpointAddrToString( activeInterface.peer ) } `
+ `${ event.type } with ${ GrabberState[ this.state.state ] }`, event );
switch( event.type )
{
case GrabRequestType.DropComplete:
{
switch( this.state.state )
{
case GrabberState.WaitingForDropComplete:
activeInterface.unlock();
this.setState( { state: GrabberState.Highlight,
grabberFromGrabbableOverride: null,
grabberFromGrabbableDirection: null,
grabberFromGrabbableRange: null,
grabberFromGrabbableRotation: null } );
break;
case GrabberState.WaitingForRegrabDropComplete:
let resPromise = activeInterface.relock( this.state.regrabTarget );
this.setState( { state: GrabberState.WaitingForRegrab,
grabberFromGrabbableOverride: null,
grabberFromGrabbableDirection: null,
grabberFromGrabbableRange: null,
grabberFromGrabbableRotation: null, } );
let res = await resPromise;
console.log( `RELOCK result ${ InterfaceLockResult[ res ] }` );
if( res != InterfaceLockResult.Success )
{
console.log( `Regrab failed with ${ InterfaceLockResult[ res ] }` );
// @ts-ignore: Bogus always false error after await and setState
if( this.state.state == GrabberState.WaitingForRegrab )
{
this.setState( { state: GrabberState.Grabbing } );
}
}
break;
default:
// other states shouldn't get here
console.log( `Unexpected grabber state ${ GrabberState[ this.state.state ] } on DropComplete event` );
break;
}
}
break;
case GrabRequestType.RequestRegrab:
{
if( this.state.state == GrabberState.Grabbing )
{
// we need to wait here to make sure the old moveable on the other
// end has a good transform relative to its new container when
// we relock below.
await activeInterface.sendEvent( { type: GrabRequestType.DropYourself } as GrabRequest );
this.setState(
{
state: GrabberState.WaitingForRegrabDropComplete,
regrabTarget: event.newMoveable,
grabberFromRegrabTarget: multiplyTransforms( activeInterface.selfFromPeer,
event.oldMoveableFromNewMoveable ),
} );
}
else
{
console.log( `REGRAB requested when we were ${ GrabberState[ this.state.state ]}` );
}
}
break;
case GrabRequestType.ReleaseMe:
{
if( this.state.state == GrabberState.Grabbing )
{
this.setState( { state: GrabberState.GrabReleased,
grabberFromGrabbableOverride: null,
grabberFromGrabbableDirection: null,
grabberFromGrabbableRange: null,
grabberFromGrabbableRotation: null, } );
}
}
break;
case GrabRequestType.OverrideTransform:
{
this.setState( { grabberFromGrabbableOverride: event.grabberFromGrabbable } );
}
break;
}
} );
activeInterface.onEnded( () =>
{
switch( this.state.state )
{
case GrabberState.GrabReleased:
case GrabberState.Grabbing:
activeInterface.unlock();
this.setState(
{
grabberFromGrabbableDirection: null,
grabberFromGrabbableRange: null,
grabberFromGrabbableRotation: null,
state: GrabberState.Idle } );
break;
case GrabberState.Highlight:
this.setState( { state: GrabberState.Idle } );
AvGadget.instance().sendHapticEvent( activeInterface.self, 0.3, 1, 0 );
break;
case GrabberState.WaitingForRegrab:
// This is the old endpoint leaving. We should get a new interface for the new
// target soon.
this.setState( { state: GrabberState.WaitingForRegrabNewMoveable })
break;
default:
// other states shouldn't get here
console.log( `Unexpected grabber state ${ GrabberState[ this.state.state ] } on interface end` );
}
console.log( `unsetting activeInterface from ${ endpointAddrToString( this.state.activeGrab?.peer ) }`)
this.setState( { activeGrab: null, wasShowingRay: false } );
} );
activeInterface.onTransformUpdated( ( entityFromPeer: AvNodeTransform ) =>
{
if( !this.state.grabberFromGrabbableOverride && this.state.state == GrabberState.Grabbing )
{
console.log( "Transform updated" );
this.setGrabberFromGrabbable( entityFromPeer );
}
} );
}
private setGrabberFromGrabbable( grabberFromGrabbable: AvNodeTransform )
{
let grabberFromGrabbableDirection = new vec3( [
grabberFromGrabbable.position?.x ?? 0,
grabberFromGrabbable.position?.y ?? 0,
grabberFromGrabbable.position?.z ?? 0
] );
let grabberFromGrabbableRange = grabberFromGrabbableDirection.length();
let grabberFromGrabbableOrigin = new vec3( [ 0, 0, 0 ] );
if( grabberFromGrabbable > 0.2 )
{
grabberFromGrabbableDirection.normalize();
}
else
{
grabberFromGrabbableOrigin = grabberFromGrabbableDirection;
grabberFromGrabbableDirection = new vec3(
[
0, -Math.SQRT2, -Math.SQRT2
]
);
grabberFromGrabbableRange = 0;
}
this.setState(
{
state: GrabberState.Grabbing,
grabberFromGrabbableOverride: null,
grabberFromGrabbableOrigin,
grabberFromGrabbableDirection,
grabberFromGrabbableRange,
grabberFromGrabbableRotation: grabberFromGrabbable.rotation,
} );
}
@bind
private onPanel1Start( activeInterface: ActiveInterface )
{
AvGadget.instance().sendHapticEvent( activeInterface.self, 0.7, 1, 0 );
activeInterface.onEnded( () =>
{
if( this.grabPressed )
{
activeInterface.unlock();
}
this.setState( { activePanel1: null } );
AvGadget.instance().sendHapticEvent(activeInterface.self, 0.3, 1, 0 );
} );
this.setState( { activePanel1: activeInterface } );
}
@bind
private onPanel2Start( activeInterface: ActiveInterface )
{
activeInterface.onEnded( () =>
{
this.setState( { activePanel2: null } );
} );
this.setState( { activePanel2: activeInterface } );
}
@bind
private onMenuStart( activeInterface: ActiveInterface )
{
AvGadget.instance().sendHapticEvent( activeInterface.self, 0.7, 1, 0 );
activeInterface.onEnded( () =>
{
this.setState( { activeMenu: null } );
AvGadget.instance().sendHapticEvent(activeInterface.self, 0.3, 1, 0 );
} );
this.setState( { activeMenu: activeInterface } );
}
public renderDebug()
{
return <div>
<div>{ GrabberState[ this.state.state ] }</div>
<div>ActiveInterface: { this.state.activeGrab ? endpointAddrToString( this.state.activeGrab.peer ): "none" }</div>
{/* <div>Transform: { this.state.grabberFromGrabbable ? JSON.stringify( this.state.grabberFromGrabbable ): "none" }</div> */}
</div>
}
public render()
{
let originPath: string;
let animationSource: string;
let modelUrl: string;
let volumeSkeleton: string;
switch( this.props.hand )
{
case EHand.Left:
originPath = "/user/hand/left/raw";
volumeSkeleton = "/user/hand/left";
animationSource = "source:/user/hand/left";
modelUrl = g_builtinModelSkinnedHandLeft;
break;
case EHand.Right:
originPath = "/user/hand/right/raw";
volumeSkeleton = "/user/hand/right";
animationSource = "source:/user/hand/right";
modelUrl = g_builtinModelSkinnedHandRight;
break;
}
let overlayOnly = true;
if( !Av().getCurrentSceneApplication() )
{
overlayOnly = false;
}
const k_containerOuterVolume: AvVolume =
{
type: EVolumeType.AABB,
context: EVolumeContext.ContinueOnly,
aabb:
{
xMin: -0.15, xMax: 0.15,
yMin: -0.15, yMax: 0.25,
zMin: -0.15, zMax: 0.15,
}
};
const k_containerInnerVolume: AvVolume =
{
type: EVolumeType.Sphere,
radius: 0.03,
};
const k_grabberVolume: AvVolume =
{
type: EVolumeType.Skeleton,
skeletonPath: volumeSkeleton + "/grip",
//visualize: this.props.hand == EHand.Left,
};
const k_pokerVolume: AvVolume =
{
type: EVolumeType.Skeleton,
skeletonPath: volumeSkeleton + "/index/tip",
//visualize: true,
};
let grabberVolumes = [ k_grabberVolume ];
let poker2Volumes = ( this.state.activePanel1 || this.state.activeGrab ) ? [] : [ k_pokerVolume ];
const k_rayVolume: AvVolume = rayVolume( new vec3( [ 0, 0, -0.05 ] ),
new vec3( [ 0, -Math.SQRT2, -Math.SQRT2 ] ) );
let ray: JSX.Element = null;
if( this.shouldShowRay() &&
( this.state.state == GrabberState.Idle || this.state.wasShowingRay ) )
{
grabberVolumes.push( k_rayVolume );
if( this.state.state == GrabberState.Idle ||
this.state.state == GrabberState.Highlight )
{
ray = <AvTransform rotateX={ -135 }>
<AvPrimitive radius={ 0.005 } height={ 4 } type={ PrimitiveType.Cylinder }
color="lightgrey" originY={ PrimitiveYOrigin.Bottom } />
</AvTransform>;
}
}
let child: JSX.Element;
if( this.state.activeGrab && this.state.state != GrabberState.GrabReleased )
{
let childEpa = this.state.activeGrab.peer;
let childEntity = <AvEntityChild child={ childEpa }/>;
if( typeof this.state.grabberFromGrabbableOverride == "string" &&
this.state.grabberFromGrabbableOverride != GrabPose.None )
{
let hand = EHand[ this.props.hand ].toLowerCase();
originPath = `/user/hand/${ hand }/root_bone`;
animationSource = g_builtinAnims + hand + "_"
+ this.state.grabberFromGrabbableOverride + ".glb";
child = <AvModelTransform modelUri={ animationSource }
modelNodeId={ this.state.grabberFromGrabbableOverride } >
{ childEntity }
</AvModelTransform>;
overlayOnly = false;
}
else if( typeof this.state.grabberFromGrabbableOverride == "object"
&& this.state.grabberFromGrabbableOverride )
{
child = <AvTransform transform={ this.state.grabberFromGrabbableOverride }>
{ childEntity }
</AvTransform>;
}
else if( this.state.grabberFromGrabbableDirection )
{
child = <AvTransform transform={
{
position:
{
x: this.state.grabberFromGrabbableOrigin.x + this.state.grabberFromGrabbableDirection.x * this.state.grabberFromGrabbableRange,
y: this.state.grabberFromGrabbableOrigin.y + this.state.grabberFromGrabbableDirection.y * this.state.grabberFromGrabbableRange,
z: this.state.grabberFromGrabbableOrigin.z + this.state.grabberFromGrabbableDirection.z * this.state.grabberFromGrabbableRange,
},
rotation: this.state.grabberFromGrabbableRotation,
} }>
{ childEntity }
</AvTransform>;
}
}
let debugName = EHand[ this.props.hand ] + " hand grabber";
return (
<>
<AvOrigin path={ originPath }>
{ modelUrl && <AvModel
uri={ modelUrl } overlayOnly={ overlayOnly } animationSource={ animationSource }/> }
{
!modelUrl && <AvPrimitive type={ PrimitiveType.Sphere } radius={ 0.02 } />
}
{ ray }
<AvComposedEntity components={ [ this.containerComponent ]}
volume={ [ k_containerInnerVolume, k_containerOuterVolume ] }
priority={ 100 } debugName={ debugName + "/container" }/>
<AvInterfaceEntity transmits={
[
{ iface: "aardvark-panel@1", processor: this.onPanel1Start },
{ iface: "aardvark-grab@1", processor: this.onGrabStart },
] }
volume={ grabberVolumes } debugName={ debugName }
priority={ 100 }>
{ child }
</AvInterfaceEntity>
<AvInterfaceEntity transmits={
[
{ iface: k_MenuInterface, processor: this.onMenuStart },
] }
volume={ grabberVolumes } debugName={ debugName + "/menu" }>
</AvInterfaceEntity>
<AvInterfaceEntity transmits={
[
{ iface: "aardvark-panel@2", processor: this.onPanel2Start },
] }
volume={ poker2Volumes } debugName={ debugName + "/poker" }>
</AvInterfaceEntity>
<AvInterfaceEntity transmits={
[
{ iface: "aardvark-grab@1", processor: this.onRayStart },
] }
volume={ k_rayVolume } debugName={ debugName + "/ray" }
priority={ 0 }>
</AvInterfaceEntity>
</AvOrigin>
{ this.renderDebug() }
</>
);
}
}
interface DefaultHandsState
{
gestureCollideMain: boolean;
gestureCollideSecondary: boolean;
displayIntro: boolean;
}
class DefaultHands extends React.Component< {}, DefaultHandsState >
{
private containerComponent = new SimpleContainerComponent();
private leftRef = React.createRef<DefaultHand>();
private rightRef = React.createRef<DefaultHand>();
private gadgetRegistry: ActiveInterface = null;
private gadgetRegistryRef = React.createRef<AvInterfaceEntity>();
private controllerVolumes: gestureVolumes;
private introTransformLeft = React.createRef<AvOrigin>();
private introTransformRight = React.createRef<AvOrigin>();
private TEMPREFERENCE = React.createRef<AvWeightedTransform>();
constructor(props:any)
{
super(props);
if (!localStorage.getItem("introCounter"))
{
localStorage.setItem("introCounter", "0")
}
this.state =
{
gestureCollideMain: false,
gestureCollideSecondary: false,
//displayIntro: Number(localStorage.getItem("introCounter")) < 5
displayIntro: true,
};
inputProcessor.registerInteractionProfileCallback( () => { this.forceUpdate(); } );
}
@bind
private onGadgetRegistryUI( gadgetRegistry: ActiveInterface )
{
this.gadgetRegistry = gadgetRegistry;
gadgetRegistry.onEnded( () =>
{
this.gadgetRegistry = null;
} )
}
@bind
private toggleGadgetMenu()
{
this.gadgetRegistry?.sendEvent( { type: "toggle_visibility" } );
}
componentDidMount()
{
if( !AvGadget.instance().getEndpointId() || !this.gadgetRegistryRef.current )
{
// this is terrible. Figure out a way to call back into the gadget when it
// actually has an endpoint ID
window.setTimeout( () =>
{
this.startGadgetMenu();
}, 100 );
}
else
{
this.startGadgetMenu();
}
// this is a solution to an issue which seems to be the same as the one above, weighted transform doesnt have
// access to valid endpoints on the first render, we need to trigger another render when it will have them
window.setTimeout(() => this.forceUpdate(), 100);
}
private startGadgetMenu()
{
if( !AvGadget.instance().getEndpointId() || !this.gadgetRegistryRef.current )
{
// this is terrible. Figure out a way to call back into the gadget when it
// actually has an endpoint ID
window.setTimeout( () =>
{
this.startGadgetMenu();
}, 100 );
return;
}
// Start the gadget menu once we have an ID
AvGadget.instance().startGadget(
"http://localhost:23842/gadgets/gadget_menu",
[ { iface: k_gadgetRegistryUI, receiver: this.gadgetRegistryRef.current.globalId } ] );
}
@bind
public gestureActiveMain(givenInterface: ActiveInterface)
{
if(givenInterface.role == InterfaceRole.Transmitter)
{
givenInterface.onEnded(() => this.setState({gestureCollideMain: false}));
this.setState({gestureCollideMain: true});
}
}
@bind
public gestureActiveSecondary(givenInterface: ActiveInterface)
{
if(givenInterface.role == InterfaceRole.Transmitter)
{
givenInterface.onEnded(() => this.setState({gestureCollideSecondary: false}));
this.setState({gestureCollideSecondary: true});
}
}
private gestureMain:InterfaceProp[] = [{iface: "menuGestureMain@1", processor: this.gestureActiveMain }]
private gestureSecondary:InterfaceProp[] = [{iface: "menuGestureSecondary@1", processor: this.gestureActiveSecondary}]
private gestureVolume:AvVolume =
{
type: EVolumeType.Sphere,
radius: 0.03,
// visualize: true,
};
private gestureVolumeLarger:AvVolume =
{
type: EVolumeType.Sphere,
radius: 0.05,
// visualize: true,
};
private gestureVolumeEnd:AvVolume =
{
type: EVolumeType.Sphere,
radius :0.25,
context: EVolumeContext.ContinueOnly
// visualize: true,
};
componentDidUpdate()
{
if (this.state.gestureCollideMain && this.state.gestureCollideSecondary)
{
this.toggleGadgetMenu();
if (this.state.displayIntro)
{
this.setState({displayIntro: false});
localStorage.setItem("introCounter", (Number(localStorage.getItem("introCounter")) + 1).toString());
}
}
}
public render()
{
const k_containerInnerVolume: AvVolume =
{
type: EVolumeType.AABB,
aabb:
{
xMin: -0.05, xMax: 0.05,
yMin: -0.06, yMax: 0.02,
zMin: -0.05, zMax: 0.05,
}
};
const k_containerOuterVolume: AvVolume =
{
type: EVolumeType.AABB,
context: EVolumeContext.ContinueOnly,
aabb:
{
xMin: -0.3, xMax: 0.3,
yMin: -0.6, yMax: 0.2,
zMin: -0.3, zMax: 0.3,
}
};
this.controllerVolumes = volumeDictionary.has(inputProcessor.currentInteractionProfile) ? volumeDictionary.get(inputProcessor.currentInteractionProfile) : null;
if ( this.controllerVolumes )
{
console.log("currentInteraction profile is " + inputProcessor.currentInteractionProfile + " and is in the volume dictionary");
}
else
{
console.log("currentInteraction profile is " + inputProcessor.currentInteractionProfile + " and isn't in the volume dictionary");
this.controllerVolumes = volumeDictionary.get( "default" );
}
return (
<>
<DefaultHand hand={ EHand.Left } ref={ this.leftRef }/>
<DefaultHand hand={ EHand.Right } ref={ this.rightRef } />
<AvOrigin path={ "/user/head" } >
<AvInterfaceEntity receives={
[
{
iface: k_gadgetRegistryUI,
processor: this.onGadgetRegistryUI,
}
]
} volume={ emptyVolume() } ref={ this.gadgetRegistryRef } />
</AvOrigin>
<AvOrigin path="/user/hand/left" ref = {this.introTransformLeft}>
{ this.controllerVolumes == null &&
<AvTransform translateZ={ 0.04 } translateY={ 0.02 }>
<AvGrabButton onClick={ this.toggleGadgetMenu } modelUri={ g_builtinModelGear }/>
</AvTransform>
/*
if we dont have a controller we recognise, then show the cog, this will likely display the cog
for a frame or two before state finished setting up even if we wil recognise the controller
but thats such a short amount of time that it shouldnt be an issue
*/
}
</AvOrigin>
<AvOrigin path = {"/user/hand/right"} ref = {this.introTransformRight}></AvOrigin>
{ this.state.displayIntro && this.controllerVolumes != null && this.introTransformLeft.current != null && this.introTransformRight.current != null &&
<AvWeightedTransform weightedParents = {[{parent: this.introTransformRight.current.endpointAddr(), weight: 1}, {parent: this.introTransformLeft.current.endpointAddr(), weight: 1}]} ref = {this.TEMPREFERENCE}>
<AvHeadFacingTransform>
<AvTransform uniformScale = {0.07} rotateX = {30}>
<AvModel uri = {g_builtinModelMenuIntro}/>
</AvTransform>
</AvHeadFacingTransform>
</AvWeightedTransform>
}
{ this.controllerVolumes != null && // set up volumes if we have a controller
<>
<AvOrigin path="/user/hand/left">
<AvTransform transform = {this.controllerVolumes.leftHandTop}>
<AvInterfaceEntity volume = {[this.gestureVolume, this.gestureVolumeEnd]} transmits = {this.gestureMain}></AvInterfaceEntity>
</AvTransform>
<AvTransform transform = {this.controllerVolumes.leftHandBottom}>
<AvInterfaceEntity volume = {[this.gestureVolumeLarger, this.gestureVolumeEnd]} transmits = {this.gestureSecondary}></AvInterfaceEntity>
</AvTransform>
</AvOrigin>
<AvOrigin path = "/user/hand/right">
<AvTransform transform = {this.controllerVolumes.rightHandTop}>
<AvInterfaceEntity volume = {[this.gestureVolume, this.gestureVolumeEnd]} receives = {this.gestureMain}></AvInterfaceEntity>
</AvTransform>
<AvTransform transform = {this.controllerVolumes.rightHandBottom}>
<AvInterfaceEntity volume = {[this.gestureVolume, this.gestureVolumeEnd]} receives = {this.gestureSecondary}></AvInterfaceEntity>
</AvTransform>
</AvOrigin>
</>
}
{/* <AvOrigin path="/user/head">
<AvComposedEntity components={ [ this.containerComponent ]}
volume={ [ k_containerInnerVolume, k_containerOuterVolume ] }
priority={ 90 }/>
</AvOrigin> */}
<AvOrigin path="/space/stage">
<AvComposedEntity components={ [this.containerComponent ] }
volume={ { type: EVolumeType.Infinite } }
debugName="stage container">
</AvComposedEntity>
</AvOrigin>
{/* <AvOrigin path="/user/head">
<AvTransform translateZ={-2}>
<AvPanel widthInMeters={1.0}>
</AvPanel>
</AvTransform>
</AvOrigin> */}
</>
);
}
}
ReactDOM.render( <DefaultHands/>, document.getElementById( "root" ) ); | the_stack |
import * as fs from 'fs';
import { tmpdir } from 'os';
import { promisify } from 'util';
import { ResourceQueue } from 'vs/base/common/async';
import { isEqualOrParent, isRootOrDriveLetter, randomPath } from 'vs/base/common/extpath';
import { normalizeNFC } from 'vs/base/common/normalization';
import { join } from 'vs/base/common/path';
import { isLinux, isMacintosh, isWindows } from 'vs/base/common/platform';
import { extUriBiasedIgnorePathCase } from 'vs/base/common/resources';
import { URI } from 'vs/base/common/uri';
//#region rimraf
export enum RimRafMode {
/**
* Slow version that unlinks each file and folder.
*/
UNLINK,
/**
* Fast version that first moves the file/folder
* into a temp directory and then deletes that
* without waiting for it.
*/
MOVE
}
/**
* Allows to delete the provided path (either file or folder) recursively
* with the options:
* - `UNLINK`: direct removal from disk
* - `MOVE`: faster variant that first moves the target to temp dir and then
* deletes it in the background without waiting for that to finish.
*/
async function rimraf(path: string, mode = RimRafMode.UNLINK): Promise<void> {
if (isRootOrDriveLetter(path)) {
throw new Error('rimraf - will refuse to recursively delete root');
}
// delete: via rm
if (mode === RimRafMode.UNLINK) {
return rimrafUnlink(path);
}
// delete: via move
return rimrafMove(path);
}
async function rimrafMove(path: string): Promise<void> {
try {
const pathInTemp = randomPath(tmpdir());
try {
// Intentionally using `fs.promises` here to skip
// the patched graceful-fs method that can result
// in very long running `rename` calls when the
// folder is locked by a file watcher. We do not
// really want to slow down this operation more
// than necessary and we have a fallback to delete
// via unlink.
// https://github.com/microsoft/vscode/issues/139908
await fs.promises.rename(path, pathInTemp);
} catch (error) {
return rimrafUnlink(path); // if rename fails, delete without tmp dir
}
// Delete but do not return as promise
rimrafUnlink(pathInTemp).catch(error => {/* ignore */ });
} catch (error) {
if (error.code !== 'ENOENT') {
throw error;
}
}
}
async function rimrafUnlink(path: string): Promise<void> {
return promisify(fs.rm)(path, { recursive: true, force: true, maxRetries: 3 });
}
export function rimrafSync(path: string): void {
if (isRootOrDriveLetter(path)) {
throw new Error('rimraf - will refuse to recursively delete root');
}
fs.rmSync(path, { recursive: true, force: true, maxRetries: 3 });
}
//#endregion
//#region readdir with NFC support (macos)
export interface IDirent {
name: string;
isFile(): boolean;
isDirectory(): boolean;
isSymbolicLink(): boolean;
}
/**
* Drop-in replacement of `fs.readdir` with support
* for converting from macOS NFD unicon form to NFC
* (https://github.com/nodejs/node/issues/2165)
*/
async function readdir(path: string): Promise<string[]>;
async function readdir(path: string, options: { withFileTypes: true }): Promise<IDirent[]>;
async function readdir(path: string, options?: { withFileTypes: true }): Promise<(string | IDirent)[]> {
return handleDirectoryChildren(await (options ? safeReaddirWithFileTypes(path) : promisify(fs.readdir)(path)));
}
async function safeReaddirWithFileTypes(path: string): Promise<IDirent[]> {
try {
return await promisify(fs.readdir)(path, { withFileTypes: true });
} catch (error) {
console.warn('[node.js fs] readdir with filetypes failed with error: ', error);
}
// Fallback to manually reading and resolving each
// children of the folder in case we hit an error
// previously.
// This can only really happen on exotic file systems
// such as explained in #115645 where we get entries
// from `readdir` that we can later not `lstat`.
const result: IDirent[] = [];
const children = await readdir(path);
for (const child of children) {
let isFile = false;
let isDirectory = false;
let isSymbolicLink = false;
try {
const lstat = await Promises.lstat(join(path, child));
isFile = lstat.isFile();
isDirectory = lstat.isDirectory();
isSymbolicLink = lstat.isSymbolicLink();
} catch (error) {
console.warn('[node.js fs] unexpected error from lstat after readdir: ', error);
}
result.push({
name: child,
isFile: () => isFile,
isDirectory: () => isDirectory,
isSymbolicLink: () => isSymbolicLink
});
}
return result;
}
/**
* Drop-in replacement of `fs.readdirSync` with support
* for converting from macOS NFD unicon form to NFC
* (https://github.com/nodejs/node/issues/2165)
*/
export function readdirSync(path: string): string[] {
return handleDirectoryChildren(fs.readdirSync(path));
}
function handleDirectoryChildren(children: string[]): string[];
function handleDirectoryChildren(children: IDirent[]): IDirent[];
function handleDirectoryChildren(children: (string | IDirent)[]): (string | IDirent)[];
function handleDirectoryChildren(children: (string | IDirent)[]): (string | IDirent)[] {
return children.map(child => {
// Mac: uses NFD unicode form on disk, but we want NFC
// See also https://github.com/nodejs/node/issues/2165
if (typeof child === 'string') {
return isMacintosh ? normalizeNFC(child) : child;
}
child.name = isMacintosh ? normalizeNFC(child.name) : child.name;
return child;
});
}
/**
* A convenience method to read all children of a path that
* are directories.
*/
async function readDirsInDir(dirPath: string): Promise<string[]> {
const children = await readdir(dirPath);
const directories: string[] = [];
for (const child of children) {
if (await SymlinkSupport.existsDirectory(join(dirPath, child))) {
directories.push(child);
}
}
return directories;
}
//#endregion
//#region whenDeleted()
/**
* A `Promise` that resolves when the provided `path`
* is deleted from disk.
*/
export function whenDeleted(path: string, intervalMs = 1000): Promise<void> {
return new Promise<void>(resolve => {
let running = false;
const interval = setInterval(() => {
if (!running) {
running = true;
fs.access(path, err => {
running = false;
if (err) {
clearInterval(interval);
resolve(undefined);
}
});
}
}, intervalMs);
});
}
//#endregion
//#region Methods with symbolic links support
export namespace SymlinkSupport {
export interface IStats {
// The stats of the file. If the file is a symbolic
// link, the stats will be of that target file and
// not the link itself.
// If the file is a symbolic link pointing to a non
// existing file, the stat will be of the link and
// the `dangling` flag will indicate this.
stat: fs.Stats;
// Will be provided if the resource is a symbolic link
// on disk. Use the `dangling` flag to find out if it
// points to a resource that does not exist on disk.
symbolicLink?: { dangling: boolean };
}
/**
* Resolves the `fs.Stats` of the provided path. If the path is a
* symbolic link, the `fs.Stats` will be from the target it points
* to. If the target does not exist, `dangling: true` will be returned
* as `symbolicLink` value.
*/
export async function stat(path: string): Promise<IStats> {
// First stat the link
let lstats: fs.Stats | undefined;
try {
lstats = await Promises.lstat(path);
// Return early if the stat is not a symbolic link at all
if (!lstats.isSymbolicLink()) {
return { stat: lstats };
}
} catch (error) {
/* ignore - use stat() instead */
}
// If the stat is a symbolic link or failed to stat, use fs.stat()
// which for symbolic links will stat the target they point to
try {
const stats = await Promises.stat(path);
return { stat: stats, symbolicLink: lstats?.isSymbolicLink() ? { dangling: false } : undefined };
} catch (error) {
// If the link points to a nonexistent file we still want
// to return it as result while setting dangling: true flag
if (error.code === 'ENOENT' && lstats) {
return { stat: lstats, symbolicLink: { dangling: true } };
}
// Windows: workaround a node.js bug where reparse points
// are not supported (https://github.com/nodejs/node/issues/36790)
if (isWindows && error.code === 'EACCES') {
try {
const stats = await Promises.stat(await Promises.readlink(path));
return { stat: stats, symbolicLink: { dangling: false } };
} catch (error) {
// If the link points to a nonexistent file we still want
// to return it as result while setting dangling: true flag
if (error.code === 'ENOENT' && lstats) {
return { stat: lstats, symbolicLink: { dangling: true } };
}
throw error;
}
}
throw error;
}
}
/**
* Figures out if the `path` exists and is a file with support
* for symlinks.
*
* Note: this will return `false` for a symlink that exists on
* disk but is dangling (pointing to a nonexistent path).
*
* Use `exists` if you only care about the path existing on disk
* or not without support for symbolic links.
*/
export async function existsFile(path: string): Promise<boolean> {
try {
const { stat, symbolicLink } = await SymlinkSupport.stat(path);
return stat.isFile() && symbolicLink?.dangling !== true;
} catch (error) {
// Ignore, path might not exist
}
return false;
}
/**
* Figures out if the `path` exists and is a directory with support for
* symlinks.
*
* Note: this will return `false` for a symlink that exists on
* disk but is dangling (pointing to a nonexistent path).
*
* Use `exists` if you only care about the path existing on disk
* or not without support for symbolic links.
*/
export async function existsDirectory(path: string): Promise<boolean> {
try {
const { stat, symbolicLink } = await SymlinkSupport.stat(path);
return stat.isDirectory() && symbolicLink?.dangling !== true;
} catch (error) {
// Ignore, path might not exist
}
return false;
}
}
//#endregion
//#region Write File
// According to node.js docs (https://nodejs.org/docs/v14.16.0/api/fs.html#fs_fs_writefile_file_data_options_callback)
// it is not safe to call writeFile() on the same path multiple times without waiting for the callback to return.
// Therefor we use a Queue on the path that is given to us to sequentialize calls to the same path properly.
const writeQueues = new ResourceQueue();
/**
* Same as `fs.writeFile` but with an additional call to
* `fs.fdatasync` after writing to ensure changes are
* flushed to disk.
*
* In addition, multiple writes to the same path are queued.
*/
function writeFile(path: string, data: string, options?: IWriteFileOptions): Promise<void>;
function writeFile(path: string, data: Buffer, options?: IWriteFileOptions): Promise<void>;
function writeFile(path: string, data: Uint8Array, options?: IWriteFileOptions): Promise<void>;
function writeFile(path: string, data: string | Buffer | Uint8Array, options?: IWriteFileOptions): Promise<void>;
function writeFile(path: string, data: string | Buffer | Uint8Array, options?: IWriteFileOptions): Promise<void> {
return writeQueues.queueFor(URI.file(path), extUriBiasedIgnorePathCase).queue(() => {
const ensuredOptions = ensureWriteOptions(options);
return new Promise((resolve, reject) => doWriteFileAndFlush(path, data, ensuredOptions, error => error ? reject(error) : resolve()));
});
}
interface IWriteFileOptions {
mode?: number;
flag?: string;
}
interface IEnsuredWriteFileOptions extends IWriteFileOptions {
mode: number;
flag: string;
}
let canFlush = true;
// Calls fs.writeFile() followed by a fs.sync() call to flush the changes to disk
// We do this in cases where we want to make sure the data is really on disk and
// not in some cache.
//
// See https://github.com/nodejs/node/blob/v5.10.0/lib/fs.js#L1194
function doWriteFileAndFlush(path: string, data: string | Buffer | Uint8Array, options: IEnsuredWriteFileOptions, callback: (error: Error | null) => void): void {
if (!canFlush) {
return fs.writeFile(path, data, { mode: options.mode, flag: options.flag }, callback);
}
// Open the file with same flags and mode as fs.writeFile()
fs.open(path, options.flag, options.mode, (openError, fd) => {
if (openError) {
return callback(openError);
}
// It is valid to pass a fd handle to fs.writeFile() and this will keep the handle open!
fs.writeFile(fd, data, writeError => {
if (writeError) {
return fs.close(fd, () => callback(writeError)); // still need to close the handle on error!
}
// Flush contents (not metadata) of the file to disk
// https://github.com/microsoft/vscode/issues/9589
fs.fdatasync(fd, (syncError: Error | null) => {
// In some exotic setups it is well possible that node fails to sync
// In that case we disable flushing and warn to the console
if (syncError) {
console.warn('[node.js fs] fdatasync is now disabled for this session because it failed: ', syncError);
canFlush = false;
}
return fs.close(fd, closeError => callback(closeError));
});
});
});
}
/**
* Same as `fs.writeFileSync` but with an additional call to
* `fs.fdatasyncSync` after writing to ensure changes are
* flushed to disk.
*/
export function writeFileSync(path: string, data: string | Buffer, options?: IWriteFileOptions): void {
const ensuredOptions = ensureWriteOptions(options);
if (!canFlush) {
return fs.writeFileSync(path, data, { mode: ensuredOptions.mode, flag: ensuredOptions.flag });
}
// Open the file with same flags and mode as fs.writeFile()
const fd = fs.openSync(path, ensuredOptions.flag, ensuredOptions.mode);
try {
// It is valid to pass a fd handle to fs.writeFile() and this will keep the handle open!
fs.writeFileSync(fd, data);
// Flush contents (not metadata) of the file to disk
try {
fs.fdatasyncSync(fd); // https://github.com/microsoft/vscode/issues/9589
} catch (syncError) {
console.warn('[node.js fs] fdatasyncSync is now disabled for this session because it failed: ', syncError);
canFlush = false;
}
} finally {
fs.closeSync(fd);
}
}
function ensureWriteOptions(options?: IWriteFileOptions): IEnsuredWriteFileOptions {
if (!options) {
return { mode: 0o666 /* default node.js mode for files */, flag: 'w' };
}
return {
mode: typeof options.mode === 'number' ? options.mode : 0o666 /* default node.js mode for files */,
flag: typeof options.flag === 'string' ? options.flag : 'w'
};
}
//#endregion
//#region Move / Copy
/**
* A drop-in replacement for `fs.rename` that:
* - allows to move across multiple disks
*/
async function move(source: string, target: string): Promise<void> {
if (source === target) {
return; // simulate node.js behaviour here and do a no-op if paths match
}
try {
await Promises.rename(source, target);
} catch (error) {
// In two cases we fallback to classic copy and delete:
//
// 1.) The EXDEV error indicates that source and target are on different devices
// In this case, fallback to using a copy() operation as there is no way to
// rename() between different devices.
//
// 2.) The user tries to rename a file/folder that ends with a dot. This is not
// really possible to move then, at least on UNC devices.
if (source.toLowerCase() !== target.toLowerCase() && error.code === 'EXDEV' || source.endsWith('.')) {
await copy(source, target, { preserveSymlinks: false /* copying to another device */ });
await rimraf(source, RimRafMode.MOVE);
} else {
throw error;
}
}
}
interface ICopyPayload {
readonly root: { source: string; target: string };
readonly options: { preserveSymlinks: boolean };
readonly handledSourcePaths: Set<string>;
}
/**
* Recursively copies all of `source` to `target`.
*
* The options `preserveSymlinks` configures how symbolic
* links should be handled when encountered. Set to
* `false` to not preserve them and `true` otherwise.
*/
async function copy(source: string, target: string, options: { preserveSymlinks: boolean }): Promise<void> {
return doCopy(source, target, { root: { source, target }, options, handledSourcePaths: new Set<string>() });
}
// When copying a file or folder, we want to preserve the mode
// it had and as such provide it when creating. However, modes
// can go beyond what we expect (see link below), so we mask it.
// (https://github.com/nodejs/node-v0.x-archive/issues/3045#issuecomment-4862588)
const COPY_MODE_MASK = 0o777;
async function doCopy(source: string, target: string, payload: ICopyPayload): Promise<void> {
// Keep track of paths already copied to prevent
// cycles from symbolic links to cause issues
if (payload.handledSourcePaths.has(source)) {
return;
} else {
payload.handledSourcePaths.add(source);
}
const { stat, symbolicLink } = await SymlinkSupport.stat(source);
// Symlink
if (symbolicLink) {
// Try to re-create the symlink unless `preserveSymlinks: false`
if (payload.options.preserveSymlinks) {
try {
return await doCopySymlink(source, target, payload);
} catch (error) {
// in any case of an error fallback to normal copy via dereferencing
console.warn('[node.js fs] copy of symlink failed: ', error);
}
}
if (symbolicLink.dangling) {
return; // skip dangling symbolic links from here on (https://github.com/microsoft/vscode/issues/111621)
}
}
// Folder
if (stat.isDirectory()) {
return doCopyDirectory(source, target, stat.mode & COPY_MODE_MASK, payload);
}
// File or file-like
else {
return doCopyFile(source, target, stat.mode & COPY_MODE_MASK);
}
}
async function doCopyDirectory(source: string, target: string, mode: number, payload: ICopyPayload): Promise<void> {
// Create folder
await Promises.mkdir(target, { recursive: true, mode });
// Copy each file recursively
const files = await readdir(source);
for (const file of files) {
await doCopy(join(source, file), join(target, file), payload);
}
}
async function doCopyFile(source: string, target: string, mode: number): Promise<void> {
// Copy file
await Promises.copyFile(source, target);
// restore mode (https://github.com/nodejs/node/issues/1104)
await Promises.chmod(target, mode);
}
async function doCopySymlink(source: string, target: string, payload: ICopyPayload): Promise<void> {
// Figure out link target
let linkTarget = await Promises.readlink(source);
// Special case: the symlink points to a target that is
// actually within the path that is being copied. In that
// case we want the symlink to point to the target and
// not the source
if (isEqualOrParent(linkTarget, payload.root.source, !isLinux)) {
linkTarget = join(payload.root.target, linkTarget.substr(payload.root.source.length + 1));
}
// Create symlink
await Promises.symlink(linkTarget, target);
}
//#endregion
//#region Promise based fs methods
/**
* Prefer this helper class over the `fs.promises` API to
* enable `graceful-fs` to function properly. Given issue
* https://github.com/isaacs/node-graceful-fs/issues/160 it
* is evident that the module only takes care of the non-promise
* based fs methods.
*
* Another reason is `realpath` being entirely different in
* the promise based implementation compared to the other
* one (https://github.com/microsoft/vscode/issues/118562)
*
* Note: using getters for a reason, since `graceful-fs`
* patching might kick in later after modules have been
* loaded we need to defer access to fs methods.
* (https://github.com/microsoft/vscode/issues/124176)
*/
export const Promises = new class {
//#region Implemented by node.js
get access() { return promisify(fs.access); }
get stat() { return promisify(fs.stat); }
get lstat() { return promisify(fs.lstat); }
get utimes() { return promisify(fs.utimes); }
get read() {
// Not using `promisify` here for a reason: the return
// type is not an object as indicated by TypeScript but
// just the bytes read, so we create our own wrapper.
return (fd: number, buffer: Uint8Array, offset: number, length: number, position: number | null) => {
return new Promise<{ bytesRead: number; buffer: Uint8Array }>((resolve, reject) => {
fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
if (err) {
return reject(err);
}
return resolve({ bytesRead, buffer });
});
});
};
}
get readFile() { return promisify(fs.readFile); }
get write() {
// Not using `promisify` here for a reason: the return
// type is not an object as indicated by TypeScript but
// just the bytes written, so we create our own wrapper.
return (fd: number, buffer: Uint8Array, offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null) => {
return new Promise<{ bytesWritten: number; buffer: Uint8Array }>((resolve, reject) => {
fs.write(fd, buffer, offset, length, position, (err, bytesWritten, buffer) => {
if (err) {
return reject(err);
}
return resolve({ bytesWritten, buffer });
});
});
};
}
get appendFile() { return promisify(fs.appendFile); }
get fdatasync() { return promisify(fs.fdatasync); }
get truncate() { return promisify(fs.truncate); }
get rename() { return promisify(fs.rename); }
get copyFile() { return promisify(fs.copyFile); }
get open() { return promisify(fs.open); }
get close() { return promisify(fs.close); }
get symlink() { return promisify(fs.symlink); }
get readlink() { return promisify(fs.readlink); }
get chmod() { return promisify(fs.chmod); }
get mkdir() { return promisify(fs.mkdir); }
get unlink() { return promisify(fs.unlink); }
get rmdir() { return promisify(fs.rmdir); }
get realpath() { return promisify(fs.realpath); }
//#endregion
//#region Implemented by us
async exists(path: string): Promise<boolean> {
try {
await Promises.access(path);
return true;
} catch {
return false;
}
}
get readdir() { return readdir; }
get readDirsInDir() { return readDirsInDir; }
get writeFile() { return writeFile; }
get rm() { return rimraf; }
get move() { return move; }
get copy() { return copy; }
//#endregion
};
//#endregion | the_stack |
import {expect} from '@loopback/testlab';
import {NamespacedReflect, Reflector} from '../../reflect';
import 'reflect-metadata';
function givenReflectContextWithNameSpace(): NamespacedReflect {
const namespace = 'sample-app-context';
return new NamespacedReflect(namespace);
}
function givenReflectContext(): NamespacedReflect {
return new NamespacedReflect();
}
function givenDefaultReflector(): NamespacedReflect {
return Reflector;
}
describe('Reflect Context', () => {
describe('with namespace', () => {
runTests(givenReflectContextWithNameSpace());
});
describe('without namespace', () => {
runTests(givenReflectContext());
});
describe('with default instance', () => {
runTests(givenDefaultReflector());
});
function runTests(reflectContext: NamespacedReflect) {
afterEach(resetMetadata);
it('adds metadata to a class', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata('key', metadataValue, SubClass);
// get the defined metadata using the namespaced reflectContext
let metadata = reflectContext.getMetadata('key', SubClass);
expect(metadata).to.be.equal(metadataValue);
metadata = reflectContext.getOwnMetadata('key', SubClass);
expect(metadata).to.be.equal(metadataValue);
// base class should not be impacted
metadata = reflectContext.getOwnMetadata('key', BaseClass);
expect(metadata).to.be.undefined();
metadata = reflectContext.getMetadata('key', BaseClass);
expect(metadata).to.be.undefined();
let result = reflectContext.hasOwnMetadata('key', SubClass);
expect(result).to.be.true();
result = reflectContext.hasMetadata('key', SubClass);
expect(result).to.be.true();
});
it('adds metadata to a static method', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata(
'key',
metadataValue,
SubClass,
'subStaticMethod',
);
// get the defined metadata using the namespaced reflectContext
let metadata = reflectContext.getMetadata(
'key',
SubClass,
'subStaticMethod',
);
expect(metadata).to.be.equal(metadataValue);
metadata = reflectContext.getOwnMetadata(
'key',
SubClass,
'subStaticMethod',
);
expect(metadata).to.be.equal(metadataValue);
let result = reflectContext.hasOwnMetadata(
'key',
SubClass,
'subStaticMethod',
);
expect(result).to.be.true();
result = reflectContext.hasMetadata('key', SubClass, 'subStaticMethod');
expect(result).to.be.true();
});
it('adds metadata to a prototype method', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata(
'key',
metadataValue,
SubClass.prototype,
'subMethod',
);
// get the defined metadata using the namespaced reflectContext
let metadata = reflectContext.getMetadata(
'key',
SubClass.prototype,
'subMethod',
);
expect(metadata).to.be.equal(metadataValue);
metadata = reflectContext.getOwnMetadata(
'key',
SubClass.prototype,
'subMethod',
);
expect(metadata).to.be.equal(metadataValue);
let result = reflectContext.hasOwnMetadata(
'key',
SubClass.prototype,
'subMethod',
);
expect(result).to.be.true();
result = reflectContext.hasMetadata(
'key',
SubClass.prototype,
'subMethod',
);
expect(result).to.be.true();
});
it('deletes metadata from a class', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata('key', metadataValue, SubClass);
// get the defined metadata using the namespaced reflectContext
let metadata = reflectContext.getMetadata('key', SubClass);
expect(metadata).to.be.equal(metadataValue);
let result = reflectContext.hasOwnMetadata('key', SubClass);
expect(result).to.be.true();
result = reflectContext.deleteMetadata('key', SubClass);
expect(result).to.be.true();
result = reflectContext.hasOwnMetadata('key', SubClass);
expect(result).to.be.false();
result = reflectContext.deleteMetadata('key1', SubClass);
expect(result).to.be.false();
metadata = reflectContext.getMetadata('key', SubClass);
expect(metadata).to.be.undefined();
});
it('deletes metadata from a class static menthod', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata(
'key',
metadataValue,
SubClass.prototype,
'staticSubMethod',
);
// get the defined metadata using the namespaced reflectContext
let metadata = reflectContext.getMetadata(
'key',
SubClass.prototype,
'staticSubMethod',
);
expect(metadata).to.be.equal(metadataValue);
let result = reflectContext.hasOwnMetadata(
'key',
SubClass.prototype,
'staticSubMethod',
);
expect(result).to.be.true();
result = reflectContext.deleteMetadata(
'key',
SubClass.prototype,
'staticSubMethod',
);
expect(result).to.be.true();
result = reflectContext.hasOwnMetadata(
'key',
SubClass.prototype,
'staticSubMethod',
);
expect(result).to.be.false();
result = reflectContext.deleteMetadata(
'key1',
SubClass.prototype,
'staticSubMethod',
);
expect(result).to.be.false();
metadata = reflectContext.getMetadata(
'key',
SubClass.prototype,
'staticSubMethod',
);
expect(metadata).to.be.undefined();
});
it('deletes metadata from a class prototype menthod', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata(
'key',
metadataValue,
SubClass,
'subMethod',
);
// get the defined metadata using the namespaced reflectContext
let metadata = reflectContext.getMetadata('key', SubClass, 'subMethod');
expect(metadata).to.be.equal(metadataValue);
let result = reflectContext.hasOwnMetadata('key', SubClass, 'subMethod');
expect(result).to.be.true();
result = reflectContext.deleteMetadata('key', SubClass, 'subMethod');
expect(result).to.be.true();
result = reflectContext.hasOwnMetadata('key', SubClass, 'subMethod');
expect(result).to.be.false();
result = reflectContext.deleteMetadata('key1', SubClass, 'subMethod');
expect(result).to.be.false();
metadata = reflectContext.getMetadata('key', SubClass, 'subMethod');
expect(metadata).to.be.undefined();
});
it('adds metadata to a base class', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata('key', metadataValue, BaseClass);
// get the defined metadata using the namespaced reflectContext
let metadata = reflectContext.getMetadata('key', BaseClass);
expect(metadata).to.be.equal(metadataValue);
metadata = reflectContext.getOwnMetadata('key', BaseClass);
expect(metadata).to.be.equal(metadataValue);
metadata = reflectContext.getOwnMetadata('key', SubClass);
expect(metadata).to.be.undefined();
metadata = reflectContext.getMetadata('key', SubClass);
expect(metadata).to.be.eql(metadataValue);
});
it('adds metadata to a base static method', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata(
'key',
metadataValue,
BaseClass,
'baseStaticMethod',
);
// get the defined metadata using the namespaced reflectContext
let metadata = reflectContext.getMetadata(
'key',
BaseClass,
'baseStaticMethod',
);
expect(metadata).to.be.equal(metadataValue);
metadata = reflectContext.getOwnMetadata(
'key',
BaseClass,
'baseStaticMethod',
);
expect(metadata).to.be.equal(metadataValue);
// sub class should have the metadata too
metadata = reflectContext.getMetadata(
'key',
SubClass,
'baseStaticMethod',
);
expect(metadata).to.be.equal(metadataValue);
// sub class should not own the metadata
metadata = reflectContext.getOwnMetadata(
'key',
SubClass,
'baseStaticMethod',
);
expect(metadata).to.be.undefined();
});
it('adds metadata to a base prototype method', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata(
'key',
metadataValue,
BaseClass.prototype,
'baseMethod',
);
// get the defined metadata using the namespaced reflectContext
let metadata = reflectContext.getMetadata(
'key',
BaseClass.prototype,
'baseMethod',
);
expect(metadata).to.be.equal(metadataValue);
metadata = reflectContext.getOwnMetadata(
'key',
BaseClass.prototype,
'baseMethod',
);
expect(metadata).to.be.equal(metadataValue);
// sub class should have the metadata too
metadata = reflectContext.getMetadata(
'key',
SubClass.prototype,
'baseMethod',
);
expect(metadata).to.be.equal(metadataValue);
// sub class should not own the metadata
metadata = reflectContext.getOwnMetadata(
'key',
SubClass.prototype,
'baseMethod',
);
expect(metadata).to.be.undefined();
});
it('lists metadata keys of classes', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata('key1', metadataValue, SubClass);
reflectContext.defineMetadata('key2', {}, BaseClass);
let keys = reflectContext.getMetadataKeys(SubClass);
expect(keys).to.eql(['key1', 'key2']);
keys = reflectContext.getOwnMetadataKeys(SubClass);
expect(keys).to.eql(['key1']);
keys = reflectContext.getMetadataKeys(BaseClass);
expect(keys).to.eql(['key2']);
keys = reflectContext.getOwnMetadataKeys(BaseClass);
expect(keys).to.eql(['key2']);
});
it('lists metadata keys of class methods', () => {
const metadataValue: object = {value: 'sample'};
reflectContext.defineMetadata(
'key3',
metadataValue,
SubClass,
'staticSubMethod',
);
reflectContext.defineMetadata(
'key4',
metadataValue,
BaseClass,
'staticBaseMethod',
);
reflectContext.defineMetadata(
'key5',
metadataValue,
SubClass.prototype,
'subMethod',
);
reflectContext.defineMetadata(
'key6',
metadataValue,
SubClass.prototype,
'baseMethod',
);
reflectContext.defineMetadata(
'abc:loopback:key7',
metadataValue,
BaseClass.prototype,
'baseMethod',
);
let keys = reflectContext.getOwnMetadataKeys(SubClass, 'staticSubMethod');
expect(keys).to.eql(['key3']);
keys = reflectContext.getOwnMetadataKeys(SubClass, 'staticBaseMethod');
expect(keys).to.eql([]);
keys = reflectContext.getOwnMetadataKeys(BaseClass, 'staticBaseMethod');
expect(keys).to.eql(['key4']);
keys = reflectContext.getOwnMetadataKeys(SubClass.prototype, 'subMethod');
expect(keys).to.eql(['key5']);
keys = reflectContext.getOwnMetadataKeys(
SubClass.prototype,
'baseMethod',
);
expect(keys).to.eql(['key6']);
keys = reflectContext.getMetadataKeys(SubClass.prototype, 'baseMethod');
expect(keys).to.eql(['key6', 'abc:loopback:key7']);
keys = reflectContext.getOwnMetadataKeys(
BaseClass.prototype,
'baseMethod',
);
expect(keys).to.eql(['abc:loopback:key7']);
});
it('checks hasMetadata against a class', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata('key1', metadataValue, SubClass);
reflectContext.defineMetadata('key2', {}, BaseClass);
let result = reflectContext.hasMetadata('key1', SubClass);
expect(result).to.be.true();
result = reflectContext.hasMetadata('key2', SubClass);
expect(result).to.be.true();
result = reflectContext.hasMetadata('key1', BaseClass);
expect(result).to.be.false();
result = reflectContext.hasMetadata('key2', BaseClass);
expect(result).to.be.true();
});
it('checks hasOwnMetadata against a class', () => {
const metadataValue: object = {value: 'sample'};
// define a metadata using the namespaced reflectContext
reflectContext.defineMetadata('key1', metadataValue, SubClass);
reflectContext.defineMetadata('key2', {}, BaseClass);
let result = reflectContext.hasOwnMetadata('key1', SubClass);
expect(result).to.be.true();
result = reflectContext.hasOwnMetadata('key2', SubClass);
expect(result).to.be.false();
result = reflectContext.hasOwnMetadata('key1', BaseClass);
expect(result).to.be.false();
result = reflectContext.hasOwnMetadata('key2', BaseClass);
expect(result).to.be.true();
});
function deleteMetadata(target: object, propertyKey?: string) {
if (propertyKey) {
const keys = reflectContext.getOwnMetadataKeys(target, propertyKey);
for (const k of keys) {
reflectContext.deleteMetadata(k, target, propertyKey);
}
} else {
const keys = reflectContext.getOwnMetadataKeys(target);
for (const k of keys) {
reflectContext.deleteMetadata(k, target);
}
}
}
// Clean up the metadata
function resetMetadata() {
deleteMetadata(BaseClass);
deleteMetadata(BaseClass, 'staticBaseMethod');
deleteMetadata(BaseClass.prototype, 'baseMethod');
deleteMetadata(SubClass);
deleteMetadata(SubClass, 'staticSubMethod');
deleteMetadata(SubClass.prototype, 'subMethod');
deleteMetadata(SubClass.prototype, 'baseMethod');
}
class BaseClass {
static staticBaseMethod() {}
constructor() {}
baseMethod() {}
}
class SubClass extends BaseClass {
static staticSubMethod() {}
constructor() {
super();
}
baseMethod() {
super.baseMethod();
}
subMethod(): boolean {
return true;
}
}
}
describe('@Reflector.metadata', () => {
const val1 = {x: 1};
const val2 = {y: 'a'};
@Reflector.metadata('key1', val1)
class TestClass {
@Reflector.metadata('key2', val2)
testMethod() {}
}
it('adds metadata', () => {
let meta = Reflector.getOwnMetadata('key1', TestClass);
expect(meta).to.eql(val1);
meta = Reflector.getOwnMetadata(
'key2',
TestClass.prototype,
'testMethod',
);
expect(meta).to.eql(val2);
});
});
describe('@Reflector.decorate', () => {
const val1 = {x: 1};
const val2 = {y: 'a'};
class TestClass {
testMethod() {}
}
it('adds metadata', () => {
const x: ClassDecorator = Reflector.metadata('key1', val1);
Reflector.decorate([x], TestClass);
const y: MethodDecorator = Reflector.metadata('key2', val2);
Reflector.decorate([y], TestClass.prototype, 'testMethod');
let meta = Reflector.getOwnMetadata('key1', TestClass);
expect(meta).to.eql(val1);
meta = Reflector.getOwnMetadata(
'key2',
TestClass.prototype,
'testMethod',
);
expect(meta).to.eql(val2);
});
});
}); | the_stack |
import type { vec3 } from "gl-matrix";
import { arrayRemove } from "kudzu/arrays/arrayRemove";
import { arraySortedInsert } from "kudzu/arrays/arraySortedInsert";
import { audioCtx, audioReady, buffer, BufferSource, ChannelMerger, connect, decodeAudioData, hasAudioListener, hasNewAudioListener, hasOldAudioListener, loop as loopAudio, MediaElementSource, MediaStreamDestination, MediaStreamSource, MediaStreamTrackSource } from "kudzu/audio";
import { TypedEvent, TypedEventBase } from "kudzu/events/EventBase";
import { once } from "kudzu/events/once";
import { autoPlay, controls, loop, muted, playsInline, src } from "kudzu/html/attrs";
import { display, styles } from "kudzu/html/css";
import type { HTMLAudioElementWithSinkID, ElementChild } from "kudzu/html/tags";
import { Audio } from "kudzu/html/tags";
import { Fetcher } from "kudzu/io/Fetcher";
import type { IFetcher } from "kudzu/io/IFetcher";
import { guessMediaTypeByFileName } from "kudzu/mediaTypes";
import type { progressCallback } from "kudzu/tasks/progressCallback";
import { assertNever } from "kudzu/typeChecks";
import type { IDisposable } from "kudzu/using";
import { canChangeAudioOutput, DeviceManager } from "../devices/DeviceManager";
import { DEFAULT_LOCAL_USER_ID } from "../tele/BaseTeleconferenceClient";
import { AudioActivityEvent } from "./AudioActivityEvent";
import { AudioDestination } from "./destinations/AudioDestination";
import type { BaseListener } from "./destinations/spatializers/BaseListener";
import { NoSpatializationListener } from "./destinations/spatializers/NoSpatializationListener";
import { ResonanceAudioListener } from "./destinations/spatializers/ResonanceAudioListener";
import { VolumeScalingListener } from "./destinations/spatializers/VolumeScalingListener";
import { WebAudioListenerNew } from "./destinations/spatializers/WebAudioListenerNew";
import { WebAudioListenerOld } from "./destinations/spatializers/WebAudioListenerOld";
import type { IPoseable } from "./IPoseable";
import type { InterpolatedPose } from "./positions/InterpolatedPose";
import { AudioBufferSpawningSource } from "./sources/AudioBufferSpawningSource";
import { AudioElementSource } from "./sources/AudioElementSource";
import type { AudioStreamSourceNode } from "./sources/AudioStreamSource";
import { AudioStreamSource } from "./sources/AudioStreamSource";
import type { IPlayableSource } from "./sources/IPlayableSource";
import { BaseEmitter } from "./sources/spatializers/BaseEmitter";
function BackgroundAudio(autoplay: boolean, mute: boolean, ...rest: ElementChild[]): HTMLAudioElementWithSinkID {
return Audio(
playsInline(true),
controls(false),
muted(mute),
autoPlay(autoplay),
styles(display("none")),
...rest);
}
if (!("AudioContext" in globalThis) && "webkitAudioContext" in globalThis) {
globalThis.AudioContext = (globalThis as any).webkitAudioContext;
}
if (!("OfflineAudioContext" in globalThis) && "webkitOfflineAudioContext" in globalThis) {
globalThis.OfflineAudioContext = (globalThis as any).webkitOfflineAudioContext;
}
type withPoseCallback<T> = (pose: InterpolatedPose) => T;
const audioReadyEvt = new TypedEvent("audioReady");
const testAudio = Audio();
const useTrackSource = "createMediaStreamTrackSource" in AudioContext.prototype;
const useElementSourceForUsers = !useTrackSource && !("createMediaStreamSource" in AudioContext.prototype);
const useElementSourceForClips = true;
function shouldTry(path: string): boolean {
const idx = path.lastIndexOf(".");
if (idx > -1) {
const types = guessMediaTypeByFileName(path);
for (const type of types) {
if (testAudio.canPlayType(type.value)) {
return true;
}
}
return false;
}
return true;
}
let tryNewAudioListener = hasNewAudioListener;
let tryOldAudioListener = hasOldAudioListener;
let tryAudioListener = hasAudioListener;
let tryResonanceAPI = hasAudioListener;
interface AudioManagerEvents {
audioReady: TypedEvent<"audioReady">,
audioActivity: AudioActivityEvent;
}
export enum SpatializerType {
None = "none",
Low = "low",
Medium = "medium",
High = "high"
}
function isMediaStreamAudioDestinationNode(destination: AudioDestinationNode | MediaStreamAudioDestinationNode): destination is MediaStreamAudioDestinationNode {
return canChangeAudioOutput && "stream" in destination;
}
/**
* A manager of audio sources, destinations, and their spatialization.
**/
export class AudioManager extends TypedEventBase<AudioManagerEvents> {
private minDistance = 1;
private maxDistance = 10;
private rolloff = 1;
private _algorithm = "logarithmic";
transitionTime = 0.5;
private _offsetRadius = 0;
private clips = new Map<string, IPlayableSource>();
private users = new Map<string, AudioStreamSource>();
public localUserID: string = null;
private sortedUserIDs = new Array<string>();
localOutput: AudioDestination = null;
listener: BaseListener = null;
//audioContext: AudioContext = null;
private destination: AudioDestinationNode | MediaStreamAudioDestinationNode = null;
private fetcher: IFetcher;
private _type: SpatializerType;
devices = new DeviceManager();
private _ready: Promise<void>;
get ready() {
return this._ready;
}
/**
* Creates a new manager of audio sources, destinations, and their spatialization.
**/
constructor(fetcher?: IFetcher, type?: SpatializerType) {
super();
this.fetcher = fetcher || new Fetcher();
this.setLocalUserID(DEFAULT_LOCAL_USER_ID);
//this.audioContext = new AudioContext();
if (canChangeAudioOutput) {
this.destination = MediaStreamDestination("final-destination",);
}
else {
this.destination = audioCtx.destination;
}
this.localOutput = new AudioDestination(this.destination);
this._ready = audioReady
.then(async () => {
if (isMediaStreamAudioDestinationNode(this.destination)) {
await this.devices.setDestination(this.destination);
}
});
this.type = type || SpatializerType.Medium;
Object.seal(this);
}
get offsetRadius() {
return this._offsetRadius;
}
set offsetRadius(v) {
this._offsetRadius = v;
this.updateUserOffsets();
}
get algorithm() {
return this._algorithm;
}
protected checkAddEventListener<T extends Event>(type: string, callback: (evt: T) => any) {
if (type === audioReadyEvt.type && this.isReady) {
callback(audioReadyEvt as any as T);
return false;
}
return true;
}
get isReady(): boolean {
return audioCtx.state !== "suspended";
}
get isRunning(): boolean {
return audioCtx.state === "running";
}
update(): void {
const t = this.currentTime;
this.localOutput.update(t);
for (const clip of this.clips.values()) {
clip.update(t);
}
for (const user of this.users.values()) {
user.update(t);
}
}
get type() {
return this._type;
}
set type(type: SpatializerType) {
const inputType = type;
if (type !== SpatializerType.High
&& type !== SpatializerType.Medium
&& type !== SpatializerType.Low
&& type !== SpatializerType.None) {
assertNever(type, "Invalid spatialization type: ");
}
// These checks are done in an arcane way because it makes the fallback logic
// for each step self-contained. It's easier to look at a single step and determine
// wether or not it is correct, without having to look at previous blocks of code.
if (type === SpatializerType.High) {
if (tryResonanceAPI) {
try {
this.listener = new ResonanceAudioListener();
}
catch (exp) {
tryResonanceAPI = false;
type = SpatializerType.Medium;
console.warn("Resonance Audio API not available!", exp);
}
}
else {
type = SpatializerType.Medium;
}
}
else {
tryResonanceAPI = false;
}
if (type === SpatializerType.Medium) {
if (!tryResonanceAPI && tryAudioListener) {
if (tryNewAudioListener) {
try {
this.listener = new WebAudioListenerNew();
}
catch (exp) {
tryNewAudioListener = false;
console.warn("No AudioListener.positionX property!", exp);
}
}
if (!tryNewAudioListener && tryOldAudioListener) {
try {
this.listener = new WebAudioListenerOld();
}
catch (exp) {
tryOldAudioListener = false;
console.warn("No WebAudio API!", exp);
}
}
if (!tryNewAudioListener && !tryOldAudioListener) {
type = SpatializerType.Low;
tryAudioListener = false;
}
}
else {
type = SpatializerType.Low;
}
}
if (type === SpatializerType.Low) {
this.listener = new VolumeScalingListener();
}
else if (type === SpatializerType.None) {
this.listener = new NoSpatializationListener();
}
if (!this.listener) {
throw new Error("Calla requires a functioning WebAudio system. Could not create one for type: " + inputType);
}
else if (type !== inputType) {
console.warn(`Wasn't able to create the listener type ${inputType}. Fell back to ${type} instead.`);
}
this._type = type;
this.localOutput.spatializer = this.listener;
for (const clip of this.clips.values()) {
clip.spatializer = this.createSpatializer(clip.spatialized, false);
}
for (const user of this.users.values()) {
user.spatializer = this.createSpatializer(user.spatialized, false);
}
}
/**
* Creates a spatialzer for an audio source.
* @param spatialize - whether or not the audio stream should be spatialized. Stereo audio streams that are spatialized will get down-mixed to a single channel.
* @param isRemoteStream - whether or not the audio stream is coming from a remote user.
*/
createSpatializer(spatialize: boolean, isRemoteStream: boolean): BaseEmitter {
return this.listener.createSpatializer(spatialize, isRemoteStream, this.localOutput);
}
/**
* Gets the current playback time.
*/
get currentTime(): number {
return audioCtx.currentTime;
}
/**
* Create a new user for audio processing.
*/
createUser(id: string): AudioStreamSource {
let user: AudioStreamSource = this.users.get(id);
if (!user) {
user = new AudioStreamSource(id);
this.users.set(id, user);
arraySortedInsert(this.sortedUserIDs, id);
this.updateUserOffsets();
}
return user;
}
/**
* Create a new user for the audio listener.
*/
setLocalUserID(id: string): AudioDestination {
if (this.localOutput) {
arrayRemove(this.sortedUserIDs, this.localUserID);
this.localUserID = id;
arraySortedInsert(this.sortedUserIDs, this.localUserID);
this.updateUserOffsets();
}
else {
}
return this.localOutput;
}
/**
* Creates a new sound effect from a series of fallback paths
* for media files.
* @param id - the name of the sound effect, to reference when executing playback.
* @param looping - whether or not the sound effect should be played on loop.
* @param autoPlaying - whether or not the sound effect should be played immediately.
* @param spatialize - whether or not the sound effect should be spatialized.
* @param vol - the volume at which to set the clip.
* @param path - a path for loading the media of the sound effect.
* @param onProgress - an optional callback function to use for tracking progress of loading the clip.
*/
async createClip(id: string, looping: boolean, autoPlaying: boolean, spatialize: boolean, vol: number, path: string, onProgress?: progressCallback): Promise<IPlayableSource> {
if (path == null || path.length === 0) {
throw new Error("No clip source path provided");
}
const clip = useElementSourceForClips
? await this.createAudioElementSource(id, looping, autoPlaying, spatialize, path, onProgress)
: await this.createAudioBufferSource(id, looping, autoPlaying, spatialize, path, onProgress);
clip.volume = vol;
this.clips.set(id, clip);
return clip;
}
private async getAudioBlob(path: string, onProgress: progressCallback): Promise<Blob> {
let goodBlob: Blob = null;
if (!shouldTry(path)) {
if (onProgress) {
onProgress(1, 1, "skip");
}
}
else {
const blob = await this.fetcher.getBlob(path, null, onProgress);
if (testAudio.canPlayType(blob.type)) {
goodBlob = blob;
}
}
if (!goodBlob) {
throw new Error("Cannot play file: " + path);
}
return goodBlob;
}
private async createAudioElementSource(id: string, looping: boolean, autoPlaying: boolean, spatialize: boolean, path: string, onProgress?: progressCallback): Promise<IPlayableSource> {
if (onProgress) {
onProgress(0, 1);
}
const blob = await this.getAudioBlob(path, onProgress);
const file = URL.createObjectURL(blob);
const elem = BackgroundAudio(
autoPlaying,
false,
loop(looping),
src(file));
await once(elem, "canplaythrough", "error");
const source = MediaElementSource("audio-element-source-" + id, elem);
if (onProgress) {
onProgress(1, 1);
}
return new AudioElementSource("audio-clip-" + id, source, this.createSpatializer(spatialize, false));
}
private async createAudioBufferSource(id: string, looping: boolean, autoPlaying: boolean, spatialize: boolean, path: string, onProgress?: progressCallback): Promise<IPlayableSource> {
let goodBlob: Blob = await this.getAudioBlob(path, onProgress);
const b = await goodBlob.arrayBuffer();
const data = await decodeAudioData(b);
const source = BufferSource(
"audio-buffer-source-" + id,
buffer(data),
loopAudio(looping)
);
const clip = new AudioBufferSpawningSource("audio-clip-" + id, source, this.createSpatializer(spatialize, false));
if (autoPlaying) {
clip.play();
}
return clip;
}
hasClip(name: string): boolean {
return this.clips.has(name);
}
/**
* Plays a named sound effect.
* @param name - the name of the effect to play.
*/
async playClip(name: string): Promise<void> {
if (this.isReady && this.hasClip(name)) {
const clip = this.clips.get(name);
await clip.play();
}
}
stopClip(name: string): void {
if (this.isReady && this.hasClip(name)) {
const clip = this.clips.get(name);
clip.stop();
}
}
/**
* Get an existing user.
*/
getUser(id: string): AudioStreamSource {
return this.users.get(id);
}
/**
* Get an existing audio clip.
*/
getClip(id: string): IPlayableSource {
return this.clips.get(id);
}
renameClip(id: string, newID: string): void {
const clip = this.clips.get(id);
if (clip) {
clip.id = "audio-clip-" + id;
this.clips.delete(id);
this.clips.set(newID, clip);
}
}
/**
* Remove an audio source from audio processing.
* @param sources - the collection of audio sources from which to remove.
* @param id - the id of the audio source to remove
**/
private removeSource<T extends IDisposable>(sources: Map<string, T>, id: string): T {
const source = sources.get(id);
if (source) {
sources.delete(id);
source.dispose();
}
return source;
}
/**
* Remove a user from audio processing.
**/
removeUser(id: string): void {
this.removeSource(this.users, id);
arrayRemove(this.sortedUserIDs, id);
this.updateUserOffsets();
}
/**
* Remove an audio clip from audio processing.
**/
removeClip(id: string): IPlayableSource {
return this.removeSource(this.clips, id);
}
private createSourceFromStream(stream: MediaStream): AudioStreamSourceNode {
if (useTrackSource) {
const tracks = stream.getAudioTracks()
.map((track) =>
MediaStreamTrackSource("track-source-" + track.id, track));
if (tracks.length === 0) {
throw new Error("No audio tracks!");
}
else if (tracks.length === 1) {
return tracks[0];
}
else {
const merger = ChannelMerger(
"track-merger-" + stream.id,
tracks.length);
for (const track of tracks) {
connect(track, merger);
}
return merger;
}
}
else {
const elem = BackgroundAudio(true, !useElementSourceForUsers);
elem.srcObject = stream;
elem.play();
if (useElementSourceForUsers) {
return MediaElementSource("media-element-source-" + stream.id, elem);
}
else {
elem.muted = true;
return MediaStreamSource("media-stream-source-" + stream.id, stream);
}
}
}
setUserStream(id: string, stream: MediaStream): void {
if (this.users.has(id)) {
const user = this.users.get(id);
user.spatializer = null;
if (stream) {
user.source = this.createSourceFromStream(stream);
user.spatializer = this.createSpatializer(true, true);
user.spatializer.setAudioProperties(this.minDistance, this.maxDistance, this.rolloff, this.algorithm, this.transitionTime);
}
}
}
updateUserOffsets(): void {
if (this.offsetRadius > 0) {
const idx = this.sortedUserIDs.indexOf(this.localUserID);
const dAngle = 2 * Math.PI / this.sortedUserIDs.length;
const localAngle = (idx + 1) * dAngle;
const dx = this.offsetRadius * Math.sin(localAngle);
const dy = this.offsetRadius * (Math.cos(localAngle) - 1);
for (let i = 0; i < this.sortedUserIDs.length; ++i) {
const id = this.sortedUserIDs[i];
const angle = (i + 1) * dAngle;
const x = this.offsetRadius * Math.sin(angle) - dx;
const z = this.offsetRadius * (Math.cos(angle) - 1) - dy;
this.setUserOffset(id, x, 0, z);
}
}
}
/**
* Sets parameters that alter spatialization.
**/
setAudioProperties(minDistance: number, maxDistance: number, rolloff: number, algorithm: string, transitionTime: number): void {
this.minDistance = minDistance;
this.maxDistance = maxDistance;
this.transitionTime = transitionTime;
this.rolloff = rolloff;
this._algorithm = algorithm;
for (const user of this.users.values()) {
if (user.spatializer) {
user.spatializer.setAudioProperties(this.minDistance, this.maxDistance, this.rolloff, this.algorithm, this.transitionTime);
}
}
}
/**
* Get a pose, normalize the transition time, and perform on operation on it, if it exists.
* @param sources - the collection of poses from which to retrieve the pose.
* @param id - the id of the pose for which to perform the operation.
* @param poseCallback
*/
private withPose<ElementT extends IPoseable, ResultT>(sources: Map<string, ElementT>, id: string, poseCallback: withPoseCallback<ResultT>): ResultT {
const source = sources.get(id);
let pose: InterpolatedPose = null;
if (source) {
pose = source.pose;
}
else if (id === this.localUserID) {
pose = this.localOutput.pose;
}
if (!pose) {
return null;
}
return poseCallback(pose);
}
/**
* Get a user pose, normalize the transition time, and perform on operation on it, if it exists.
* @param id - the id of the user for which to perform the operation.
* @param poseCallback
*/
private withUser<T>(id: string, poseCallback: withPoseCallback<T>): T {
return this.withPose(this.users, id, poseCallback);
}
/**
* Set the comfort position offset for a given user.
* @param id - the id of the user for which to set the offset.
* @param x - the horizontal component of the offset.
* @param y - the vertical component of the offset.
* @param z - the lateral component of the offset.
*/
private setUserOffset(id: string, x: number, y: number, z: number): void {
this.withUser(id, (pose) => {
pose.setOffset(x, y, z);
});
}
/**
* Get the comfort position offset for a given user.
* @param id - the id of the user for which to set the offset.
*/
public getUserOffset(id: string): vec3 {
return this.withUser(id, pose => pose.offset);
}
/**
* Set the position and orientation of a user.
* @param id - the id of the user for which to set the position.
* @param px - the horizontal component of the position.
* @param py - the vertical component of the position.
* @param pz - the lateral component of the position.
* @param fx - the horizontal component of the forward vector.
* @param fy - the vertical component of the forward vector.
* @param fz - the lateral component of the forward vector.
* @param ux - the horizontal component of the up vector.
* @param uy - the vertical component of the up vector.
* @param uz - the lateral component of the up vector.
* @param dt - the amount of time to take to make the transition. Defaults to this AudioManager's `transitionTime`.
**/
setUserPose(id: string, px: number, py: number, pz: number, fx: number, fy: number, fz: number, ux: number, uy: number, uz: number): void {
this.withUser(id, (pose) => {
pose.setTarget(px, py, pz, fx, fy, fz, ux, uy, uz, this.currentTime, this.transitionTime);
});
}
/**
* Get an audio clip pose, normalize the transition time, and perform on operation on it, if it exists.
* @param id - the id of the audio clip for which to perform the operation.
* @param dt - the amount of time to take to make the transition. Defaults to this AudioManager's `transitionTime`.
* @param poseCallback
*/
private withClip<T>(id: string, poseCallback: withPoseCallback<T>): T {
return this.withPose(this.clips, id, poseCallback);
}
/**
* Set the position of an audio clip.
* @param id - the id of the audio clip for which to set the position.
* @param x - the horizontal component of the position.
* @param y - the vertical component of the position.
* @param z - the lateral component of the position.
**/
setClipPosition(id: string, x: number, y: number, z: number): void {
this.withClip(id, (pose) => {
pose.setTargetPosition(x, y, z, this.currentTime, this.transitionTime);
});
}
/**
* Set the orientation of an audio clip.
* @param id - the id of the audio clip for which to set the position.
* @param fx - the horizontal component of the forward vector.
* @param fy - the vertical component of the forward vector.
* @param fz - the lateral component of the forward vector.
* @param ux - the horizontal component of the up vector.
* @param uy - the vertical component of the up vector.
* @param uz - the lateral component of the up vector.
**/
setClipOrientation(id: string, fx: number, fy: number, fz: number, ux: number, uy: number, uz: number): void {
this.withClip(id, (pose) => {
pose.setTargetOrientation(fx, fy, fz, ux, uy, uz, this.currentTime, this.transitionTime);
});
}
/**
* Set the position and orientation of an audio clip.
* @param id - the id of the audio clip for which to set the position.
* @param px - the horizontal component of the position.
* @param py - the vertical component of the position.
* @param pz - the lateral component of the position.
* @param fx - the horizontal component of the forward vector.
* @param fy - the vertical component of the forward vector.
* @param fz - the lateral component of the forward vector.
* @param ux - the horizontal component of the up vector.
* @param uy - the vertical component of the up vector.
* @param uz - the lateral component of the up vector.
**/
setClipPose(id: string, px: number, py: number, pz: number, fx: number, fy: number, fz: number, ux: number, uy: number, uz: number): void {
this.withClip(id, (pose) => {
pose.setTarget(px, py, pz, fx, fy, fz, ux, uy, uz, this.currentTime, 0.5);
});
}
} | the_stack |
import React from 'react';
import { Typography, Grid, Button } from 'antd'
const { Title, Paragraph } = Typography
import { useIntl, FormattedMessage, IntlShape } from 'gatsby-plugin-intl';
import { Link } from 'gatsby'
import { Layout } from '~/components/Layout';
import { SEO } from '~/components/SEO';
import { bodyStyles, buttonStylesLg, headingStyles, titleStyles } from '~/styles'
const { useBreakpoint } = Grid
import { ReactComponent as LayeredCircles } from '~/icons/layered-circles.svg';
import { ReactComponent as CircledArrowDown } from '~/icons/circled-arrow-down.svg';
import { ReactComponent as BinanceChainIcon } from '~/icons/binancechain.svg';
import { ReactComponent as EthereumIcon } from '~/icons/ethereum.svg';
import { ReactComponent as SolanaIcon } from '~/icons/solana.svg';
import { ReactComponent as TerraIcon } from '~/icons/terra.svg';
const OpenForBizSection = ({ intl, smScreen, howAnchor }: { intl: IntlShape, smScreen: boolean, howAnchor: string }) => (
<div className="center-content">
<div
className="responsive-padding max-content-width"
style={{
width: '100%',
display: 'flex',
justifyContent: 'space-around',
marginBlock: 180,
}}>
<div style={{
height: '100%',
maxWidth: 650,
display: 'flex', flexDirection: 'column',
justifyContent: 'center', zIndex: 2,
marginRight: 'auto'
}}>
<Title level={1} style={{ ...titleStyles, fontSize: 64 }}>
<FormattedMessage id="homepage.openForBiz.title" />
</Title>
<Paragraph style={{ ...bodyStyles, marginRight: 'auto', marginBottom: 60 }} type="secondary">
<FormattedMessage id="homepage.openForBiz.body" />
</Paragraph>
{/* Placeholder: call to action from designs- to explorer or elsewhere */}
{/* <Link to={`/${intl.locale}/explorer`}>
<Button ghost style={buttonStylesLg} size="large">
<FormattedMessage id="homepage.openForBiz.callToAction" />
</Button>
</Link> */}
</div>
{smScreen ? null : (
<div style={{ display: 'flex', flexDirection: 'column', placeContent: 'center', marginRight: 'auto' }}>
{/* Placeholder: live metric of some kind from designs, commented out until we have some data to put here. */}
{/* <div style={{ display: 'flex', flexDirection: 'column', alignContent: 'flex-end', marginTop: 80, marginRight: 80 }}>
<Text style={{ fontSize: 16 }} type="secondary"><FormattedMessage id="homepage.openForBiz.dataLabel" /></Text>
<Text style={{ fontSize: 24 }} type="warning">12,319,215</Text>
</div> */}
<Link to={'#' + howAnchor} title={intl.formatMessage({ id: "homepage.openForBiz.scrollDownAltText" })} >
<CircledArrowDown style={{ width: 252 }} />
</Link>
</div>
)}
</div>
</div>
)
const AboutUsSection = ({ intl, smScreen, howAnchor }: { intl: IntlShape, smScreen: boolean, howAnchor: string }) => (
<div className="center-content blue-background">
<div
className="responsive-padding max-content-width"
style={{
width: '100%',
display: 'flex',
flexDirection: smScreen ? 'column' : 'row',
justifyContent: smScreen ? 'flex-start' : 'space-between',
marginBlockStart: smScreen ? 200 : 0,
marginBlockEnd: smScreen ? 100 : 0,
}}>
{/* copy layout & formatting */}
<div style={{
display: 'flex',
flexDirection: 'column',
justifyContent: smScreen ? 'flex-start' : 'center',
alignItems: 'flex-start',
marginBlock: smScreen ? 0 : 200,
zIndex: 2,
}}>
<div style={{ borderBottom: "0.5px solid #808088", width: 160, marginBottom: 60 }}>
<Paragraph style={headingStyles} id={howAnchor}>
{intl.formatMessage({ id: "homepage.aboutUs.heading" }).toLocaleUpperCase()}
</Paragraph>
</div>
<Paragraph style={{ ...bodyStyles, maxWidth: smScreen ? '100%' : 500, marginBottom: 30 }} >
<FormattedMessage id="homepage.aboutUs.body" />
</Paragraph>
<Link to={`/${intl.locale}/about/`}>
<Button style={buttonStylesLg} size="large">
<FormattedMessage id="homepage.aboutUs.callToAction" />
</Button>
</Link>
</div>
{/* background image, ternary for seperate mobile layout */}
{smScreen ? (
<div style={{ position: 'relative', marginTop: 60, height: 260, }}>
<div style={{ position: 'absolute', right: 40, height: '100%', display: 'flex', alignItems: 'center', zIndex: 2, }}>
<LayeredCircles style={{ height: 260 }} />
</div>
</div>
) : (
<div style={{
position: 'relative', height: '100%', display: 'flex', alignItems: 'center',
}}>
<div style={{ position: 'absolute', right: -16, height: '100%', display: 'flex', alignItems: 'center', }}>
<LayeredCircles style={{ height: '80%' }} />
</div>
</div>
)}
</div>
</div>
)
const NetworkSection = ({ intl, smScreen }: { intl: IntlShape, smScreen: boolean }) => {
const PartnersImg = <img
src="/images/Partners.gif"
style={{ width: 345, height: 375 }}
alt={intl.formatMessage({ id: 'homepage.network.partnersAnimationAltText' })}
/>
return (
<div className="center-content">
<div
className="responsive-padding max-content-width"
style={{
width: '100%',
minHeight: 550,
display: 'flex',
flexDirection: smScreen ? 'column' : 'row',
justifyContent: smScreen ? 'center' : 'space-between',
overflow: 'hidden',
}}>
<div style={{
height: '100%',
display: 'flex', flexDirection: 'column',
justifyContent: smScreen ? 'flex-start' : 'center',
paddingBlockStart: smScreen ? 100 : 0,
zIndex: 2,
}}>
<div style={{ borderBottom: "0.5px solid #808088", width: 160, marginBottom: 90 }}>
<Paragraph style={headingStyles} type="secondary">
{intl.formatMessage({ id: "homepage.network.heading" }).toLocaleUpperCase()}
</Paragraph>
</div>
<Title level={1} style={{ ...titleStyles, maxWidth: '100%', minWidth: '40%' }}>
{intl.formatMessage({ id: "homepage.network.title" })}
</Title>
<Paragraph style={{ ...bodyStyles, maxWidth: '100%', minWidth: '40%', marginBottom: 30 }} type="secondary" >
<FormattedMessage id="homepage.network.body" />
</Paragraph>
</div>
{smScreen ? (
<div style={{
display: 'flex', justifyContent: 'center',
alignContent: 'center', alignItems: 'center',
marginBottom: 60, width: '100%'
}}>
{PartnersImg}
</div>
) : (
<div style={{
display: 'flex', flexDirection: 'column',
justifyContent: 'center', alignItems: 'center',
margin: '0 8px', minWidth: '40%', maxWidth: 400
}}>
{PartnersImg}
</div>
)}
</div>
</div>
)
}
const WhatWeDoSection = ({ intl, smScreen }: { intl: IntlShape, smScreen: boolean }) => {
const iconStyles = { width: 160, margin: '0 4px' }
const iconWithCaption = (IconEle: React.ElementType, caption: string, figureStyle: object = {}) => {
return <figure style={{ ...iconStyles, ...figureStyle }}>
<IconEle />
<figcaption style={{ textAlign: 'center' }}>{caption}</figcaption>
</figure>
}
return (
<div className="center-content blue-background">
<div
className="responsive-padding max-content-width"
style={{
width: '100%',
display: 'flex',
flexDirection: smScreen ? 'column' : 'row',
justifyContent: smScreen ? 'center' : 'space-between',
marginBlock: 100,
}}>
<div style={{
height: '100%',
display: 'flex', flexDirection: 'column',
justifyContent: smScreen ? 'flex-start' : 'center',
// paddingBlockStart: 100,
}}>
<div style={{ borderBottom: "0.5px solid #808088", width: 160, marginBottom: 60 }}>
<Paragraph style={headingStyles}>
{intl.formatMessage({ id: "homepage.whatWeDo.heading" }).toLocaleUpperCase()}
</Paragraph>
</div>
<Paragraph style={{ ...bodyStyles, maxWidth: '100%', minWidth: '40%', marginBottom: 0 }} type="secondary" >
<FormattedMessage id="homepage.whatWeDo.problem" />
</Paragraph>
<Title level={1} style={{ ...titleStyles, maxWidth: '100%', minWidth: '40%', marginBottom: 40 }}>
{intl.formatMessage({ id: "homepage.whatWeDo.title" })}
</Title>
<Paragraph style={{ ...bodyStyles, maxWidth: '100%', minWidth: '40%' }} type="secondary" >
<FormattedMessage id="homepage.whatWeDo.body" />
</Paragraph>
</div>
{smScreen ? (
<div style={{
display: 'flex', justifyContent: 'space-evenly',
alignContent: 'flex-end', alignItems: 'baseline',
width: '100%', height: 150
}}>
{iconWithCaption(EthereumIcon, 'Ethereum', { width: 70 })}
{iconWithCaption(SolanaIcon, 'Solana', { width: 90 })}
{iconWithCaption(TerraIcon, 'Terra', { width: 90 })}
{iconWithCaption(BinanceChainIcon, 'Binance Smart Chain', { width: 90 })}
</div>
) : (
<div style={{
display: 'flex', flexWrap: 'wrap',
placeContent: 'space-evenly', alignItems: 'center',
margin: '8px',
maxWidth: 400,
width: '100%',
}}>
{iconWithCaption(EthereumIcon, 'Ethereum', { width: 130 })}
{iconWithCaption(SolanaIcon, 'Solana', {})}
{iconWithCaption(TerraIcon, 'Terra', {})}
{iconWithCaption(BinanceChainIcon, 'Binance Smart Chain', {})}
</div>
)}
</div>
</div>
)
}
const Index = () => {
const intl = useIntl()
const screens = useBreakpoint();
const smScreen = screens.md === false
const howAnchor = intl.formatMessage({ id: "homepage.aboutUs.heading" }).replace(/\s+/g, '-').toLocaleLowerCase()
return (
<Layout>
<SEO
title={intl.formatMessage({ id: 'homepage.title' })}
description={intl.formatMessage({ id: 'homepage.description' })}
/>
<OpenForBizSection intl={intl} smScreen={smScreen} howAnchor={howAnchor} />
<AboutUsSection intl={intl} smScreen={smScreen} howAnchor={howAnchor} />
<NetworkSection intl={intl} smScreen={smScreen} />
{/* <WhatWeDoSection intl={intl} smScreen={smScreen} /> */}
</Layout>
);
};
export default Index | the_stack |
import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces');
import compatBase = require("././GalleryCompatHttpClientBase");
import GalleryInterfaces = require("./interfaces/GalleryInterfaces");
export interface IGalleryApi extends compatBase.GalleryCompatHttpClientBase {
shareExtensionById(extensionId: string, accountName: string): Promise<void>;
unshareExtensionById(extensionId: string, accountName: string): Promise<void>;
shareExtension(publisherName: string, extensionName: string, accountName: string): Promise<void>;
unshareExtension(publisherName: string, extensionName: string, accountName: string): Promise<void>;
getAcquisitionOptions(itemId: string, installationTarget: string, testCommerce?: boolean, isFreeOrTrialInstall?: boolean): Promise<GalleryInterfaces.AcquisitionOptions>;
requestAcquisition(acquisitionRequest: GalleryInterfaces.ExtensionAcquisitionRequest): Promise<GalleryInterfaces.ExtensionAcquisitionRequest>;
getAssetByName(customHeaders: any, publisherName: string, extensionName: string, version: string, assetType: string, accountToken?: string, acceptDefault?: boolean, accountTokenHeader?: String): Promise<NodeJS.ReadableStream>;
getAsset(customHeaders: any, extensionId: string, version: string, assetType: string, accountToken?: string, acceptDefault?: boolean, accountTokenHeader?: String): Promise<NodeJS.ReadableStream>;
getAssetAuthenticated(customHeaders: any, publisherName: string, extensionName: string, version: string, assetType: string, accountToken?: string, accountTokenHeader?: String): Promise<NodeJS.ReadableStream>;
associateAzurePublisher(publisherName: string, azurePublisherId: string): Promise<GalleryInterfaces.AzurePublisher>;
queryAssociatedAzurePublisher(publisherName: string): Promise<GalleryInterfaces.AzurePublisher>;
getCategories(languages?: string): Promise<string[]>;
getCategoryDetails(categoryName: string, languages?: string, product?: string): Promise<GalleryInterfaces.CategoriesResult>;
getCategoryTree(product: string, categoryId: string, lcid?: number, source?: string, productVersion?: string, skus?: string, subSkus?: string): Promise<GalleryInterfaces.ProductCategory>;
getRootCategories(product: string, lcid?: number, source?: string, productVersion?: string, skus?: string, subSkus?: string): Promise<GalleryInterfaces.ProductCategoriesResult>;
getCertificate(publisherName: string, extensionName: string, version?: string): Promise<NodeJS.ReadableStream>;
getContentVerificationLog(publisherName: string, extensionName: string): Promise<NodeJS.ReadableStream>;
createDraftForEditExtension(publisherName: string, extensionName: string): Promise<GalleryInterfaces.ExtensionDraft>;
performEditExtensionDraftOperation(draftPatch: GalleryInterfaces.ExtensionDraftPatch, publisherName: string, extensionName: string, draftId: string): Promise<GalleryInterfaces.ExtensionDraft>;
updatePayloadInDraftForEditExtension(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, extensionName: string, draftId: string, fileName?: String): Promise<GalleryInterfaces.ExtensionDraft>;
addAssetForEditExtensionDraft(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, extensionName: string, draftId: string, assetType: string): Promise<GalleryInterfaces.ExtensionDraftAsset>;
createDraftForNewExtension(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, product: String, fileName?: String): Promise<GalleryInterfaces.ExtensionDraft>;
performNewExtensionDraftOperation(draftPatch: GalleryInterfaces.ExtensionDraftPatch, publisherName: string, draftId: string): Promise<GalleryInterfaces.ExtensionDraft>;
updatePayloadInDraftForNewExtension(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, draftId: string, fileName?: String): Promise<GalleryInterfaces.ExtensionDraft>;
addAssetForNewExtensionDraft(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, draftId: string, assetType: string): Promise<GalleryInterfaces.ExtensionDraftAsset>;
getAssetFromEditExtensionDraft(publisherName: string, draftId: string, assetType: string, extensionName: string): Promise<NodeJS.ReadableStream>;
getAssetFromNewExtensionDraft(publisherName: string, draftId: string, assetType: string): Promise<NodeJS.ReadableStream>;
getExtensionEvents(publisherName: string, extensionName: string, count?: number, afterDate?: Date, include?: string, includeProperty?: string): Promise<GalleryInterfaces.ExtensionEvents>;
publishExtensionEvents(extensionEvents: GalleryInterfaces.ExtensionEvents[]): Promise<void>;
queryExtensions(customHeaders: any, extensionQuery: GalleryInterfaces.ExtensionQuery, accountToken?: string, accountTokenHeader?: String): Promise<GalleryInterfaces.ExtensionQueryResult>;
createExtension(customHeaders: any, contentStream: NodeJS.ReadableStream): Promise<GalleryInterfaces.PublishedExtension>;
deleteExtensionById(extensionId: string, version?: string): Promise<void>;
getExtensionById(extensionId: string, version?: string, flags?: GalleryInterfaces.ExtensionQueryFlags): Promise<GalleryInterfaces.PublishedExtension>;
updateExtensionById(extensionId: string): Promise<GalleryInterfaces.PublishedExtension>;
createExtensionWithPublisher(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string): Promise<GalleryInterfaces.PublishedExtension>;
deleteExtension(publisherName: string, extensionName: string, version?: string): Promise<void>;
getExtension(customHeaders: any, publisherName: string, extensionName: string, version?: string, flags?: GalleryInterfaces.ExtensionQueryFlags, accountToken?: string, accountTokenHeader?: String): Promise<GalleryInterfaces.PublishedExtension>;
updateExtension(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, extensionName: string, bypassScopeCheck?: boolean): Promise<GalleryInterfaces.PublishedExtension>;
updateExtensionProperties(publisherName: string, extensionName: string, flags: GalleryInterfaces.PublishedExtensionFlags): Promise<GalleryInterfaces.PublishedExtension>;
shareExtensionWithHost(publisherName: string, extensionName: string, hostType: string, hostName: string): Promise<void>;
unshareExtensionWithHost(publisherName: string, extensionName: string, hostType: string, hostName: string): Promise<void>;
extensionValidator(azureRestApiRequestModel: GalleryInterfaces.AzureRestApiRequestModel): Promise<void>;
sendNotifications(notificationData: GalleryInterfaces.NotificationsData): Promise<void>;
getPackage(customHeaders: any, publisherName: string, extensionName: string, version: string, accountToken?: string, acceptDefault?: boolean, accountTokenHeader?: String): Promise<NodeJS.ReadableStream>;
getAssetWithToken(customHeaders: any, publisherName: string, extensionName: string, version: string, assetType: string, assetToken?: string, accountToken?: string, acceptDefault?: boolean, accountTokenHeader?: String): Promise<NodeJS.ReadableStream>;
deletePublisherAsset(publisherName: string, assetType?: string): Promise<void>;
getPublisherAsset(publisherName: string, assetType?: string): Promise<NodeJS.ReadableStream>;
updatePublisherAsset(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, assetType?: string, fileName?: String): Promise<{
[key: string]: string;
}>;
queryPublishers(publisherQuery: GalleryInterfaces.PublisherQuery): Promise<GalleryInterfaces.PublisherQueryResult>;
createPublisher(publisher: GalleryInterfaces.Publisher): Promise<GalleryInterfaces.Publisher>;
deletePublisher(publisherName: string): Promise<void>;
getPublisher(publisherName: string, flags?: number): Promise<GalleryInterfaces.Publisher>;
updatePublisher(publisher: GalleryInterfaces.Publisher, publisherName: string): Promise<GalleryInterfaces.Publisher>;
getQuestions(publisherName: string, extensionName: string, count?: number, page?: number, afterDate?: Date): Promise<GalleryInterfaces.QuestionsResult>;
reportQuestion(concern: GalleryInterfaces.Concern, pubName: string, extName: string, questionId: number): Promise<GalleryInterfaces.Concern>;
createQuestion(question: GalleryInterfaces.Question, publisherName: string, extensionName: string): Promise<GalleryInterfaces.Question>;
deleteQuestion(publisherName: string, extensionName: string, questionId: number): Promise<void>;
updateQuestion(question: GalleryInterfaces.Question, publisherName: string, extensionName: string, questionId: number): Promise<GalleryInterfaces.Question>;
createResponse(response: GalleryInterfaces.Response, publisherName: string, extensionName: string, questionId: number): Promise<GalleryInterfaces.Response>;
deleteResponse(publisherName: string, extensionName: string, questionId: number, responseId: number): Promise<void>;
updateResponse(response: GalleryInterfaces.Response, publisherName: string, extensionName: string, questionId: number, responseId: number): Promise<GalleryInterfaces.Response>;
getExtensionReports(publisherName: string, extensionName: string, days?: number, count?: number, afterDate?: Date): Promise<any>;
getReviews(publisherName: string, extensionName: string, count?: number, filterOptions?: GalleryInterfaces.ReviewFilterOptions, beforeDate?: Date, afterDate?: Date): Promise<GalleryInterfaces.ReviewsResult>;
getReviewsSummary(pubName: string, extName: string, beforeDate?: Date, afterDate?: Date): Promise<GalleryInterfaces.ReviewSummary>;
createReview(review: GalleryInterfaces.Review, pubName: string, extName: string): Promise<GalleryInterfaces.Review>;
deleteReview(pubName: string, extName: string, reviewId: number): Promise<void>;
updateReview(reviewPatch: GalleryInterfaces.ReviewPatch, pubName: string, extName: string, reviewId: number): Promise<GalleryInterfaces.ReviewPatch>;
createCategory(category: GalleryInterfaces.ExtensionCategory): Promise<GalleryInterfaces.ExtensionCategory>;
getGalleryUserSettings(userScope: string, key?: string): Promise<{
[key: string]: any;
}>;
setGalleryUserSettings(entries: {
[key: string]: any;
}, userScope: string): Promise<void>;
generateKey(keyType: string, expireCurrentSeconds?: number): Promise<void>;
getSigningKey(keyType: string): Promise<string>;
updateExtensionStatistics(extensionStatisticsUpdate: GalleryInterfaces.ExtensionStatisticUpdate, publisherName: string, extensionName: string): Promise<void>;
getExtensionDailyStats(publisherName: string, extensionName: string, days?: number, aggregate?: GalleryInterfaces.ExtensionStatsAggregateType, afterDate?: Date): Promise<GalleryInterfaces.ExtensionDailyStats>;
getExtensionDailyStatsAnonymous(publisherName: string, extensionName: string, version: string): Promise<GalleryInterfaces.ExtensionDailyStats>;
incrementExtensionDailyStat(publisherName: string, extensionName: string, version: string, statType: string): Promise<void>;
getVerificationLog(publisherName: string, extensionName: string, version: string): Promise<NodeJS.ReadableStream>;
}
export declare class GalleryApi extends compatBase.GalleryCompatHttpClientBase implements IGalleryApi {
constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions);
static readonly RESOURCE_AREA_ID: string;
/**
* @param {string} extensionId
* @param {string} accountName
*/
shareExtensionById(extensionId: string, accountName: string): Promise<void>;
/**
* @param {string} extensionId
* @param {string} accountName
*/
unshareExtensionById(extensionId: string, accountName: string): Promise<void>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} accountName
*/
shareExtension(publisherName: string, extensionName: string, accountName: string): Promise<void>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} accountName
*/
unshareExtension(publisherName: string, extensionName: string, accountName: string): Promise<void>;
/**
* @param {string} itemId
* @param {string} installationTarget
* @param {boolean} testCommerce
* @param {boolean} isFreeOrTrialInstall
*/
getAcquisitionOptions(itemId: string, installationTarget: string, testCommerce?: boolean, isFreeOrTrialInstall?: boolean): Promise<GalleryInterfaces.AcquisitionOptions>;
/**
* @param {GalleryInterfaces.ExtensionAcquisitionRequest} acquisitionRequest
*/
requestAcquisition(acquisitionRequest: GalleryInterfaces.ExtensionAcquisitionRequest): Promise<GalleryInterfaces.ExtensionAcquisitionRequest>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} version
* @param {string} assetType
* @param {string} accountToken
* @param {boolean} acceptDefault
* @param {String} accountTokenHeader - Header to pass the account token
*/
getAssetByName(customHeaders: any, publisherName: string, extensionName: string, version: string, assetType: string, accountToken?: string, acceptDefault?: boolean, accountTokenHeader?: String): Promise<NodeJS.ReadableStream>;
/**
* @param {string} extensionId
* @param {string} version
* @param {string} assetType
* @param {string} accountToken
* @param {boolean} acceptDefault
* @param {String} accountTokenHeader - Header to pass the account token
*/
getAsset(customHeaders: any, extensionId: string, version: string, assetType: string, accountToken?: string, acceptDefault?: boolean, accountTokenHeader?: String): Promise<NodeJS.ReadableStream>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} version
* @param {string} assetType
* @param {string} accountToken
* @param {String} accountTokenHeader - Header to pass the account token
*/
getAssetAuthenticated(customHeaders: any, publisherName: string, extensionName: string, version: string, assetType: string, accountToken?: string, accountTokenHeader?: String): Promise<NodeJS.ReadableStream>;
/**
* @param {string} publisherName
* @param {string} azurePublisherId
*/
associateAzurePublisher(publisherName: string, azurePublisherId: string): Promise<GalleryInterfaces.AzurePublisher>;
/**
* @param {string} publisherName
*/
queryAssociatedAzurePublisher(publisherName: string): Promise<GalleryInterfaces.AzurePublisher>;
/**
* @param {string} languages
*/
getCategories(languages?: string): Promise<string[]>;
/**
* @param {string} categoryName
* @param {string} languages
* @param {string} product
*/
getCategoryDetails(categoryName: string, languages?: string, product?: string): Promise<GalleryInterfaces.CategoriesResult>;
/**
* @param {string} product
* @param {string} categoryId
* @param {number} lcid
* @param {string} source
* @param {string} productVersion
* @param {string} skus
* @param {string} subSkus
*/
getCategoryTree(product: string, categoryId: string, lcid?: number, source?: string, productVersion?: string, skus?: string, subSkus?: string): Promise<GalleryInterfaces.ProductCategory>;
/**
* @param {string} product
* @param {number} lcid
* @param {string} source
* @param {string} productVersion
* @param {string} skus
* @param {string} subSkus
*/
getRootCategories(product: string, lcid?: number, source?: string, productVersion?: string, skus?: string, subSkus?: string): Promise<GalleryInterfaces.ProductCategoriesResult>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} version
*/
getCertificate(publisherName: string, extensionName: string, version?: string): Promise<NodeJS.ReadableStream>;
/**
* @param {string} publisherName
* @param {string} extensionName
*/
getContentVerificationLog(publisherName: string, extensionName: string): Promise<NodeJS.ReadableStream>;
/**
* @param {string} publisherName
* @param {string} extensionName
*/
createDraftForEditExtension(publisherName: string, extensionName: string): Promise<GalleryInterfaces.ExtensionDraft>;
/**
* @param {GalleryInterfaces.ExtensionDraftPatch} draftPatch
* @param {string} publisherName
* @param {string} extensionName
* @param {string} draftId
*/
performEditExtensionDraftOperation(draftPatch: GalleryInterfaces.ExtensionDraftPatch, publisherName: string, extensionName: string, draftId: string): Promise<GalleryInterfaces.ExtensionDraft>;
/**
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} publisherName
* @param {string} extensionName
* @param {string} draftId
* @param {String} fileName - Header to pass the filename of the uploaded data
*/
updatePayloadInDraftForEditExtension(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, extensionName: string, draftId: string, fileName?: String): Promise<GalleryInterfaces.ExtensionDraft>;
/**
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} publisherName
* @param {string} extensionName
* @param {string} draftId
* @param {string} assetType
*/
addAssetForEditExtensionDraft(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, extensionName: string, draftId: string, assetType: string): Promise<GalleryInterfaces.ExtensionDraftAsset>;
/**
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} publisherName
* @param {String} product - Header to pass the product type of the payload file
* @param {String} fileName - Header to pass the filename of the uploaded data
*/
createDraftForNewExtension(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, product: String, fileName?: String): Promise<GalleryInterfaces.ExtensionDraft>;
/**
* @param {GalleryInterfaces.ExtensionDraftPatch} draftPatch
* @param {string} publisherName
* @param {string} draftId
*/
performNewExtensionDraftOperation(draftPatch: GalleryInterfaces.ExtensionDraftPatch, publisherName: string, draftId: string): Promise<GalleryInterfaces.ExtensionDraft>;
/**
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} publisherName
* @param {string} draftId
* @param {String} fileName - Header to pass the filename of the uploaded data
*/
updatePayloadInDraftForNewExtension(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, draftId: string, fileName?: String): Promise<GalleryInterfaces.ExtensionDraft>;
/**
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} publisherName
* @param {string} draftId
* @param {string} assetType
*/
addAssetForNewExtensionDraft(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, draftId: string, assetType: string): Promise<GalleryInterfaces.ExtensionDraftAsset>;
/**
* @param {string} publisherName
* @param {string} draftId
* @param {string} assetType
* @param {string} extensionName
*/
getAssetFromEditExtensionDraft(publisherName: string, draftId: string, assetType: string, extensionName: string): Promise<NodeJS.ReadableStream>;
/**
* @param {string} publisherName
* @param {string} draftId
* @param {string} assetType
*/
getAssetFromNewExtensionDraft(publisherName: string, draftId: string, assetType: string): Promise<NodeJS.ReadableStream>;
/**
* Get install/uninstall events of an extension. If both count and afterDate parameters are specified, count takes precedence.
*
* @param {string} publisherName - Name of the publisher
* @param {string} extensionName - Name of the extension
* @param {number} count - Count of events to fetch, applies to each event type.
* @param {Date} afterDate - Fetch events that occurred on or after this date
* @param {string} include - Filter options. Supported values: install, uninstall, review, acquisition, sales. Default is to fetch all types of events
* @param {string} includeProperty - Event properties to include. Currently only 'lastContactDetails' is supported for uninstall events
*/
getExtensionEvents(publisherName: string, extensionName: string, count?: number, afterDate?: Date, include?: string, includeProperty?: string): Promise<GalleryInterfaces.ExtensionEvents>;
/**
* API endpoint to publish extension install/uninstall events. This is meant to be invoked by EMS only for sending us data related to install/uninstall of an extension.
*
* @param {GalleryInterfaces.ExtensionEvents[]} extensionEvents
*/
publishExtensionEvents(extensionEvents: GalleryInterfaces.ExtensionEvents[]): Promise<void>;
/**
* @param {GalleryInterfaces.ExtensionQuery} extensionQuery
* @param {string} accountToken
* @param {String} accountTokenHeader - Header to pass the account token
*/
queryExtensions(customHeaders: any, extensionQuery: GalleryInterfaces.ExtensionQuery, accountToken?: string, accountTokenHeader?: String): Promise<GalleryInterfaces.ExtensionQueryResult>;
/**
* @param {NodeJS.ReadableStream} contentStream - Content to upload
*/
createExtension(customHeaders: any, contentStream: NodeJS.ReadableStream): Promise<GalleryInterfaces.PublishedExtension>;
/**
* @param {string} extensionId
* @param {string} version
*/
deleteExtensionById(extensionId: string, version?: string): Promise<void>;
/**
* @param {string} extensionId
* @param {string} version
* @param {GalleryInterfaces.ExtensionQueryFlags} flags
*/
getExtensionById(extensionId: string, version?: string, flags?: GalleryInterfaces.ExtensionQueryFlags): Promise<GalleryInterfaces.PublishedExtension>;
/**
* @param {string} extensionId
*/
updateExtensionById(extensionId: string): Promise<GalleryInterfaces.PublishedExtension>;
/**
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} publisherName
*/
createExtensionWithPublisher(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string): Promise<GalleryInterfaces.PublishedExtension>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} version
*/
deleteExtension(publisherName: string, extensionName: string, version?: string): Promise<void>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} version
* @param {GalleryInterfaces.ExtensionQueryFlags} flags
* @param {string} accountToken
* @param {String} accountTokenHeader - Header to pass the account token
*/
getExtension(customHeaders: any, publisherName: string, extensionName: string, version?: string, flags?: GalleryInterfaces.ExtensionQueryFlags, accountToken?: string, accountTokenHeader?: String): Promise<GalleryInterfaces.PublishedExtension>;
/**
* REST endpoint to update an extension.
*
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} publisherName - Name of the publisher
* @param {string} extensionName - Name of the extension
* @param {boolean} bypassScopeCheck - This parameter decides if the scope change check needs to be invoked or not
*/
updateExtension(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, extensionName: string, bypassScopeCheck?: boolean): Promise<GalleryInterfaces.PublishedExtension>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {GalleryInterfaces.PublishedExtensionFlags} flags
*/
updateExtensionProperties(publisherName: string, extensionName: string, flags: GalleryInterfaces.PublishedExtensionFlags): Promise<GalleryInterfaces.PublishedExtension>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} hostType
* @param {string} hostName
*/
shareExtensionWithHost(publisherName: string, extensionName: string, hostType: string, hostName: string): Promise<void>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} hostType
* @param {string} hostName
*/
unshareExtensionWithHost(publisherName: string, extensionName: string, hostType: string, hostName: string): Promise<void>;
/**
* @param {GalleryInterfaces.AzureRestApiRequestModel} azureRestApiRequestModel
*/
extensionValidator(azureRestApiRequestModel: GalleryInterfaces.AzureRestApiRequestModel): Promise<void>;
/**
* Send Notification
*
* @param {GalleryInterfaces.NotificationsData} notificationData - Denoting the data needed to send notification
*/
sendNotifications(notificationData: GalleryInterfaces.NotificationsData): Promise<void>;
/**
* This endpoint gets hit when you download a VSTS extension from the Web UI
*
* @param {string} publisherName
* @param {string} extensionName
* @param {string} version
* @param {string} accountToken
* @param {boolean} acceptDefault
* @param {String} accountTokenHeader - Header to pass the account token
*/
getPackage(customHeaders: any, publisherName: string, extensionName: string, version: string, accountToken?: string, acceptDefault?: boolean, accountTokenHeader?: String): Promise<NodeJS.ReadableStream>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} version
* @param {string} assetType
* @param {string} assetToken
* @param {string} accountToken
* @param {boolean} acceptDefault
* @param {String} accountTokenHeader - Header to pass the account token
*/
getAssetWithToken(customHeaders: any, publisherName: string, extensionName: string, version: string, assetType: string, assetToken?: string, accountToken?: string, acceptDefault?: boolean, accountTokenHeader?: String): Promise<NodeJS.ReadableStream>;
/**
* Delete publisher asset like logo
*
* @param {string} publisherName - Internal name of the publisher
* @param {string} assetType - Type of asset. Default value is 'logo'.
*/
deletePublisherAsset(publisherName: string, assetType?: string): Promise<void>;
/**
* Get publisher asset like logo as a stream
*
* @param {string} publisherName - Internal name of the publisher
* @param {string} assetType - Type of asset. Default value is 'logo'.
*/
getPublisherAsset(publisherName: string, assetType?: string): Promise<NodeJS.ReadableStream>;
/**
* Update publisher asset like logo. It accepts asset file as an octet stream and file name is passed in header values.
*
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} publisherName - Internal name of the publisher
* @param {string} assetType - Type of asset. Default value is 'logo'.
* @param {String} fileName - Header to pass the filename of the uploaded data
*/
updatePublisherAsset(customHeaders: any, contentStream: NodeJS.ReadableStream, publisherName: string, assetType?: string, fileName?: String): Promise<{
[key: string]: string;
}>;
/**
* @param {GalleryInterfaces.PublisherQuery} publisherQuery
*/
queryPublishers(publisherQuery: GalleryInterfaces.PublisherQuery): Promise<GalleryInterfaces.PublisherQueryResult>;
/**
* @param {GalleryInterfaces.Publisher} publisher
*/
createPublisher(publisher: GalleryInterfaces.Publisher): Promise<GalleryInterfaces.Publisher>;
/**
* @param {string} publisherName
*/
deletePublisher(publisherName: string): Promise<void>;
/**
* @param {string} publisherName
* @param {number} flags
*/
getPublisher(publisherName: string, flags?: number): Promise<GalleryInterfaces.Publisher>;
/**
* @param {GalleryInterfaces.Publisher} publisher
* @param {string} publisherName
*/
updatePublisher(publisher: GalleryInterfaces.Publisher, publisherName: string): Promise<GalleryInterfaces.Publisher>;
/**
* Returns a list of questions with their responses associated with an extension.
*
* @param {string} publisherName - Name of the publisher who published the extension.
* @param {string} extensionName - Name of the extension.
* @param {number} count - Number of questions to retrieve (defaults to 10).
* @param {number} page - Page number from which set of questions are to be retrieved.
* @param {Date} afterDate - If provided, results questions are returned which were posted after this date
*/
getQuestions(publisherName: string, extensionName: string, count?: number, page?: number, afterDate?: Date): Promise<GalleryInterfaces.QuestionsResult>;
/**
* Flags a concern with an existing question for an extension.
*
* @param {GalleryInterfaces.Concern} concern - User reported concern with a question for the extension.
* @param {string} pubName - Name of the publisher who published the extension.
* @param {string} extName - Name of the extension.
* @param {number} questionId - Identifier of the question to be updated for the extension.
*/
reportQuestion(concern: GalleryInterfaces.Concern, pubName: string, extName: string, questionId: number): Promise<GalleryInterfaces.Concern>;
/**
* Creates a new question for an extension.
*
* @param {GalleryInterfaces.Question} question - Question to be created for the extension.
* @param {string} publisherName - Name of the publisher who published the extension.
* @param {string} extensionName - Name of the extension.
*/
createQuestion(question: GalleryInterfaces.Question, publisherName: string, extensionName: string): Promise<GalleryInterfaces.Question>;
/**
* Deletes an existing question and all its associated responses for an extension. (soft delete)
*
* @param {string} publisherName - Name of the publisher who published the extension.
* @param {string} extensionName - Name of the extension.
* @param {number} questionId - Identifier of the question to be deleted for the extension.
*/
deleteQuestion(publisherName: string, extensionName: string, questionId: number): Promise<void>;
/**
* Updates an existing question for an extension.
*
* @param {GalleryInterfaces.Question} question - Updated question to be set for the extension.
* @param {string} publisherName - Name of the publisher who published the extension.
* @param {string} extensionName - Name of the extension.
* @param {number} questionId - Identifier of the question to be updated for the extension.
*/
updateQuestion(question: GalleryInterfaces.Question, publisherName: string, extensionName: string, questionId: number): Promise<GalleryInterfaces.Question>;
/**
* Creates a new response for a given question for an extension.
*
* @param {GalleryInterfaces.Response} response - Response to be created for the extension.
* @param {string} publisherName - Name of the publisher who published the extension.
* @param {string} extensionName - Name of the extension.
* @param {number} questionId - Identifier of the question for which response is to be created for the extension.
*/
createResponse(response: GalleryInterfaces.Response, publisherName: string, extensionName: string, questionId: number): Promise<GalleryInterfaces.Response>;
/**
* Deletes a response for an extension. (soft delete)
*
* @param {string} publisherName - Name of the publisher who published the extension.
* @param {string} extensionName - Name of the extension.
* @param {number} questionId - Identifies the question whose response is to be deleted.
* @param {number} responseId - Identifies the response to be deleted.
*/
deleteResponse(publisherName: string, extensionName: string, questionId: number, responseId: number): Promise<void>;
/**
* Updates an existing response for a given question for an extension.
*
* @param {GalleryInterfaces.Response} response - Updated response to be set for the extension.
* @param {string} publisherName - Name of the publisher who published the extension.
* @param {string} extensionName - Name of the extension.
* @param {number} questionId - Identifier of the question for which response is to be updated for the extension.
* @param {number} responseId - Identifier of the response which has to be updated.
*/
updateResponse(response: GalleryInterfaces.Response, publisherName: string, extensionName: string, questionId: number, responseId: number): Promise<GalleryInterfaces.Response>;
/**
* Returns extension reports
*
* @param {string} publisherName - Name of the publisher who published the extension
* @param {string} extensionName - Name of the extension
* @param {number} days - Last n days report. If afterDate and days are specified, days will take priority
* @param {number} count - Number of events to be returned
* @param {Date} afterDate - Use if you want to fetch events newer than the specified date
*/
getExtensionReports(publisherName: string, extensionName: string, days?: number, count?: number, afterDate?: Date): Promise<any>;
/**
* Returns a list of reviews associated with an extension
*
* @param {string} publisherName - Name of the publisher who published the extension
* @param {string} extensionName - Name of the extension
* @param {number} count - Number of reviews to retrieve (defaults to 5)
* @param {GalleryInterfaces.ReviewFilterOptions} filterOptions - FilterOptions to filter out empty reviews etcetera, defaults to none
* @param {Date} beforeDate - Use if you want to fetch reviews older than the specified date, defaults to null
* @param {Date} afterDate - Use if you want to fetch reviews newer than the specified date, defaults to null
*/
getReviews(publisherName: string, extensionName: string, count?: number, filterOptions?: GalleryInterfaces.ReviewFilterOptions, beforeDate?: Date, afterDate?: Date): Promise<GalleryInterfaces.ReviewsResult>;
/**
* Returns a summary of the reviews
*
* @param {string} pubName - Name of the publisher who published the extension
* @param {string} extName - Name of the extension
* @param {Date} beforeDate - Use if you want to fetch summary of reviews older than the specified date, defaults to null
* @param {Date} afterDate - Use if you want to fetch summary of reviews newer than the specified date, defaults to null
*/
getReviewsSummary(pubName: string, extName: string, beforeDate?: Date, afterDate?: Date): Promise<GalleryInterfaces.ReviewSummary>;
/**
* Creates a new review for an extension
*
* @param {GalleryInterfaces.Review} review - Review to be created for the extension
* @param {string} pubName - Name of the publisher who published the extension
* @param {string} extName - Name of the extension
*/
createReview(review: GalleryInterfaces.Review, pubName: string, extName: string): Promise<GalleryInterfaces.Review>;
/**
* Deletes a review
*
* @param {string} pubName - Name of the pubilsher who published the extension
* @param {string} extName - Name of the extension
* @param {number} reviewId - Id of the review which needs to be updated
*/
deleteReview(pubName: string, extName: string, reviewId: number): Promise<void>;
/**
* Updates or Flags a review
*
* @param {GalleryInterfaces.ReviewPatch} reviewPatch - ReviewPatch object which contains the changes to be applied to the review
* @param {string} pubName - Name of the pubilsher who published the extension
* @param {string} extName - Name of the extension
* @param {number} reviewId - Id of the review which needs to be updated
*/
updateReview(reviewPatch: GalleryInterfaces.ReviewPatch, pubName: string, extName: string, reviewId: number): Promise<GalleryInterfaces.ReviewPatch>;
/**
* @param {GalleryInterfaces.ExtensionCategory} category
*/
createCategory(category: GalleryInterfaces.ExtensionCategory): Promise<GalleryInterfaces.ExtensionCategory>;
/**
* Get all setting entries for the given user/all-users scope
*
* @param {string} userScope - User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
* @param {string} key - Optional key under which to filter all the entries
*/
getGalleryUserSettings(userScope: string, key?: string): Promise<{
[key: string]: any;
}>;
/**
* Set all setting entries for the given user/all-users scope
*
* @param {{ [key: string] : any; }} entries - A key-value pair of all settings that need to be set
* @param {string} userScope - User-Scope at which to get the value. Should be "me" for the current user or "host" for all users.
*/
setGalleryUserSettings(entries: {
[key: string]: any;
}, userScope: string): Promise<void>;
/**
* @param {string} keyType
* @param {number} expireCurrentSeconds
*/
generateKey(keyType: string, expireCurrentSeconds?: number): Promise<void>;
/**
* @param {string} keyType
*/
getSigningKey(keyType: string): Promise<string>;
/**
* @param {GalleryInterfaces.ExtensionStatisticUpdate} extensionStatisticsUpdate
* @param {string} publisherName
* @param {string} extensionName
*/
updateExtensionStatistics(extensionStatisticsUpdate: GalleryInterfaces.ExtensionStatisticUpdate, publisherName: string, extensionName: string): Promise<void>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {number} days
* @param {GalleryInterfaces.ExtensionStatsAggregateType} aggregate
* @param {Date} afterDate
*/
getExtensionDailyStats(publisherName: string, extensionName: string, days?: number, aggregate?: GalleryInterfaces.ExtensionStatsAggregateType, afterDate?: Date): Promise<GalleryInterfaces.ExtensionDailyStats>;
/**
* This route/location id only supports HTTP POST anonymously, so that the page view daily stat can be incremented from Marketplace client. Trying to call GET on this route should result in an exception. Without this explicit implementation, calling GET on this public route invokes the above GET implementation GetExtensionDailyStats.
*
* @param {string} publisherName - Name of the publisher
* @param {string} extensionName - Name of the extension
* @param {string} version - Version of the extension
*/
getExtensionDailyStatsAnonymous(publisherName: string, extensionName: string, version: string): Promise<GalleryInterfaces.ExtensionDailyStats>;
/**
* Increments a daily statistic associated with the extension
*
* @param {string} publisherName - Name of the publisher
* @param {string} extensionName - Name of the extension
* @param {string} version - Version of the extension
* @param {string} statType - Type of stat to increment
*/
incrementExtensionDailyStat(publisherName: string, extensionName: string, version: string, statType: string): Promise<void>;
/**
* @param {string} publisherName
* @param {string} extensionName
* @param {string} version
*/
getVerificationLog(publisherName: string, extensionName: string, version: string): Promise<NodeJS.ReadableStream>;
} | the_stack |
import * as tstl from "../../src";
import { forbiddenForIn, unsupportedForTarget } from "../../src/transformation/utils/diagnostics";
import * as util from "../util";
test("while", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3];
let i = 0;
while (i < arrTest.length) {
arrTest[i] = arrTest[i] + 1;
i++;
}
return arrTest;
`.expectToMatchJsResult();
});
test("while with continue", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3, 4];
let i = 0;
while (i < arrTest.length) {
if (i % 2 == 0) {
i++;
continue;
}
let j = 2;
while (j > 0) {
if (j == 2) {
j--
continue;
}
arrTest[i] = j;
j--;
}
i++;
}
return arrTest;
`.expectToMatchJsResult();
});
test("dowhile with continue", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3, 4];
let i = 0;
do {
if (i % 2 == 0) {
i++;
continue;
}
let j = 2;
do {
if (j == 2) {
j--
continue;
}
arrTest[i] = j;
j--;
} while (j > 0)
i++;
} while (i < arrTest.length)
return arrTest;
`.expectToMatchJsResult();
});
test("for", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3];
for (let i = 0; i < arrTest.length; ++i) {
arrTest[i] = arrTest[i] + 1;
}
return arrTest;
`.expectToMatchJsResult();
});
test("for with expression", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3];
let i: number;
for (i = 0 * 1; i < arrTest.length; ++i) {
arrTest[i] = arrTest[i] + 1;
}
return arrTest;
`.expectToMatchJsResult();
});
test("for with continue", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3, 4];
for (let i = 0; i < arrTest.length; i++) {
if (i % 2 == 0) {
continue;
}
for (let j = 0; j < 2; j++) {
if (j == 1) {
continue;
}
arrTest[i] = j;
}
}
return arrTest;
`.expectToMatchJsResult();
});
test("forMirror", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3];
for (let i = 0; arrTest.length > i; i++) {
arrTest[i] = arrTest[i] + 1;
}
return arrTest;
`.expectToMatchJsResult();
});
test("forBreak", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3];
for (let i = 0; i < arrTest.length; ++i) {
break;
arrTest[i] = arrTest[i] + 1;
}
return arrTest;
`.expectToMatchJsResult();
});
test("forNoDeclarations", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3];
let i = 0;
for (; i < arrTest.length; ++i) {
arrTest[i] = arrTest[i] + 1;
}
return arrTest;
`.expectToMatchJsResult();
});
test("forNoCondition", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3];
let i = 0;
for (;; ++i) {
if (i >= arrTest.length) {
break;
}
arrTest[i] = arrTest[i] + 1;
}
return arrTest;
`.expectToMatchJsResult();
});
test("forNoPostExpression", () => {
util.testFunction`
let arrTest = [0, 1, 2, 3];
let i = 0;
for (;;) {
if (i >= arrTest.length) {
break;
}
arrTest[i] = arrTest[i] + 1;
i++;
}
return arrTest;
`.expectToMatchJsResult();
});
test.each([
{ inp: [0, 1, 2, 3], header: "let i = 0; i < arrTest.length; i++" },
{ inp: [0, 1, 2, 3], header: "let i = 0; i <= arrTest.length - 1; i++" },
{ inp: [0, 1, 2, 3], header: "let i = 0; arrTest.length > i; i++" },
{ inp: [0, 1, 2, 3], header: "let i = 0; arrTest.length - 1 >= i; i++" },
{ inp: [0, 1, 2, 3], header: "let i = 0; i < arrTest.length; i += 2" },
{ inp: [0, 1, 2, 3], header: "let i = arrTest.length - 1; i >= 0; i--" },
{ inp: [0, 1, 2, 3], header: "let i = arrTest.length - 1; i >= 0; i -= 2" },
{ inp: [0, 1, 2, 3], header: "let i = arrTest.length - 1; i > 0; i -= 2" },
])("forheader (%p)", ({ inp, header }) => {
util.testFunction`
let arrTest = ${util.formatCode(inp)};
for (${header}) {
arrTest[i] = arrTest[i] + 1;
}
return arrTest;
`.expectToMatchJsResult();
});
test("for scope", () => {
util.testFunction`
let i = 42;
for (let i = 0; i < 10; ++i) {}
return i;
`.expectToMatchJsResult();
});
test.each([
{
inp: { test1: 0, test2: 1, test3: 2 },
},
])("forin[Object] (%p)", ({ inp }) => {
util.testFunctionTemplate`
let objTest = ${inp};
for (let key in objTest) {
objTest[key] = objTest[key] + 1;
}
return objTest;
`.expectToMatchJsResult();
});
test("forin[Array]", () => {
util.testFunction`
const array = [];
for (const key in array) {}
`.expectDiagnosticsToMatchSnapshot([forbiddenForIn.code]);
});
test.each([{ inp: { a: 0, b: 1, c: 2, d: 3, e: 4 } }])("forin with continue (%p)", ({ inp }) => {
util.testFunctionTemplate`
let obj = ${inp};
for (let i in obj) {
if (obj[i] % 2 == 0) {
continue;
}
obj[i] = 0;
}
return obj;
`.expectToMatchJsResult();
});
test.each([{ inp: [0, 1, 2] }])("forof (%p)", ({ inp }) => {
util.testFunctionTemplate`
let objTest = ${inp};
let arrResultTest = [];
for (let value of objTest) {
arrResultTest.push(value + 1)
}
return arrResultTest;
`.expectToMatchJsResult();
});
test("Tuple loop", () => {
util.testFunction`
const tuple: [number, number, number] = [3,5,1];
let count = 0;
for (const value of tuple) { count += value; }
return count;
`.expectToMatchJsResult();
});
test("forof existing variable", () => {
util.testFunction`
let objTest = [0, 1, 2];
let arrResultTest = [];
let value: number;
for (value of objTest) {
arrResultTest.push(value + 1)
}
return arrResultTest;
`.expectToMatchJsResult();
});
test("forof destructing", () => {
const input = [
[1, 2],
[2, 3],
[3, 4],
];
util.testFunction`
let objTest = ${util.formatCode(input)};
let arrResultTest = [];
for (let [a,b] of objTest) {
arrResultTest.push(a + b)
}
return arrResultTest;
`.expectToMatchJsResult();
});
test("forof destructing scope", () => {
util.testFunction`
let x = 7;
for (let [x] of [[1], [2], [3]]) {
x *= 2;
}
return x;
`.expectToMatchJsResult();
});
// This catches the case where x is falsely seen as globally scoped and the 'local' is stripped out
test("forof destructing scope (global)", () => {
util.testModule`
let x = 7;
for (let [x] of [[1], [2], [3]]) {
x *= 2;
}
if (x !== 7) throw x;
`.expectNoExecutionError();
});
test("forof nested destructing", () => {
util.testFunction`
const obj = { a: [3], b: [5] };
let result = 0;
for(const [k, [v]] of Object.entries(obj)){
result += v;
}
return result;
`.expectToMatchJsResult();
});
test("forof destructing with existing variables", () => {
const input = [
[1, 2],
[2, 3],
[3, 4],
];
util.testFunction`
let objTest = ${util.formatCode(input)};
let arrResultTest = [];
let a: number;
let b: number;
for ([a,b] of objTest) {
arrResultTest.push(a + b)
}
return arrResultTest;
`.expectToMatchJsResult();
});
test("forof with continue", () => {
util.testFunction`
let testArr = [0, 1, 2, 3, 4];
let a = 0;
for (let i of testArr) {
if (i % 2 == 0) {
a++;
continue;
}
for (let j of [0, 1]) {
if (j == 1) {
continue;
}
testArr[a] = j;
}
a++;
}
return testArr;
`.expectToMatchJsResult();
});
test("forof with iterator", () => {
util.testFunction`
const arr = ["a", "b", "c"];
function iter(): IterableIterator<string> {
let i = 0;
return {
[Symbol.iterator]() { return this; },
next() { return {value: arr[i], done: i++ >= arr.length} },
}
}
let result = "";
for (let e of iter()) {
result += e;
}
return result;
`.expectToMatchJsResult();
});
test("forof with iterator and existing variable", () => {
util.testFunction`
const arr = ["a", "b", "c"];
function iter(): IterableIterator<string> {
let i = 0;
return {
[Symbol.iterator]() { return this; },
next() { return {value: arr[i], done: i++ >= arr.length} },
}
}
let result = "";
let e: string;
for (e of iter()) {
result += e;
}
return result;
`.expectToMatchJsResult();
});
test("forof destructuring with iterator", () => {
util.testFunction`
const arr = ["a", "b", "c"];
function iter(): IterableIterator<[string, string]> {
let i = 0;
return {
[Symbol.iterator]() { return this; },
next() { return {value: [i.toString(), arr[i]], done: i++ >= arr.length} },
}
}
let result = "";
for (let [a, b] of iter()) {
result += a + b;
}
return result;
`.expectToMatchJsResult();
});
test("forof destructuring with iterator and existing variables", () => {
util.testFunction`
const arr = ["a", "b", "c"];
function iter(): IterableIterator<[string, string]> {
let i = 0;
return {
[Symbol.iterator]() { return this; },
next() { return {value: [i.toString(), arr[i]], done: i++ >= arr.length} },
}
}
let result = "";
let a: string;
let b: string;
for ([a, b] of iter()) {
result += a + b;
}
return result;
`.expectToMatchJsResult();
});
test("forof array which modifies length", () => {
util.testFunction`
const arr = ["a", "b", "c"];
let result = "";
for (const v of arr) {
if (v === "a") {
arr.push("d");
}
result += v;
}
return result;
`.expectToMatchJsResult();
});
test("forof nested destructuring", () => {
util.testFunction`
let result = 0;
for (const [[x]] of [[[1]]]) {
result = x;
}
return result;
`.expectToMatchJsResult();
});
test("forof with array typed as iterable", () => {
util.testFunction`
function foo(): Iterable<string> {
return ["A", "B", "C"];
}
let result = "";
for (const x of foo()) {
result += x;
}
return result;
`.expectToMatchJsResult();
});
test.each(["", "abc", "a\0c"])("forof string (%p)", string => {
util.testFunctionTemplate`
const results: string[] = [];
for (const x of ${string}) {
results.push(x);
}
return results;
`.expectToMatchJsResult();
});
describe("for...of empty destructuring", () => {
const declareTests = (destructuringPrefix: string) => {
test("array", () => {
util.testFunction`
const arr = [["a"], ["b"], ["c"]];
let i = 0;
for (${destructuringPrefix}[] of arr) {
++i;
}
return i;
`.expectToMatchJsResult();
});
test("iterable", () => {
util.testFunction`
const iter: Iterable<string[]> = [["a"], ["b"], ["c"]];
let i = 0;
for (${destructuringPrefix}[] of iter) {
++i;
}
return i;
`.expectToMatchJsResult();
});
};
describe("declaration", () => {
declareTests("const ");
});
describe("assignment", () => {
declareTests("");
});
});
for (const testCase of [
"while (false) { continue; }",
"do { continue; } while (false)",
"for (;;) { continue; }",
"for (const a in {}) { continue; }",
"for (const a of []) { continue; }",
]) {
const expectContinueGotoLabel: util.TapCallback = builder =>
expect(builder.getMainLuaCodeChunk()).toMatch("::__continue2::");
util.testEachVersion(`loop continue (${testCase})`, () => util.testModule(testCase), {
[tstl.LuaTarget.Universal]: builder => builder.expectDiagnosticsToMatchSnapshot([unsupportedForTarget.code]),
[tstl.LuaTarget.Lua51]: builder => builder.expectDiagnosticsToMatchSnapshot([unsupportedForTarget.code]),
[tstl.LuaTarget.Lua52]: expectContinueGotoLabel,
[tstl.LuaTarget.Lua53]: expectContinueGotoLabel,
[tstl.LuaTarget.Lua54]: expectContinueGotoLabel,
[tstl.LuaTarget.LuaJIT]: expectContinueGotoLabel,
});
}
test("do...while", () => {
util.testFunction`
let result = 0;
do {
++result;
} while (result < 2);
return result;
`.expectToMatchJsResult();
});
test("do...while scoping", () => {
util.testFunction`
let x = 0;
let result = 0;
do {
let x = 1;
++result;
} while (x === 0 && result < 2);
return result;
`.expectToMatchJsResult();
});
test("do...while double-negation", () => {
const builder = util.testFunction`
let result = 0;
do {
++result;
} while (!(result >= 2));
return result;
`.expectToMatchJsResult();
expect(builder.getMainLuaCodeChunk()).not.toMatch("not");
});
test("for...in with pre-defined variable", () => {
const testBuilder = util.testFunction`
const obj = { x: "y", foo: "bar" };
let x = "";
let result = [];
for (x in obj) {
result.push(x);
}
return result;
`;
// Need custom matcher because order is not guaranteed in neither JS nor Lua
expect(testBuilder.getJsExecutionResult()).toEqual(expect.arrayContaining(testBuilder.getLuaExecutionResult()));
});
test("for...in with pre-defined variable keeps last value", () => {
const keyX = "x";
const keyFoo = "foo";
const result = util.testFunction`
const obj = { ${keyX}: "y", ${keyFoo}: "bar" };
let x = "";
for (x in obj) {
}
return x;
`.getLuaExecutionResult();
// Need custom matcher because order is not guaranteed in neither JS nor Lua
expect([keyX, keyFoo]).toContain(result);
}); | the_stack |
import memoize from "fast-memoize";
import { zipWith, reduce, times } from "lodash";
import seedrandom from "seedrandom";
import { Properties } from "types/shape";
import { Color } from "types/value";
seedrandom("secret-seed", { global: true }); // HACK: constant seed for pseudorandomness
/**
* Generate a random float. The maximum is exclusive and the minimum is inclusive
* @param min minimum (inclusive)
* @param max maximum (exclusive)
*/
export const randFloats = (
count: number,
[min, max]: [number, number]
): number[] => times(count, () => randFloat(min, max));
/**
* Generate a random float. The maximum is exclusive and the minimum is inclusive
* @param min minimum (inclusive)
* @param max maximum (exclusive)
*/
export const randFloat = (min: number, max: number): number => {
// TODO: better error reporting
console.assert(
max > min,
"min should be smaller than max for random number generation!"
);
return Math.random() * (max - min) + min;
};
/**
* Generate a random integer. The maximum is exclusive and the minimum is inclusive
* @param min minimum (inclusive)
* @param max maximum (exclusive)
*/
export const randInt = (min: number, max: number) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
};
/**
* Find the Euclidean distance between two points
* @param param0 point 1 [x1, y1]
* @param param1 point 2 [x2, y2]
*/
export const dist = ([x1, y1]: [number, number], [x2, y2]: [number, number]) =>
Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
export const arrowheads = {
"arrowhead-1": {
width: 8,
height: 8,
viewbox: "0 0 8 8",
refX: "4",
refY: "4", // HACK: to avoid paths from bleeding through the arrowhead
path: "M0,0 A30,30,0,0,0,8,4 A30,30,0,0,0,0,8 L2.5,4 z",
},
"arrowhead-2": {
width: 9.95,
height: 8.12,
viewbox: "0 0 9.95 8.12",
refX: "2.36", // HACK: to avoid paths from bleeding through the arrowhead
refY: "4.06",
path: "M9.95 4.06 0 8.12 2.36 4.06 0 0 9.95 4.06z",
},
};
// calculates bounding box dimensions of a shape - used in inspector views
export const bBoxDims = (properties: Properties<number>, shapeType: string) => {
let [w, h] = [0, 0];
if (shapeType === "Circle") {
[w, h] = [
(properties.r.contents as number) * 2,
(properties.r.contents as number) * 2,
];
} else if (shapeType === "Square") {
[w, h] = [
properties.side.contents as number,
properties.side.contents as number,
];
} else if (shapeType === "Ellipse") {
[w, h] = [
(properties.rx.contents as number) * 2,
(properties.ry.contents as number) * 2,
];
} else if (shapeType === "Arrow" || shapeType === "Line") {
const [[sx, sy], [ex, ey]] = [
properties.start.contents as [number, number],
properties.end.contents as [number, number],
];
const padding = 50; // Because arrow may be horizontal or vertical, and we don't want the size to be zero in that case
[w, h] = [
Math.max(Math.abs(ex - sx), padding),
Math.max(Math.abs(ey - sy), padding),
];
} else if (shapeType === "Path") {
[w, h] = [20, 20]; // TODO: find a better measure for this... check with max?
} else if (shapeType === "Polygon") {
[w, h] = [20, 20]; // TODO: find a better measure for this... check with max?
} else if (shapeType === "FreeformPolygon") {
[w, h] = [20, 20]; // TODO: find a better measure for this... check with max?
} else if (shapeType === "Polyline") {
[w, h] = [20, 20]; // TODO: find a better measure for this... check with max?
} else if (shapeType === "PathString") {
[w, h] = [properties.w.contents as number, properties.h.contents as number];
} else if (properties.w && properties.h) {
[w, h] = [properties.w.contents as number, properties.h.contents as number];
} else {
[w, h] = [20, 20];
}
return [w, h];
};
// export const Shadow = (props: { id: string }) => {
// return (
// <filter id={props.id} x="0" y="0" width="200%" height="200%">
// <feOffset result="offOut" in="SourceAlpha" dx="5" dy="5" />
// <feGaussianBlur result="blurOut" in="offOut" stdDeviation="4" />
// <feBlend in="SourceGraphic" in2="blurOut" mode="normal" />
// <feComponentTransfer>
// <feFuncA type="linear" slope="0.5" />
// </feComponentTransfer>
// <feMerge>
// <feMergeNode />
// <feMergeNode in="SourceGraphic" />
// </feMerge>
// </filter>
// );
// };
export const toScreen = (
[x, y]: [number, number],
canvasSize: [number, number]
) => {
const [width, height] = canvasSize;
return [width / 2 + x, height / 2 - y];
};
export const penroseToSVG = (canvasSize: [number, number]) => {
const [width, height] = canvasSize;
const flipYStr = "matrix(1 0 0 -1 0 0)";
const translateStr = "translate(" + width / 2 + ", " + height / 2 + ")";
// Flip Y direction, then translate shape to origin mid-canvas
return [translateStr, flipYStr].join(" ");
};
export const penroseTransformStr = (tf: any) => {
const transformList = [
tf.xScale,
tf.ySkew,
tf.xSkew,
tf.yScale,
tf.dx,
tf.dy,
];
const penroseTransform = "matrix(" + transformList.join(" ") + ")";
return penroseTransform;
};
export const svgTransformString = (tf: any, canvasSize: [number, number]) => {
// https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/transform
// `tf` is `shape.transformation.contents`, an HMatrix from the backend
// It is the *full* transform, incl. default transform
// Do Penrose transform, then SVG
const transformStr = [penroseToSVG(canvasSize), penroseTransformStr(tf)].join(
" "
);
return transformStr;
};
// BUG: ptList needs to be properly typed
export const toPointListString = memoize(
// Why memoize?
(ptList: any[], canvasSize: [number, number]) =>
ptList
.map((coords: [number, number]) => {
const pt = coords;
return pt[0].toString() + " " + pt[1].toString();
})
.join(" ")
);
export const getAlpha = (color: any) => color.contents[3];
export const toHexRGB = (color: [number, number, number]): string => {
return color.reduce((prev: string, cur: number) => {
const hex = Math.round(255 * cur).toString(16);
const padded = hex.length === 1 ? "0" + hex : hex;
return prev + padded;
}, "#");
};
// TODO nest this
function hsv2rgb(
r1: number,
g1: number,
b1: number,
m: number
): [number, number, number] {
return [r1 + m, g1 + m, b1 + m];
}
// Expects H as angle in degrees, S in [0,100], L in [0,100] and converts the latter two to fractions.
// Returns rgb in range [0, 1]
// From https://github.com/d3/d3-hsv/blob/master/src/hsv.js
export const hsvToRGB = (
hsv: [number, number, number]
): [number, number, number] => {
const [h0, s0, v0] = hsv;
const h = isNaN(h0) ? 0 : (h0 % 360) + Number(h0 < 0) * 360;
const s = isNaN(h0) || isNaN(s0) ? 0 : s0 / 100.0;
const v = v0 / 100.0;
const c = v * s;
const x = c * (1 - Math.abs(((h / 60) % 2) - 1));
const m = v - c;
return h < 60
? hsv2rgb(c, x, 0, m)
: h < 120
? hsv2rgb(x, c, 0, m)
: h < 180
? hsv2rgb(0, c, x, m)
: h < 240
? hsv2rgb(0, x, c, m)
: h < 300
? hsv2rgb(x, 0, c, m)
: hsv2rgb(c, 0, x, m);
};
export const toSvgPaintProperty = (color: Color<number>): string => {
switch (color.tag) {
case "RGBA":
return toHexRGB([
color.contents[0],
color.contents[1],
color.contents[2],
]);
case "HSVA":
return toHexRGB(
hsvToRGB([color.contents[0], color.contents[1], color.contents[2]])
);
case "NONE":
return "none";
}
};
export const toSvgOpacityProperty = (color: Color<number>): number => {
switch (color.tag) {
case "RGBA":
return color.contents[3];
case "HSVA":
return color.contents[3];
case "NONE":
return 1;
}
};
export const getAngle = (x1: number, y1: number, x2: number, y2: number) => {
const x = x1 - x2;
const y = y1 - y2;
if (!x && !y) {
return 0;
}
return (180 + (Math.atan2(-y, -x) * 180) / Math.PI + 360) % 360;
};
export const getLen = (x1: number, y1: number, x2: number, y2: number) => {
return Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
};
export const loadImageElement = memoize(
async (url: string): Promise<any> =>
new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
})
);
// Load images asynchronously so we can send the dimensions to the backend and use it in the frontend
export const loadImages = async (allShapes: any[]) => {
return Promise.all(
allShapes.map(async ({ shapeType, properties }: any) => {
if (shapeType === "ImageTransform") {
const path = properties.path.contents;
const fullPath = process.env.PUBLIC_URL + path;
const loadedImage = await loadImageElement(fullPath);
const obj2 = { ...properties };
obj2.initWidth.contents = loadedImage.naturalWidth;
obj2.initHeight.contents = loadedImage.naturalHeight;
return { shapeType, properties: obj2 };
} else {
return { shapeType, properties };
}
})
);
};
export const round2 = (n: number) => roundTo(n, 2);
// https://stackoverflow.com/questions/15762768/javascript-math-round-to-two-decimal-places
// Ported so string conversion works in typescript...
export const roundTo = (n: number, digits: number) => {
let negative = false;
if (digits === undefined) {
digits = 0;
}
if (n < 0) {
negative = true;
n = n * -1;
}
const multiplicator = Math.pow(10, digits);
const nNum = parseFloat((n * multiplicator).toFixed(11));
const n2 = parseFloat((Math.round(nNum) / multiplicator).toFixed(2));
let n3 = n2;
if (negative) {
n3 = parseFloat((n2 * -1).toFixed(2));
}
return n3;
};
// https://stackoverflow.com/questions/31084619/map-a-javascript-es6-map
// Basically Haskell's mapByValue (?)
export function mapMap(map: Map<any, any>, fn: any) {
return new Map(Array.from(map, ([key, value]) => [key, fn(value, key, map)]));
}
/**
* Safe wrapper for any function that might return `undefined`.
* @borrows https://stackoverflow.com/questions/54738221/typescript-array-find-possibly-undefind
* @param argument Possible unsafe function call
* @param message Error message
*/
export const safe = <T extends unknown>(
argument: T | undefined | null,
message: string
): T => {
if (argument === undefined || argument === null) {
throw new TypeError(message);
}
return argument;
};
// ----------------
//#region Some geometry-related utils.
/**
* Some vector operations that can be used on lists.
*/
export const ops = {
/**
* Return the norm of the 2-vector `[c1, c2]`.
*/
norm: (c1: number, c2: number) => ops.vnorm([c1, c2]),
/**
* Return the Euclidean distance between scalars `c1, c2`.
*/
dist: (c1: number, c2: number) => ops.vnorm([c1, c2]),
/**
* Return the sum of vectors `v1, v2.
*/
vadd: (v1: number[], v2: number[]): number[] => {
if (v1.length !== v2.length) {
throw Error("expected vectors of same length");
}
const res = zipWith(v1, v2, (a, b) => a + b);
return res;
},
/**
* Return the difference of vectors `v1, v2.
*/
vsub: (v1: number[], v2: number[]): number[] => {
if (v1.length !== v2.length) {
throw Error("expected vectors of same length");
}
const res = zipWith(v1, v2, (a, b) => a - b);
return res;
},
/**
* Return the Euclidean norm squared of vector `v`.
*/
vnormsq: (v: number[]): number => {
const res = v.map((e) => e * e);
return reduce(res, (x, y) => x + y, 0.0); // TODO: Will this one (var(0)) have its memory freed?
// Note (performance): the use of 0 adds an extra +0 to the comp graph, but lets us prevent undefined if the list is empty
},
/**
* Return the Euclidean norm of vector `v`.
*/
vnorm: (v: number[]): number => {
const res = ops.vnormsq(v);
return Math.sqrt(res);
},
/**
* Return the vector `v` scaled by scalar `c`.
*/
vmul: (c: number, v: number[]): number[] => {
return v.map((e) => c * e);
},
/**
* Return the vector `v`, scaled by `-1`.
*/
vneg: (v: number[]): number[] => {
return ops.vmul(-1.0, v);
},
/**
* Return the vector `v` divided by scalar `c`.
*/
vdiv: (v: number[], c: number): number[] => {
return v.map((e) => e / c);
},
/**
* Return the vector `v`, normalized.
*/
vnormalize: (v: number[]): number[] => {
const vsize = ops.vnorm(v) + 10e-10;
return ops.vdiv(v, vsize);
},
/**
* Return the Euclidean distance between vectors `v` and `w`.
*/
vdist: (v: number[], w: number[]): number => {
if (v.length !== w.length) {
throw Error("expected vectors of same length");
}
return ops.vnorm(ops.vsub(v, w));
},
/**
* Return the Euclidean distance squared between vectors `v` and `w`.
*/
vdistsq: (v: number[], w: number[]): number => {
if (v.length !== w.length) {
throw Error("expected vectors of same length");
}
return ops.vnormsq(ops.vsub(v, w));
},
/**
* Return the dot product of vectors `v1, v2`.
* Note: if you want to compute a norm squared, use `vnormsq` instead, it generates a smaller computational graph
*/
vdot: (v1: number[], v2: number[]): number => {
if (v1.length !== v2.length) {
throw Error("expected vectors of same length");
}
const res = zipWith(v1, v2, (a, b) => a * b);
return reduce(res, (x, y) => x + y, 0.0);
},
/**
* Return the sum of elements in vector `v`.
*/
vsum: (v: number[]): number => {
return reduce(v, (x, y) => x + y, 0.0);
},
/**
* Return `v + c * u`.
*/
vmove: (v: number[], c: number, u: number[]) => {
return ops.vadd(v, ops.vmul(c, u));
},
/**
* Rotate a 2D point `[x, y]` by 90 degrees counterclockwise.
*/
rot90: ([x, y]: number[]): number[] => {
return [-y, x];
},
/**
* Return 2D determinant/cross product of 2D vectors
*/
cross2: (v: number[], w: number[]): number => {
if (v.length !== 2 || w.length !== 2) {
throw Error("expected two 2-vectors");
}
return v[0] * w[1] - v[1] * w[0];
},
/**
* Return the angle between two 2D vectors `v` and `w` in radians.
* From https://github.com/thi-ng/umbrella/blob/develop/packages/vectors/src/angle-between.ts#L11
*/
angleBetween2: (v: number[], w: number[]): number => {
if (v.length !== 2 || w.length !== 2) {
throw Error("expected two 2-vectors");
}
const t = Math.atan2(ops.cross2(v, w), ops.vdot(v, w));
return t;
},
};
/**
* Return the bounding box (as 4 segments) of an axis-aligned box-like shape given by `center`, width `w`, height `h` as an object with `top, bot, left, right`.
*/
export const bboxSegs = (center: number[], w: number, h: number): any => {
const halfWidth = w / 2;
const halfHeight = h / 2;
const nhalfWidth = -halfWidth;
const nhalfHeight = -halfHeight;
// CCW: TR, TL, BL, BR
const ptsR = [
[halfWidth, halfHeight],
[nhalfWidth, halfHeight],
[nhalfWidth, nhalfHeight],
[halfWidth, nhalfHeight],
].map((p) => ops.vadd(center, p));
const cornersR = {
topRight: ptsR[0],
topLeft: ptsR[1],
bottomLeft: ptsR[2],
bottomRight: ptsR[3],
};
const segsR = {
top: [cornersR.topLeft, cornersR.topRight],
bot: [cornersR.bottomLeft, cornersR.bottomRight],
left: [cornersR.bottomLeft, cornersR.topLeft],
right: [cornersR.bottomRight, cornersR.topRight],
};
const linesR = {
minX: cornersR.topLeft[0],
maxX: cornersR.topRight[0],
minY: cornersR.bottomLeft[1],
maxY: cornersR.topLeft[1],
};
return { ptsR, cornersR, segsR, linesR };
};
// returns true if the line from (a,b)->(c,d) intersects with (p,q)->(r,s)
export const intersects = (s1: number[][], s2: number[][]): boolean => {
const [l1_p1, l1_p2, l2_p1, l2_p2] = [s1[0], s1[1], s2[0], s2[1]];
const [[a, b], [c, d]] = [l1_p1, l1_p2];
const [[p, q], [r, s]] = [l2_p1, l2_p2];
var det, gamma, lambda;
det = (c - a) * (s - q) - (r - p) * (d - b);
if (det === 0) {
return false;
} else {
lambda = ((s - q) * (r - a) + (p - r) * (s - b)) / det;
gamma = ((b - d) * (r - a) + (c - a) * (s - b)) / det;
return 0 < lambda && lambda < 1 && 0 < gamma && gamma < 1;
}
};
export interface Point2D {
x: number;
y: number;
}
export const toPt = (v: number[]): Point2D => ({ x: v[0], y: v[1] });
export function intersection(s1: number[][], s2: number[][]): number[] {
const [from1, to1, from2, to2] = [s1[0], s1[1], s2[0], s2[1]];
const res = intersection2(toPt(from1), toPt(to1), toPt(from2), toPt(to2));
return [res.x, res.y];
}
// https://stackoverflow.com/posts/58657254/revisions
// Assumes lines don'intersect! Use intersect to check it first
function intersection2(
from1: Point2D,
to1: Point2D,
from2: Point2D,
to2: Point2D
): Point2D {
const dX: number = to1.x - from1.x;
const dY: number = to1.y - from1.y;
const determinant: number = dX * (to2.y - from2.y) - (to2.x - from2.x) * dY;
if (determinant === 0) {
throw Error("parallel lines");
} // parallel lines
const lambda: number =
((to2.y - from2.y) * (to2.x - from1.x) +
(from2.x - to2.x) * (to2.y - from1.y)) /
determinant;
const gamma: number =
((from1.y - to1.y) * (to2.x - from1.x) + dX * (to2.y - from1.y)) /
determinant;
// check if there is an intersection
if (!(0 <= lambda && lambda <= 1) || !(0 <= gamma && gamma <= 1)) {
throw Error("lines don't intersect");
}
return {
x: from1.x + lambda * dX,
y: from1.y + lambda * dY,
};
}
/**
* Return true iff `p` is in rect `b`, assuming `rect` is an axis-aligned bounding box (AABB) with properties `minX, maxX, minY, maxY`.
*/
export const pointInBox = (p: any, rect: any): boolean => {
return (
p.x > rect.minX && p.x < rect.maxX && p.y > rect.minY && p.y < rect.maxY
);
};
//#endregion | the_stack |
import * as B from 'benchmark';
import { Tuple, Segmentation, OrderedSet as OrdSet } from '../mol-data/int';
// import { ElementSet } from 'mol-model/structure'
// export namespace Iteration {
// const U = 1000, V = 2500;
// const control: number[] = [];
// const sets = Object.create(null);
// for (let i = 1; i < U; i++) {
// const set = [];
// for (let j = 1; j < V; j++) {
// control[control.length] = j * j + 1;
// set[set.length] = j * j + 1;
// }
// sets[i * i] = OrdSet.ofSortedArray(set);
// }
// const ms = ElementSet.create(sets);
// export function native() {
// let s = 0;
// for (let i = 0, _i = control.length; i < _i; i++) s += control[i];
// return s;
// }
// export function iterators() {
// let s = 0;
// const it = ElementSet.atoms(ms);
// while (it.hasNext) {
// const v = it.move();
// s += Tuple.snd(v);
// }
// return s;
// }
// export function elementAt() {
// let s = 0;
// for (let i = 0, _i = ElementSet.atomCount(ms); i < _i; i++) s += Tuple.snd(ElementSet.atomGetAt(ms, i));
// return s;
// }
// export function manual() {
// let s = 0;
// const keys = ElementSet.unitIds(ms);
// for (let i = 0, _i = OrdSet.size(keys); i < _i; i++) {
// const set = ElementSet.unitGetById(ms, OrdSet.getAt(keys, i));
// for (let j = 0, _j = OrdSet.size(set); j < _j; j++) {
// s += OrdSet.getAt(set, j);
// }
// }
// return s;
// }
// export function manual1() {
// let s = 0;
// for (let i = 0, _i = ElementSet.unitCount(ms); i < _i; i++) {
// const set = ElementSet.unitGetByIndex(ms, i);
// for (let j = 0, _j = OrdSet.size(set); j < _j; j++) {
// s += OrdSet.getAt(set, j);
// }
// }
// return s;
// }
// export function run() {
// const suite = new B.Suite();
// // const values: number[] = [];
// // for (let i = 0; i < 1000000; i++) values[i] = (Math.random() * 1000) | 0;
// console.log(Iteration.native(), Iteration.iterators(), Iteration.elementAt(), Iteration.manual(), Iteration.manual1());
// suite
// .add('native', () => Iteration.native())
// .add('iterators', () => Iteration.iterators())
// .add('manual', () => Iteration.manual())
// .add('manual1', () => Iteration.manual1())
// .add('el at', () => Iteration.elementAt())
// .on('cycle', (e: any) => console.log(String(e.target)))
// .run();
// }
// }
export namespace Union {
function createArray(n: number) {
const data = new Int32Array(n);
let c = (Math.random() * 100) | 0;
for (let i = 0; i < n; i++) {
data[i] = c;
c += 1 + (Math.random() * 100) | 0;
}
return data;
}
function rangeArray(o: number, n: number) {
const data = new Int32Array(n);
for (let i = 0; i < n; i++) {
data[i] = o + i;
}
return data;
}
function createData(array: ArrayLike<number>) {
const obj = Object.create(null);
const set = new Set<number>();
for (let i = 0; i < array.length; i++) {
const a = array[i];
obj[a] = 1;
set.add(a);
}
return { ordSet: OrdSet.ofSortedArray(array), obj, set };
}
function unionOS(a: OrdSet, b: OrdSet) {
return OrdSet.union(a, b);
}
function intOS(a: OrdSet, b: OrdSet) {
return OrdSet.intersect(a, b);
}
function unionO(a: object, b: object) {
const ret = Object.create(null);
for (const k of Object.keys(a)) ret[k] = 1;
for (const k of Object.keys(b)) ret[k] = 1;
return ret;
}
function intO(a: object, b: object) {
const ret = Object.create(null);
for (const k of Object.keys(a)) if ((b as any)[k]) ret[k] = 1;
return ret;
}
function _setAdd(this: Set<number>, x: number) { this.add(x); }
function unionS(a: Set<number>, b: Set<number>) {
const ret = new Set<number>();
a.forEach(_setAdd, ret);
b.forEach(_setAdd, ret);
return ret;
}
function _setInt(this: { set: Set<number>, other: Set<number> }, x: number) { if (this.other.has(x)) this.set.add(x); }
function intS(a: Set<number>, b: Set<number>) {
if (a.size < b.size) {
const ctx = { set: new Set<number>(), other: b };
a.forEach(_setInt, ctx);
return ctx.set;
} else {
const ctx = { set: new Set<number>(), other: a };
b.forEach(_setInt, ctx);
return ctx.set;
}
}
export function run() {
const suite = new B.Suite();
const { ordSet: osA, set: sA, obj: oA } = createData(createArray(1000));
const { ordSet: osB, set: sB, obj: oB } = createData(createArray(1000));
console.log(OrdSet.size(unionOS(osA, osB)), Object.keys(unionO(oA, oB)).length, unionS(sA, sB).size);
console.log(OrdSet.size(intOS(osA, osB)), Object.keys(intO(oA, oB)).length, intS(sA, sB).size);
suite
.add('u ord set', () => unionOS(osA, osB))
.add('u obj', () => unionO(oA, oB))
.add('u ES6 set', () => unionS(sA, sB))
.add('i ord set', () => intOS(osA, osB))
.add('i obj', () => intO(oA, oB))
.add('i ES6 set', () => intS(sA, sB))
.on('cycle', (e: any) => console.log(String(e.target)))
.run();
}
export function runR() {
const suite = new B.Suite();
const rangeA = rangeArray(145, 1000);
const rangeB = rangeArray(456, 1000);
const { ordSet: osA, set: sA, obj: oA } = createData(rangeA);
const { ordSet: osB, set: sB, obj: oB } = createData(rangeB);
console.log(OrdSet.size(unionOS(osA, osB)), Object.keys(unionO(oA, oB)).length, unionS(sA, sB).size);
console.log(OrdSet.size(intOS(osA, osB)), Object.keys(intO(oA, oB)).length, intS(sA, sB).size);
suite
.add('u ord set', () => unionOS(osA, osB))
.add('u obj', () => unionO(oA, oB))
.add('u ES6 set', () => unionS(sA, sB))
.add('i ord set', () => intOS(osA, osB))
.add('i obj', () => intO(oA, oB))
.add('i ES6 set', () => intS(sA, sB))
.on('cycle', (e: any) => console.log(String(e.target)))
.run();
}
}
// export namespace Build {
// function createSorted() {
// const b = ElementSet.LinearBuilder(ElementSet.Empty);
// for (let i = 0; i < 10; i++) {
// for (let j = 0; j < 1000; j++) {
// b.add(i, j);
// }
// }
// return b.getSet();
// }
// function createByUnit() {
// const b = ElementSet.LinearBuilder(ElementSet.Empty);
// for (let i = 0; i < 10; i++) {
// b.beginUnit();
// for (let j = 0; j < 1000; j++) {
// b.addToUnit(j);
// }
// b.commitUnit(i);
// }
// return b.getSet();
// }
// export function run() {
// const suite = new B.Suite();
// suite
// .add('create sorted', () => createSorted())
// .add('create by unit', () => createByUnit())
// .on('cycle', (e: any) => console.log(String(e.target)))
// .run();
// }
// }
export namespace Tuples {
function createData(n: number) {
const ret: Tuple[] = new Float64Array(n) as any;
for (let i = 0; i < n; i++) {
ret[i] = Tuple.create(i, i * i + 1);
}
return ret;
}
function sum1(data: ArrayLike<Tuple>) {
let s = 0;
for (let i = 0, _i = data.length; i < _i; i++) {
s += Tuple.fst(data[i]) + Tuple.snd(data[i]);
}
return s;
}
function sum2(data: ArrayLike<Tuple>) {
let s = 0;
for (let i = 0, _i = data.length; i < _i; i++) {
const t = data[i];
s += Tuple.fst(t) + Tuple.snd(t);
}
return s;
}
export function run() {
const suite = new B.Suite();
const data = createData(10000);
suite
.add('sum fst/snd', () => sum1(data))
.add('sum fst/snd 1', () => sum2(data))
.on('cycle', (e: any) => console.log(String(e.target)))
.run();
}
}
export function testSegments() {
const data = OrdSet.ofSortedArray([4, 9, 10, 11, 14, 15, 16]);
const segs = Segmentation.create([0, 4, 10, 12, 13, 15, 25]);
const it = Segmentation.transientSegments(segs, data);
while (it.hasNext) {
const s = it.move();
for (let j = s.start; j < s.end; j++) {
console.log(`${s.index}: ${OrdSet.getAt(data, j)}`);
}
}
}
export namespace ObjectVsMap {
function objCreate(keys: string[]) {
const m = Object.create(null);
m.x = 0;
delete m.x;
for (let i = 0, _i = keys.length; i < _i; i++) {
m[keys[i]] = i * i;
}
return m;
}
function mapCreate(keys: string[]) {
const m = new Map<string, number>();
for (let i = 0, _i = keys.length; i < _i; i++) {
m.set(keys[i], i * i);
}
return m;
}
function objQuery(keys: string[], n: number, obj: any) {
let ret = 0;
for (let i = 0; i < n; i++) ret += obj[keys[i % n]];
return ret;
}
function mapQuery(keys: string[], n: number, map: Map<string, number>) {
let ret = 0;
for (let i = 0; i < n; i++) ret += map.get(keys[i % n])!;
return ret;
}
export function run() {
const suite = new B.Suite();
const keys: string[] = [];
for (let i = 0; i < 1000; i++) keys[i] = 'k' + i;
const N = 100000;
const obj = objCreate(keys);
const map = mapCreate(keys);
suite
.add('c obj', () => objCreate(keys))
.add('c map', () => mapCreate(keys))
.add('q obj', () => objQuery(keys, N, obj))
.add('q map', () => mapQuery(keys, N, map))
.on('cycle', (e: any) => console.log(String(e.target)))
.run();
}
}
export namespace IntVsStringIndices {
type WithKeys<K> = { keys: K[], data: { [key: number]: number } }
type MapWithKeys = { keys: number[], map: Map<number, number> }
function createCacheKeys(n: number): WithKeys<number> {
const data = Object.create(null), keys = [];
data.__ = void 0;
delete data.__;
for (let i = 1; i <= n; i++) {
const k = i * (i + 1);
keys[keys.length] = k;
data[k] = i + 1;
}
return { data, keys };
}
function createMapKeys(n: number): MapWithKeys {
const map = new Map<number, number>(), keys = [];
for (let i = 1; i <= n; i++) {
const k = i * (i + 1);
keys[keys.length] = k;
map.set(k, i + 1);
}
return { map, keys };
}
export function createInt(n: number) {
const ret = Object.create(null);
ret.__ = void 0;
delete ret.__;
for (let i = 1; i <= n; i++) ret[i * (i + 1)] = i + 1;
return ret;
}
export function createStr(n: number) {
const ret = Object.create(null);
ret.__ = void 0;
delete ret.__;
for (let i = 1; i <= n; i++) ret['' + (i * (i + 1))] = i + 1;
return ret;
}
export function createMap(n: number) {
const map = new Map<number, number>();
for (let i = 1; i <= n; i++) map.set(i * (i + 1), i + 1);
return map;
}
export function sumInt(xs: { [key: number]: number }) {
let s = 0;
const keys = Object.keys(xs);
for (let i = 0, _i = keys.length; i < _i; i++) s += xs[+keys[i]];
return s;
}
export function sumStr(xs: { [key: string]: number }) {
let s = 0;
const keys = Object.keys(xs);
for (let i = 0, _i = keys.length; i < _i; i++) s += xs[keys[i]];
return s;
}
export function sumMap(map: Map<number, number>) {
let s = 0;
const values = map.keys();
while (true) {
const { done, value } = values.next();
if (done) break;
s += value;
}
return s;
}
export function sumCached(xs: WithKeys<number>) {
let s = 0;
const keys = xs.keys, data = xs.data;
for (let i = 0, _i = keys.length; i < _i; i++) s += data[keys[i]];
return s;
}
export function sumKeyMap(xs: MapWithKeys) {
let s = 0;
const keys = xs.keys, map = xs.map;
for (let i = 0, _i = keys.length; i < _i; i++) s += map.get(keys[i])!;
return s;
}
export function run() {
const N = 1000;
// const int = createInt(N);
const map = createMap(N);
// const str = createStr(N);
const keys = createCacheKeys(N);
const keyMap = createMapKeys(N);
console.log(sumMap(map), sumCached(keys), sumKeyMap(keyMap));
new B.Suite()
// .add('c int', () => createInt(N))
.add('q map', () => sumMap(map))
.add('c map', () => createMap(N))
.add('c mk', () => createMapKeys(N))
// .add('c str', () => createStr(N))
.add('c cc', () => createCacheKeys(N))
// .add('q int', () => sumInt(int))
.add('q mk', () => sumKeyMap(keyMap))
// .add('q str', () => sumStr(str))
.add('q cc', () => sumCached(keys))
.on('cycle', (e: any) => console.log(String(e.target)))
.run();
}
}
IntVsStringIndices.run();
// ObjectVsMap.run();
// testSegments();
// Tuples.run();
// interface AA { kind: 'a' }
// //interface BB { kind: 'b' }
// interface AB { kind: 'a' | 'b' }
// declare const a: AA;
// export const ab: AB = a; | the_stack |
* @module Curve
*/
import { Geometry } from "../Geometry";
import { GrowableXYZArray } from "../geometry3d/GrowableXYZArray";
import { IndexedXYZCollection } from "../geometry3d/IndexedXYZCollection";
import { Point3dArrayCarrier } from "../geometry3d/Point3dArrayCarrier";
import { Point3d } from "../geometry3d/Point3dVector3d";
import { PolylineCompressionContext } from "../geometry3d/PolylineCompressionByEdgeOffset";
import { Range3d } from "../geometry3d/Range";
import { SortablePolygon } from "../geometry3d/SortablePolygon";
import { Transform } from "../geometry3d/Transform";
import { MomentData } from "../geometry4d/MomentData";
import { Polyface } from "../polyface/Polyface";
import { PolyfaceBuilder } from "../polyface/PolyfaceBuilder";
import { HalfEdge, HalfEdgeGraph, HalfEdgeMask } from "../topology/Graph";
import { LineStringDataVariant, MultiLineStringDataVariant, Triangulator } from "../topology/Triangulation";
import { ChainCollectorContext } from "./ChainCollectorContext";
import { AnyCurve, AnyRegion } from "./CurveChain";
import { BagOfCurves, ConsolidateAdjacentCurvePrimitivesOptions, CurveChain, CurveCollection } from "./CurveCollection";
import { CurveCurve } from "./CurveCurve";
import { CurvePrimitive } from "./CurvePrimitive";
import { CurveWireMomentsXYZ } from "./CurveWireMomentsXYZ";
import { CurveChainWireOffsetContext, JointOptions, OffsetOptions, PolygonWireOffsetContext } from "./internalContexts/PolygonOffsetContext";
import { LineString3d } from "./LineString3d";
import { Loop, SignedLoops } from "./Loop";
import { Path } from "./Path";
import { ConsolidateAdjacentCurvePrimitivesContext } from "./Query/ConsolidateAdjacentPrimitivesContext";
import { CurveSplitContext } from "./Query/CurveSplitContext";
import { PointInOnOutContext } from "./Query/InOutTests";
import { PlanarSubdivision } from "./Query/PlanarSubdivision";
import { RegionMomentsXY } from "./RegionMomentsXY";
import { OffsetHelpers } from "./internalContexts/MultiChainCollector";
import { GeometryQuery } from "./GeometryQuery";
import { RegionBooleanContext, RegionGroupOpType, RegionOpsFaceToFaceSearch } from "./RegionOpsClassificationSweeps";
import { UnionRegion } from "./UnionRegion";
import { HalfEdgeGraphSearch } from "../topology/HalfEdgeGraphSearch";
import { ParityRegion } from "./ParityRegion";
/**
* Possible return types from
* @public
*/
export type ChainTypes = CurvePrimitive | Path | BagOfCurves | Loop | undefined;
/**
* * `properties` is a string with special characters indicating
* * "U" -- contains unmerged stick data
* * "M" -- merged
* * "R" -- regularized
* * "X" -- has exterior markup
* @internal
*/
export type GraphCheckPointFunction = (name: string, graph: HalfEdgeGraph, properties: string, extraData?: any) => any;
/**
* Enumeration of the binary operation types for a booleans among regions
* @public
*/
export enum RegionBinaryOpType {
Union = 0,
Parity = 1,
Intersection = 2,
AMinusB = 3,
BMinusA = 4,
}
/**
* class `RegionOps` has static members for calculations on regions (areas).
* * Regions are represented by these `CurveCollection` subclasses:
* * `Loop` -- a single loop
* * `ParityRegion` -- a collection of loops, interpreted by parity rules.
* * The common "One outer loop and many Inner loops" is a parity region.
* * `UnionRegion` -- a collection of `Loop` and `ParityRegion` objects understood as a (probably disjoint) union.
* @beta
*/
export class RegionOps {
/**
* Return moment sums for a loop, parity region, or union region.
* * If `rawMomentData` is the MomentData returned by computeXYAreaMoments, convert to principal axes and moments with
* call `principalMomentData = MomentData.inertiaProductsToPrincipalAxes (rawMomentData.origin, rawMomentData.sums);`
* @param root any Loop, ParityRegion, or UnionRegion.
*/
public static computeXYAreaMoments(root: AnyRegion): MomentData | undefined {
const handler = new RegionMomentsXY();
const result = root.dispatchToGeometryHandler(handler);
if (result instanceof MomentData) {
result.shiftOriginAndSumsToCentroidOfSums();
return result;
}
return undefined;
}
/**
* Return an xy area for a loop, parity region, or union region.
* * If `rawMomentData` is the MomentData returned by computeXYAreaMoments, convert to principal axes and moments with
* call `principalMomentData = MomentData.inertiaProductsToPrincipalAxes (rawMomentData.origin, rawMomentData.sums);`
* @param root any Loop, ParityRegion, or UnionRegion.
*/
public static computeXYArea(root: AnyRegion): number | undefined {
const handler = new RegionMomentsXY();
const result = root.dispatchToGeometryHandler(handler);
if (result instanceof MomentData) {
return result.quantitySum;
}
return undefined;
}
/** Return MomentData with the sums of wire moments.
* * If `rawMomentData` is the MomentData returned by computeXYAreaMoments, convert to principal axes and moments with
* call `principalMomentData = MomentData.inertiaProductsToPrincipalAxes (rawMomentData.origin, rawMomentData.sums);`
*/
public static computeXYZWireMomentSums(root: AnyCurve): MomentData | undefined {
const handler = new CurveWireMomentsXYZ();
handler.visitLeaves(root);
const result = handler.momentData;
result.shiftOriginAndSumsToCentroidOfSums();
return result;
}
/**
* * create loops in the graph.
* @internal
*/
public static addLoopsToGraph(graph: HalfEdgeGraph, data: MultiLineStringDataVariant, announceIsolatedLoop: (graph: HalfEdgeGraph, seed: HalfEdge) => void) {
if (data instanceof Loop) {
const points = data.getPackedStrokes();
if (points)
this.addLoopsToGraph(graph, points, announceIsolatedLoop);
} else if (data instanceof ParityRegion) {
for (const child of data.children) {
const points = child.getPackedStrokes();
if (points)
this.addLoopsToGraph(graph, points, announceIsolatedLoop);
}
} else if (data instanceof IndexedXYZCollection) {
const loopSeed = Triangulator.directCreateFaceLoopFromCoordinates(graph, data);
if (loopSeed !== undefined)
announceIsolatedLoop(graph, loopSeed);
} else if (Array.isArray(data)) {
if (data.length > 0) {
if (Point3d.isAnyImmediatePointType(data[0])) {
const loopSeed = Triangulator.directCreateFaceLoopFromCoordinates(graph, data as LineStringDataVariant);
if (loopSeed !== undefined)
announceIsolatedLoop(graph, loopSeed);
} else if (data[0] instanceof IndexedXYZCollection) {
for (const loop of data) {
const loopSeed = Triangulator.directCreateFaceLoopFromCoordinates(graph, loop as IndexedXYZCollection);
if (loopSeed !== undefined)
announceIsolatedLoop(graph, loopSeed);
}
} else {
for (const child of data) {
if (Array.isArray(child))
this.addLoopsToGraph(graph, child as MultiLineStringDataVariant, announceIsolatedLoop);
}
}
}
}
}
/** Add multiple loops to a graph.
* * Apply edgeTag and mask to each edge.
* @internal
*/
public static addLoopsWithEdgeTagToGraph(graph: HalfEdgeGraph, data: MultiLineStringDataVariant, mask: HalfEdgeMask, edgeTag: any): HalfEdge[] | undefined {
const loopSeeds: HalfEdge[] = [];
this.addLoopsToGraph(graph, data, (_graph: HalfEdgeGraph, seed: HalfEdge) => {
if (seed) {
loopSeeds.push(seed);
seed.setMaskAndEdgeTagAroundFace(mask, edgeTag, true);
}
});
if (loopSeeds.length > 0)
return loopSeeds;
return undefined;
}
/**
* Given a graph just produced by booleans, convert to a polyface
* * "just produced" implies exterior face markup.
*
* @param graph
* @param triangulate
*/
private static finishGraphToPolyface(graph: HalfEdgeGraph | undefined, triangulate: boolean): Polyface | undefined {
if (graph) {
if (triangulate) {
Triangulator.triangulateAllPositiveAreaFaces(graph);
Triangulator.flipTriangles(graph);
}
return PolyfaceBuilder.graphToPolyface(graph);
}
return undefined;
}
/**
* return a polyface containing the area union of two XY regions.
* * Within each region, in and out is determined by parity rules.
* * Any face that is an odd number of crossings from the far outside is IN
* * Any face that is an even number of crossings from the far outside is OUT
* @param loopsA first set of loops
* @param loopsB second set of loops
*/
public static polygonXYAreaIntersectLoopsToPolyface(loopsA: MultiLineStringDataVariant, loopsB: MultiLineStringDataVariant, triangulate: boolean = false): Polyface | undefined {
const graph = RegionOpsFaceToFaceSearch.doPolygonBoolean(loopsA, loopsB,
(inA: boolean, inB: boolean) => (inA && inB),
this._graphCheckPointFunction);
return this.finishGraphToPolyface(graph, triangulate);
}
/**
* return a polyface containing the area union of two XY regions.
* * Within each region, in and out is determined by parity rules.
* * Any face that is an odd number of crossings from the far outside is IN
* * Any face that is an even number of crossings from the far outside is OUT
* @param loopsA first set of loops
* @param loopsB second set of loops
*/
public static polygonXYAreaUnionLoopsToPolyface(loopsA: MultiLineStringDataVariant, loopsB: MultiLineStringDataVariant, triangulate: boolean = false): Polyface | undefined {
const graph = RegionOpsFaceToFaceSearch.doPolygonBoolean(loopsA, loopsB,
(inA: boolean, inB: boolean) => (inA || inB),
this._graphCheckPointFunction);
return this.finishGraphToPolyface(graph, triangulate);
}
/**
* return a polyface containing the area difference of two XY regions.
* * Within each region, in and out is determined by parity rules.
* * Any face that is an odd number of crossings from the far outside is IN
* * Any face that is an even number of crossings from the far outside is OUT
* @param loopsA first set of loops
* @param loopsB second set of loops
*/
public static polygonXYAreaDifferenceLoopsToPolyface(loopsA: MultiLineStringDataVariant, loopsB: MultiLineStringDataVariant, triangulate: boolean = false): Polyface | undefined {
const graph = RegionOpsFaceToFaceSearch.doPolygonBoolean(loopsA, loopsB,
(inA: boolean, inB: boolean) => (inA && !inB),
this._graphCheckPointFunction);
return this.finishGraphToPolyface(graph, triangulate);
}
/**
* return areas defined by a boolean operation.
* * If there are multiple regions in loopsA, they are treated as a union.
* * If there are multiple regions in loopsB, they are treated as a union.
* @param loopsA first set of loops
* @param loopsB second set of loops
* @param operation indicates Union, Intersection, Parity, AMinusB, or BMinusA
* @alpha
*/
public static regionBooleanXY(loopsA: AnyRegion | AnyRegion[] | undefined, loopsB: AnyRegion | AnyRegion[] | undefined, operation: RegionBinaryOpType): AnyRegion | undefined {
// create and load a context . . .
const result = UnionRegion.create();
const context = RegionBooleanContext.create(RegionGroupOpType.Union, RegionGroupOpType.Union);
context.addMembers(loopsA, loopsB);
context.annotateAndMergeCurvesInGraph();
context.runClassificationSweep(operation, (_graph: HalfEdgeGraph, face: HalfEdge, faceType: -1 | 0 | 1, area: number) => {
if (face.countEdgesAroundFace() < 3 && Geometry.isSameCoordinate(area, 0)) // NEED BETTER TOLERANCE
return;
if (faceType === 1) {
const loop = PlanarSubdivision.createLoopInFace(face);
if (loop)
result.tryAddChild(loop);
}
});
return result;
}
/**
* return a polyface whose facets area a boolean operation between the input regions.
* * Each of the two inputs is an array of multiple loops or parity regions.
* * Within each of these input arrays, the various entries (loop or set of loops) are interpreted as a union.
* * In each "array of loops and parity regions", each entry inputA[i] or inputB[i] is one of:
* * A simple loop, e.g. array of Point3d.
* * Several simple loops, each of which is an array of Point3d.
* @param loopsA first set of loops
* @param loopsB second set of loops
*/
public static polygonBooleanXYToPolyface(inputA: MultiLineStringDataVariant[], operation: RegionBinaryOpType,
inputB: MultiLineStringDataVariant[], triangulate: boolean = false): Polyface | undefined {
const graph = RegionOpsFaceToFaceSearch.doBinaryBooleanBetweenMultiLoopInputs(
inputA, RegionGroupOpType.Union,
operation,
inputB, RegionGroupOpType.Union, true);
return this.finishGraphToPolyface(graph, triangulate);
}
/**
* return loops of linestrings around areas of a boolean operation between the input regions.
* * Each of the two inputs is an array of multiple loops or parity regions.
* * Within each of these input arrays, the various entries (loop or set of loops) are interpreted as a union.
* * In each "array of loops and parity regions", each entry inputA[i] or inputB[i] is one of:
* * A simple loop, e.g. array of Point3d.
* * Several simple loops, each of which is an array of Point3d.
* @param loopsA first set of loops
* @param loopsB second set of loops
*/
public static polygonBooleanXYToLoops(
inputA: MultiLineStringDataVariant[],
operation: RegionBinaryOpType,
inputB: MultiLineStringDataVariant[]): AnyRegion | undefined {
const graph = RegionOpsFaceToFaceSearch.doBinaryBooleanBetweenMultiLoopInputs(
inputA, RegionGroupOpType.Union,
operation,
inputB, RegionGroupOpType.Union, true);
if (!graph)
return undefined;
const loopEdges = HalfEdgeGraphSearch.collectExtendedBoundaryLoopsInGraph(graph, HalfEdgeMask.EXTERIOR);
const allLoops: Loop[] = [];
for (const graphLoop of loopEdges) {
const points = new GrowableXYZArray();
for (const edge of graphLoop)
points.pushXYZ(edge.x, edge.y, edge.z);
points.pushWrap(1);
const loop = Loop.create();
loop.tryAddChild(LineString3d.createCapture(points));
allLoops.push(loop);
}
return RegionOps.sortOuterAndHoleLoopsXY(allLoops);
}
/** Construct a wire (not area!!) that is offset from given polyline or polygon.
* * This is a simple wire offset, not an area.
* * The construction algorithm attempts to eliminate some self-intersections within the offsets, but does not guarantee a simple area offset.
* * The construction algorithm is subject to being changed, resulting in different (hopefully better) self-intersection behavior on the future.
* @param points a single loop or path
* @param wrap true to include wraparound
* @param offsetDistance distance of offset from wire. Positive is left.
*/
public static constructPolygonWireXYOffset(points: Point3d[], wrap: boolean, offsetDistance: number): CurveCollection | undefined {
const context = new PolygonWireOffsetContext();
return context.constructPolygonWireXYOffset(points, wrap, offsetDistance);
}
/**
* Construct curves that are offset from a Path or Loop as viewed in xy-plane (ignoring z).
* * The construction will remove "some" local effects of features smaller than the offset distance, but will not detect self intersection among widely separated edges.
* * If offsetDistance is given as a number, default OffsetOptions are applied.
* * When the offset needs to do an "outside" turn, the first applicable construction is applied:
* * If the turn is larger than `options.minArcDegrees`, a circular arc is constructed.
* * If the turn is less than or equal to `options.maxChamferTurnDegrees`, extend curves along tangent to single intersection point.
* * If the turn is larger than `options.maxChamferDegrees`, the turn is constructed as a sequence of straight lines that are:
* * outside the arc
* * have uniform turn angle less than `options.maxChamferDegrees`
* * each line segment (except first and last) touches the arc at its midpoint.
* @param curves base curves.
* @param offsetDistanceOrOptions offset distance (positive to left of curve, negative to right) or options object.
*/
public static constructCurveXYOffset(curves: Path | Loop, offsetDistanceOrOptions: number | JointOptions | OffsetOptions): CurveCollection | undefined {
return CurveChainWireOffsetContext.constructCurveXYOffset(curves, offsetDistanceOrOptions);
}
/**
* Test if point (x,y) is IN, OUT or ON a polygon.
* @return (1) for in, (-1) for OUT, (0) for ON
* @param x x coordinate
* @param y y coordinate
* @param points array of xy coordinates.
*/
public static testPointInOnOutRegionXY(curves: AnyRegion, x: number, y: number): number {
return PointInOnOutContext.testPointInOnOutRegionXY(curves, x, y);
}
/** Create curve collection of subtype determined by gaps between the input curves.
* * If (a) wrap is requested and (b) all curves connect head-to-tail (including wraparound), assemble as a `loop`.
* * If all curves connect head-to-tail except for closure, return a `Path`.
* * If there are internal gaps, return a `BagOfCurves`
* * If input array has zero length, return undefined.
*/
public static createLoopPathOrBagOfCurves(curves: CurvePrimitive[], wrap: boolean = true, consolidateAdjacentPrimitives: boolean = false): CurveCollection | undefined {
const n = curves.length;
if (n === 0)
return undefined;
let maxGap = 0.0;
let isPath = false;
if (wrap)
maxGap = Geometry.maxXY(maxGap, curves[0].startPoint().distance(curves[n - 1].endPoint()));
for (let i = 0; i + 1 < n; i++)
maxGap = Geometry.maxXY(maxGap, curves[i].endPoint().distance(curves[i + 1].startPoint()));
let collection: Loop | Path | BagOfCurves;
if (Geometry.isSmallMetricDistance(maxGap)) {
collection = wrap ? Loop.create() : Path.create();
isPath = true;
} else {
collection = BagOfCurves.create();
}
for (const c of curves)
collection.tryAddChild(c);
if (isPath && consolidateAdjacentPrimitives)
RegionOps.consolidateAdjacentPrimitives(collection);
return collection;
}
private static _graphCheckPointFunction?: GraphCheckPointFunction;
/**
* Announce Checkpoint function for use during booleans
* @internal
*/
public static setCheckPointFunction(f?: GraphCheckPointFunction) { this._graphCheckPointFunction = f; }
/**
* * Find all intersections among curves in `curvesToCut` and `cutterCurves`
* * Return fragments of `curvesToCut`.
* * For a `Loop`, `ParityRegion`, or `UnionRegion` in `curvesToCut`
* * if it is never cut by any `cutter` curve, it will be left unchanged.
* * if cut, the input is downgraded to a set of `Path` curves joining at the cut points.
* * All cutting is "as viewed in the xy plane"
*/
public static cloneCurvesWithXYSplitFlags(curvesToCut: CurvePrimitive | CurveCollection | undefined, cutterCurves: CurveCollection): CurveCollection | CurvePrimitive | undefined {
return CurveSplitContext.cloneCurvesWithXYSplitFlags(curvesToCut, cutterCurves);
}
/**
* Create paths assembled from many curves.
* * Assemble consecutive curves NOT separated by either end flags or gaps into paths.
* * Return simplest form -- single primitive, single path, or bag of curves.
* @param curves
*/
public static splitToPathsBetweenFlagBreaks(source: CurveCollection | CurvePrimitive | undefined,
makeClones: boolean): BagOfCurves | Path | CurvePrimitive | Loop | undefined {
if (source === undefined)
return undefined;
if (source instanceof CurvePrimitive)
return source;
// source is a collection . ..
const primitives = source.collectCurvePrimitives();
const chainCollector = new ChainCollectorContext(makeClones);
for (const primitive of primitives) {
chainCollector.announceCurvePrimitive(primitive);
}
return chainCollector.grabResult();
}
/**
* * Restructure curve fragments as chains and offsets
* * Return object with named chains, insideOffsets, outsideOffsets
* * BEWARE that if the input is not a loop the classification of outputs is suspect.
* @param fragments fragments to be chained
* @param offsetDistance offset distance.
*/
public static collectInsideAndOutsideOffsets(fragments: GeometryQuery[], offsetDistance: number, gapTolerance: number): { insideOffsets: GeometryQuery[], outsideOffsets: GeometryQuery[], chains: ChainTypes } {
return OffsetHelpers.collectInsideAndOutsideOffsets(fragments, offsetDistance, gapTolerance);
}
/**
* * Restructure curve fragments as chains
* * Return the chains, possibly wrapped in BagOfCurves if there multiple chains.
* @param fragments fragments to be chained
* @param offsetDistance offset distance.
*/
public static collectChains(fragments: GeometryQuery[], gapTolerance: number = Geometry.smallMetricDistance): ChainTypes {
return OffsetHelpers.collectChains(fragments, gapTolerance);
}
/**
* * Find intersections of `curvesToCut` with boundaries of `region`.
* * Break `curvesToCut` into parts inside, outside, and coincident.
* * Return all fragments, split among `insideParts`, `outsideParts`, and `coincidentParts` in the output object.
*/
public static splitPathsByRegionInOnOutXY(curvesToCut: CurveCollection | CurvePrimitive | undefined, region: AnyRegion): { insideParts: AnyCurve[], outsideParts: AnyCurve[], coincidentParts: AnyCurve[] } {
const result = { insideParts: [], outsideParts: [], coincidentParts: [] };
const pathWithIntersectionMarkup = RegionOps.cloneCurvesWithXYSplitFlags(curvesToCut, region);
const splitPaths = RegionOps.splitToPathsBetweenFlagBreaks(pathWithIntersectionMarkup, true);
if (splitPaths instanceof CurveCollection) {
for (const child of splitPaths.children) {
const pointOnChild = CurveCollection.createCurveLocationDetailOnAnyCurvePrimitive(child);
if (pointOnChild) {
const inOnOut = RegionOps.testPointInOnOutRegionXY(region, pointOnChild.point.x, pointOnChild.point.y);
pushToInOnOutArrays(child, inOnOut, result.outsideParts, result.coincidentParts, result.insideParts);
}
}
} else if (splitPaths instanceof CurvePrimitive) {
const pointOnChild = CurveCollection.createCurveLocationDetailOnAnyCurvePrimitive(splitPaths);
if (pointOnChild) {
const inOnOut = RegionOps.testPointInOnOutRegionXY(region, pointOnChild.point.x, pointOnChild.point.y);
pushToInOnOutArrays(splitPaths, inOnOut, result.outsideParts, result.coincidentParts, result.insideParts);
}
}
return result;
}
/** Test if `data` is one of several forms of a rectangle.
* * If so, return transform with
* * origin at one corner
* * x and y columns extend along two adjacent sides
* * z column is unit normal.
* * The recognized data forms for simple analysis of points are:
* * LineString
* * Loop containing rectangle content
* * Path containing rectangle content
* * Array of Point3d[]
* * IndexedXYZCollection
* * Points are considered a rectangle if
* * Within the first 4 points
* * vectors from 0 to 1 and 0 to 3 are perpendicular and have a non-zero cross product
* * vectors from 0 to 3 and 1 to 2 are the same
* * optionally require a 5th point that closes back to point0
* * If there are other than the basic number of points (4 or 5) the data
*/
public static rectangleEdgeTransform(data: AnyCurve | Point3d[] | IndexedXYZCollection, requireClosurePoint: boolean = true): Transform | undefined {
if (data instanceof LineString3d) {
return this.rectangleEdgeTransform(data.packedPoints);
} else if (data instanceof IndexedXYZCollection) {
let dataToUse;
if (requireClosurePoint && data.length === 5) {
if (!Geometry.isSmallMetricDistance(data.distanceIndexIndex(0, 4)!))
return undefined;
dataToUse = data;
} else if (!requireClosurePoint && data.length === 4)
dataToUse = data;
else if (data.length < (requireClosurePoint ? 5 : 4)) {
return undefined;
} else {
dataToUse = GrowableXYZArray.create(data);
PolylineCompressionContext.compressInPlaceByShortEdgeLength(dataToUse, Geometry.smallMetricDistance);
}
const vector01 = dataToUse.vectorIndexIndex(0, 1)!;
const vector03 = dataToUse.vectorIndexIndex(0, 3)!;
const vector12 = dataToUse.vectorIndexIndex(1, 2)!;
const normalVector = vector01.crossProduct(vector03);
if (normalVector.normalizeInPlace()
&& vector12.isAlmostEqual(vector03)
&& vector01.isPerpendicularTo(vector03)) {
return Transform.createOriginAndMatrixColumns(dataToUse.getPoint3dAtUncheckedPointIndex(0), vector01, vector03, normalVector);
}
} else if (Array.isArray(data)) {
return this.rectangleEdgeTransform(new Point3dArrayCarrier(data), requireClosurePoint);
} else if (data instanceof Loop && data.children.length === 1 && data.children[0] instanceof LineString3d) {
return this.rectangleEdgeTransform(data.children[0].packedPoints, true);
} else if (data instanceof Path && data.children.length === 1 && data.children[0] instanceof LineString3d) {
return this.rectangleEdgeTransform(data.children[0].packedPoints, requireClosurePoint);
} else if (data instanceof CurveChain) {
if (!data.checkForNonLinearPrimitives()) {
// const linestring = LineString3d.create();
const strokes = data.getPackedStrokes();
if (strokes) {
return this.rectangleEdgeTransform(strokes);
}
}
}
return undefined;
}
/**
* Look for and simplify:
* * Contiguous `LineSegment3d` and `LineString3d` objects.
* * collect all points
* * eliminate duplicated points
* * eliminate points colinear with surrounding points.
* * Contiguous concentric circular or elliptic arcs
* * combine angular ranges
* @param curves Path or loop (or larger collection containing paths and loops) to be simplified
* @param options options for tolerance and selective simplification.
*/
public static consolidateAdjacentPrimitives(curves: CurveCollection, options?: ConsolidateAdjacentCurvePrimitivesOptions) {
const context = new ConsolidateAdjacentCurvePrimitivesContext(options);
curves.dispatchToGeometryHandler(context);
}
/**
* If reverse loops as necessary to make them all have CCW orientation for given outward normal.
* * Return an array of arrays which capture the input pointers.
* * In each first level array:
* * The first loop is an outer loop.
* * all subsequent loops are holes
* * The outer loop is CCW
* * The holes are CW.
* * Call PolygonOps.sortOuterAndHoleLoopsXY to have the result returned as an array of arrays of polygons.
* @param loops multiple loops to sort and reverse.
*/
public static sortOuterAndHoleLoopsXY(loops: Array<Loop | IndexedXYZCollection>): AnyRegion {
const loopAndArea: SortablePolygon[] = [];
for (const candidate of loops) {
if (candidate instanceof Loop)
SortablePolygon.pushLoop(loopAndArea, candidate);
else if (candidate instanceof IndexedXYZCollection) {
const loop = Loop.createPolygon(candidate);
SortablePolygon.pushLoop(loopAndArea, loop);
}
}
return SortablePolygon.sortAsAnyRegion(loopAndArea);
}
/**
* Find all areas bounded by the unstructured, possibly intersecting curves.
* * In `curvesAndRegions`, Loop/ParityRegion/UnionRegion contribute curve primitives.
* * Each returned [[SignedLoops]] object describes faces in a single connected component.
* * Within the [[SignedLoops]]:
* * positiveAreaLoops contains typical "interior" loops with positive area loop ordered counterclockwise
* * negativeAreaLoops contains (probably just one) "exterior" loop which is ordered clockwise and
* * slivers contains sliver areas such as appear between coincident curves.
* * edges contains [[LoopCurveLoopCurve]] about each edge within the component. In each edge object
* * loopA = a loop on one side of the edge
* * curveA = a curve that appears as one of loopA.children.
* * loopB = the loop on the other side
* * curveB = a curve that appears as one of loopB.children
* @param curvesAndRegions Any collection of curves.
* @alpha
*/
public static constructAllXYRegionLoops(curvesAndRegions: AnyCurve | AnyCurve[]): SignedLoops[] {
const primitivesA = RegionOps.collectCurvePrimitives(curvesAndRegions, undefined, true);
const primitivesB = this.expandLineStrings(primitivesA);
const range = this.curveArrayRange(primitivesB);
const intersections = CurveCurve.allIntersectionsAmongPrimitivesXY(primitivesB);
const graph = PlanarSubdivision.assembleHalfEdgeGraph(primitivesB, intersections);
return PlanarSubdivision.collectSignedLoopSetsInHalfEdgeGraph(graph, 1.0e-12 * range.xLength() * range.yLength());
}
/**
* collect all `CurvePrimitives` in loosely typed input.
* * This (always) recurses into primitives within collections (Path, Loop, ParityRegion, UnionRegion)
* * It (optionally) recurses to hidden primitives within primitives (i.e. CurveChainWithDistanceIndex)
* * If collectorArray is given, it is NOT cleared -- primitives are appended.
* @param candidates array of various CurvePrimitive and CurveCollection
* @param smallestPossiblePrimitives if false, leave CurveChainWithDistanceIndex as single primitives. If true, recurse to their children.
*/
public static collectCurvePrimitives(candidates: AnyCurve | AnyCurve[], collectorArray?: CurvePrimitive[],
smallestPossiblePrimitives: boolean = false,
explodeLinestrings: boolean = false): CurvePrimitive[] {
const results: CurvePrimitive[] = collectorArray === undefined ? [] : collectorArray;
if (candidates instanceof CurvePrimitive) {
candidates.collectCurvePrimitives(results, smallestPossiblePrimitives, explodeLinestrings);
} else if (candidates instanceof CurveCollection) {
candidates.collectCurvePrimitives(results, smallestPossiblePrimitives, explodeLinestrings);
} else if (Array.isArray(candidates)) {
for (const c of candidates) {
this.collectCurvePrimitives(c, results, smallestPossiblePrimitives, explodeLinestrings);
}
}
return results;
}
/**
* Copy primitive pointers from candidates to result array.
* * replace LineString3d by individual LineSegment3d.
* * all others unchanged.
* @param candidates
*/
public static expandLineStrings(candidates: CurvePrimitive[]): CurvePrimitive[] {
const result: CurvePrimitive[] = [];
for (const c of candidates) {
if (c instanceof LineString3d) {
for (let i = 0; i + 1 < c.packedPoints.length; i++) {
const q = c.getIndexedSegment(i);
if (q !== undefined)
result.push(q);
}
} else {
result.push(c);
}
}
return result;
}
/**
* Return the overall range of given curves.
* @param curves candidate curves
*/
public static curveArrayRange(data: any, worldToLocal?: Transform): Range3d {
const range = Range3d.create();
if (data instanceof GeometryQuery)
data.extendRange(range, worldToLocal);
else if (Array.isArray(data)) {
for (const c of data) {
if (c instanceof GeometryQuery)
c.extendRange(range, worldToLocal);
else if (c instanceof Point3d)
range.extendPoint(c, worldToLocal);
else if (c instanceof GrowableXYZArray)
range.extendRange(c.getRange(worldToLocal));
else if (Array.isArray(c))
range.extendRange(this.curveArrayRange(c, worldToLocal));
}
}
return range;
}
}
function pushToInOnOutArrays(curve: AnyCurve, select: number, arrayNegative: AnyCurve[], array0: AnyCurve[], arrayPositive: AnyCurve[]) {
if (select > 0)
arrayPositive.push(curve);
else if (select < 0)
arrayNegative.push(curve);
else
array0.push(curve);
} | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* A NotificationChannel is a medium through which an alert is delivered
* when a policy violation is detected. Examples of channels include email, SMS,
* and third-party messaging applications. Fields containing sensitive information
* like authentication tokens or contact info are only partially populated on retrieval.
*
* Notification Channels are designed to be flexible and are made up of a supported `type`
* and labels to configure that channel. Each `type` has specific labels that need to be
* present for that channel to be correctly configured. The labels that are required to be
* present for one channel `type` are often different than those required for another.
* Due to these loose constraints it's often best to set up a channel through the UI
* and import it to the provider when setting up a brand new channel type to determine which
* labels are required.
*
* A list of supported channels per project the `list` endpoint can be
* accessed programmatically or through the api explorer at https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.notificationChannelDescriptors/list .
* This provides the channel type and all of the required labels that must be passed.
*
* To get more information about NotificationChannel, see:
*
* * [API documentation](https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.notificationChannels)
* * How-to Guides
* * [Notification Options](https://cloud.google.com/monitoring/support/notification-options)
* * [Monitoring API Documentation](https://cloud.google.com/monitoring/api/v3/)
*
* ## Example Usage
* ### Notification Channel Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const basic = new gcp.monitoring.NotificationChannel("basic", {
* displayName: "Test Notification Channel",
* labels: {
* email_address: "fake_email@blahblah.com",
* },
* type: "email",
* });
* ```
* ### Notification Channel Sensitive
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const defaultNotificationChannel = new gcp.monitoring.NotificationChannel("default", {
* displayName: "Test Slack Channel",
* labels: {
* channel_name: "#foobar",
* },
* sensitiveLabels: {
* authToken: "one",
* },
* type: "slack",
* });
* ```
*
* ## Import
*
* NotificationChannel can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:monitoring/notificationChannel:NotificationChannel default {{name}}
* ```
*/
export class NotificationChannel extends pulumi.CustomResource {
/**
* Get an existing NotificationChannel 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?: NotificationChannelState, opts?: pulumi.CustomResourceOptions): NotificationChannel {
return new NotificationChannel(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:monitoring/notificationChannel:NotificationChannel';
/**
* Returns true if the given object is an instance of NotificationChannel. 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 NotificationChannel {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === NotificationChannel.__pulumiType;
}
/**
* An optional human-readable description of this notification channel. This description may provide additional details, beyond the display name, for the channel. This may not exceed 1024 Unicode characters.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* An optional human-readable name for this notification channel. It is recommended that you specify a non-empty and unique name in order to make it easier to identify the channels in your project, though this is not enforced. The display name is limited to 512 Unicode characters.
*/
public readonly displayName!: pulumi.Output<string | undefined>;
/**
* Whether notifications are forwarded to the described channel. This makes it possible to disable delivery of notifications to a particular channel without removing the channel from all alerting policies that reference the channel. This is a more convenient approach when the change is temporary and you want to receive notifications from the same set of alerting policies on the channel at some point in the future.
*/
public readonly enabled!: pulumi.Output<boolean | undefined>;
/**
* Configuration fields that define the channel and its behavior. The
* permissible and required labels are specified in the
* NotificationChannelDescriptor corresponding to the type field.
* Labels with sensitive data are obfuscated by the API and therefore the provider cannot
* determine if there are upstream changes to these fields. They can also be configured via
* the sensitiveLabels block, but cannot be configured in both places.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* The full REST resource name for this channel. The syntax is: projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID] The
* [CHANNEL_ID] is automatically assigned by the server on creation.
*/
public /*out*/ readonly name!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* Different notification type behaviors are configured primarily using the the `labels` field on this
* resource. This block contains the labels which contain secrets or passwords so that they can be marked
* sensitive and hidden from plan output. The name of the field, eg: password, will be the key
* in the `labels` map in the api request.
* Credentials may not be specified in both locations and will cause an error. Changing from one location
* to a different credential configuration in the config will require an apply to update state.
* Structure is documented below.
*/
public readonly sensitiveLabels!: pulumi.Output<outputs.monitoring.NotificationChannelSensitiveLabels | undefined>;
/**
* The type of the notification channel. This field matches the value of the NotificationChannelDescriptor.type field. See https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.notificationChannelDescriptors/list to get the list of valid values such as "email", "slack", etc...
*/
public readonly type!: pulumi.Output<string>;
/**
* User-supplied key/value data that does not need to conform to the corresponding NotificationChannelDescriptor's schema, unlike the labels field. This field is intended to be used for organizing and identifying the NotificationChannel objects.The field can contain up to 64 entries. Each key and value is limited to 63 Unicode characters or 128 bytes, whichever is smaller. Labels and values can contain only lowercase letters, numerals, underscores, and dashes. Keys must begin with a letter.
*/
public readonly userLabels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Indicates whether this channel has been verified or not. On a ListNotificationChannels or GetNotificationChannel
* operation, this field is expected to be populated.If the value is UNVERIFIED, then it indicates that the channel is
* non-functioning (it both requires verification and lacks verification); otherwise, it is assumed that the channel
* works.If the channel is neither VERIFIED nor UNVERIFIED, it implies that the channel is of a type that does not require
* verification or that this specific channel has been exempted from verification because it was created prior to
* verification being required for channels of this type.This field cannot be modified using a standard
* UpdateNotificationChannel operation. To change the value of this field, you must call VerifyNotificationChannel.
*/
public /*out*/ readonly verificationStatus!: pulumi.Output<string>;
/**
* Create a NotificationChannel 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: NotificationChannelArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: NotificationChannelArgs | NotificationChannelState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as NotificationChannelState | undefined;
inputs["description"] = state ? state.description : undefined;
inputs["displayName"] = state ? state.displayName : undefined;
inputs["enabled"] = state ? state.enabled : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["sensitiveLabels"] = state ? state.sensitiveLabels : undefined;
inputs["type"] = state ? state.type : undefined;
inputs["userLabels"] = state ? state.userLabels : undefined;
inputs["verificationStatus"] = state ? state.verificationStatus : undefined;
} else {
const args = argsOrState as NotificationChannelArgs | undefined;
if ((!args || args.type === undefined) && !opts.urn) {
throw new Error("Missing required property 'type'");
}
inputs["description"] = args ? args.description : undefined;
inputs["displayName"] = args ? args.displayName : undefined;
inputs["enabled"] = args ? args.enabled : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["sensitiveLabels"] = args ? args.sensitiveLabels : undefined;
inputs["type"] = args ? args.type : undefined;
inputs["userLabels"] = args ? args.userLabels : undefined;
inputs["name"] = undefined /*out*/;
inputs["verificationStatus"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(NotificationChannel.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering NotificationChannel resources.
*/
export interface NotificationChannelState {
/**
* An optional human-readable description of this notification channel. This description may provide additional details, beyond the display name, for the channel. This may not exceed 1024 Unicode characters.
*/
description?: pulumi.Input<string>;
/**
* An optional human-readable name for this notification channel. It is recommended that you specify a non-empty and unique name in order to make it easier to identify the channels in your project, though this is not enforced. The display name is limited to 512 Unicode characters.
*/
displayName?: pulumi.Input<string>;
/**
* Whether notifications are forwarded to the described channel. This makes it possible to disable delivery of notifications to a particular channel without removing the channel from all alerting policies that reference the channel. This is a more convenient approach when the change is temporary and you want to receive notifications from the same set of alerting policies on the channel at some point in the future.
*/
enabled?: pulumi.Input<boolean>;
/**
* Configuration fields that define the channel and its behavior. The
* permissible and required labels are specified in the
* NotificationChannelDescriptor corresponding to the type field.
* Labels with sensitive data are obfuscated by the API and therefore the provider cannot
* determine if there are upstream changes to these fields. They can also be configured via
* the sensitiveLabels block, but cannot be configured in both places.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The full REST resource name for this channel. The syntax is: projects/[PROJECT_ID]/notificationChannels/[CHANNEL_ID] The
* [CHANNEL_ID] is automatically assigned by the server on creation.
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Different notification type behaviors are configured primarily using the the `labels` field on this
* resource. This block contains the labels which contain secrets or passwords so that they can be marked
* sensitive and hidden from plan output. The name of the field, eg: password, will be the key
* in the `labels` map in the api request.
* Credentials may not be specified in both locations and will cause an error. Changing from one location
* to a different credential configuration in the config will require an apply to update state.
* Structure is documented below.
*/
sensitiveLabels?: pulumi.Input<inputs.monitoring.NotificationChannelSensitiveLabels>;
/**
* The type of the notification channel. This field matches the value of the NotificationChannelDescriptor.type field. See https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.notificationChannelDescriptors/list to get the list of valid values such as "email", "slack", etc...
*/
type?: pulumi.Input<string>;
/**
* User-supplied key/value data that does not need to conform to the corresponding NotificationChannelDescriptor's schema, unlike the labels field. This field is intended to be used for organizing and identifying the NotificationChannel objects.The field can contain up to 64 entries. Each key and value is limited to 63 Unicode characters or 128 bytes, whichever is smaller. Labels and values can contain only lowercase letters, numerals, underscores, and dashes. Keys must begin with a letter.
*/
userLabels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Indicates whether this channel has been verified or not. On a ListNotificationChannels or GetNotificationChannel
* operation, this field is expected to be populated.If the value is UNVERIFIED, then it indicates that the channel is
* non-functioning (it both requires verification and lacks verification); otherwise, it is assumed that the channel
* works.If the channel is neither VERIFIED nor UNVERIFIED, it implies that the channel is of a type that does not require
* verification or that this specific channel has been exempted from verification because it was created prior to
* verification being required for channels of this type.This field cannot be modified using a standard
* UpdateNotificationChannel operation. To change the value of this field, you must call VerifyNotificationChannel.
*/
verificationStatus?: pulumi.Input<string>;
}
/**
* The set of arguments for constructing a NotificationChannel resource.
*/
export interface NotificationChannelArgs {
/**
* An optional human-readable description of this notification channel. This description may provide additional details, beyond the display name, for the channel. This may not exceed 1024 Unicode characters.
*/
description?: pulumi.Input<string>;
/**
* An optional human-readable name for this notification channel. It is recommended that you specify a non-empty and unique name in order to make it easier to identify the channels in your project, though this is not enforced. The display name is limited to 512 Unicode characters.
*/
displayName?: pulumi.Input<string>;
/**
* Whether notifications are forwarded to the described channel. This makes it possible to disable delivery of notifications to a particular channel without removing the channel from all alerting policies that reference the channel. This is a more convenient approach when the change is temporary and you want to receive notifications from the same set of alerting policies on the channel at some point in the future.
*/
enabled?: pulumi.Input<boolean>;
/**
* Configuration fields that define the channel and its behavior. The
* permissible and required labels are specified in the
* NotificationChannelDescriptor corresponding to the type field.
* Labels with sensitive data are obfuscated by the API and therefore the provider cannot
* determine if there are upstream changes to these fields. They can also be configured via
* the sensitiveLabels block, but cannot be configured in both places.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Different notification type behaviors are configured primarily using the the `labels` field on this
* resource. This block contains the labels which contain secrets or passwords so that they can be marked
* sensitive and hidden from plan output. The name of the field, eg: password, will be the key
* in the `labels` map in the api request.
* Credentials may not be specified in both locations and will cause an error. Changing from one location
* to a different credential configuration in the config will require an apply to update state.
* Structure is documented below.
*/
sensitiveLabels?: pulumi.Input<inputs.monitoring.NotificationChannelSensitiveLabels>;
/**
* The type of the notification channel. This field matches the value of the NotificationChannelDescriptor.type field. See https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.notificationChannelDescriptors/list to get the list of valid values such as "email", "slack", etc...
*/
type: pulumi.Input<string>;
/**
* User-supplied key/value data that does not need to conform to the corresponding NotificationChannelDescriptor's schema, unlike the labels field. This field is intended to be used for organizing and identifying the NotificationChannel objects.The field can contain up to 64 entries. Each key and value is limited to 63 Unicode characters or 128 bytes, whichever is smaller. Labels and values can contain only lowercase letters, numerals, underscores, and dashes. Keys must begin with a letter.
*/
userLabels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
} | the_stack |
import {repository} from "@loopback/repository";
import {PatientRepository} from "../repositories";
import {Contact, InfectionExposure, Patient} from "../models";
import {PatientStatus} from "../common/utils/enums";
import {HttpErrors} from "@loopback/rest";
import {PushNotificationService} from "./pushnotification.service";
import {service} from "@loopback/core";
import {ExposureRisk, ExposureRiskDecisor} from "./exposure-risk-decisor";
import {BluetoothUuidGenerator} from "../common/utils/bluetooth-uuid-generator";
import {UserValidatorService} from "./user-validator.service";
export class PatientService {
constructor(
@repository(PatientRepository) public patientRepository : PatientRepository,
@service('UserValidatorService') public userValidatorService: UserValidatorService,
@service(PushNotificationService) public pushNotificationService: PushNotificationService,
@service('ExposureRiskDecisor') public exposureRiskDecisor: ExposureRiskDecisor,
) {}
async signUpPatient(patient: Patient): Promise<Patient | null> {
if(patient != null) {
//generate an unique uuid for each patient (it will be used on centralized model only)
patient.serviceAdvertisementUUID = BluetoothUuidGenerator.generateUUID();
patient.status = PatientStatus.UNKNOWN; //initial status
patient.created = new Date();
let existingPatinet = null;
//try to find the patient by the health insurance card number
if (patient.healthInsuranceCardNumber != null && patient.healthInsuranceCardNumber.length > 0) {
patient.healthInsuranceCardNumber = this.normalizeDocumentId(patient.healthInsuranceCardNumber);
existingPatinet = await this.patientRepository.findOne({where: {healthInsuranceCardNumber: patient.healthInsuranceCardNumber}});
}
//if no existing patient, try with the document number (need to refactor this piece to be configurable)
if (existingPatinet == null && patient.documentNumber != null && patient.documentNumber.length > 0) {
patient.documentNumber = this.normalizeDocumentId(patient.documentNumber);
existingPatinet = await this.patientRepository.findOne({where: {documentNumber: patient.documentNumber}});
}
if (existingPatinet != null) {
//ovewrite everything with the given patient data (to avoid issues with validateUsers because the
//user has been loaded from database, so it was previously validated
existingPatinet.copy(patient);
existingPatinet.updated = new Date();
//and now set the existing patient to the current patient variable
patient = existingPatinet;
}
//very important: validation not just validate the user information against the
//correspondent health department or authority, but also alter the patient with
//info from them
let validationResult = await this.userValidatorService.validateUser(<Patient>patient);
if (validationResult.isValid) {
patient = validationResult.patient; //recover the patient from the validation result before creating it:
if(existingPatinet != null) {
await this.patientRepository.update(patient);
return new Promise<Patient>(resolve => resolve(patient));
}
else {
return this.patientRepository.create(patient);
}
} else {
throw new HttpErrors.UnprocessableEntity(validationResult.message);
}
}
else {
throw new HttpErrors.BadRequest("Internal Server Error");
}
}
public normalizeDocumentId(documentId: string) {
let returnValue = documentId;
if(documentId != null && documentId.length > 0) {
returnValue = documentId.replace(/\s+/gi, "").toUpperCase();
}
return returnValue;
}
/**
* Centralized model to decide to put in quarantine
*
* @param contacts
*/
async putInQuarantine(contacts: Contact[]) {
//resolve:
let uniqueContactUUIDs = new Map<string, boolean>();
contacts.forEach(contact => {
uniqueContactUUIDs.set(contact.targetUuid, true);
});
for (let key of uniqueContactUUIDs.keys()) {
let patient = await this.patientRepository.findOne({"where": { "serviceAdvertisementUUID": key.toLowerCase() }});
if(patient != null) {
//update status of unknown users or uninfected users (that may be now infected). Also do not change the status if it's already infection suspected!
if(patient.status != PatientStatus.IMMUNE && patient.status != PatientStatus.INFECTED && patient.status != PatientStatus.INFECTION_SUSPECTED) {
this.doChangeStatus(patient, PatientStatus.INFECTION_SUSPECTED);
}
}
else {
console.error("No patient found for advertisement uuid: " + key.toLowerCase());
}
}
}
/**
* Decentralized model to decide to put in quarantine
*
* @param contacts
*/
async decideToPutInQuarantine(infectionExposures: InfectionExposure[]) {
let patientsToPutInQuarantine = new Map<string, InfectionExposure[]>()
infectionExposures.forEach(infectionExposure => {
if(!patientsToPutInQuarantine.has(infectionExposure.patientId)) {
patientsToPutInQuarantine.set(infectionExposure.patientId, []);
}
patientsToPutInQuarantine.get(infectionExposure.patientId)?.push(infectionExposure);
});
for (let patientId of patientsToPutInQuarantine.keys()) {
let patientInfectionExposures = patientsToPutInQuarantine.get(patientId);
if(patientInfectionExposures != undefined) {
let patient = await this.patientRepository.findById(patientId);
if (patient != null) {
let risk = this.exposureRiskDecisor.decideRisk(patientInfectionExposures);
switch(risk) {
case ExposureRisk.HIGH:
console.log('HIGH RISK DETECTED on patient: ' + patientId);
break;
case ExposureRisk.LOW:
console.log('LOW RISK DETECTED on patient: ' + patientId);
break;
case ExposureRisk.NONE:
console.log('NO RISK DETECTED on patient: ' + patientId);
break;
}
if ((risk == ExposureRisk.HIGH && process.env.EXPOSURE_RISK_LEVEL_TO_QUARANTINE == 'HIGH') ||
(risk == ExposureRisk.LOW && process.env.EXPOSURE_RISK_LEVEL_TO_QUARANTINE == 'LOW')) {
//update status of unknown users or uninfected users (that may be now infected). Also do not change the status if it's already infection suspected!
if (patient.status != PatientStatus.IMMUNE && patient.status != PatientStatus.INFECTED && patient.status != PatientStatus.INFECTION_SUSPECTED) {
await this.doChangeStatus(patient, PatientStatus.INFECTION_SUSPECTED);
}
} else if(risk == ExposureRisk.LOW) {
//back to need to make a test (but not quarantine) since the exposure exists but with no risk
if (patient.status != PatientStatus.IMMUNE && patient.status != PatientStatus.INFECTED && patient.status != PatientStatus.INFECTION_SUSPECTED && patient.status != PatientStatus.UNKNOWN) {
await this.doChangeStatus(patient, PatientStatus.UNKNOWN);
}
}
}
else {
console.error("No patient found for id: " + patientId);
}
}
}
}
public changeStatus(documentNumber: string, healthInsuranceCardNumber: string, status: number, date: string) {
let where: any = {};
if(documentNumber != null && documentNumber.length > 0) {
where['documentNumber'] = this.normalizeDocumentId(documentNumber);
}
if(healthInsuranceCardNumber != null && healthInsuranceCardNumber.length > 0) {
where['healthInsuranceCardNumber'] = this.normalizeDocumentId(healthInsuranceCardNumber);
}
let filter = {'where': where};
let returnValue: Promise<Patient | null> = new Promise((resolve, reject) => {
this.patientRepository.find(filter).then(patients => {
if (patients != null && patients.length > 0) {
patients.forEach(async patient => {
await this.doChangeStatus(patient, status, date);
});
resolve(patients[0]); //for legacy compatibility
}
else {
reject(new HttpErrors[404]);
}
})
.catch(error => {
console.error("Error trying to locate patient with document number " + documentNumber + ", healthInsuranceCardNumber " + healthInsuranceCardNumber + ": " + JSON.stringify(error));
reject(new HttpErrors[404]);
});
});
return returnValue;
}
protected async doChangeStatus(patient: any, status: number, date: string | null = null) {
patient.status = status;
patient.statusDate = date;
patient.updated = new Date();
await this.patientRepository.update(patient);
let title = "Atención";
let text = null;
switch (status) {
case PatientStatus.INFECTED:
text = "Ya tienes los resultados de tu test: POSITIVO. Ponte en cuarentena y contacta con tu centro de salud.";
break;
case PatientStatus.UNINFECTED:
text = "Ya tienes los resultados de tu test: NEGATIVO. Enhorabuena!";
break;
case PatientStatus.INFECTION_SUSPECTED:
text = "Has estado en contacto activamente con pacientes con riesgo de coronavirus en los últimos días. Por favor, ponte en cuarentena y contacta con tu centro de salud.";
break;
case PatientStatus.IMMUNE:
text = "Ya tienes los resultados de tu test: NEGATIVO. Enhorabuena!";
break;
}
if (text != null) {
this.pushNotificationService.sendNotificationToPatient(patient.id, title, text);
}
}
} | the_stack |
import yargs = require("yargs");
import path = require("path");
import { execSync } from "child_process";
import * as ts from "typescript";
import glob = require("glob");
import * as util from "util";
import * as handlebars from "handlebars";
import * as fs from "fs";
import mkdirp = require("mkdirp");
import _ = require("lodash");
interface FidlFilesJson {
interfaces: Record<string, string[]>;
}
const globAsync = util.promisify(glob);
const version = require("../package.json").version;
const generatorName = `joynr-generator-standalone-${version}.jar`;
const generatorPath = path.join(__dirname, "../jars", generatorName);
const fidlFileDesc = `Json file containing .fidl files grouped by fidlFileGroups used to create joynr-includes.
Automatically sets -i option.
interface FidlFilesJson {
interfaces: Record<string (fidlFileGroup), string[] (relative Paths to fidl files)>;
}`;
// eslint-disable-next-line no-console
const log = console.log;
// eslint-disable-next-line no-console
const error = console.error;
async function main(): Promise<void> {
const argv = yargs
.usage("Usage: $0 [options]")
.example(`$0 -m Radio.fidl -m Test.fidl -o src-gen`, "compile 2 different .fidl files")
.example(`$0 -m model -js`, "use all fidl files inside the ’model’ directory. Compile to js")
.example(
`$0 -f model fidl-files.json`,
`compile all .fidl files listed in fidl-files.json and generate includes`
)
.example(
`$0 -f -m Radio.fidl -t proxy|provider|both`,
"create code from Radio.fidl relevant for proxy|provider|both cases"
)
.option("modelPath", {
alias: "m",
desc: "path to a directory with fidl files, or a single fidl file (can be supplied multiple times)"
})
.option("fidlFile", {
alias: "f",
desc: fidlFileDesc
})
.option("outputPath", { alias: "o", demandOption: true, desc: "output path will be created if not existing" })
.option("js", {
alias: "j",
boolean: true,
desc: "compile to js with d.ts instead of ts"
})
.option("includes", {
alias: "i",
boolean: true,
desc: "create joynr includes"
})
.option("target", {
alias: "t",
desc: "target is proxy|provider|both code"
})
.help()
.wrap(yargs.terminalWidth()).argv;
const outputPath = argv.outputPath as string;
const modelPath = argv.modelPath as string | undefined;
const fidlFile = argv.fidlFile as string | undefined;
let target = argv.target as string | undefined;
if (!target) {
target = "";
}
if (!modelPath && !fidlFile) {
error("Please provide either modelPath or fidlFile option");
process.exit(1);
}
let parsedJson: FidlFilesJson;
let modelPathArray: string[] = Array.isArray(modelPath) ? modelPath : modelPath ? [modelPath] : [];
const baseArray = modelPathArray;
if (fidlFile) {
parsedJson = JSON.parse(fs.readFileSync(fidlFile, "utf8"));
Object.values(parsedJson.interfaces).forEach(paths => {
modelPathArray = modelPathArray.concat(paths);
});
}
await generateTSSources(modelPathArray, outputPath, target);
if (fidlFile) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
Object.entries(parsedJson!.interfaces).forEach(([fidlFileGroup, fidlFiles]) => {
createJoynrIncludes(fidlFiles, outputPath, fidlFileGroup);
});
} else if (argv.includes) {
let files: string[] = [];
baseArray.forEach(modelPath => {
if (modelPath.endsWith(".fidl")) {
files.push(modelPath);
} else {
// assume directory
files = files.concat(glob.sync(`${modelPath}/**/*.fidl`));
}
});
createJoynrIncludes(files, outputPath);
}
const files = (await globAsync(`${outputPath}/**/*.ts`)).filter(file => !file.includes(".d.ts"));
if (argv.js) {
compileToJS(files);
}
log("All done!");
process.exit(0);
}
async function generateTSSources(modelPaths: string | string[], outputPath: string, target: string): Promise<void> {
([] as string[]).concat(modelPaths).forEach(path => {
let targetCommandParameter = "";
if (target != "") {
targetCommandParameter = ` -target ${target}`;
}
const command =
`java -jar ${generatorPath}` +
` -modelPath ${path} -outputPath ${outputPath}` +
` -generationLanguage javascript` +
`${targetCommandParameter}`;
log(`executing command: ${command}`);
execSync(command);
});
log(`ts generation done`);
}
/**
* Compile JS files to TS according to
* https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API
* @param fileNames list of files to be compiled
*/
function compileToJS(fileNames: string[]): void {
log(`compiling ${fileNames.length} files to JS`);
const compileOptions = {
noEmitOnError: true,
noImplicitAny: true,
strictNullChecks: true,
noUnusedParameters: true,
noImplicitThis: true,
target: ts.ScriptTarget.ES2017,
module: ts.ModuleKind.CommonJS,
esModuleInterop: true,
declaration: true
};
const program = ts.createProgram(fileNames, compileOptions);
const emitResult = program.emit();
const allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
allDiagnostics.forEach(diagnostic => {
if (diagnostic.file) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start!);
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
log(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
} else {
log(`${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`);
}
});
const exitCode = emitResult.emitSkipped ? 1 : 0;
log(`Process exiting with code '${exitCode}'.`);
process.exit(exitCode);
}
// Setup the template file that will be used to generate the JavaScript file(s). A handler
// must be registered so Handlebars can determine if a variable is an object or not.
handlebars.registerHelper("ifObject", function(this: any, item, options) {
if (typeof item === "object") {
return options.fn(this);
} else {
return options.inverse(this);
}
});
handlebars.registerHelper("concat", (...args) => {
return new handlebars.SafeString(
args
.slice(0, -1)
.filter(Boolean)
.join("_")
);
});
/**
* Scans a directory, creating a map of data in order to generate the JavaScript file.
*
* @returns An object mapping bracket notation interface to file path to required file
* @param dir The directory to begin scanning for files
* @param relativeFromDir The file path will be calculated as a relative path
* from this directory
*/
function createRequiresFromDir(dir: string, relativeFromDir: string): Record<string, any> {
const files = fs.readdirSync(dir);
const modulePaths: Record<string, any> = {};
files.forEach(file => {
const fullPath = path.join(dir, file);
const currentFileStat = fs.statSync(fullPath);
if (currentFileStat.isDirectory()) {
const subDirModules = createRequiresFromDir(fullPath, relativeFromDir);
const transformedSubDirModules: Record<string, any> = {};
Object.keys(subDirModules).forEach(subModule => {
transformedSubDirModules[subModule] = subDirModules[subModule];
});
modulePaths[file] = transformedSubDirModules;
} else if (currentFileStat.isFile()) {
// potential issue if basename equals other directory name.
const moduleName = path.basename(file);
// remove Suffix to get only one entry for .js .ts and .d.ts in case old compiled code is still there
const moduleNameWithoutSuffix = moduleName.split(".")[0];
const modulePath = path.relative(relativeFromDir, path.join(dir, moduleNameWithoutSuffix));
modulePaths[moduleNameWithoutSuffix] = modulePath;
}
});
return modulePaths;
}
function createJoynrIncludes(
fidlFiles: string[],
outputFolder: string,
fidlFileGroup: string = "joynr-includes"
): void {
log(`creating joynr includes for fidlFiles ${JSON.stringify(fidlFiles)} and fidlFileGroup ${fidlFileGroup}`);
const templateFilePath = path.join(__dirname, "joynr-require-interface.hbs");
const templateFile = fs.readFileSync(templateFilePath, "utf8");
const requiresTemplate = handlebars.compile(templateFile, { noEscape: true });
const requiresPerFile: Record<string, any> = {};
fidlFiles.forEach(fidlFile => {
// Gather the package name in order to construct a path, generate the method
// names and paths and then generate the file's contents.
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const fidlFileContents = fs.readFileSync(fidlFile, "utf8")!;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const packagePath = fidlFileContents.match(/^package\s+(.+)$/m)![1];
const packagePathParts = packagePath.split(".");
// eslint-disable-next-line prefer-spread
const outputPathSuffix = path.join.apply(path, packagePathParts);
const outputFolderPerGroup = path.join(outputFolder, fidlFileGroup);
const newFilename = path.join(outputFolderPerGroup, `${packagePathParts.pop()}`);
const requires = createRequiresFromDir(
path.join(outputFolder, "joynr", outputPathSuffix),
outputFolderPerGroup
);
requiresPerFile[newFilename] = _.merge(requiresPerFile[newFilename], requires);
try {
mkdirp.sync(outputFolderPerGroup);
} catch (e) {
if (e.code !== "EEXIST") {
throw e;
}
}
});
for (const file in requiresPerFile) {
if (requiresPerFile.hasOwnProperty(file)) {
const requires = requiresPerFile[file];
fs.writeFileSync(`${file}.ts`, requiresTemplate({ requires, fileName: path.basename(file, ".ts") }));
}
}
}
if (!module.parent) {
main().catch(err => {
log(err);
process.exit(1);
});
} | the_stack |
import ui, { setupSelectedNode } from "./ui";
import { data } from "./network";
import { Node, getShapeTextureFaceSize } from "../../data/CubicModelNodes";
import { TextureEdit } from "../../data/CubicModelAsset";
const THREE = SupEngine.THREE;
const tmpVector3 = new THREE.Vector3();
const textureArea: {
gameInstance: SupEngine.GameInstance;
cameraControls: any;
shapeLineMeshesByNodeId: { [nodeId: string]: THREE.LineSegments; }
textureMesh: THREE.Mesh;
selectionRenderer: any;
mode: string;
paintTool: string;
colorInput: HTMLInputElement;
pasteActor: SupEngine.Actor;
pasteMesh: THREE.Mesh;
} = { shapeLineMeshesByNodeId: {} } as any;
export default textureArea;
const canvas = document.querySelector(".texture-container canvas") as HTMLCanvasElement;
if (SupApp != null) {
document.addEventListener("copy", (event: ClipboardEvent) => {
if (document.activeElement !== canvas) return;
const dataURL = data.cubicModelUpdater.cubicModelAsset.clientTextureDatas["map"].ctx.canvas.toDataURL();
SupApp.clipboard.copyFromDataURL(dataURL);
});
}
const pasteCtx = document.createElement("canvas").getContext("2d");
document.addEventListener("paste", (event: ClipboardEvent) => {
if (document.activeElement !== canvas) return;
if (event.clipboardData.items[0] == null) return;
if (event.clipboardData.items[0].type.indexOf("image") === -1) return;
if (textureArea.mode !== "paint") return;
if (textureArea.pasteMesh != null) clearPasteSelection();
const imageBlob = (event.clipboardData.items[0] as any).getAsFile();
const image = new Image();
image.src = URL.createObjectURL(imageBlob);
image.onload = () => {
pasteCtx.canvas.width = image.width;
pasteCtx.canvas.height = image.height;
pasteCtx.drawImage(image, 0, 0);
const texture = new THREE.Texture(pasteCtx.canvas);
texture.needsUpdate = true;
texture.magFilter = THREE.NearestFilter;
texture.minFilter = THREE.NearestFilter;
const geom = new THREE.PlaneBufferGeometry(image.width, image.height, 1, 1);
const mat = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, map: texture });
textureArea.pasteMesh = new THREE.Mesh(geom, mat);
textureArea.pasteActor.threeObject.add(textureArea.pasteMesh);
textureArea.pasteActor.setLocalPosition(tmpVector3.set(image.width / 2, -image.height / 2, 1));
textureArea.selectionRenderer.setSize(image.width, image.height);
textureArea.selectionRenderer.actor.setParent(textureArea.pasteActor);
textureArea.selectionRenderer.actor.setLocalPosition(tmpVector3.set(0, 0, 5));
textureArea.selectionRenderer.actor.threeObject.visible = true;
};
});
textureArea.gameInstance = new SupEngine.GameInstance(canvas);
textureArea.gameInstance.threeRenderer.setClearColor(0xbbbbbb);
const cameraActor = new SupEngine.Actor(textureArea.gameInstance, "Camera");
cameraActor.setLocalPosition(new SupEngine.THREE.Vector3(0, 0, 10));
const cameraComponent = new SupEngine.componentClasses["Camera"](cameraActor);
cameraComponent.setOrthographicMode(true);
cameraComponent.setOrthographicScale(10);
textureArea.cameraControls = new SupEngine.editorComponentClasses["Camera2DControls"](cameraActor, cameraComponent,
{ zoomSpeed: 1.5, zoomMin: 1, zoomMax: 200 });
const selectionActor = new SupEngine.Actor(textureArea.gameInstance, "Selection");
textureArea.selectionRenderer = new SupEngine.editorComponentClasses["SelectionRenderer"](selectionActor);
textureArea.pasteActor = new SupEngine.Actor(textureArea.gameInstance, "Paste");
function clearPasteSelection() {
textureArea.pasteActor.threeObject.remove(textureArea.pasteMesh);
textureArea.selectionRenderer.actor.setParent(null);
textureArea.selectionRenderer.actor.threeObject.visible = false;
textureArea.pasteMesh = null;
}
export function setup() {
setupTexture();
data.cubicModelUpdater.cubicModelAsset.nodes.walk(addNode);
}
export function setupTexture() {
if (textureArea.textureMesh != null) textureArea.gameInstance.threeScene.remove(textureArea.textureMesh);
const asset = data.cubicModelUpdater.cubicModelAsset;
const threeTexture = data.cubicModelUpdater.cubicModelAsset.pub.textures["map"];
const geom = new THREE.PlaneBufferGeometry(asset.pub.textureWidth, asset.pub.textureHeight, 1, 1);
const mat = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, map: threeTexture });
textureArea.textureMesh = new THREE.Mesh(geom, mat);
textureArea.textureMesh.position.set(asset.pub.textureWidth / 2, -asset.pub.textureHeight / 2, -1);
textureArea.gameInstance.threeScene.add(textureArea.textureMesh);
textureArea.textureMesh.updateMatrixWorld(false);
}
textureArea.mode = "layout";
updateMode();
document.querySelector(".texture-container .controls .mode-selection").addEventListener("click", (event) => {
const target = event.target as HTMLInputElement;
if (target.tagName !== "INPUT") return;
textureArea.mode = target.value;
updateMode();
clearPasteSelection();
});
textureArea.paintTool = "brush";
document.querySelector(".texture-container .controls .paint-mode-container .tool").addEventListener("click", (event) => {
const target = event.target as HTMLInputElement;
if (target.tagName !== "INPUT") return;
textureArea.paintTool = target.value;
});
function updateMode() {
for (const mode of [ "layout", "paint" ]) {
const container = document.querySelector(`.${mode}-mode-container`) as HTMLDivElement;
container.hidden = mode !== textureArea.mode;
}
}
textureArea.colorInput = document.querySelector("input.color") as HTMLInputElement;
const lineMaterial = new THREE.LineBasicMaterial({ color: 0xff00ff, opacity: 0.4, depthTest: false, depthWrite: false, transparent: true });
const selectedLineMaterial = new THREE.LineBasicMaterial({ color: 0xff00ff, opacity: 1, depthTest: false, depthWrite: false, transparent: true });
const verticesByShapeType: { [type: string]: number } = {
"none": 0,
"box": 20
};
export function addNode(node: Node) {
const geometry = new THREE.Geometry();
const line = new THREE.LineSegments(geometry, lineMaterial);
textureArea.shapeLineMeshesByNodeId[node.id] = line;
textureArea.gameInstance.threeScene.add(line);
line.updateMatrixWorld(false);
updateNode(node);
}
export function updateNode(node: Node) {
const line = textureArea.shapeLineMeshesByNodeId[node.id];
const verticesCount = verticesByShapeType[node.shape.type];
const vertices = (line.geometry as THREE.Geometry).vertices;
if (vertices.length < verticesCount) {
for (let i = vertices.length; i < verticesCount; i++) vertices.push(new THREE.Vector3(0, 0, 0));
} else if (vertices.length > verticesCount) {
vertices.length = verticesCount;
}
// let origin = { x: node.shape.textureOffset.x, y: -node.shape.textureOffset.y };
// TEMPORARY
const origin = { x: node.shape.textureLayout["left"].offset.x, y: -node.shape.textureLayout["top"].offset.y };
switch (node.shape.type) {
case "box":
const size: { x: number; y: number; z: number; } = node.shape.settings.size;
// Top horizontal line
vertices[0].set(origin.x + size.z, origin.y, 1);
vertices[1].set(origin.x + size.z + size.x * 2, origin.y, 1);
// Shared horizontal line
vertices[2].set(origin.x, origin.y - size.z, 1);
vertices[3].set(origin.x + size.x * 2 + size.z * 2, origin.y - size.z, 1);
// Bottom horizontal line
vertices[4].set(origin.x, origin.y - size.z - size.y, 1);
vertices[5].set(origin.x + size.x * 2 + size.z * 2, origin.y - size.z - size.y, 1);
// Shared vertical line
vertices[6].set(origin.x + size.z, origin.y, 1);
vertices[7].set(origin.x + size.z, origin.y - size.z - size.y, 1);
// First row, second vertical line
vertices[8].set(origin.x + size.z + size.x, origin.y, 1);
vertices[9].set(origin.x + size.z + size.x, origin.y - size.z, 1);
// First row, third vertical line
vertices[10].set(origin.x + size.z + size.x * 2, origin.y, 1);
vertices[11].set(origin.x + size.z + size.x * 2, origin.y - size.z, 1);
// Second row, first vertical line
vertices[12].set(origin.x, origin.y - size.z, 1);
vertices[13].set(origin.x, origin.y - size.z - size.y, 1);
// Second row, fifth vertical line
vertices[14].set(origin.x + size.x * 2 + size.z * 2, origin.y - size.z, 1);
vertices[15].set(origin.x + size.x * 2 + size.z * 2, origin.y - size.z - size.y, 1);
// Second row, third vertical line
vertices[16].set(origin.x + size.x + size.z, origin.y - size.z, 1);
vertices[17].set(origin.x + size.x + size.z, origin.y - size.z - size.y, 1);
// Second row, fourth vertical line
vertices[18].set(origin.x + size.x + size.z * 2, origin.y - size.z, 1);
vertices[19].set(origin.x + size.x + size.z * 2, origin.y - size.z - size.y, 1);
break;
}
(line.geometry as THREE.Geometry).verticesNeedUpdate = true;
}
export function updateRemovedNode() {
for (const nodeId in textureArea.shapeLineMeshesByNodeId) {
if (data.cubicModelUpdater.cubicModelAsset.nodes.byId[nodeId] != null) continue;
const line = textureArea.shapeLineMeshesByNodeId[nodeId];
line.parent.remove(line);
line.geometry.dispose();
delete textureArea.shapeLineMeshesByNodeId[nodeId];
}
}
const selectedNodeLineMeshes: THREE.LineSegments[] = [];
export function setSelectedNode(nodeIds: string[]) {
for (const selectedNodeLineMesh of selectedNodeLineMeshes) selectedNodeLineMesh.material = lineMaterial;
selectedNodeLineMeshes.length = 0;
for (const nodeId of nodeIds) {
const selectedNodeLineMesh = textureArea.shapeLineMeshesByNodeId[nodeId];
selectedNodeLineMesh.material = selectedLineMaterial;
selectedNodeLineMeshes.push(selectedNodeLineMesh);
}
}
const mousePosition = new THREE.Vector3();
const cameraPosition = new THREE.Vector3();
let isDrawing = false;
let isDragging = false;
let isMouseDown = false;
let hasMouseMoved = false;
const previousMousePosition = new THREE.Vector3();
export function handleTextureArea() {
const inputs = textureArea.gameInstance.input;
const keys = (window as any).KeyEvent;
mousePosition.set(inputs.mousePosition.x, inputs.mousePosition.y, 0);
cameraComponent.actor.getLocalPosition(cameraPosition);
mousePosition.x /= textureArea.gameInstance.threeRenderer.domElement.width;
mousePosition.x = mousePosition.x * 2 - 1;
mousePosition.x *= cameraComponent.orthographicScale / 2 * cameraComponent.cachedRatio;
mousePosition.x += cameraPosition.x;
mousePosition.x = Math.floor(mousePosition.x);
mousePosition.y /= textureArea.gameInstance.threeRenderer.domElement.height;
mousePosition.y = mousePosition.y * 2 - 1;
mousePosition.y *= cameraComponent.orthographicScale / 2;
mousePosition.y -= cameraPosition.y;
mousePosition.y = Math.floor(mousePosition.y);
if (textureArea.mode === "layout") {
if (isMouseDown && !inputs.mouseButtons[0].isDown) {
isDragging = false;
isMouseDown = false;
if (!hasMouseMoved && !isDragging) {
const hoveredNodeIds = getHoveredNodeIds();
const isShiftDown = inputs.keyboardButtons[keys.DOM_VK_SHIFT].isDown;
if (!isShiftDown) ui.nodesTreeView.clearSelection();
if (hoveredNodeIds.length > 0) {
if (!isShiftDown) {
const nodeElt = ui.nodesTreeView.treeRoot.querySelector(`li[data-id='${hoveredNodeIds[0]}']`) as HTMLLIElement;
ui.nodesTreeView.addToSelection(nodeElt);
} else {
for (const nodeId of hoveredNodeIds) {
let isAlreadyAdded = false;
for (const nodeElt of ui.nodesTreeView.selectedNodes) {
if (nodeId === nodeElt.dataset["id"]) {
isAlreadyAdded = true;
break;
}
}
if (!isAlreadyAdded) {
const nodeElt = ui.nodesTreeView.treeRoot.querySelector(`li[data-id='${nodeId}']`) as HTMLLIElement;
ui.nodesTreeView.addToSelection(nodeElt);
break;
}
}
}
}
setupSelectedNode();
}
hasMouseMoved = false;
} else if (isDragging) {
const x = mousePosition.x - previousMousePosition.x;
const y = mousePosition.y - previousMousePosition.y;
if (x !== 0 || y !== 0) {
hasMouseMoved = true;
const nodeIds = [] as string[];
for (const selectedNode of ui.nodesTreeView.selectedNodes) nodeIds.push(selectedNode.dataset["id"]);
data.projectClient.editAsset(SupClient.query.asset, "moveNodeTextureOffset", nodeIds, { x, y });
}
} else if (inputs.mouseButtons[0].wasJustPressed) {
isMouseDown = true;
hasMouseMoved = false;
const hoveredNodeIds = getHoveredNodeIds();
for (const selectedNode of ui.nodesTreeView.selectedNodes) {
if (hoveredNodeIds.indexOf(selectedNode.dataset["id"]) !== -1) {
isDragging = true;
break;
}
}
}
previousMousePosition.set(mousePosition.x, mousePosition.y, 0);
} else if (textureArea.mode === "paint") {
if (isMouseDown && !inputs.mouseButtons[0].isDown) isMouseDown = false;
// Paste element
if (textureArea.pasteMesh != null) {
if (isMouseDown) {
tmpVector3.set(mousePosition.x + previousMousePosition.x, -mousePosition.y + previousMousePosition.y, 0);
textureArea.pasteActor.setLocalPosition(tmpVector3);
return;
}
if (inputs.keyboardButtons[keys.DOM_VK_RIGHT].wasJustPressed) {
textureArea.pasteMesh.position.x += 1;
textureArea.pasteMesh.updateMatrixWorld(false);
}
if (inputs.keyboardButtons[keys.DOM_VK_LEFT].wasJustPressed) {
textureArea.pasteMesh.position.x -= 1;
textureArea.pasteMesh.updateMatrixWorld(false);
}
if (inputs.keyboardButtons[keys.DOM_VK_UP].wasJustPressed) {
textureArea.pasteMesh.position.y += 1;
textureArea.pasteMesh.updateMatrixWorld(false);
}
if (inputs.keyboardButtons[keys.DOM_VK_DOWN].wasJustPressed) {
textureArea.pasteMesh.position.y -= 1;
textureArea.pasteMesh.updateMatrixWorld(false);
}
if (inputs.mouseButtons[0].wasJustPressed) {
const position = textureArea.pasteActor.getLocalPosition(tmpVector3);
const width = pasteCtx.canvas.width;
const height = pasteCtx.canvas.height;
if (mousePosition.x > position.x - width / 2 && mousePosition.x < position.x + width / 2 &&
-mousePosition.y > position.y - height / 2 && -mousePosition.y < position.y + height / 2) {
isMouseDown = true;
previousMousePosition.set(position.x - mousePosition.x, position.y + mousePosition.y, 0);
return;
}
const imageData = pasteCtx.getImageData(0, 0, width, height).data;
const edits: TextureEdit[] = [];
const startX = position.x - width / 2;
const startY = -position.y - height / 2;
for (let i = 0; i < width; i++) {
for (let j = 0; j < height; j++) {
const index = (j * width + i) * 4;
const x = startX + i;
if (x < 0 || x >= data.cubicModelUpdater.cubicModelAsset.pub.textureWidth) continue;
const y = startY + j;
if (y < 0 || y >= data.cubicModelUpdater.cubicModelAsset.pub.textureHeight) continue;
edits.push({ x, y, value: { r: imageData[index], g: imageData[index + 1], b: imageData[index + 2], a: imageData[index + 3] } });
}
}
data.projectClient.editAsset(SupClient.query.asset, "editTexture", "map", edits);
clearPasteSelection();
}
return;
}
// Edit texture
if (!isDrawing) {
if (inputs.mouseButtons[0].wasJustPressed) isDrawing = true;
else if (inputs.mouseButtons[2].wasJustPressed) {
if (mousePosition.x < 0 || mousePosition.x >= data.cubicModelUpdater.cubicModelAsset.pub.textureWidth) return;
if (mousePosition.y < 0 || mousePosition.y >= data.cubicModelUpdater.cubicModelAsset.pub.textureHeight) return;
const textureData = data.cubicModelUpdater.cubicModelAsset.textureDatas["map"];
const index = (mousePosition.y * data.cubicModelUpdater.cubicModelAsset.pub.textureWidth + mousePosition.x) * 4;
const r = textureData[index + 0];
const g = textureData[index + 1];
const b = textureData[index + 2];
const a = textureData[index + 3];
if (a === 0) {
(document.getElementById("eraser-tool") as HTMLInputElement).checked = true;
textureArea.paintTool = "eraser";
} else {
(document.getElementById("brush-tool") as HTMLInputElement).checked = true;
textureArea.paintTool = "brush";
const hex = ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
textureArea.colorInput.value = `#${hex}`;
}
}
} else if (!inputs.mouseButtons[0].isDown) isDrawing = false;
if (isDrawing) {
if (mousePosition.x < 0 || mousePosition.x >= data.cubicModelUpdater.cubicModelAsset.pub.textureWidth) return;
if (mousePosition.y < 0 || mousePosition.y >= data.cubicModelUpdater.cubicModelAsset.pub.textureHeight) return;
const hex = parseInt(textureArea.colorInput.value.slice(1), 16);
const brush = { r: 0, g: 0, b: 0, a: 0 };
if (textureArea.paintTool === "brush") {
brush.r = (hex >> 16 & 255);
brush.g = (hex >> 8 & 255);
brush.b = (hex & 255);
brush.a = 255;
}
const mapName = "map";
const textureData = data.cubicModelUpdater.cubicModelAsset.textureDatas[mapName];
const index = (mousePosition.y * data.cubicModelUpdater.cubicModelAsset.pub.textureWidth + mousePosition.x) * 4;
if (textureData[index + 0] !== brush.r || textureData[index + 1] !== brush.g || textureData[index + 2] !== brush.b || textureData[index + 3] !== brush.a) {
const edits: TextureEdit[] = [];
edits.push({ x: mousePosition.x, y: mousePosition.y, value: brush });
data.projectClient.editAsset(SupClient.query.asset, "editTexture", mapName, edits);
}
}
}
}
function getHoveredNodeIds() {
const hoveredNodeIds = [] as string[];
for (const nodeId in data.cubicModelUpdater.cubicModelAsset.nodes.byId) {
const node = data.cubicModelUpdater.cubicModelAsset.nodes.byId[nodeId];
for (const faceName in node.shape.textureLayout) {
const face = node.shape.textureLayout[faceName];
const size = getShapeTextureFaceSize(node.shape, faceName);
if (mousePosition.x >= face.offset.x && mousePosition.x < face.offset.x + size.width &&
mousePosition.y >= face.offset.y && mousePosition.y < face.offset.y + size.height) {
hoveredNodeIds.push(nodeId);
break;
}
}
}
return hoveredNodeIds;
} | the_stack |
import {assert} from '../platform/assert-web.js';
import {Loader} from '../platform/loader.js';
import {TextEncoder, TextDecoder} from '../platform/text-encoder-web.js';
import {Entity} from './entity.js';
import {Reference} from './reference.js';
import {Type, EntityType, CollectionType, ReferenceType, SingletonType, Schema} from '../types/lib-types.js';
import {Storable} from './storable.js';
import {Particle} from './particle.js';
import {Dictionary, BiMap} from '../utils/lib-utils.js';
import {PECInnerPort} from './api-channel.js';
import {UserException} from './arc-exceptions.js';
import {CollectionHandle, SingletonHandle, Handle} from './storage/handle.js';
import {CRDTTypeRecord} from '../crdt/lib-crdt.js';
import {StorageFrontend} from './storage/storage-frontend.js';
type EntityTypeMap = BiMap<string, EntityType>;
// Wraps a Uint8Array buffer which is automatically resized as more space is needed.
export class DynamicBuffer {
private data: Uint8Array;
size = 0;
constructor(initialSize = 100) {
this.data = new Uint8Array(initialSize);
}
// Returns a view of the populated region of the underlying Uint8Array.
view() {
return this.data.subarray(0, this.size);
}
// Adds "plain text" strings, which should not contain any non-ascii characters.
addAscii(...strs: string[]) {
for (const str of strs) {
this.ensureSpace(str.length);
for (let i = 0; i < str.length; i++) {
this.data[this.size++] = str.charCodeAt(i);
}
}
}
// Adds UTF8 strings, prefixed with their byte length: '<len>:<string>'.
addUnicode(str: string) {
if (!str) {
this.addAscii('0:');
} else {
const bytes = new TextEncoder().encode(str);
this.addAscii(bytes.length + ':');
this.ensureSpace(bytes.length);
this.data.set(bytes, this.size);
this.size += bytes.length;
}
}
// Adds raw bytes from another DynamicBuffer, prefixed with the length: '<len>:<bytes>'.
addBytes(buf: DynamicBuffer) {
this.addAscii(buf.size + ':');
this.ensureSpace(buf.size);
this.data.set(buf.view(), this.size);
this.size += buf.size;
}
private ensureSpace(required: number) {
let newSize = this.data.length;
while (newSize - this.size < required) {
newSize *= 2;
}
if (newSize !== this.data.length) {
// ArrayBuffer.transfer() would make this more efficient, but it's not implemented yet.
const old = this.data;
this.data = new Uint8Array(newSize);
this.data.set(old);
}
}
}
// Encoders/decoders for the wire format for transferring entities over the wasm boundary.
// Note that entities must have an id before serializing for use in a wasm particle.
//
// <singleton> = <id-length>:<id>|<field-name>:<value>|<field-name>:<value>| ... |
// <value> depends on the field type:
// Text T<length>:<text>
// URL U<length>:<text>
// Number N<number>:
// Boolean B<zero-or-one>
// Reference R<length>:<id>|<length>:<storage-key>|<schema-hash>:
// Dictionary D<length>:<dictionary format>
// Array A<length>:<array format>
//
// <collection> = <num-entities>:<length>:<encoded><length>:<encoded> ...
//
// The encoder classes also supports two "Dictionary" formats of key:value string pairs.
//
// The first format supports only string-type values:
// <size>:<key-len>:<key><value-len>:<value><key-len>:<key><value-len>:<value>...
// alternate format supports typed-values using <value> syntax defined above
// <size>:<key-len>:<key><value><key-len>:<key><value>...
//
// Examples:
// Singleton: 4:id05|txt:T3:abc|lnk:U10:http://def|num:N37:|flg:B1|
// Collection: 3:29:4:id12|txt:T4:qwer|num:N9.2:|18:6:id2670|num:N-7:|15:5:id501|flg:B0|
export abstract class StringEncoder {
protected constructor(protected readonly schema: Schema) {}
static create(type: Type): StringEncoder {
if (type instanceof CollectionType || type instanceof SingletonType) {
type = type.getContainedType();
}
if (type instanceof EntityType) {
return new EntityEncoder(type.getEntitySchema());
}
if (type instanceof ReferenceType) {
return new ReferenceEncoder(type.getEntitySchema());
}
throw new Error(`Unsupported type for StringEncoder: ${type}`);
}
protected abstract encodeStorable(buf: DynamicBuffer, storable: Storable);
async encodeSingleton(storable: Storable): Promise<DynamicBuffer> {
const buf = new DynamicBuffer();
await this.encodeStorable(buf, storable);
return buf;
}
async encodeCollection(entities: Storable[]): Promise<DynamicBuffer> {
const bufs: DynamicBuffer[] = [];
let len = 10; // for 'num-entities:' prefix
for (const entity of entities) {
const buf = await this.encodeSingleton(entity);
bufs.push(buf);
len += 10 + buf.size; // +10 for 'length:' prefix
}
const collection = new DynamicBuffer(len);
collection.addAscii(entities.length + ':');
for (const buf of bufs) {
collection.addBytes(buf);
}
return collection;
}
static encodeDictionary(dict: Dictionary<string>): DynamicBuffer {
const buf = new DynamicBuffer();
const entries = Object.entries(dict);
buf.addAscii(entries.length + ':');
for (const [key, value] of entries) {
buf.addUnicode(key);
buf.addUnicode(value);
}
return buf;
}
protected async encodeField(buf: DynamicBuffer, field, name: string, value: string|number|boolean|Reference) {
// TODO: support unicode field names
switch (field.kind) {
case 'schema-primitive':
buf.addAscii(name, ':', field.type.substr(0, 1));
this.encodeValue(buf, field.type, value as string|number|boolean);
buf.addAscii('|');
break;
case 'schema-reference':
buf.addAscii(name, ':R');
await this.encodeReference(buf, value as Reference);
buf.addAscii('|');
break;
case 'schema-collection':
case 'schema-union':
case 'schema-tuple':
throw new Error(`'${field.kind}' not yet supported for entity packaging`);
default:
throw new Error(`Unknown field kind '${field.kind}' in schema`);
}
}
protected async encodeReference(buf: DynamicBuffer, ref: Reference) {
const entityType = ref.type.referredType as EntityType;
assert(entityType instanceof EntityType);
const {id, entityStorageKey: storageKey} = ref.dataClone();
const hash = await entityType.getEntitySchema().hash();
buf.addUnicode(id);
buf.addAscii('|');
buf.addUnicode(storageKey);
buf.addAscii('|', hash + ':');
}
protected encodeValue(buf: DynamicBuffer, type: string, value: string|number|boolean) {
switch (type) {
case 'Text':
case 'URL':
buf.addUnicode(value as string);
break;
case 'Number':
buf.addAscii(value + ':');
break;
case 'Boolean':
buf.addAscii(value ? '1' : '0');
break;
case 'Bytes':
case 'Object':
throw new Error(`'${type}' not yet supported for entity packaging`);
default:
throw new Error(`Unknown primitive value type '${type}' in schema`);
}
}
}
class EntityEncoder extends StringEncoder {
async encodeStorable(buf: DynamicBuffer, entity: Storable) {
if (!(entity instanceof Entity)) {
throw new Error(`non-Entity passed to EntityEncoder: ${entity}`);
}
buf.addUnicode(Entity.id(entity));
buf.addAscii('|');
for (const [name, value] of Object.entries(entity)) {
await this.encodeField(buf, this.schema.fields[name], name, value);
}
}
}
class ReferenceEncoder extends StringEncoder {
async encodeStorable(buf: DynamicBuffer, ref: Storable) {
if (!(ref instanceof Reference)) {
throw new Error(`non-Reference passed to EntityEncoder: ${ref}`);
}
await this.encodeReference(buf, ref);
buf.addAscii('|');
}
}
export abstract class StringDecoder {
protected bytes: Uint8Array;
protected pos: number;
protected textDecoder = new TextDecoder();
protected constructor(protected readonly schema: Schema,
protected typeMap: EntityTypeMap,
protected storageFrontend: StorageFrontend) {}
static create(type: Type, typeMap: EntityTypeMap, storageFrontend: StorageFrontend): StringDecoder {
if (type instanceof CollectionType || type instanceof SingletonType) {
type = type.getContainedType();
}
if (type instanceof EntityType) {
return new EntityDecoder(type.getEntitySchema(), typeMap, storageFrontend);
}
if (type instanceof ReferenceType) {
return new ReferenceDecoder(type.getEntitySchema(), typeMap, storageFrontend);
}
throw new Error(`Unsupported type for StringDecoder: ${type}`);
}
protected init(bytes: Uint8Array) {
this.bytes = bytes;
this.pos = 0;
}
abstract decodeSingleton(bytes: Uint8Array): Storable;
static decodeDictionary(bytes: Uint8Array): Dictionary<string> {
const decoder = new EntityDecoder(null, null, null);
decoder.init(bytes);
const dict = {};
let num = Number(decoder.upTo(':'));
while (num--) {
const klen = Number(decoder.upTo(':'));
const key = decoder.chomp(klen);
// be backward compatible with encoders that only encode string values
const typeChar = decoder.chomp(1);
// if typeChar is a digit, it's part of a length specifier
if (typeChar >= '0' && typeChar <= '9') {
const vlen = Number(`${typeChar}${decoder.upTo(':')}`);
dict[key] = decoder.chomp(vlen);
} else {
// otherwise typeChar is value-type specifier
dict[key] = decoder.decodeValue(typeChar);
}
}
return dict;
}
// TODO: make work in the new world.
static decodeArray(bytes: Uint8Array): string[] {
const decoder = new EntityDecoder(null, null, null);
decoder.init(bytes);
const arr = [];
let num = Number(decoder.upTo(':'));
while (num--) {
// be backward compatible with encoders that only encode string values
const typeChar = decoder.chomp(1);
// if typeChar is a digit, it's part of a length specifier
if (typeChar >= '0' && typeChar <= '9') {
const len = Number(`${typeChar}${decoder.upTo(':')}`);
arr.push(decoder.chomp(len));
} else {
// otherwise typeChar is value-type specifier
arr.push(decoder.decodeValue(typeChar));
}
}
return arr;
}
protected upTo(char: string): string {
assert(char.length === 1);
const i = this.bytes.indexOf(char.charCodeAt(0), this.pos);
if (i < 0) {
throw new Error(`Packaged entity decoding fail: could not find '${char}'`);
}
const token = this.textDecoder.decode(this.bytes.subarray(this.pos, i));
this.pos = i + 1;
return token;
}
protected chomp(len: number): string {
return this.textDecoder.decode(this.chompBytes(len));
}
protected chompBytes(len: number): Uint8Array {
if (this.pos + len > this.bytes.length) {
throw new Error(`Packaged entity decoding fail: expected ${len} chars to remain ` +
`but only had ${this.bytes.length - this.pos}`);
}
const start = this.pos;
this.pos += len;
return this.bytes.subarray(start, this.pos);
}
protected validate(token: string) {
if (this.chomp(token.length) !== token) {
throw new Error(`Packaged entity decoding fail: expected '${token}'`);
}
}
protected decodeValue(typeChar: string): string|number|boolean|Reference|Dictionary<string>|string[] {
switch (typeChar) {
case 'T':
case 'U': {
const len = Number(this.upTo(':'));
return this.chomp(len);
}
case 'N':
return Number(this.upTo(':'));
case 'B':
return Boolean(this.chomp(1) === '1');
case 'R':
return this.decodeReference();
case 'D': {
const len = Number(this.upTo(':'));
const dictionary = this.chompBytes(len);
return StringDecoder.decodeDictionary(dictionary);
}
case 'A': {
const len = Number(this.upTo(':'));
const array = this.chompBytes(len);
return StringDecoder.decodeArray(array);
}
default:
throw new Error(`Packaged entity decoding fail: unknown primitive value type '${typeChar}'`);
}
}
protected decodeReference(): Reference {
const ilen = Number(this.upTo(':'));
const id = this.chomp(ilen);
this.validate('|');
const klen = Number(this.upTo(':'));
const storageKey = this.chomp(klen);
this.validate('|');
const schemaHash = this.upTo(':');
const entityType = this.typeMap.getL(schemaHash);
if (!entityType) {
throw new Error(`Packaged entity decoding fail: invalid schema hash '${schemaHash}' for reference '${id}|${storageKey}'`);
}
return new Reference({id, entityStorageKey: storageKey}, new ReferenceType(entityType), this.storageFrontend);
}
}
class EntityDecoder extends StringDecoder {
decodeSingleton(bytes: Uint8Array): Storable {
this.init(bytes);
const len = Number(this.upTo(':'));
const id = this.chomp(len);
this.validate('|');
const data = {};
while (this.pos < this.bytes.length) {
const name = this.upTo(':');
const typeChar = this.chomp(1);
data[name] = this.decodeValue(typeChar);
this.validate('|');
}
const entity = new (Entity.createEntityClass(this.schema, null))(data);
if (id !== '') {
Entity.identify(entity, id, null);
}
return entity;
}
}
class ReferenceDecoder extends StringDecoder {
decodeSingleton(bytes: Uint8Array): Storable {
this.init(bytes);
return this.decodeReference();
}
}
/**
* Per-language platform environment and startup specializations for Emscripten and Kotlin.
*/
interface WasmDriver {
/**
* Adds required import functions into env for a given language runtime and initializes
* any fields needed on the wasm container, such as memory, tables, etc.
*/
configureEnvironment(module: WebAssembly.Module, container: WasmContainer, env: {});
/**
* Initializes the instantiated WebAssembly, runs any startup lifecycle, and if this
* runtime manages its own memory initialization, initializes the heap pointers.
*/
initializeInstance(container: WasmContainer, instance: WebAssembly.Instance);
}
class EmscriptenWasmDriver implements WasmDriver {
private readonly cfg: {memSize: number, tableSize: number, globalBase: number, dynamicBase: number, dynamictopPtr: number};
// Records file and line for console logging in C++. This is set by the console/error macros in
// arcs.h and used immediately in the following printf call (implemented by sysWritev() below).
private logInfo: [string, number]|null = null;
constructor(customSection: ArrayBuffer) {
// Wasm modules built by emscripten require some external memory configuration by the caller,
// which is usually built into the glue code generated alongside the module. We're not using
// the glue code, but if we set the EMIT_EMSCRIPTEN_METADATA flag when building, emscripten
// will provide a custom section in the module itself with the required values.
const METADATA_SIZE = 11;
const METADATA_MAJOR = 0;
const METADATA_MINOR = 2;
const ABI_MAJOR = 0;
const ABI_MINOR = 4;
// The logic for reading metadata values here was copied from the emscripten source.
const buffer = new Uint8Array(customSection);
const metadata: number[] = [];
let offset = 0;
while (offset < buffer.byteLength) {
let result = 0;
let shift = 0;
while (1) {
const byte = buffer[offset++];
result |= (byte & 0x7f) << shift;
if (!(byte & 0x80)) {
break;
}
shift += 7;
}
metadata.push(result);
}
// The specifics of the section are not published anywhere official (yet). The values here
// correspond to emscripten version 1.38.42:
// https://github.com/emscripten-core/emscripten/blob/1.38.42/tools/shared.py#L3051
if (metadata.length < 4) {
throw new Error(`emscripten metadata section should have at least 4 values; ` +
`got ${metadata.length}`);
}
if (metadata[0] !== METADATA_MAJOR || metadata[1] !== METADATA_MINOR) {
throw new Error(`emscripten metadata version should be ${METADATA_MAJOR}.${METADATA_MINOR}; ` +
`got ${metadata[0]}.${metadata[1]}`);
}
if (metadata[2] !== ABI_MAJOR || metadata[3] !== ABI_MINOR) {
throw new Error(`emscripten ABI version should be ${ABI_MAJOR}.${ABI_MINOR}; ` +
`got ${metadata[2]}.${metadata[3]}`);
}
if (metadata.length !== METADATA_SIZE) {
throw new Error(`emscripten metadata section should have ${METADATA_SIZE} values; ` +
`got ${metadata.length}`);
}
// metadata[4] is 'Settings.WASM_BACKEND'; whether the binary is from wasm backend or fastcomp.
// metadata[10] is 'tempdoublePtr'; appears to be related to pthreads and is not used here.
this.cfg = {
memSize: metadata[5],
tableSize: metadata[6],
globalBase: metadata[7],
dynamicBase: metadata[8],
dynamictopPtr: metadata[9],
};
}
configureEnvironment(module: WebAssembly.Module, container: WasmContainer, env: {}) {
container.memory = new WebAssembly.Memory({initial: this.cfg.memSize, maximum: this.cfg.memSize});
container.heapU8 = new Uint8Array(container.memory.buffer);
container.heap32 = new Int32Array(container.memory.buffer);
// We need to poke the address of the heap base into the memory buffer prior to instantiating.
container.heap32[this.cfg.dynamictopPtr >> 2] = this.cfg.dynamicBase;
Object.assign(env, {
// Memory setup
memory: container.memory,
__memory_base: this.cfg.globalBase,
table: new WebAssembly.Table({initial: this.cfg.tableSize, maximum: this.cfg.tableSize, element: 'anyfunc'}),
__table_base: 0,
DYNAMICTOP_PTR: this.cfg.dynamictopPtr,
// Heap management
_emscripten_get_heap_size: () => container.heapU8.length, // Matches emscripten glue js
_emscripten_resize_heap: (size) => false, // TODO
_emscripten_memcpy_big: (dst, src, num) => container.heapU8.set(container.heapU8.subarray(src, src + num), dst),
// Error handling
_systemError: (msg) => { throw new Error(container.readStr(msg)); },
abortOnCannotGrowMemory: (size) => { throw new Error(`abortOnCannotGrowMemory(${size})`); },
// Logging
_setLogInfo: (file, line) => this.logInfo = [container.readStr(file).split(/[/\\]/).pop(), line],
___syscall146: (which, varargs) => this.sysWritev(container, which, varargs),
});
}
initializeInstance(container: WasmContainer, instance: WebAssembly.Instance) {
// Emscripten doesn't need main() invoked
}
// C++ printf support cribbed from emscripten glue js.
sysWritev(container, which, varargs) {
const get = () => {
varargs += 4;
return container.heap32[(((varargs)-(4))>>2)];
};
const output = (get() === 1) ? console.log : console.error;
const iov = get();
const iovcnt = get();
const decoder = new TextDecoder();
let info = '';
if (this.logInfo) {
info = `[${this.logInfo[0]}:${this.logInfo[1]}] `;
this.logInfo = null;
}
let bytes = [];
let ret = 0;
for (let i = 0; i < iovcnt; i++) {
const ptr = container.heap32[(((iov)+(i*8))>>2)];
const len = container.heap32[(((iov)+(i*8 + 4))>>2)];
for (let j = 0; j < len; j++) {
const curr = container.heapU8[ptr+j];
if (curr === 0 || curr === 10) { // NUL or \n
output(info + decoder.decode(Uint8Array.from(bytes)));
info = '';
bytes = [];
} else {
bytes.push(curr);
}
}
ret += len;
}
return ret;
}
}
class KotlinWasmDriver implements WasmDriver {
configureEnvironment(module: WebAssembly.Module, container: WasmContainer, env: {}) {
Object.assign(env, {
// These two are used by launcher.cpp
Konan_js_arg_size: (index) => 1,
Konan_js_fetch_arg: (index, ptr) => 'dummyArg',
// These two are imported, but never used
Konan_js_allocateArena: (array) => {},
Konan_js_freeArena: (arenaIndex) => {},
// These two are used by logging functions
write: (ptr) => console.log(container.readStr(ptr)),
flush: () => {},
// Apparently used by Kotlin Memory management
Konan_notify_memory_grow: () => this.updateMemoryViews(container),
// Kotlin's own glue for abort and exit
Konan_abort: (pointer) => { throw new Error('Konan_abort(' + container.readStr(pointer) + ')'); },
Konan_exit: (status) => {},
// Needed by some code that tries to get the current time in it's runtime
Konan_date_now: (pointer) => {
const now = Date.now();
const high = Math.floor(now / 0xffffffff);
const low = Math.floor(now % 0xffffffff);
container.heap32[pointer] = low;
container.heap32[pointer + 1] = high;
},
});
}
// Kotlin manages its own heap construction, as well as tables.
initializeInstance(container: WasmContainer, instance: WebAssembly.Instance) {
this.updateMemoryViews(container);
// Kotlin main() must be invoked before everything else.
// TODO(alxrsngtn): Work out how to give Konan_js_main a type signature.
(instance.exports.Konan_js_main as (a: number, b: number) => void)(1, 0);
}
updateMemoryViews(container: WasmContainer) {
container.memory = container.exports.memory;
container.heapU8 = new Uint8Array(container.memory.buffer);
container.heap32 = new Int32Array(container.memory.buffer);
}
}
type WasmAddress = number;
// Holds an instance of a running wasm module, which may contain multiple particles.
export class WasmContainer {
storageFrontend: StorageFrontend;
loader: Loader;
apiPort: PECInnerPort;
memory: WebAssembly.Memory;
heapU8: Uint8Array;
heap32: Int32Array;
wasm: WebAssembly.Instance;
// tslint:disable-next-line: no-any
exports: any;
particleMap = new Map<WasmAddress, WasmParticle>();
constructor(storageFrontend: StorageFrontend, loader: Loader, apiPort: PECInnerPort) {
this.storageFrontend = storageFrontend;
this.loader = loader;
this.apiPort = apiPort;
}
async initialize(buffer: ArrayBuffer) {
// TODO: vet the imports/exports on 'module'
// TODO: use compileStreaming? requires passing the fetch() Response, not its ArrayBuffer
const module = await WebAssembly.compile(buffer);
const driver = this.driverForModule(module);
// Shared ENV between Emscripten and Kotlin
const env = {
abort: () => { throw new Error('Abort!'); },
// Inner particle API
// TODO: guard against null/empty args from the wasm side
_singletonSet: (p, h, entity) => this.getParticle(p).singletonSet(h, entity),
_singletonClear: (p, h) => this.getParticle(p).singletonClear(h),
_collectionStore: (p, h, entity) => this.getParticle(p).collectionStore(h, entity),
_collectionRemove: (p, h, entity) => this.getParticle(p).collectionRemove(h, entity),
_collectionClear: (p, h) => this.getParticle(p).collectionClear(h),
_onRenderOutput: (p, template, model) => this.getParticle(p).onRenderOutput(template, model),
_dereference: (p, id, key, hash, cid) => this.getParticle(p).dereference(id, key, hash, cid),
_serviceRequest: (p, call, args, tag) => this.getParticle(p).serviceRequest(call, args, tag),
_resolveUrl: (url) => this.resolve(url),
};
driver.configureEnvironment(module, this, env);
const global = {'NaN': NaN, 'Infinity': Infinity};
this.wasm = await WebAssembly.instantiate(module, {env, global});
this.exports = this.wasm.exports;
driver.initializeInstance(this, this.wasm);
}
private driverForModule(module: WebAssembly.Module): WasmDriver {
const customSections = WebAssembly.Module.customSections(module, 'emscripten_metadata');
if (customSections.length === 1) {
return new EmscriptenWasmDriver(customSections[0]);
}
return new KotlinWasmDriver();
}
private getParticle(innerParticle: WasmAddress): WasmParticle {
return this.particleMap.get(innerParticle);
}
register(particle: WasmParticle, innerParticle: WasmAddress) {
this.particleMap.set(innerParticle, particle);
}
// Allocates memory in the wasm container; the calling particle is responsible for freeing.
resolve(urlPtr: WasmAddress): WasmAddress {
return this.storeStr(this.loader.resolve(this.readStr(urlPtr)));
}
// Allocates memory in the wasm container and stores a null-terminated UTF8 string.
storeStr(str: string): WasmAddress {
const bytes = new TextEncoder().encode(str);
const p = this.exports._malloc(bytes.length + 1);
this.heapU8.set(bytes, p);
this.heapU8[p + bytes.length] = 0;
return p;
}
// Allocates memory in the wasm container and stores the given byte array.
storeBytes(buf: DynamicBuffer): WasmAddress {
const p = this.exports._malloc(buf.size + 1);
this.heapU8.set(buf.view(), p);
this.heapU8[p + buf.size] = 0;
return p;
}
// Convenience function for freeing one or more wasm memory allocations. Null pointers are ignored.
free(...ptrs: WasmAddress[]) {
ptrs.forEach(p => p && this.exports._free(p));
}
readStr(idx: WasmAddress): string {
return new TextDecoder().decode(this.readBytes(idx));
}
readBytes(idx: WasmAddress): Uint8Array {
let end = idx;
while (end < this.heapU8.length && this.heapU8[end] !== 0) {
end++;
}
return this.heapU8.subarray(idx, end);
}
}
// Creates and interfaces to a particle inside a WasmContainer's module.
export class WasmParticle extends Particle {
private id: string;
private container: WasmContainer;
// tslint:disable-next-line: no-any
private exports: any;
private innerParticle: WasmAddress;
private handleMap = new BiMap<Handle<CRDTTypeRecord>, WasmAddress>();
private encoders = new Map<Type, StringEncoder>();
private decoders = new Map<Type, StringDecoder>();
// Map of schema hashes to the EntityTypes used by Reference values.
private typeMap: EntityTypeMap = new BiMap<string, EntityType>();
constructor(id: string, container: WasmContainer) {
super();
this.id = id;
this.container = container;
this.exports = container.exports;
const fn = `_new${this.spec.name}`;
if (!(fn in this.exports)) {
throw this.reportedError(`wasm module does not export instantiator function '${fn}' for particle '${this.spec.name}'`);
}
this.innerParticle = this.exports[fn]();
this.container.register(this, this.innerParticle);
// TODO(sjmiles): probably rendering too soon: we need to render at least once, but we may have handle
// work pending. @shans says: if the particle has readable handles, onHandleUpdate is guaranteed
// to be called, otherwise we need `renderOutput` manually. Need to optimize this across all
// particle bases.
setTimeout(() => this.renderOutput(), 100);
}
renderOutput() {
// not yet implemented in CPP
if (this.exports['_renderOutput']) {
this.exports._renderOutput(this.innerParticle);
}
}
// TODO: for now we set up Handle objects with onDefineHandle and map them into the
// wasm container through this call, which creates corresponding Handle objects in there.
// That means entity transfer goes from the StorageProxy, deserializes at the outer Handle
// which then notifies this class (calling onHandle*), and we then serialize into the wasm
// transfer format. Obviously this can be improved.
async setHandles(handles: ReadonlyMap<string, Handle<CRDTTypeRecord>>) {
const refTypePromises = [];
for (const [name, handle] of handles) {
const p = this.container.storeStr(name);
const wasmHandle = this.exports._connectHandle(this.innerParticle, p, handle.canRead, handle.canWrite);
this.container.free(p);
if (wasmHandle === 0) {
throw this.reportedError(`Wasm particle failed to connect handle '${name}'`);
}
this.handleMap.set(handle, wasmHandle);
refTypePromises.push(this.extractReferenceTypes(this.getEntityType(handle.type)));
}
await Promise.all(refTypePromises);
this.exports._init(this.innerParticle);
}
private getEntityType(type: Type): null|EntityType {
while (type) {
if (type instanceof EntityType) {
return type;
}
type = type.getContainedType();
}
return null;
}
private async extractReferenceTypes(entityType: EntityType) {
if (!entityType) return;
const schema = entityType.getEntitySchema();
this.typeMap.set(await schema.hash(), entityType);
for (const [field, descriptor] of Object.entries(schema.fields)) {
await this.extractReferenceTypes(descriptor.getEntityType());
}
}
async onHandleSync(handle: Handle<CRDTTypeRecord>, model) {
const wasmHandle = this.handleMap.getL(handle);
if (!model) {
this.exports._syncHandle(this.innerParticle, wasmHandle, 0);
return;
}
const encoder = this.getEncoder(handle.type);
let p;
if (handle instanceof SingletonHandle) {
p = this.container.storeBytes(await encoder.encodeSingleton(model));
} else {
p = this.container.storeBytes(await encoder.encodeCollection(model));
}
this.exports._syncHandle(this.innerParticle, wasmHandle, p);
this.container.free(p);
}
// tslint:disable-next-line: no-any
async onHandleUpdate(handle: Handle<CRDTTypeRecord>, update: {data?: any, added?: any, removed?: any, originator?: any}) {
if (update.originator) {
return;
}
const wasmHandle = this.handleMap.getL(handle);
const encoder = this.getEncoder(handle.type);
let p1 = 0;
let p2 = 0;
if (handle instanceof SingletonHandle) {
if (update.data) {
p1 = this.container.storeBytes(await encoder.encodeSingleton(update.data));
}
} else {
p1 = this.container.storeBytes(await encoder.encodeCollection(update.added || []));
p2 = this.container.storeBytes(await encoder.encodeCollection(update.removed || []));
}
this.exports._updateHandle(this.innerParticle, wasmHandle, p1, p2);
this.container.free(p1, p2);
}
// Ignored for wasm particles.
async onHandleDesync(handle: Handle<CRDTTypeRecord>) {}
async onFirstStart() {
// TODO(heimlich, 4798): not yet implemented in CPP
if (this.exports['_onFirstStart']) {
this.exports._onFirstStart(this.innerParticle);
}
}
// Store API.
//
// Each of these calls an async storage method, but we don't want to await them because returning
// a Promise to wasm doesn't work, and control (surprisingly) returns to the calling wasm function
// at the first await point anyway. However, our CRDTs make it safe to fire-and-forget the storage
// updates, and the wasm handles already have the updated version of the stored data, so it's safe
// to leave the promises floating.
// If the given entity doesn't have an id, this will create one for it and return the new id
// in allocated memory that the wasm particle must free. If the entity already has an id this
// returns 0 (nulltpr).
singletonSet(wasmHandle: WasmAddress, entityPtr: WasmAddress): WasmAddress {
// tslint:disable-next-line: no-any
const singleton = this.getHandle(wasmHandle) as SingletonHandle<any>;
const decoder = this.getDecoder(singleton.type);
const entity = decoder.decodeSingleton(this.container.readBytes(entityPtr));
const p = this.ensureIdentified(entity, singleton);
void singleton.set(entity);
return p;
}
singletonClear(wasmHandle: WasmAddress) {
// tslint:disable-next-line: no-any
const singleton = this.getHandle(wasmHandle) as SingletonHandle<any>;
void singleton.clear();
}
// If the given entity doesn't have an id, this will create one for it and return the new id
// in allocated memory that the wasm particle must free. If the entity already has an id this
// returns 0 (nulltpr).
collectionStore(wasmHandle: WasmAddress, entityPtr: WasmAddress): WasmAddress {
// tslint:disable-next-line: no-any
const collection = this.getHandle(wasmHandle) as CollectionHandle<any>;
const decoder = this.getDecoder(collection.type);
const entity = decoder.decodeSingleton(this.container.readBytes(entityPtr));
const p = this.ensureIdentified(entity, collection);
void collection.add(entity);
return p;
}
collectionRemove(wasmHandle: WasmAddress, entityPtr: WasmAddress) {
// tslint:disable-next-line: no-any
const collection = this.getHandle(wasmHandle) as CollectionHandle<any>;
const decoder = this.getDecoder(collection.type);
const entity = decoder.decodeSingleton(this.container.readBytes(entityPtr));
void collection.remove(entity);
}
collectionClear(wasmHandle: WasmAddress) {
// tslint:disable-next-line: no-any
const collection = this.getHandle(wasmHandle) as CollectionHandle<any>;
void collection.clear();
}
// Retrieves the entity held by a reference.
async dereference(idPtr: WasmAddress, keyPtr: WasmAddress, hashPtr: WasmAddress, continuationId: number) {
const id = this.container.readStr(idPtr);
const storageKey = this.container.readStr(keyPtr);
const hash = this.container.readStr(hashPtr);
const entityType = this.typeMap.getL(hash);
if (!entityType) {
throw this.reportedError(`entity type not found for schema hash '${hash}'`);
}
const encoder = this.getEncoder(entityType);
const entity = await Reference.retrieve(this.container.storageFrontend, id, storageKey, entityType, this.id);
const p = this.container.storeBytes(await encoder.encodeSingleton(entity));
this.exports._dereferenceResponse(this.innerParticle, continuationId, p);
this.container.free(p);
}
private getEncoder(type: Type) {
let encoder = this.encoders.get(type);
if (!encoder) {
encoder = StringEncoder.create(type);
this.encoders.set(type, encoder);
}
return encoder;
}
private getDecoder(type: Type) {
let decoder = this.decoders.get(type);
if (!decoder) {
decoder = StringDecoder.create(type, this.typeMap, this.container.storageFrontend);
this.decoders.set(type, decoder);
}
return decoder;
}
private getHandle(wasmHandle: WasmAddress): Handle<CRDTTypeRecord> {
const handle = this.handleMap.getR(wasmHandle);
if (!handle) {
throw this.reportedError('attempted to write to unconnected handle');
}
return handle;
}
private ensureIdentified(entity: Storable, handle: Handle<CRDTTypeRecord>): WasmAddress {
let p = 0;
// TODO: rework Reference/Entity internals to avoid this instance check?
if (entity instanceof Entity && !Entity.isIdentified(entity)) {
handle.createIdentityFor(entity);
p = this.container.storeStr(Entity.id(entity));
}
return p;
}
// in TS output is provided by `capabilities`, which is not available in WASM, so just go straight to output
output(content) {
this.container.apiPort.Output(this, content);
}
// render request call-back from wasm
onRenderOutput(templatePtr: WasmAddress, modelPtr: WasmAddress) {
const content = {};
if (templatePtr) {
content['template'] = this.container.readStr(templatePtr);
}
if (modelPtr) {
content['model'] = StringDecoder.decodeDictionary(this.container.readBytes(modelPtr));
}
this.output(content);
}
// Wasm particles can request service calls with a Dictionary of arguments and an optional string
// tag to disambiguate different requests to the same service call.
async serviceRequest(callPtr: WasmAddress, argsPtr: WasmAddress, tagPtr: WasmAddress) {
const call = this.container.readStr(callPtr);
const args = StringDecoder.decodeDictionary(this.container.readBytes(argsPtr));
const tag = this.container.readStr(tagPtr);
// tslint:disable-next-line: no-any
const response: any = await this.service({call, ...args});
// Convert the arbitrary response object to key:value string pairs.
const dict: Dictionary<string> = {};
if (typeof response === 'object') {
for (const entry of Object.entries(response)) {
// tslint:disable-next-line: no-any
const [key, value]: [string, any] = entry;
dict[key] = (typeof value === 'object') ? JSON.stringify(value) : (value + '');
}
} else {
// Convert a plain value response to {value: 'string'}
dict['value'] = response + '';
}
// We can't re-use the string pointers passed in as args to this method, because the await
// point above means the call to internal::serviceRequest inside the wasm module will already
// have completed, and the memory for those args will have been freed.
const cp = this.container.storeStr(call);
const rp = this.container.storeBytes(StringEncoder.encodeDictionary(dict));
const tp = this.container.storeStr(tag);
this.exports._serviceResponse(this.innerParticle, cp, rp, tp);
this.container.free(cp, rp, tp);
}
fireEvent(slotName: string, event) {
const sp = this.container.storeStr(slotName);
const hp = this.container.storeStr(event.handler);
const data = this.container.storeBytes(StringEncoder.encodeDictionary(event.data || {}));
this.exports._fireEvent(this.innerParticle, sp, hp, data);
this.container.free(sp, hp, data);
}
reportedError(msg: string): Error {
const err = new Error(msg);
// 1st line = 'Error: <msg>', 2nd line = this method, 3rd line = calling method, with the form:
// ' at WasmParticle.<method> (<file-info>)'
const method = err.stack.split('\n')[2].match(/ at ([a-zA-Z._]+) /)[1];
const userException = new UserException(err, method, this.id, this.spec.name);
this.container.apiPort.ReportExceptionInHost(userException);
return err;
}
} | the_stack |
import { Stereotype } from '../types';
import { DatePattern,
DateTimePattern,
DateTimeNoTzPattern } from '../lib/util';
const FyPattern = /^first-date-of-fy\(([0-9]+)\)$/;
const FormulaPattern = /^([-+@])([0-9]+)(yr|mo|day|days|hr|min|sec|ms)$/;
class UtcDate extends Date {
public constructor();
// tslint:disable-next-line: unified-signatures
public constructor(str: string);
public constructor(
year: number, month: number, date?: number,
hours?: number, minutes?: number, seconds?: number, ms?: number)
public constructor(
year?: number | string, month?: number, date?: number,
hours?: number, minutes?: number, seconds?: number, ms?: number) {
super();
if (year === void 0) {
return;
}
if (typeof year === 'string') {
if (DateTimePattern.test(year)) {
// string parameter is expected to be treated as specified TZ
this.setTime(Date.parse(year)); // returns date in specified TZ
} else if (DatePattern.test(year)) {
// string parameter is expected to be treated as UTC
const d = new Date(year); // returns date in UTC TZ (getUTC??? returns string parameter's date & time digits)
this.setTime(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
} else if (DateTimeNoTzPattern.test(year)) {
// string parameter is expected to be treated as UTC
const d = new Date(year); // returns date in local TZ (get??? returns string parameter's date & time digits)
this.setTime(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(),
d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));
} else {
this.setTime(NaN);
}
return;
}
this.setUTCDate(1);
this.setUTCFullYear(year);
this.setUTCMonth(typeof month === 'number' ? month : 0);
this.setUTCDate(typeof date === 'number' ? date : 1);
this.setUTCHours(typeof hours === 'number' ? hours : 0);
this.setUTCMinutes(typeof minutes === 'number' ? minutes : 0);
this.setUTCSeconds(typeof seconds === 'number' ? seconds : 0);
this.setUTCMilliseconds(typeof ms === 'number' ? ms : 0);
}
public getFullYear(): number {
return this.getUTCFullYear();
}
public getMonth(): number {
return this.getUTCMonth();
}
public getDate(): number {
return this.getUTCDate();
}
public getHours(): number {
return this.getUTCHours();
}
public getMinutes(): number {
return this.getUTCMinutes();
}
public getSeconds(): number {
return this.getUTCSeconds();
}
public getMilliseconds(): number {
return this.getUTCMilliseconds();
}
// NOTE: set???() are not overridden!
}
class LcDate extends Date {
public constructor();
// tslint:disable-next-line: unified-signatures
public constructor(str: string);
public constructor(
year: number, month: number, date?: number,
hours?: number, minutes?: number, seconds?: number, ms?: number)
public constructor(
year?: number | string, month?: number, date?: number,
hours?: number, minutes?: number, seconds?: number, ms?: number) {
super();
if (year === void 0) {
return;
}
if (typeof year === 'string') {
if (DateTimePattern.test(year)) {
// string parameter is expected to be treated as specified TZ
this.setTime(Date.parse(year)); // returns date in specified TZ
} else if (DatePattern.test(year)) {
// string parameter is expected to be treated as local TZ
const d = new Date(year); // returns date in UTC TZ (getUTC??? returns string parameter's date & time digits)
const l = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
this.setTime(l.getTime());
} else if (DateTimeNoTzPattern.test(year)) {
// string parameter is expected to be treated as local TZ
const d = new Date(year); // returns date in local TZ (get??? returns string parameter's date & time digits)
this.setTime(d.getTime());
} else {
this.setTime(NaN);
}
return;
}
this.setDate(1);
this.setFullYear(year);
this.setMonth(typeof month === 'number' ? month : 0);
this.setDate(typeof date === 'number' ? date : 1);
this.setHours(typeof hours === 'number' ? hours : 0);
this.setMinutes(typeof minutes === 'number' ? minutes : 0);
this.setSeconds(typeof seconds === 'number' ? seconds : 0);
this.setMilliseconds(typeof ms === 'number' ? ms : 0);
}
}
interface DateConstructor {
new (): Date;
// tslint:disable-next-line: unified-signatures
new (str: string): Date;
new (year: number, month: number, date?: number,
hours?: number, minutes?: number, seconds?: number, ms?: number): Date;
}
function evaluateFormulaBase(dateCtor: DateConstructor, valueOrFormula: string): Date {
const errMsg = `evaluateFormula: invalid parameter ${valueOrFormula}`;
if (typeof valueOrFormula !== 'string') {
throw new Error(errMsg);
}
if (valueOrFormula.startsWith('=')) {
const formula = valueOrFormula.slice(1).split(' ');
let d = new dateCtor();
const now = new dateCtor(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes());
const today = new dateCtor(d.getFullYear(), d.getMonth(), d.getDate());
d = now;
for (const f of formula) {
switch (f) {
case 'current': case 'now':
d = now;
break;
case 'today':
d = today;
break;
case 'first-date-of-yr': case 'first-date-of-fy(1)':
d = new dateCtor(d.getFullYear(), 0, 1);
break;
case 'last-date-of-yr':
d = new dateCtor(d.getFullYear(), 11, 31);
break;
case 'first-date-of-mo':
d = new dateCtor(d.getFullYear(), d.getMonth(), 1);
break;
case 'last-date-of-mo':
d = new dateCtor(d.getFullYear(), d.getMonth() + 1, 0);
break;
default:
if (f.startsWith('first-date-of-fy(')) {
const m = FyPattern.exec(f);
if (m) {
const n = Number.parseInt(m[1], 10);
if (0 < n && n <= 12) {
const mo = d.getMonth() + 1;
let yr = d.getFullYear();
if (mo < n) {
yr--;
}
d = new dateCtor(yr, n - 1, 1);
} else {
throw new Error(errMsg);
}
} else {
throw new Error(errMsg);
}
} else {
const m = FormulaPattern.exec(f);
if (m) {
let n = Number.parseInt(m[2], 10);
switch (m[3]) {
case 'yr':
switch (m[1]) {
case '@':
break;
case '+':
n = d.getFullYear() + n;
break;
case '-':
n = d.getFullYear() - n;
break;
}
d = new dateCtor(n, d.getMonth(), d.getDate(),
d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
break;
case 'mo':
switch (m[1]) {
case '@':
n -= 1;
break;
case '+':
n = d.getMonth() + n;
break;
case '-':
n = d.getMonth() - n;
break;
}
d = new dateCtor(d.getFullYear(), n, d.getDate(),
d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
break;
case 'day': case 'days':
switch (m[1]) {
case '@':
break;
case '+':
n = d.getDate() + n;
break;
case '-':
n = d.getDate() - n;
break;
}
d = new dateCtor(d.getFullYear(), d.getMonth(), n,
d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
break;
case 'hr':
switch (m[1]) {
case '@':
break;
case '+':
n = d.getHours() + n;
break;
case '-':
n = d.getHours() - n;
break;
}
d = new dateCtor(d.getFullYear(), d.getMonth(), d.getDate(),
n, d.getMinutes(), d.getSeconds(), d.getMilliseconds());
break;
case 'min':
switch (m[1]) {
case '@':
break;
case '+':
n = d.getMinutes() + n;
break;
case '-':
n = d.getMinutes() - n;
break;
}
d = new dateCtor(d.getFullYear(), d.getMonth(), d.getDate(),
d.getHours(), n, d.getSeconds(), d.getMilliseconds());
break;
case 'sec':
switch (m[1]) {
case '@':
break;
case '+':
n = d.getSeconds() + n;
break;
case '-':
n = d.getSeconds() - n;
break;
}
d = new dateCtor(d.getFullYear(), d.getMonth(), d.getDate(),
d.getHours(), d.getMinutes(), n, d.getMilliseconds());
break;
case 'ms':
switch (m[1]) {
case '@':
break;
case '+':
n = d.getMilliseconds() + n;
break;
case '-':
n = d.getMilliseconds() - n;
break;
}
d = new dateCtor(d.getFullYear(), d.getMonth(), d.getDate(),
d.getHours(), d.getMinutes(), d.getSeconds(), n);
break;
default:
throw new Error(errMsg);
}
} else {
if (!(DatePattern.test(f) || DateTimePattern.test(f) || DateTimeNoTzPattern.test(f))) {
throw new Error(errMsg);
}
d = new dateCtor(f);
}
}
}
}
return d;
} else {
if (! DatePattern.test(valueOrFormula)) {
throw new Error(errMsg);
}
return new dateCtor(valueOrFormula);
}
}
export const dateStereotype: Stereotype = {
tryParse: (value: unknown) => {
return (
typeof value === 'string' && DatePattern.test(value)
? { value: (new UtcDate(value)).getTime() }
: null
);
},
evaluateFormula: valueOrFormula => {
const d = evaluateFormulaBase(UtcDate, valueOrFormula);
return (new UtcDate(d.getFullYear(), d.getMonth(), d.getDate())).getTime();
},
compare: (a: number, b: number) => a - b,
doCast: false,
};
export const lcDateStereotype: Stereotype = {
...dateStereotype,
tryParse: (value: unknown) => {
if (typeof value === 'string' && DatePattern.test(value)) {
return ({ value: (new LcDate(value)).getTime() });
} else {
return null;
}
},
evaluateFormula: valueOrFormula => {
const d = evaluateFormulaBase(LcDate, valueOrFormula);
return (new LcDate(d.getFullYear(), d.getMonth(), d.getDate())).getTime();
},
}
export const datetimeStereotype: Stereotype = {
tryParse: (value: unknown) => {
return (
typeof value === 'string' && (DateTimePattern.test(value) || DateTimeNoTzPattern.test(value))
? { value: (new UtcDate(value)).getTime() } // If timezone is not specified, it is local time
: null
);
},
evaluateFormula: valueOrFormula => evaluateFormulaBase(UtcDate, valueOrFormula).getTime(),
compare: (a: number, b: number) => a - b,
doCast: false,
};
export const lcDatetimeStereotype: Stereotype = {
...datetimeStereotype,
tryParse: (value: unknown) => {
return (
typeof value === 'string' && (DateTimePattern.test(value) || DateTimeNoTzPattern.test(value))
? { value: (new LcDate(value)).getTime() }
: null
);
},
evaluateFormula: valueOrFormula => evaluateFormulaBase(LcDate, valueOrFormula).getTime(),
}
export const stereotypes: Array<[string, Stereotype]> = [
['date', dateStereotype],
['lcdate', lcDateStereotype],
['datetime', datetimeStereotype],
['lcdatetime', lcDatetimeStereotype],
]; | the_stack |
import React from "react";
import { snackbar } from "mdui";
import { FileInput, Button } from "mdui-in-react";
import "./caption.css";
class captionMosaic {
img: any[];
constructor() {
this.img = [];
// @ts-expect-error ts-migrate(2551) FIXME: Property 'cutedImg' does not exist on type 'captio... Remove this comment to see the full error message
this.cutedImg = [];
}
// @ts-expect-error ts-migrate(7006) FIXME: Parameter 'base64' implicitly has an 'any' type.
async loadImg(base64) {
var img = new Image();
img.src = base64;
return img;
}
// @ts-expect-error ts-migrate(7006) FIXME: Parameter 'base64' implicitly has an 'any' type.
addImg(base64, top, bottom) {
this.img.push({
base64,
top,
bottom,
});
}
// @ts-expect-error ts-migrate(7006) FIXME: Parameter 'base64' implicitly has an 'any' type.
async cutImg(base64, top, bottom) {
var cutWork = document.createElement("canvas"),
workCtx = cutWork.getContext("2d"),
ele = await this.loadImg(base64);
top *= ele.height;
bottom *= ele.height;
cutWork.height = ele.height - top - bottom;
cutWork.width = ele.width;
console.log(`
the image is ${ele.width} x ${ele.height},
cut starts at (0,${top}),
cut height is ${ele.height - top - bottom}
`);
// @ts-expect-error ts-migrate(2531) FIXME: Object is possibly 'null'.
workCtx.drawImage(
ele,
0,
top,
ele.width,
ele.height - top - bottom,
0,
0,
ele.width,
ele.height - top - bottom
);
var res = cutWork.toDataURL();
console.log(res);
return res;
}
async imgMosaic_Y() {
for (var i = 0; i <= this.img.length - 1; i++) {
let { top, bottom, base64 } = this.img[i];
// @ts-expect-error ts-migrate(2551) FIXME: Property 'cutedImg' does not exist on type 'captio... Remove this comment to see the full error message
this.cutedImg.push(await this.cutImg(base64, top, bottom));
}
// @ts-expect-error ts-migrate(2551) FIXME: Property 'cutedImg' does not exist on type 'captio... Remove this comment to see the full error message
console.log(this.cutedImg);
var c = document.createElement("canvas");
var ctx = c.getContext("2d");
var imgs = [];
c.width = 0;
c.height = 0;
// @ts-expect-error ts-migrate(2551) FIXME: Property 'cutedImg' does not exist on type 'captio... Remove this comment to see the full error message
for (var i = 0; i <= this.cutedImg.length; i++) {
// @ts-expect-error ts-migrate(2551) FIXME: Property 'cutedImg' does not exist on type 'captio... Remove this comment to see the full error message
var ele = await this.loadImg(this.cutedImg[i]);
c.height += ele.height;
if (ele.width > c.width) c.width = ele.width;
imgs.push(ele);
}
var startY = 0;
for (let j = 0; j <= imgs.length - 1; j++) {
// @ts-expect-error ts-migrate(2531) FIXME: Object is possibly 'null'.
ctx.drawImage(imgs[j], 0, startY, imgs[j].width, imgs[j].height);
startY += imgs[j].height;
}
var res = c.toDataURL();
return res;
}
}
const Preview = ({ res }: { res: any }) => {
if (!res) return null;
return <img className="mdui-img-fluid" src={res} />;
};
type AlbumState = any;
type AlbumProps = {
assets: {
img: string;
top: number;
bottom: number;
getConHeight(): void;
}[];
/**上边界移动 */
onTopDrag: (distance: number, index: number) => void;
/** 下边界移动 */
onBottomDrag: (distance: number, index: number) => void;
/** 删除照片 */
deleteImg: (index: number) => void;
/** */
getConHeight: (height: number, index: number) => void;
/** 图片前移 */
putForward: (index: number) => void;
putBack: (index: number) => void;
};
/** 相册组件
*/
class Album extends React.Component<AlbumProps, AlbumState> {
constructor(props: AlbumProps) {
super(props);
this.state = {
startPosition: 0,
};
}
render() {
const {
assets,
onTopDrag,
onBottomDrag,
deleteImg,
getConHeight,
} = this.props;
const { startPosition } = this.state;
return (
<div className="mdui-row-xs-2 mdui-row-sm-3">
{assets.map((assest, i) => (
<div
style={{ marginTop: "5px" }}
className="mdui-card mdui-col"
>
<div key={i} className="mdui-card-media mdui-center">
<img
onLoad={(e) => {
getConHeight(
// @ts-expect-error ts-migrate(2339) FIXME: Property 'getConHeight' does not exist on type 'Re... Remove this comment to see the full error message
e.target.offsetHeight,
i
);
}}
src={assest.img}
/>
<span
draggable={true}
onDragStart={(e) => {
e.pageY >= 0 &&
this.setState({
startPosition: e.pageY,
});
}}
onDrag={(e) => {
var distance = e.pageY - startPosition;
console.log(distance);
e.pageY > 0 && onTopDrag(distance, i);
e.pageY > 0 &&
this.setState({
startPosition: e.pageY,
});
}}
onTouchStart={(e) => {
var ev = e || window.event;
var touch = ev.targetTouches[0];
this.setState({
startPosition: touch.clientY,
});
}}
onTouchMove={(e) => {
var ev = e || window.event;
var touch = ev.targetTouches[0];
var distance =
touch.clientY - startPosition;
console.log(distance);
onTopDrag(distance, i);
this.setState({
startPosition: touch.clientY,
});
}}
style={{ height: `${assest.top}px` }}
className="mask mask-top"
></span>
<span
draggable={true}
onDragStart={(e) => {
e.pageY >= 0 &&
this.setState({
startPosition: e.pageY,
});
}}
onDrag={(e) => {
var distance = e.pageY - startPosition;
console.log(distance);
e.pageY > 0 && onBottomDrag(distance, i);
e.pageY > 0 &&
this.setState({
startPosition: e.pageY,
});
}}
onTouchStart={(e) => {
e.preventDefault();
var ev = e || window.event;
var touch = ev.targetTouches[0];
this.setState({
startPosition: touch.clientY,
});
}}
onTouchMove={(e) => {
e.preventDefault();
var ev = e || window.event;
var touch = ev.targetTouches[0];
var distance =
touch.clientY - startPosition;
console.log(distance);
onBottomDrag(distance, i);
this.setState({
startPosition: touch.clientY,
});
}}
style={{ height: `${assest.bottom}px` }}
className="mask mask-bottom"
></span>
<div className="mdui-card-menu">
<button
style={{
background: "rgba(0, 0, 0, 0.27)",
}}
onClick={() => {
deleteImg(i);
}}
className="mdui-btn mdui-btn-icon mdui-text-color-white"
>
<i className="mdui-icon material-icons">
close
</i>
</button>
{i >= 1 && (
<Button
onClick={() => {
this.props.putForward(i);
}}
icon="arrow_upward"
iconColor="white"
/>
)}
{i >= 1 && i < assets.length - 1 && (
<Button
onClick={() => {
this.props.putBack(i);
}}
icon="arrow_downward"
iconColor="white"
/>
)}
</div>
</div>
</div>
))}
</div>
);
}
}
/** 视频截图器 */
class VideoShotter extends React.Component<
{
addImg(imgSrc: string): void;
video: any;
},
{}
> {
videoDom: any;
takeShot() {
const { addImg } = this.props;
var { videoDom } = this;
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = videoDom.videoWidth;
canvas.height = videoDom.videoHeight;
ctx &&
ctx.drawImage(
videoDom,
0,
0,
videoDom.videoWidth,
videoDom.videoHeight
);
var res = canvas.toDataURL();
addImg(res);
}
componentDidUpdate(){
this.videoDom.load()
}
render() {
const { video } = this.props;
if (!video) return null;
return (
<>
<video
ref={(r) => (this.videoDom = r)}
className="mdui-video-fluid"
controls
>
<source src={video} type="video/mp4" />
</video>
<br></br>
<Button
onClick={this.takeShot.bind(this)}
primary
raised
title="截图"
/>
</>
);
}
}
type ComponentState = any;
export default class extends React.Component<{}, ComponentState> {
constructor(props: {}) {
super(props);
this.state = {
assets: [],
res: null,
video: null,
};
}
render() {
const { assets, res, video } = this.state;
return (
<>
<Album
onTopDrag={(distance, i) => {
if (assets[i].top + distance >= 0)
assets[i].top += distance;
this.setState({ assets: assets });
}}
onBottomDrag={(distance, i) => {
if (assets[i].bottom - distance >= 0)
assets[i].bottom -= distance;
this.setState({ assets: assets });
}}
getConHeight={(cHeight, i) => {
assets[i].cHeight = cHeight;
}}
putForward={(i) => {
var cache = assets[i];
assets.splice(i, 1);
assets.splice(i - 1, 0, cache);
this.setState({ assets: assets });
}}
putBack={(i) => {
var cache = assets[i];
assets.splice(i, 1);
assets.splice(i + 1, 0, cache);
this.setState({ assets: assets });
}}
assets={assets}
deleteImg={(i) => {
assets.splice(i, 1);
this.setState({ assets: assets });
}}
/>
<div className="bottom-dashboard mdui-card mdui-p-a-1">
<FileInput
fileType="image/*"
multiple={true}
onFileUpload={(file) => {
assets.push({
img: file,
top:
assets.length >= 1
? assets[0].cHeight - assets[0].bottom
: 50,
bottom: assets.length >= 1 ? 0 : 50,
cHeight: 200,
});
this.setState({ assets: assets });
}}
/>
<span style={{ margin: "0px 5px 0px 5px" }}></span>
<FileInput
fileType="video/*"
onFileUpload={(file) => {
this.setState({ video: file });
}}
title="截取视频"
/>
</div>
<VideoShotter
video={video}
addImg={(img) => {
assets.push({
img: img,
top:
assets.length >= 1
? assets[0].cHeight - assets[0].bottom
: 50,
bottom: assets.length >= 1 ? 0 : 50,
cHeight: 200,
});
this.setState({ assets: assets }, () => {
snackbar({
message: "已添加截图",
});
});
}}
/>
<button
style={{ zIndex: 1003 }}
className="mdui-fab mdui-fab-fixed mdui-color-theme"
onClick={() => {
var mos = new captionMosaic();
// @ts-expect-error ts-migrate(7006) FIXME: Parameter 'assest' implicitly has an 'any' type.
assets.map((assest) => {
mos.addImg(
assest.img,
assest.top / assest.cHeight,
assest.bottom / assest.cHeight
);
});
mos.imgMosaic_Y().then((res) => {
this.setState({ res: res }, () => {
snackbar({
message: "图片制作成功,请在页面底部查看",
});
});
});
}}
>
<i className="mdui-icon material-icons"></i>
</button>
<br></br>
<Preview res={res} />
</>
);
}
} | the_stack |
import {
CObject,
MessageMeta,
CollabEvent,
CollabEventsRecord,
InitToken,
Pre,
Message,
Optional,
} from "@collabs/core";
import { CNumberComponentMessage } from "../../generated/proto_compiled";
import {
MultipleSemidirectProduct,
StatefulCRDT,
} from "../constructions/multiple_semidirect_product";
import { ToggleCBoolean } from "../boolean";
import { PrimitiveCRDT } from "../constructions";
export interface CNumberEvent extends CollabEvent {
readonly arg: number;
readonly previousValue: number;
}
export interface CNumberEventsRecord extends CollabEventsRecord {
Add: CNumberEvent;
Mult: CNumberEvent;
Min: CNumberEvent;
Max: CNumberEvent;
}
export class CNumberState {
value: number;
constructor(readonly initialValue: number) {
this.value = initialValue;
}
}
// Exporting just for tests, it's not exported at top-level
export class AddComponent
extends PrimitiveCRDT<CNumberEventsRecord>
implements StatefulCRDT<CNumberState>
{
readonly state: CNumberState;
constructor(initToken: InitToken, initialState: CNumberState) {
super(initToken);
this.state = initialState;
}
add(toAdd: number) {
if (toAdd !== 0) {
const message = CNumberComponentMessage.create({ arg: toAdd });
const buffer = CNumberComponentMessage.encode(message).finish();
this.sendCRDT(buffer);
}
}
protected receiveCRDT(message: string | Uint8Array, meta: MessageMeta) {
const decoded = CNumberComponentMessage.decode(<Uint8Array>message);
const previousValue = this.state.value;
this.state.value += decoded.arg;
this.emit("Add", {
meta,
arg: decoded.arg,
previousValue,
});
}
canGC() {
return this.state.value === this.state.initialValue;
}
save(): Uint8Array {
const message = CNumberComponentMessage.create({
arg: this.state.value,
});
return CNumberComponentMessage.encode(message).finish();
}
load(saveData: Optional<Uint8Array>) {
if (!saveData.isPresent) return;
this.state.value = CNumberComponentMessage.decode(saveData.get()).arg;
}
}
export class MultComponent
extends PrimitiveCRDT<CNumberEventsRecord>
implements StatefulCRDT<CNumberState>
{
readonly state: CNumberState;
constructor(initToken: InitToken, initialState: CNumberState) {
super(initToken);
this.state = initialState;
}
mult(toMult: number) {
if (toMult !== 1) {
const message = CNumberComponentMessage.create({ arg: toMult });
const buffer = CNumberComponentMessage.encode(message).finish();
this.sendCRDT(buffer);
}
}
protected receiveCRDT(message: string | Uint8Array, meta: MessageMeta) {
const decoded = CNumberComponentMessage.decode(<Uint8Array>message);
const previousValue = this.state.value;
this.state.value *= decoded.arg;
this.emit("Mult", {
meta,
arg: decoded.arg,
previousValue,
});
}
canGC() {
return this.state.value === this.state.initialValue;
}
save(): Uint8Array {
const message = CNumberComponentMessage.create({
arg: this.state.value,
});
return CNumberComponentMessage.encode(message).finish();
}
load(saveData: Optional<Uint8Array>) {
if (!saveData.isPresent) return;
this.state.value = CNumberComponentMessage.decode(saveData.get()).arg;
}
}
export class MinComponent
extends PrimitiveCRDT<CNumberEventsRecord>
implements StatefulCRDT<CNumberState>
{
readonly state: CNumberState;
constructor(initToken: InitToken, initialState: CNumberState) {
super(initToken);
this.state = initialState;
}
min(toComp: number) {
const message = CNumberComponentMessage.create({ arg: toComp });
const buffer = CNumberComponentMessage.encode(message).finish();
this.sendCRDT(buffer);
}
protected receiveCRDT(message: string | Uint8Array, meta: MessageMeta) {
const decoded = CNumberComponentMessage.decode(<Uint8Array>message);
const previousValue = this.state.value;
this.state.value = Math.min(this.state.value, decoded.arg);
this.emit("Min", {
meta,
arg: decoded.arg,
previousValue,
});
}
canGC() {
return this.state.value === this.state.initialValue;
}
save(): Uint8Array {
const message = CNumberComponentMessage.create({
arg: this.state.value,
});
return CNumberComponentMessage.encode(message).finish();
}
load(saveData: Optional<Uint8Array>) {
if (!saveData.isPresent) return;
this.state.value = CNumberComponentMessage.decode(saveData.get()).arg;
}
}
export class MaxComponent
extends PrimitiveCRDT<CNumberEventsRecord>
implements StatefulCRDT<CNumberState>
{
readonly state: CNumberState;
constructor(initToken: InitToken, initialState: CNumberState) {
super(initToken);
this.state = initialState;
}
max(toComp: number) {
const message = CNumberComponentMessage.create({ arg: toComp });
const buffer = CNumberComponentMessage.encode(message).finish();
this.sendCRDT(buffer);
}
protected receiveCRDT(message: string | Uint8Array, meta: MessageMeta) {
const decoded = CNumberComponentMessage.decode(<Uint8Array>message);
const previousValue = this.state.value;
this.state.value = Math.max(this.state.value, decoded.arg);
this.emit("Max", {
meta,
arg: decoded.arg,
previousValue,
});
}
canGC() {
return this.state.value === this.state.initialValue;
}
save(): Uint8Array {
const message = CNumberComponentMessage.create({
arg: this.state.value,
});
return CNumberComponentMessage.encode(message).finish();
}
load(saveData: Optional<Uint8Array>) {
if (!saveData.isPresent) return;
this.state.value = CNumberComponentMessage.decode(saveData.get()).arg;
}
}
/**
* Unlike CNumber, this doesn't allow multiplications with
* negative args.
*/
class CNumberBase extends MultipleSemidirectProduct<CNumberState> {
minCRDT: MinComponent;
maxCRDT: MaxComponent;
addCRDT: AddComponent;
multCRDT: MultComponent;
constructor(initToken: InitToken, initialValue: number) {
super(initToken);
const state = new CNumberState(initialValue);
super.setupState(state);
/**
* Arbitration order
* 0: min
* 1: max
* 2: add
* 3: mult
*/
this.minCRDT = super.setupOneCRDT(Pre(MinComponent)(state));
this.maxCRDT = super.setupOneCRDT(Pre(MaxComponent)(state));
this.addCRDT = super.setupOneCRDT(Pre(AddComponent)(state));
this.multCRDT = super.setupOneCRDT(Pre(MultComponent)(state));
}
protected action(
m2MessagePath: Message[],
_m2Meta: MessageMeta,
m2Index: number,
m1MessagePath: Message[],
_m1Meta: MessageMeta | null
): { m1MessagePath: Message[] } | null {
const m2Decoded = CNumberComponentMessage.decode(
<Uint8Array>m2MessagePath[0]
);
const m1Decoded = CNumberComponentMessage.decode(
<Uint8Array>m1MessagePath[0]
);
let actedArg: number;
switch (m2Index) {
case 3:
actedArg = m2Decoded.arg * m1Decoded.arg;
break;
case 2:
actedArg = m2Decoded.arg + m1Decoded.arg;
break;
case 1:
actedArg = Math.max(m2Decoded.arg, m1Decoded.arg);
break;
default:
actedArg = m1Decoded.arg;
}
const acted = CNumberComponentMessage.create({
arg: actedArg,
});
return {
m1MessagePath: [CNumberComponentMessage.encode(acted).finish()],
};
}
get value(): number {
return this.state.internalState.value;
}
}
/**
* Experimental; stable alternatives are [[CCounter]], [[ResettableCCounter]],
* and [[LwwCVariable]]`<number>`.
*
* Experimental warnings:
* - Eventual consistency may fail due to rounding issues.
* The only safe way is to stick to integer operands that aren't
* large enough to overflow anything.
* - Uses tombstones (one per operation). So the memory
* usage will grow without bound, unlike most of our Collabs.
*
* See https://github.com/composablesys/collabs/issues/177
*/
export class CNumber extends CObject<CNumberEventsRecord> {
private base: CNumberBase;
/**
* Used to implement negative multiplications, which don't
* directly obey the semidirect product rules with min and
* max. Instead, we use this boolean. If true, the value
* is a negated view of our internal state. Correspondingly,
* add, min, and max args must be negated, and min/max must
* be switched.
*/
private negated: ToggleCBoolean;
constructor(initToken: InitToken, initialValue = 0) {
super(initToken);
this.base = this.addChild("", Pre(CNumberBase)(initialValue));
this.negated = this.addChild("0", Pre(ToggleCBoolean)());
this.base.minCRDT.on("Min", (event) => {
if (this.negated.value) {
super.emit("Max", {
arg: -event.arg,
previousValue: -event.previousValue,
meta: event.meta,
});
} else super.emit("Min", event);
});
this.base.maxCRDT.on("Max", (event) => {
if (this.negated.value) {
super.emit("Min", {
arg: -event.arg,
previousValue: -event.previousValue,
meta: event.meta,
});
} else super.emit("Max", event);
});
this.base.addCRDT.on("Add", (event) => {
if (this.negated.value) {
super.emit("Add", {
arg: -event.arg,
previousValue: -event.previousValue,
meta: event.meta,
});
} else super.emit("Add", event);
});
this.base.multCRDT.on("Mult", (event) => super.emit("Mult", event));
this.negated.on("Set", (event) =>
super.emit("Mult", {
arg: -1,
previousValue: -this.value,
meta: event.meta,
})
);
}
add(toAdd: number) {
if (this.negated.value) {
this.base.addCRDT.add(-toAdd);
} else this.base.addCRDT.add(toAdd);
}
mult(toMult: number) {
if (toMult < 0) {
this.negated.toggle();
this.base.multCRDT.mult(-toMult);
} else this.base.multCRDT.mult(toMult);
}
min(toComp: number) {
if (this.negated.value) {
this.base.maxCRDT.max(-toComp);
} else this.base.minCRDT.min(toComp);
}
max(toComp: number) {
if (this.negated.value) {
this.base.minCRDT.min(-toComp);
} else this.base.maxCRDT.max(toComp);
}
get value(): number {
const value = (this.negated.value ? -1 : 1) * this.base.value;
// Although -0 === 0, some notions of equality
// (in particular chai's assert.deepStrictEqual)
// treat them differently. This is a hack to prevent
// -0 vs 0 from violating EC under this equality def.
// It might be related to general floating point
// noncommutativity and will go away once we fix that.
return value === 0 ? 0 : value;
}
/**
* @return this.value.toString()
*/
toString(): string {
return this.value.toString();
}
} | the_stack |
import i18next from "i18next";
import { action, computed, runInAction } from "mobx";
import containsAny from "../../../Core/containsAny";
import filterOutUndefined from "../../../Core/filterOutUndefined";
import isDefined from "../../../Core/isDefined";
import isReadOnlyArray from "../../../Core/isReadOnlyArray";
import replaceUnderscores from "../../../Core/replaceUnderscores";
import runLater from "../../../Core/runLater";
import TerriaError from "../../../Core/TerriaError";
import CatalogMemberMixin from "../../../ModelMixins/CatalogMemberMixin";
import GetCapabilitiesMixin from "../../../ModelMixins/GetCapabilitiesMixin";
import GroupMixin from "../../../ModelMixins/GroupMixin";
import UrlMixin from "../../../ModelMixins/UrlMixin";
import { InfoSectionTraits } from "../../../Traits/TraitsClasses/CatalogMemberTraits";
import ModelReference from "../../../Traits/ModelReference";
import WebMapServiceCatalogGroupTraits from "../../../Traits/TraitsClasses/WebMapServiceCatalogGroupTraits";
import CatalogGroup from "../CatalogGroup";
import CommonStrata from "../../Definition/CommonStrata";
import CreateModel from "../../Definition/CreateModel";
import createStratumInstance from "../../Definition/createStratumInstance";
import LoadableStratum from "../../Definition/LoadableStratum";
import { BaseModel } from "../../Definition/Model";
import proxyCatalogItemUrl from "../proxyCatalogItemUrl";
import StratumFromTraits from "../../Definition/StratumFromTraits";
import WebMapServiceCapabilities, {
CapabilitiesLayer
} from "./WebMapServiceCapabilities";
import WebMapServiceCatalogItem from "./WebMapServiceCatalogItem";
class GetCapabilitiesStratum extends LoadableStratum(
WebMapServiceCatalogGroupTraits
) {
static async load(
catalogItem: WebMapServiceCatalogGroup
): Promise<GetCapabilitiesStratum> {
if (catalogItem.getCapabilitiesUrl === undefined) {
throw new TerriaError({
title: i18next.t("models.webMapServiceCatalogGroup.missingUrlTitle"),
message: i18next.t("models.webMapServiceCatalogGroup.missingUrlMessage")
});
}
const capabilities = await WebMapServiceCapabilities.fromUrl(
proxyCatalogItemUrl(
catalogItem,
catalogItem.getCapabilitiesUrl,
catalogItem.getCapabilitiesCacheDuration
)
);
return new GetCapabilitiesStratum(catalogItem, capabilities);
}
constructor(
readonly catalogGroup: WebMapServiceCatalogGroup,
readonly capabilities: WebMapServiceCapabilities
) {
super();
}
duplicateLoadableStratum(model: BaseModel): this {
return new GetCapabilitiesStratum(
model as WebMapServiceCatalogGroup,
this.capabilities
) as this;
}
@computed get name() {
if (
this.capabilities &&
this.capabilities.Service &&
this.capabilities.Service.Title
) {
return replaceUnderscores(this.capabilities.Service.Title);
}
}
@computed get info() {
const result: StratumFromTraits<InfoSectionTraits>[] = [];
const service = this.capabilities && this.capabilities.Service;
if (service) {
// Show the service abstract if there is one and if it isn't the Geoserver default "A compliant implementation..."
if (
service &&
service.Abstract &&
!containsAny(
service.Abstract,
WebMapServiceCatalogItem.abstractsToIgnore
)
) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.webMapServiceCatalogGroup.abstract"),
content: this.capabilities.Service.Abstract
})
);
}
// Show the Access Constraints if it isn't "none" (because that's the default, and usually a lie).
if (
service &&
service.AccessConstraints &&
!/^none$/i.test(service.AccessConstraints)
) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t(
"models.webMapServiceCatalogGroup.accessConstraints"
),
content: this.capabilities.Service.AccessConstraints
})
);
}
// Show the Fees if it isn't "none".
if (service && service.Fees && !/^none$/i.test(service.Fees)) {
result.push(
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.webMapServiceCatalogGroup.fees"),
content: this.capabilities.Service.Fees
})
);
}
}
return result;
}
@computed
get members(): ModelReference[] {
return filterOutUndefined(
this.topLevelLayers.map(layer => this.getLayerId(layer))
);
}
get topLevelLayers(): readonly CapabilitiesLayer[] {
if (this.catalogGroup.flatten) {
return this.capabilities.allLayers;
} else {
let rootLayers: readonly CapabilitiesLayer[] = this.capabilities
.rootLayers;
while (
rootLayers &&
rootLayers.length === 1 &&
rootLayers[0].Name === undefined
) {
const subLayer:
| CapabilitiesLayer
| readonly CapabilitiesLayer[]
| undefined = rootLayers[0].Layer;
if (subLayer && isReadOnlyArray(subLayer)) {
rootLayers = subLayer;
} else if (subLayer) {
rootLayers = [subLayer as CapabilitiesLayer];
} else {
break;
}
}
return rootLayers;
}
}
@action
createMembersFromLayers() {
this.topLevelLayers.forEach(layer => this.createMemberFromLayer(layer));
}
@action
createMemberFromLayer(layer: CapabilitiesLayer) {
const layerId = this.getLayerId(layer);
if (!layerId) {
return;
}
// If has nested layers -> create model for CatalogGroup
if (layer.Layer) {
// Create nested layers
let members: CapabilitiesLayer[] = [];
if (Array.isArray(layer.Layer)) {
members = layer.Layer;
} else {
members = [layer.Layer as CapabilitiesLayer];
}
members.forEach(member => this.createMemberFromLayer(member));
// Create group
const existingModel = this.catalogGroup.terria.getModelById(
CatalogGroup,
layerId
);
let model: CatalogGroup;
if (existingModel === undefined) {
model = new CatalogGroup(layerId, this.catalogGroup.terria);
this.catalogGroup.terria.addModel(model, this.getLayerShareKeys(layer));
} else {
model = existingModel;
}
model.setTrait(CommonStrata.underride, "name", layer.Title);
model.setTrait(
CommonStrata.underride,
"members",
filterOutUndefined(members.map(member => this.getLayerId(member)))
);
// Set group `info` trait if applicable
if (
layer &&
layer.Abstract &&
!containsAny(layer.Abstract, WebMapServiceCatalogItem.abstractsToIgnore)
) {
model.setTrait(CommonStrata.underride, "info", [
createStratumInstance(InfoSectionTraits, {
name: i18next.t("models.webMapServiceCatalogGroup.abstract"),
content: layer.Abstract
})
]);
}
return;
}
// No nested layers -> create model for WebMapServiceCatalogItem
const existingModel = this.catalogGroup.terria.getModelById(
WebMapServiceCatalogItem,
layerId
);
let model: WebMapServiceCatalogItem;
if (existingModel === undefined) {
model = new WebMapServiceCatalogItem(layerId, this.catalogGroup.terria);
this.catalogGroup.terria.addModel(model, this.getLayerShareKeys(layer));
} else {
model = existingModel;
}
// Replace the stratum inherited from the parent group.
const stratum = CommonStrata.underride;
model.strata.delete(stratum);
model.setTrait(stratum, "name", layer.Title);
model.setTrait(stratum, "url", this.catalogGroup.url);
model._webMapServiceCatalogGroup = this.catalogGroup;
model.setTrait(
stratum,
"getCapabilitiesUrl",
this.catalogGroup.getCapabilitiesUrl
);
model.setTrait(
stratum,
"getCapabilitiesCacheDuration",
this.catalogGroup.getCapabilitiesCacheDuration
);
model.setTrait(stratum, "layers", layer.Name);
// if user defined following properties on th group level we should pass them to all group members
model.setTrait(stratum, "hideSource", this.catalogGroup.hideSource);
model.setTrait(
stratum,
"isOpenInWorkbench",
this.catalogGroup.isOpenInWorkbench
);
model.setTrait(
stratum,
"isExperiencingIssues",
this.catalogGroup.isExperiencingIssues
);
model.setTrait(
stratum,
"hideLegendInWorkbench",
this.catalogGroup.hideLegendInWorkbench
);
if (this.catalogGroup.itemProperties !== undefined) {
Object.keys(this.catalogGroup.itemProperties).map((k: any) =>
model.setTrait(stratum, k, this.catalogGroup.itemProperties![k])
);
}
model.createGetCapabilitiesStratumFromParent(this.capabilities);
}
getLayerId(layer: CapabilitiesLayer) {
if (!isDefined(this.catalogGroup.uniqueId)) {
return;
}
return `${this.catalogGroup.uniqueId}/${layer.Name ?? layer.Title}`;
}
/** For backward-compatibility.
* If layer.Name is defined, we will use it to create layer autoID (see `this.getLayerId`).
* Previously we used layer.Title, so we now add it as a shareKey
*/
getLayerShareKeys(layer: CapabilitiesLayer) {
if (isDefined(layer.Name) && layer.Title !== layer.Name)
return [`${this.catalogGroup.uniqueId}/${layer.Title}`];
return [];
}
}
/**
* Creates an item in the catalog for each available WMS layer.
* Note: To present a single layer in the catalog you can also use `WebMapServiceCatalogItem`.
* @public
* @example
* {
* "type": "wms-group",
* "name": "Digital Earth Australia",
* "url": "https://ows.services.dea.ga.gov.au",
* }
*/
export default class WebMapServiceCatalogGroup extends GetCapabilitiesMixin(
UrlMixin(
GroupMixin(CatalogMemberMixin(CreateModel(WebMapServiceCatalogGroupTraits)))
)
) {
static readonly type = "wms-group";
get type() {
return WebMapServiceCatalogGroup.type;
}
protected async forceLoadMetadata(): Promise<void> {
let getCapabilitiesStratum = <GetCapabilitiesStratum | undefined>(
this.strata.get(GetCapabilitiesMixin.getCapabilitiesStratumName)
);
if (getCapabilitiesStratum === undefined) {
getCapabilitiesStratum = await GetCapabilitiesStratum.load(this);
runInAction(() => {
this.strata.set(
GetCapabilitiesMixin.getCapabilitiesStratumName,
getCapabilitiesStratum!
);
});
}
}
protected async forceLoadMembers(): Promise<void> {
let getCapabilitiesStratum = <GetCapabilitiesStratum | undefined>(
this.strata.get(GetCapabilitiesMixin.getCapabilitiesStratumName)
);
if (getCapabilitiesStratum !== undefined) {
await runLater(() => getCapabilitiesStratum!.createMembersFromLayers());
}
}
protected get defaultGetCapabilitiesUrl(): string | undefined {
if (this.uri) {
return this.uri
.clone()
.setSearch({
service: "WMS",
version: "1.3.0",
request: "GetCapabilities"
})
.toString();
} else {
return undefined;
}
}
} | the_stack |
import {
CidrBlock,
NetworkUtils,
} from '@aws-cdk/aws-ec2/lib/network-util';
import * as CloudFormation from 'aws-sdk/clients/cloudformation';
import * as SecretsManager from 'aws-sdk/clients/secretsmanager';
import * as AWS from 'aws-sdk/global';
import awaitSsmCommand from '../../common/functions/awaitSsmCommand';
// Name of testing stack is derived from env variable to ensure uniqueness
const testingStackName = 'RFDKInteg-SM-TestingTier' + process.env.INTEG_STACK_TAG?.toString();
const cloudformation = new CloudFormation({ apiVersion: '2017-10-17' });
const secretsManager = new SecretsManager({ apiVersion: '2017-10-17' });
const bastionRegex = /bastionId/;
const smSecretRegex = /deadlineSecretsManagementCredentialsSM(\d)/;
const renderQueueAlbSubnetIdsRegex = /renderQueueAlbSubnetIdsSM(\d)/;
const ublSubnetIdsRegex = /ublSubnetIdsSM(\d)/;
const sepFleetSubnetIdsRegex = /sepFleetSubnetIdsSM(\d)/;
const workerInstanceFleetSubnetIdsRegex = /workerInstanceFleetSubnetIdsSM(\d)/;
const renderQueueAlbSubnetCidrBlocksRegex = /renderQueueAlbSubnetCidrBlocksSM(\d)/;
const ublSubnetCidrBlocksRegex = /ublSubnetCidrBlocksSM(\d)/;
const sepFleetSubnetCidrBlocksRegex = /sepFleetSubnetCidrBlocksSM(\d)/;
const workerInstanceFleetSubnetCidrBlocksRegex = /workerInstanceFleetSubnetCidrBlocksSM(\d)/;
const identityRegistrationSettingsNameRegex = /RfdkSubnet\|(?<connectionSubnetId>subnet-[0-9a-z]+)\|(?<sourceSubnetId>subnet-[0-9a-z]+)/;
let bastionId: string;
let smSecretArn: string;
const renderQueueAlbSubnetIds: string[] = [];
const ublSubnetIds: string[] = [];
const sepFleetSubnetIds: string[] = [];
const workerInstanceFleetSubnetIds: string[] = [];
const renderQueueAlbSubnetCidrBlocks: string[] = [];
const ublSubnetCidrBlocks: string[] = [];
const sepFleetSubnetCidrBlocks: string[] = [];
const workerInstanceFleetSubnetCidrBlocks: string[] = [];
beforeAll(async () => {
// Query the TestingStack and await its outputs to use as test inputs
const describeStacksResponse = await cloudformation.describeStacks({ StackName: testingStackName }).promise();
let stackOutput = describeStacksResponse.Stacks![0].Outputs!;
stackOutput.forEach(output => {
let outputKey = output.OutputKey!;
let outputValue = output.OutputValue!;
if (bastionRegex.test(outputKey)) {
bastionId = outputValue;
} else if (smSecretRegex.test(outputKey)) {
smSecretArn = outputValue;
// Subnet IDs
} else if (renderQueueAlbSubnetIdsRegex.test(outputKey)) {
renderQueueAlbSubnetIds.push(...JSON.parse(outputValue) as string[]);
} else if (ublSubnetIdsRegex.test(outputKey)) {
ublSubnetIds.push(...JSON.parse(outputValue) as string[]);
} else if (sepFleetSubnetIdsRegex.test(outputKey)) {
sepFleetSubnetIds.push(...JSON.parse(outputValue) as string[]);
} else if (workerInstanceFleetSubnetIdsRegex.test(outputKey)) {
workerInstanceFleetSubnetIds.push(...JSON.parse(outputValue) as string[]);
// Subnet CIDR blocks
} else if (renderQueueAlbSubnetCidrBlocksRegex.test(outputKey)) {
renderQueueAlbSubnetCidrBlocks.push(...JSON.parse(outputValue) as string[]);
} else if (ublSubnetCidrBlocksRegex.test(outputKey)) {
ublSubnetCidrBlocks.push(...JSON.parse(outputValue) as string[]);
} else if (sepFleetSubnetCidrBlocksRegex.test(outputKey)) {
sepFleetSubnetCidrBlocks.push(...JSON.parse(outputValue) as string[]);
} else if (workerInstanceFleetSubnetCidrBlocksRegex.test(outputKey)) {
workerInstanceFleetSubnetCidrBlocks.push(...JSON.parse(outputValue) as string[]);
}
});
// Assert the required outputs are found, failing if any are missing
const errors = [];
if (!bastionId) {
errors.push('A stack output for "bastionId" is required but was not found');
}
if (!smSecretArn) {
errors.push('A stack output for deadlineSecretsManagementCredentialsSM1 is required but was not found');
}
if (!renderQueueAlbSubnetIds.length) {
errors.push('A stack output for renderQueueAlbSubnetIdsSM1 is required but was not found');
}
if (!ublSubnetIds.length) {
errors.push('A stack output for ublSubnetIdsSM1 is required but was not found');
}
if (!sepFleetSubnetIds.length) {
errors.push('A stack output for sepFleetSubnetIdsSM1 is required but was not found');
}
if (!workerInstanceFleetSubnetIds.length) {
errors.push('A stack output for workerInstanceFleetSubnetIdsSM1 is required but was not found');
}
if (!renderQueueAlbSubnetCidrBlocks.length) {
errors.push('A stack output for renderQueueAlbSubnetCidrBlocksSM1 is required but was not found');
}
if (!ublSubnetCidrBlocks.length) {
errors.push('A stack output for ublSubnetCidrBlocksSM1 is required but was not found');
}
if (!sepFleetSubnetCidrBlocks.length) {
errors.push('A stack output for sepFleetSubnetCidrBlocksSM1 is required but was not found');
}
if (!workerInstanceFleetSubnetCidrBlocks.length) {
errors.push('A stack output for workerInstanceFleetSubnetCidrBlocksSM1 is required but was not found');
}
if (errors.length > 0) {
throw new Error(`Test failed to initialize for the following reasons:\n${errors.join('\n')}`);
}
});
describe('Deadline Secrets Management tests', () => {
test('SM-1-1: Deadline Repository configures Secrets Management', async () => {
/**********************************************************************************************************
* TestID: SM-1
* Description: Confirm that Deadline Repository configures Secrets Management
* Input: Output from "deadlinecommand secrets ListAllAdminUsers" call delivered via SSM command
* Expected result: List of admin users which shows that the user created by RFDK is registered
**********************************************************************************************************/
// GIVEN
const params = {
DocumentName: 'AWS-RunShellScript',
Comment: 'Execute ListAllAdminUsers via test script SM-run-secrets-command.sh',
InstanceIds: [bastionId],
Parameters: {
commands: [
`sudo -u ec2-user ~ec2-user/testScripts/SM-run-secrets-command.sh '${AWS.config.region}' '${smSecretArn}' ListAllAdminUsers`,
],
},
};
const secret = await secretsManager.getSecretValue({ SecretId: smSecretArn }).promise();
const smCreds = JSON.parse(secret.SecretString!);
const adminUserRegex = new RegExp(`${smCreds.username}\\s+Registered`);
// WHEN
const response = await awaitSsmCommand(bastionId, params);
// THEN
expect(response.output).toMatch(adminUserRegex);
});
test('SM-1-2: Deadline Render Queue has a Server role', async () => {
/**********************************************************************************************************
* TestID: SM-2
* Description: Confirm that Deadline Render Queue configures itself as a Server role
* Input: Output from "deadlinecommand secrets ListAllMachines" call delivered via SSM command
* Expected result: List of machine identities contains an entry for the Render Queue machine and it has
* the Server role assigned to it
**********************************************************************************************************/
// GIVEN
const params = {
DocumentName: 'AWS-RunShellScript',
Comment: 'Execute ListAllMachines via test script SM-run-secrets-command.sh',
InstanceIds: [bastionId],
Parameters: {
commands: [
`sudo -u ec2-user ~ec2-user/testScripts/SM-run-secrets-command.sh '${AWS.config.region}' '${smSecretArn}' ListAllMachines "*" Server`,
],
},
};
// WHEN
const response = await awaitSsmCommand(bastionId, params);
// THEN
// Assert there is exactly one Server identity (the RCS)
expect(response.output).toMatchTimes(/ec2-user\s+\[Server\]\s+Registered/g, 1);
});
test.each<[number, string, string[]]>([
[3, 'Usage Based Licensing', ublSubnetIds],
[4, 'Worker Instance Fleet', workerInstanceFleetSubnetIds],
[5, 'Spot Event Plugin Fleet', sepFleetSubnetIds],
])('SM-1-%s: Deadline %s has an identity registration setting', async (_testId, _componentName, clientSubnetIdMap) => {
/**********************************************************************************************************
* Description: Confirm that a Deadline client has an identity registration settings created for it
* Input: Output from "deadlinecommand secrets GetLoadBalancerIdentityRegistrationSettings" call
* delivered via SSM command
* Expected result: List of identity registration settings contains an entry for the Deadline client
* machine's subnet and it has the Client role assigned to it
**********************************************************************************************************/
// GIVEN
const params = {
DocumentName: 'AWS-RunShellScript',
Comment: 'Execute GetLoadBalancerIdentityRegistrationSettings via test script SM-run-secrets-command.sh',
InstanceIds: [bastionId],
Parameters: {
commands: [
`sudo -u ec2-user ~ec2-user/testScripts/SM-run-secrets-command.sh '${AWS.config.region}' '${smSecretArn}' GetLoadBalancerIdentityRegistrationSettings`,
],
},
};
const rqAlbSubnetIds = renderQueueAlbSubnetIds;
const expectedSubnetPairs: { connectionSubnetId: string, sourceSubnetId: string }[] = [];
rqAlbSubnetIds.forEach(albSubnetId => {
clientSubnetIdMap.forEach(clientSubnetId => {
expectedSubnetPairs.push(expect.objectContaining({
connectionSubnetId: albSubnetId,
sourceSubnetId: clientSubnetId,
}));
});
});
// WHEN
const response = await awaitSsmCommand(bastionId, params);
// Parse the output into connection and source subnet ID pairs
const result = JSON.parse(response.output) as any[];
const settingSubnetPairs = result.filter(setting =>
'SettingsName' in setting &&
identityRegistrationSettingsNameRegex.test(setting.SettingsName),
).map(setting => {
const matches = identityRegistrationSettingsNameRegex.exec(setting.SettingsName);
return {
connectionSubnetId: matches!.groups!.connectionSubnetId,
sourceSubnetId: matches!.groups!.sourceSubnetId,
};
});
// THEN
// Verify that the identity registration settings received contain the expected settings
expect(settingSubnetPairs).toEqual(expect.arrayContaining(expectedSubnetPairs));
});
test.each<[number, string, string[]]>([
[6, 'Usage Based Licensing', ublSubnetCidrBlocks],
[7, 'Worker Instance Fleet', workerInstanceFleetSubnetCidrBlocks],
// TODO: In the future, we should add the ability to submit Deadline jobs so that a SEP fleet can be spun up and used for this test
// [8, 'Spot Event Plugin Fleet', sepFleetSubnetCidrBlocks],
])('SM-1-%s: Deadline %s is automatically registered as a Client', async (_testId, _componentName, clientSubnetCidrBlockMap) => {
/**********************************************************************************************************
* Description: Confirm that a Deadline client is automatically registered as a Client role.
* Input: Output from "deadlinecommand secrets "ListAllMachines" call delivered via SSM command
* Expected result: List of identities contains an entry where the source IP and connection IP are within the
* Deadline client machine's subnet CIDR and the Render Queue ALB subnet CIDR, respectively.
* Also assert that this entry shows the Deadline client is registered as a Client role.
**********************************************************************************************************/
// GIVEN
const params = {
DocumentName: 'AWS-RunShellScript',
Comment: 'Execute ListAllMachines via test script SM-run-secrets-command.sh',
InstanceIds: [bastionId],
Parameters: {
commands: [
`sudo -u ec2-user ~ec2-user/testScripts/SM-run-secrets-command.sh '${AWS.config.region}' '${smSecretArn}' ListAllMachines "*" Client`,
],
},
};
const rqAlbSubnetCidrBlocks = renderQueueAlbSubnetCidrBlocks;
const expectedSubnetCidrPairs: { connectionSubnetCidrBlock: string, sourceSubnetCidrBlock: string }[] = [];
rqAlbSubnetCidrBlocks.forEach(albSubnetCidrblock => {
clientSubnetCidrBlockMap.forEach(clientSubnetCidrBlock => {
expectedSubnetCidrPairs.push({
connectionSubnetCidrBlock: albSubnetCidrblock,
sourceSubnetCidrBlock: clientSubnetCidrBlock,
});
});
});
// WHEN
const response = await awaitSsmCommand(bastionId, params);
// Parse the output into connection and source subnet ID pairs
const lines = response.output.split('\n').slice(2);
const identityInfos = lines.filter(line => line).map(line => parseListAllMachinesLine(line));
// THEN
// Verify that there exists at least one identity that is registered for this component by checking that its
// source IP and connection IP are within the expected subnet CIDR blocks.
expect(identityInfos.some(identityInfo => {
return expectedSubnetCidrPairs.some(expected => {
const connectionIpNum = NetworkUtils.ipToNum(identityInfo.connectionIpAddress);
const connectionSubnetCidr = new CidrBlock(expected.connectionSubnetCidrBlock);
const sourceIpNum = NetworkUtils.ipToNum(identityInfo.sourceIpAddress);
const sourceIpSubnetCidr = new CidrBlock(expected.sourceSubnetCidrBlock);
return sourceIpSubnetCidr.minAddress() <= sourceIpNum && sourceIpNum <= sourceIpSubnetCidr.maxAddress() &&
connectionSubnetCidr.minAddress() <= connectionIpNum && connectionIpNum <= connectionSubnetCidr.maxAddress();
});
})).toBeTruthy();
});
});
/**
* Parses a line containing data from the ListAllMachines Deadline Secrets Command into an object.
* @param line The line to parse.
* @returns An object containing the data from a Deadline Secrets Command ListAllMachines output line.
* @see https://docs.thinkboxsoftware.com/products/deadline/10.1/1_User%20Manual/manual/secrets-management/deadline-secrets-management.html#listallmachines
*/
function parseListAllMachinesLine(line: string): {
readonly machineName: string,
readonly sourceIpAddress: string,
readonly connectionIpAddress: string,
readonly osUser: string,
readonly roles: string[],
readonly status: string,
readonly id: string,
} {
const tokens = line.split(/\s+/).filter(token => token.trim().length > 0);
return {
machineName: tokens[0],
sourceIpAddress: tokens[1],
connectionIpAddress: tokens[2],
osUser: tokens[3],
// Parse the list of roles that are presented as an array of unquoted strings
roles: tokens[4].substring(1, tokens[4].length - 1).split(', '),
status: tokens[5],
id: tokens[6],
};
} | the_stack |
import fs from 'fs';
import { assert } from 'chai';
import Connection from '../../src/connection';
import Request from '../../src/request';
import { typeByName as TYPES } from '../../src/data-type';
import { homedir } from 'os';
const debug = false;
const config = JSON.parse(
fs.readFileSync(homedir() + '/.tedious/test-connection.json', 'utf8')
).config;
config.options.textsize = 8 * 1024;
if (debug) {
config.options.debug = {
packet: true,
data: true,
payload: true,
token: true,
log: true,
};
} else {
config.options.debug = {};
}
config.options.tdsVersion = process.env.TEDIOUS_TDS_VERSION;
describe('Datatypes in results test', function() {
let connection: Connection;
beforeEach(function(done) {
connection = new Connection(config);
connection.on('errorMessage', function(error) {
console.log(`${error.number} : ${error.message}`);
});
connection.on('debug', function(message) {
if (debug) {
console.log(message);
}
});
connection.connect(done);
});
afterEach(function(done) {
if (!connection.closed) {
connection.on('end', done);
connection.close();
} else {
done();
}
});
function testDataType(expectedType: typeof TYPES[keyof typeof TYPES], cases: { [key: string]: [string, any] | [string, any, string] }) {
describe(expectedType.name, function() {
for (const description in cases) {
if (!cases.hasOwnProperty(description)) {
continue;
}
const [sql, expectedValue, tdsVersion] = cases[description];
if (tdsVersion && tdsVersion > config.options.tdsVersion) {
it.skip(description);
continue;
}
it(description, function(done) {
let rowProcessed = 0;
const request = new Request(sql, done);
request.on('row', function(columns) {
const expectedRowVal = (expectedValue instanceof Array) ? expectedValue[rowProcessed++] : expectedValue;
if (expectedRowVal instanceof Date) {
assert.strictEqual(columns[0].value.getTime(), expectedRowVal.getTime());
} else if (
expectedRowVal instanceof Array ||
expectedRowVal instanceof Buffer
) {
assert.deepEqual(columns[0].value, expectedRowVal);
} else {
assert.strictEqual(columns[0].value, expectedRowVal);
}
});
connection.execSqlBatch(request);
});
}
});
}
testDataType(TYPES.TinyInt, {
'should handle small value': ['select cast(8 as tinyint)', 8],
'should handle large value': ['select cast(252 as tinyint)', 252],
'should handle null value': ['select cast(null as tinyint)', null]
});
testDataType(TYPES.SmallInt, {
'should test small value': ['select cast(8 as smallint)', 8],
'should test negative value': ['select cast(-8 as smallint)', -8],
'should test large value': ['select cast(1443 as smallint)', 1443],
'should test null value': ['select cast(null as smallint)', null]
});
testDataType(TYPES.Int, {
'should test int': ['select cast(8 as int)', 8],
'should test int null': ['select cast(null as int)', null]
});
testDataType(TYPES.Real, {
'should test real': ['select cast(9.5 as real)', 9.5],
'should test real null': ['select cast(null as real)', null]
});
testDataType(TYPES.Float, {
'should test float': ['select cast(9.5 as float)', 9.5],
'should test float null': ['select cast(null as float)', null]
});
testDataType(TYPES.BigInt, {
'should test big int': ['select cast(8 as bigint)', '8'],
'should test negative big int': ['select cast(-8 as bigint)', '-8'],
'should test big int null': ['select cast(null as bigint)', null],
});
testDataType(TYPES.Bit, {
'should test bit false': ["select cast('false' as bit)", false],
'should test bit true': ["select cast('true' as bit)", true],
'should test bit null': ['select cast(null as bit)', null]
});
testDataType(TYPES.DateTime, {
'should test date time': [
"select cast('2011-12-4 10:04:23' as datetime)",
new Date('December 4, 2011 10:04:23 GMT')
],
'should test date time null': ['select cast(null as datetime)', null],
// The tests below validates DateTime precision as described in the section
// "Rounding of datetime Fractional Second Precision" from
// https://msdn.microsoft.com/en-us/library/ms187819.aspx
'should test date time precision_0': [
"select cast('1998-1-1 23:59:59.990' as datetime)",
new Date('January 1, 1998 23:59:59.990 GMT')
],
'should test date time precision_1': [
"select cast('1998-1-1 23:59:59.991' as datetime)",
new Date('January 1, 1998 23:59:59.990 GMT')
],
'should test date time precision_2': [
"select cast('1998-1-1 23:59:59.992' as datetime)",
new Date('January 1, 1998 23:59:59.993 GMT')
],
'should test date time precision_3': [
"select cast('1998-1-1 23:59:59.993' as datetime)",
new Date('January 1, 1998 23:59:59.993 GMT')
],
'should test date time precision_4': [
"select cast('1998-1-1 23:59:59.994' as datetime)",
new Date('January 1, 1998 23:59:59.993 GMT')
],
'should test date time precision_5': [
"select cast('1998-1-1 23:59:59.995' as datetime)",
new Date('January 1, 1998 23:59:59.997 GMT')
],
'should test date time precision_6': [
"select cast('1998-1-1 23:59:59.996' as datetime)",
new Date('January 1, 1998 23:59:59.997 GMT')
],
'should test date time precision_7': [
"select cast('1998-1-1 23:59:59.997' as datetime)",
new Date('January 1, 1998 23:59:59.997 GMT')
],
'should test date time precision_8': [
"select cast('1998-1-1 23:59:59.998' as datetime)",
new Date('January 1, 1998 23:59:59.997 GMT')
],
'should test date time precision_9': [
"select cast('1998-1-1 23:59:59.999' as datetime)",
new Date('January 2, 1998 00:00:00.000 GMT')
]
});
testDataType(TYPES.SmallDateTime, {
'should test small date time': [
"select cast('2011-12-4 10:04:23' as smalldatetime)",
new Date('December 4, 2011 10:04:00 GMT')
],
'should test small date time null': [
'select cast(null as smalldatetime)', null
]
});
testDataType(TYPES.DateTime2, {
'should test datetime2': [
"select cast('2011-12-4 10:04:23' as datetime2)",
new Date('December 4, 2011 10:04:23 +00'),
'7_3_A'
],
'should test datetime2 null': [
'select cast(null as datetime2)', null, '7_3_A'
]
});
testDataType(TYPES.Time, {
'should test time': [
"select cast('10:04:23' as time)",
new Date(Date.UTC(1970, 0, 1, 10, 4, 23)),
'7_3_A'
],
'should test time null': [
'select cast(null as time)', null, '7_3_A'
]
});
testDataType(TYPES.Date, {
'should test date': [
"select cast('2014-03-08' as date)",
new Date(Date.UTC(2014, 2, 8)),
'7_3_A'
],
'should test date null': [
'select cast(null as date)', null, '7_3_A'
]
});
testDataType(TYPES.DateTimeOffset, {
'should test datetimeoffset': [
"select cast('2014-02-14 22:59:59.9999999 +05:00' as datetimeoffset)",
new Date(Date.UTC(2014, 1, 14, 17, 59, 59, 999)),
'7_3_A'
],
'should test datetimeoffset null': [
'select cast(null as datetimeoffset)', null
]
});
testDataType(TYPES.Numeric, {
'should test numeric small value': [
'select cast(9.3 as numeric(3,2))', 9.3
],
'should test numeric large value': [
'select cast(9876543.3456 as numeric(12,5))', 9876543.3456
],
'should test numeric very large value': [
'select cast(9876543219876543.3456 as numeric(25,5))',
9876543219876543.3456
],
'should test numeric extremely large value': [
'select cast(98765432198765432198765432.3456 as numeric(35,5))',
98765432198765432198765432.3456
],
'should test numeric null': [
'select cast(null as numeric(3,2))', null
]
});
testDataType(TYPES.SmallMoney, {
'should test small money': ['select cast(1.22229 as smallmoney)', 1.2223],
'should test small money negative': ['select cast(-1.22229 as smallmoney)', -1.2223],
'should test small money null': ['select cast(null as smallmoney)', null]
});
testDataType(TYPES.Money, {
'should test money': [
'select cast(1.22229 as money)',
1.2223
],
'should test money negative': [
'select cast(-1.22229 as money)',
-1.2223
],
'should test money large': [
'select cast(123456789012345.11 as money)',
123456789012345.11
],
'should test money large negative': [
'select cast(-123456789012345.11 as money)',
-123456789012345.11
],
'should test money null': [
'select cast(null as money)',
null
]
});
testDataType(TYPES.VarChar, {
'should test varchar': ["select cast('abcde' as varchar(10))", 'abcde'],
'should test varchar empty': ["select cast('' as varchar(10))", ''],
'should test varchar null': ['select cast(null as varchar(10))', null],
// The codepage used is WINDOWS-1251.
'should test varchar collation': [
`create table #tab1 (col1 nvarchar(10) collate Cyrillic_General_CS_AS);
insert into #tab1 values(N'abcdШ');
select cast(col1 as varchar(10)) from #tab1`,
'abcdШ'
],
'should test varchar(max)': [
"select cast('abc' as varchar(max))",
'abc',
'7_2'
],
'should test varchar(max) null': [
'select cast(null as varchar(max))',
null,
'7_2'
],
'should test varchar(max) long as text size': [
`select cast('${'x'.repeat(config.options.textsize)}' as varchar(max))`,
'x'.repeat(config.options.textsize),
'7_2'
],
'should test varchar(max) larger than text size': [
`select cast('${'x'.repeat(config.options.textsize + 10)}' as varchar(max))`,
'x'.repeat(config.options.textsize),
'7_2'
]
});
testDataType(TYPES.NVarChar, {
'should test nvarchar': [
"select cast('abc' as nvarchar(10))",
'abc'
],
'should test nvarchar null': [
'select cast(null as nvarchar(10))',
null
],
'should test nvarchar(max)': [
"select cast('abc' as nvarchar(max))", 'abc', '7_2'
],
'should test nvarchar(max) null': [
'select cast(null as nvarchar(max))', null, '7_2'
]
});
testDataType(TYPES.VarBinary, {
'should test varbinary': [
'select cast(0x1234 as varbinary(4))',
Buffer.from([0x12, 0x34])
],
'should test varbinary null': [
'select cast(null as varbinary(10))', null
],
'should test varbinary(max)': [
'select cast(0x1234 as varbinary(max))',
Buffer.from([0x12, 0x34]),
'7_2'
],
'should test varbinary(max) null': [
'select cast(null as varbinary(max))', null, '7_2'
]
});
testDataType(TYPES.Binary, {
'should test binary': [
'select cast(0x1234 as binary(4))',
Buffer.from([0x12, 0x34, 0x00, 0x00])
],
'should test binary null': [
'select cast(null as binary(10))', null
]
});
testDataType(TYPES.Char, {
'should test char': [
"select cast('abc' as char(5))", 'abc '
],
'should test char null': [
'select cast(null as char(5))', null
]
});
testDataType(TYPES.NChar, {
'should test nchar': [
"select cast('abc' as nchar(5))", 'abc '
],
'should test nchar null': [
'select cast(null as nchar(5))', null
]
});
testDataType(TYPES.Text, {
'should test text': [
"select cast('abc' as text) as text", 'abc'
],
'should test text emtpy': [
"select cast('' as text) as text", ''
],
'should test text null': [
'select cast(null as text) as text', null
]
});
testDataType(TYPES.NText, {
'should test text': [
"select cast('abc' as ntext) as text", 'abc'
],
'should test text emtpy': [
"select cast('' as ntext) as text", ''
],
'should test text null': [
'select cast(null as ntext) as text', null
]
});
testDataType(TYPES.Image, {
'should test image': ['select cast(0x1234 as image)', Buffer.from([0x12, 0x34])],
'should test image null': ['select cast(null as image)', null]
});
testDataType(TYPES.UniqueIdentifier, {
'should test guid': [
"select cast('01234567-89AB-CDEF-0123-456789ABCDEF' as uniqueidentifier)",
'01234567-89AB-CDEF-0123-456789ABCDEF'
],
'should test guid null': [
'select cast(null as uniqueidentifier)', null
]
});
testDataType(TYPES.Variant, {
'should test variant int': [
'select cast(11 as sql_variant)', 11, '7_2'
],
'should test variant numeric': [
'select cast(11.16 as sql_variant)', 11.16, '7_2'
],
'should test variant varchar': [
"select cast('abc' as sql_variant)", 'abc', '7_2'
],
'should test variant varbinary': [
'select cast(cast(0x1234 as varbinary(16)) as sql_variant)',
Buffer.from([0x12, 0x34]),
'7_2'
],
'should test variant datetimeoffset': [
"select cast(cast('2014-02-14 22:59:59.9999999 +05:00' as datetimeoffset) as sql_variant)",
new Date(Date.UTC(2014, 1, 14, 17, 59, 59, 999)),
'7_3_A'
],
'should test variant nvarchar': [
"select N'abcdШ' as sql_variant",
'abcdШ'
],
'should test variant decimal': [
'select cast(cast(3148.29 as decimal(20,8)) as sql_variant)',
3148.29
],
'should test variant uniqueidentifier': [
"select cast(cast('01234567-89AB-CDEF-0123-456789ABCDEF' as uniqueidentifier) as sql_variant)",
'01234567-89AB-CDEF-0123-456789ABCDEF'
],
'should test variant datetime': [
"select cast(cast('2011-12-4 10:04:23' as datetime) as sql_variant)",
new Date('December 4, 2011 10:04:23 GMT')
],
'should test variant null': [
'select cast(null as sql_variant)', null, '7_2'
]
});
testDataType(TYPES.Xml, {
'should test xml': (() => {
const xml = '<root><child attr="attr-value"/></root>';
return [`select cast('${xml}' as xml)`, xml, '7_2'] as [string, string, string];
})(),
'should test xml null': [
'select cast(null as xml)', null, '7_2'
],
'should test xml with schema': (() => {
// Cannot use temp tables, as schema collections as not available to them.
// Schema must be created manually in database in order to make this done work properly (sql 2012)
const xml = '<root/>';
const schemaName = 'test_tedious_schema';
const tableName = 'test_tedious_table';
const schema = `
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="root">
</xsd:element>
</xsd:schema>
`;
const sql = `
-- Check if we have permissions to create schema collections
IF HAS_PERMS_BY_NAME(db_name(), 'DATABASE', 'CREATE XML SCHEMA COLLECTION') = 1
BEGIN
IF OBJECT_ID('${tableName}', 'U') IS NOT NULL
DROP TABLE [${tableName}];
IF EXISTS (SELECT * FROM [sys].[xml_schema_collections] WHERE [name] = '${schemaName}' AND [schema_id] = SCHEMA_ID())
DROP XML SCHEMA COLLECTION [${schemaName}];
CREATE XML SCHEMA COLLECTION [${schemaName}] AS N'${schema}';
EXEC('CREATE TABLE [${tableName}] ([xml] [xml]([${schemaName}]))');
INSERT INTO [${tableName}] ([xml]) VALUES ('${xml}');
SELECT [xml] FROM [${tableName}];\
END
ELSE
BEGIN
SELECT '<root/>'
END
`;
return [sql, xml, '7_2'] as [string, string, string];
})()
});
testDataType(TYPES.UDT, {
'should test udt': [
"select geography::STGeomFromText('LINESTRING(-122.360 47.656, -122.343 47.656 )', 4326) as geo",
Buffer.from([
230, 16, 0, 0, 1, 20, 135, 22, 217, 206, 247, 211, 71, 64, 215, 163, 112, 61, 10, 151, 94, 192, 135, 22, 217, 206, 247, 211, 71, 64, 203, 161, 69, 182, 243, 149, 94, 192
]),
'7_2'
],
'should test udt null': [
'select cast(null as geography)', null, '7_2'
]
});
}); | the_stack |
import { assertNever } from "./assert";
import { FunctionDecl, ParameterDecl } from "./declaration";
import { Err } from "./error";
import {
Argument,
ArrayLiteralExpr,
BinaryExpr,
BooleanLiteralExpr,
CallExpr,
ComputedPropertyNameExpr,
ConditionExpr,
ElementAccessExpr,
Expr,
FunctionExpr,
Identifier,
NewExpr,
NullLiteralExpr,
NumberLiteralExpr,
ObjectElementExpr,
ObjectLiteralExpr,
PropAccessExpr,
PropAssignExpr,
ReferenceExpr,
SpreadAssignExpr,
SpreadElementExpr,
StringLiteralExpr,
TemplateExpr,
TypeOfExpr,
UnaryExpr,
UndefinedLiteralExpr,
} from "./expression";
import {
isArgument,
isArrayLiteralExpr,
isBinaryExpr,
isBlockStmt,
isBooleanLiteralExpr,
isBreakStmt,
isCallExpr,
isCatchClause,
isComputedPropertyNameExpr,
isConditionExpr,
isContinueStmt,
isDoStmt,
isErr,
isExpr,
isExprStmt,
isForInStmt,
isForOfStmt,
isFunctionDecl,
isFunctionExpr,
isIdentifier,
isIfStmt,
isNativeFunctionDecl,
isNewExpr,
isNullLiteralExpr,
isNumberLiteralExpr,
isObjectElementExpr,
isObjectLiteralExpr,
isParameterDecl,
isPropAccessExpr,
isPropAssignExpr,
isReferenceExpr,
isReturnStmt,
isSpreadAssignExpr,
isSpreadElementExpr,
isStmt,
isStringLiteralExpr,
isTemplateExpr,
isThrowStmt,
isTryStmt,
isTypeOfExpr,
isUnaryExpr,
isUndefinedLiteralExpr,
isVariableStmt,
isWhileStmt,
} from "./guards";
import { FunctionlessNode } from "./node";
import {
BlockStmt,
BreakStmt,
CatchClause,
ContinueStmt,
DoStmt,
ExprStmt,
FinallyBlock,
ForInStmt,
ForOfStmt,
IfStmt,
ReturnStmt,
Stmt,
ThrowStmt,
TryStmt,
VariableStmt,
WhileStmt,
} from "./statement";
import { anyOf, ensure, ensureItemOf, flatten } from "./util";
/**
* Visits each child of a Node using the supplied visitor, possibly returning a new Node of the same kind in its place.
*
* @param node The Node whose children will be visited.
* @param visitor The callback used to visit each child.
* @param context A lexical environment context for the visitor.
*/
export function visitEachChild<T extends FunctionlessNode>(
node: T,
visitor: (
node: FunctionlessNode
) => FunctionlessNode | FunctionlessNode[] | undefined
): T {
if (isArgument(node)) {
if (!node.expr) {
return node.clone() as T;
}
const expr = visitor(node.expr);
ensure(expr, isExpr, "an Argument's expr must be an Expr");
return new Argument(expr, node.name) as T;
} else if (isArrayLiteralExpr(node)) {
return new ArrayLiteralExpr(
node.items.reduce((items: Expr[], item) => {
let result = visitor(item);
if (Array.isArray(result)) {
result = flatten(result);
ensureItemOf(
result,
isExpr,
"Items of an ArrayLiteralExpr must be Expr nodes"
);
return items.concat(result as Expr[]);
} else {
return [...items, result] as any;
}
}, [])
) as T;
} else if (isBinaryExpr(node)) {
const left = visitor(node.left);
const right = visitor(node.right);
if (isExpr(left) && isExpr(right)) {
return new BinaryExpr(left, node.op, right) as T;
} else {
throw new Error(
"visitEachChild of BinaryExpr must return an Expr for both the left and right operands"
);
}
} else if (isBlockStmt(node)) {
return new BlockStmt(
node.statements.reduce((stmts: Stmt[], stmt) => {
let result = visitor(stmt);
if (Array.isArray(result)) {
result = flatten(result);
ensureItemOf(
result,
isStmt,
"Statements in BlockStmt must be Stmt nodes"
);
return stmts.concat(result);
} else if (isStmt(result)) {
return [...stmts, result];
} else {
throw new Error(
"visitEachChild of a BlockStmt's child statements must return a Stmt"
);
}
}, [])
) as T;
} else if (isBooleanLiteralExpr(node)) {
return new BooleanLiteralExpr(node.value) as T;
} else if (isBreakStmt(node)) {
return new BreakStmt() as T;
} else if (isContinueStmt(node)) {
return new ContinueStmt() as T;
} else if (isCallExpr(node) || isNewExpr(node)) {
const expr = visitor(node.expr);
ensure(
expr,
isExpr,
`visitEachChild of a ${node.kind}'s expr must return a single Expr`
);
const args = node.args.flatMap((arg) => {
if (!arg.expr) {
return arg.clone();
}
const expr = visitor(arg.expr);
ensure(
expr,
isExpr,
`visitEachChild of a ${node.kind}'s argument must return a single Expr`
);
return new Argument(expr, arg.name);
});
return new (isCallExpr(node) ? CallExpr : NewExpr)(expr, args) as T;
} else if (isCatchClause(node)) {
const variableDecl = node.variableDecl
? visitor(node.variableDecl)
: undefined;
if (variableDecl !== undefined && variableDecl) {
ensure(
variableDecl,
isVariableStmt,
"visitEachChild of a CatchClause's VariableStmt must return another VariableStmt"
);
}
let block = visitor(node.block);
if (Array.isArray(block)) {
block = flatten(block);
ensureItemOf(block, isStmt, "Statements in BlockStmt must be Stmt nodes");
block = new BlockStmt(block);
} else {
ensure(
block,
isBlockStmt,
"visitEachChild of a CatchClause's BlockStmt must return another BlockStmt or an Array of Stmt"
);
}
return new CatchClause(variableDecl, block) as T;
} else if (isComputedPropertyNameExpr(node)) {
const expr = visitor(node.expr);
ensure(
expr,
isExpr,
"a ComputedPropertyNameExpr's expr property must be an Expr"
);
return new ComputedPropertyNameExpr(expr) as T;
} else if (isConditionExpr(node)) {
const when = visitor(node.when);
const then = visitor(node.then);
const _else = visitor(node._else);
ensure(when, isExpr, "ConditionExpr's when must be an Expr");
ensure(then, isExpr, "ConditionExpr's then must be an Expr");
ensure(_else, isExpr, "ConditionExpr's else must be an Expr");
return new ConditionExpr(when, then, _else) as T;
} else if (isDoStmt(node)) {
const block = visitor(node.block);
ensure(block, isBlockStmt, "a DoStmt's block must be a BlockStmt");
const condition = visitor(node.condition);
ensure(condition, isExpr, "a DoStmt's condition must be an Expr");
return new DoStmt(block, condition) as T;
} else if (isErr(node)) {
return new Err(node.error) as T;
} else if (node.kind == "ElementAccessExpr") {
const expr = visitor(node.expr);
const element = visitor(node.element);
ensure(expr, isExpr, "ElementAccessExpr's expr property must be an Expr");
ensure(
element,
isExpr,
"ElementAccessExpr's element property must be an Expr"
);
return new ElementAccessExpr(expr, element) as T;
} else if (isExprStmt(node)) {
const expr = visitor(node.expr);
ensure(expr, isExpr, "The Expr in an ExprStmt must be an Expr");
return new ExprStmt(expr) as T;
} else if (isForInStmt(node) || isForOfStmt(node)) {
const variableDecl = visitor(node.variableDecl);
ensure(
variableDecl,
isVariableStmt,
`VariableDecl in ${node.kind} must be a VariableDecl`
);
const expr = visitor(node.expr);
ensure(expr, isExpr, `Expr in ${node.kind} must be an Expr`);
let body = visitor(node.body);
if (Array.isArray(body)) {
body = flatten(body);
ensureItemOf(body, isStmt, "Statements in BlockStmt must be Stmt nodes");
body = new BlockStmt(body);
} else {
ensure(body, isBlockStmt, `Body in ${node.kind} must be a BlockStmt`);
}
return new (isForInStmt(node) ? ForInStmt : ForOfStmt)(
variableDecl,
expr,
body
) as T;
} else if (isFunctionDecl(node) || isFunctionExpr(node)) {
const parameters = node.parameters.reduce(
(params: ParameterDecl[], parameter) => {
let p = visitor(parameter);
if (Array.isArray(p)) {
p = flatten(p);
ensureItemOf(
p,
isParameterDecl,
`a ${node.kind}'s parameters must be ParameterDecl nodes`
);
return params.concat(p);
} else {
ensure(
p,
isParameterDecl,
`a ${node.kind}'s parameters must be ParameterDecl nodes`
);
return [...params, p];
}
},
[]
);
const body = visitor(node.body);
ensure(body, isBlockStmt, `a ${node.kind}'s body must be a BlockStmt`);
return new (isFunctionDecl(node) ? FunctionDecl : FunctionExpr)(
parameters,
body
) as T;
} else if (isIdentifier(node)) {
return new Identifier(node.name) as T;
} else if (isIfStmt(node)) {
const when = visitor(node.when);
const then = visitor(node.then);
const _else = node._else ? visitor(node._else) : undefined;
ensure(when, isExpr, "a IfStmt's when must be an Expr");
ensure(then, isBlockStmt, "a IfStmt's then must be a BlockStmt");
if (_else) {
ensure(
_else,
anyOf(isIfStmt, isBlockStmt),
"a IfStmt's else must be an IfStmt or BlockStmt"
);
}
return new IfStmt(when, then, _else) as T;
} else if (isNullLiteralExpr(node)) {
return new NullLiteralExpr() as T;
} else if (isNumberLiteralExpr(node)) {
return new NumberLiteralExpr(node.value) as T;
} else if (isObjectLiteralExpr(node)) {
return new ObjectLiteralExpr(
node.properties.reduce((props: ObjectElementExpr[], prop) => {
let p = visitor(prop);
if (Array.isArray(p)) {
p = flatten(p);
ensureItemOf(
p,
isObjectElementExpr,
"an ObjectLiteralExpr's properties must be ObjectElementExpr nodes"
);
return props.concat(p);
} else {
ensure(
p,
isObjectElementExpr,
"an ObjectLiteralExpr's properties must be ObjectElementExpr nodes"
);
return [...props, p];
}
}, [])
) as T;
} else if (isParameterDecl(node)) {
return new ParameterDecl(node.name) as T;
} else if (isPropAccessExpr(node)) {
const expr = visitor(node.expr);
ensure(
expr,
isExpr,
"a PropAccessExpr's expr property must be an Expr node type"
);
return new PropAccessExpr(expr, node.name) as T;
} else if (isPropAssignExpr(node)) {
const name = visitor(node.name);
const expr = visitor(node.expr);
ensure(
name,
anyOf(isIdentifier, isStringLiteralExpr, isComputedPropertyNameExpr),
"a PropAssignExpr's name property must be an Identifier, StringLiteralExpr or ComputedNameProperty node type"
);
ensure(
expr,
isExpr,
"a PropAssignExpr's expr property must be an Expr node type"
);
return new PropAssignExpr(name, expr) as T;
} else if (isReferenceExpr(node)) {
return new ReferenceExpr(node.name, node.ref) as T;
} else if (isReturnStmt(node)) {
const expr = visitor(node.expr);
ensure(expr, isExpr, "a ReturnStmt's expr must be an Expr node type");
return new ReturnStmt(expr) as T;
} else if (isSpreadAssignExpr(node)) {
const expr = visitor(node.expr);
ensure(expr, isExpr, "a SpreadAssignExpr's expr must be an Expr node type");
return new SpreadAssignExpr(expr) as T;
} else if (isSpreadElementExpr(node)) {
const expr = visitor(node.expr);
ensure(
expr,
isExpr,
"a SpreadElementExpr's expr must be an Expr node type"
);
return new SpreadElementExpr(expr) as T;
} else if (isStringLiteralExpr(node)) {
return new StringLiteralExpr(node.value) as T;
} else if (isTemplateExpr(node)) {
return new TemplateExpr(
node.exprs.reduce((exprs: Expr[], expr) => {
let e = visitor(expr);
if (e === undefined) {
return exprs;
} else if (Array.isArray(e)) {
e = flatten(e);
ensureItemOf(
e,
isExpr,
"a TemplateExpr's expr property must only contain Expr node types"
);
return exprs.concat(e);
} else {
ensure(
e,
isExpr,
"a TemplateExpr's expr property must only contain Expr node types"
);
return [...exprs, e];
}
}, [])
) as T;
} else if (isThrowStmt(node)) {
const expr = visitor(node.expr);
ensure(expr, isExpr, "a ThrowStmt's expr must be an Expr node type");
return new ThrowStmt(expr) as T;
} else if (isTryStmt(node)) {
const tryBlock = visitor(node.tryBlock);
ensure(tryBlock, isBlockStmt, "a TryStmt's tryBlock must be a BlockStmt");
const catchClause = visitor(node.catchClause);
ensure(
catchClause,
isCatchClause,
"a TryStmt's catchClause must be a CatchClause"
);
const finallyBlock = node.finallyBlock
? visitor(node.finallyBlock)
: undefined;
if (finallyBlock) {
ensure(
finallyBlock,
isBlockStmt,
"a TryStmt's finallyBlock must be a BlockStmt"
);
}
return new TryStmt(
tryBlock,
catchClause,
finallyBlock as FinallyBlock
) as T;
} else if (isTypeOfExpr(node)) {
const expr = visitor(node.expr);
ensure(expr, isExpr, "a TypeOfExpr's expr property must be an Expr");
return new TypeOfExpr(expr) as T;
} else if (isUnaryExpr(node)) {
const expr = visitor(node.expr);
ensure(expr, isExpr, "a UnaryExpr's expr property must be an Expr");
return new UnaryExpr(node.op, expr) as T;
} else if (isUndefinedLiteralExpr(node)) {
return new UndefinedLiteralExpr() as T;
} else if (isVariableStmt(node)) {
const expr = node.expr ? visitor(node.expr) : undefined;
if (expr) {
ensure(expr, isExpr, "a VariableStmt's expr property must be an Expr");
}
return new VariableStmt(node.name, expr) as T;
} else if (isWhileStmt(node)) {
const condition = visitor(node.condition);
ensure(condition, isExpr, "a WhileStmt's condition must be an Expr");
const block = visitor(node.block);
ensure(block, isBlockStmt, "a WhileStmt's block must be a BlockStmt");
return new WhileStmt(condition, block) as T;
} else if (isNativeFunctionDecl(node)) {
throw Error(`${node.kind} are not supported.`);
}
return assertNever(node);
} | the_stack |
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./sw.js')
.then(function() {
console.log('service worker is all cool.');
})
.catch(function(e) {
console.error('service worker is not so cool.', e);
throw e;
});
if (navigator.serviceWorker.controller) {
// Correctly prompt the user to reload during SW phase change.
navigator.serviceWorker.controller.onstatechange = e => {
if ((e.target as any).state === 'redundant') {
(document.querySelector(
'#reload-prompt'
)! as HTMLElement).classList.remove('hidden');
}
};
}
}
// thx https://github.com/Modernizr/Modernizr/blob/master/feature-detects/pointerevents.js
const USE_POINTER_EVENTS = 'onpointerdown' in document.createElement('div');
let velocity = 0;
const ac = new (typeof webkitAudioContext !== 'undefined'
? webkitAudioContext
: AudioContext)();
const masterVolume = ac.createGain();
masterVolume.connect(ac.destination);
const appState = {
pickerOpen: false,
spinner:
window.localStorage.getItem('fidget_spinner') ||
'./assets/spinners/base.png',
muted: window.localStorage.getItem('fidget_muted') === 'true' ? true : false,
spins: window.localStorage.getItem('fidget_spins')
? parseInt(window.localStorage.getItem('fidget_spins')!, 10)
: 0,
maxVelocity: window.localStorage.getItem('fidget_max_velocity')
? parseInt(window.localStorage.getItem('fidget_max_velocity')!, 10)
: 0
};
const spinners = [
{
path: './assets/spinners/base.png',
name: 'The Classic',
unlockedAt: 0
},
{
path: './assets/spinners/triple.png',
name: 'The Triple',
unlockedAt: 500
},
{
path: './assets/spinners/pokeball.png',
name: "The 'Chu",
unlockedAt: 2000
},
{
path: './assets/spinners/cube.png',
name: 'The Cubist',
unlockedAt: 5000
},
{
path: './assets/spinners/fractal.png',
name: 'The Fractal',
unlockedAt: 10000
}
];
const domElements = {
turns: document.getElementById('turns')!,
velocity: document.getElementById('velocity')!,
maxVelocity: document.getElementById('maxVelocity')!,
spinner: document.getElementById('spinner')!,
traceSlow: document.getElementById('trace-slow')!,
traceFast: document.getElementById('trace-fast')!,
toggleAudio: document.getElementById('toggle-audio')!,
spinners: Array.from(
document.getElementsByClassName('spinner')!
) as HTMLImageElement[],
pickerToggle: document.getElementById('picker')!,
pickerPane: document.getElementById('spinner-picker')!
};
let fidgetAlpha = 0;
let fidgetSpeed = 0;
function deferWork(fn: () => void) {
if ((typeof requestIdleCallback as any) !== 'undefined') {
requestIdleCallback(fn, { timeout: 60 });
} else if (typeof requestAnimationFrame !== 'undefined') {
requestAnimationFrame(fn);
} else {
setTimeout(fn, 16.66);
}
}
function stats() {
velocity =
Math.abs(fidgetSpeed * 60 /* fps */ * 60 /* sec */ / 2 / Math.PI) | 0;
const newMaxVelocity = Math.max(velocity, appState.maxVelocity);
if (appState.maxVelocity !== newMaxVelocity) {
deferWork(() =>
window.localStorage.setItem(
'fidget_max_velocity',
`${appState.maxVelocity}`
)
);
appState.maxVelocity = newMaxVelocity;
}
appState.spins += Math.abs(fidgetSpeed / 2 / Math.PI);
deferWork(() =>
window.localStorage.setItem('fidget_spins', `${appState.spins}`)
);
const turnsText = appState.spins.toLocaleString(undefined, {
maximumFractionDigits: 0
});
const maxVelText = appState.maxVelocity.toLocaleString(undefined, {
maximumFractionDigits: 1
});
domElements.turns.textContent = `${turnsText}`;
domElements.velocity.textContent = `${velocity}`;
domElements.maxVelocity.textContent = `${maxVelText}`;
}
const spinnerPos = domElements.spinner.getBoundingClientRect();
const centerX = spinnerPos.left + spinnerPos.width / 2;
const centerY = spinnerPos.top + spinnerPos.height / 2;
const centerRadius = spinnerPos.width / 10;
//
// Spin code
//
const touchInfo: {
alpha: number;
radius: number;
down: boolean;
} = { alpha: 0, radius: 0, down: false };
let touchSpeed = 0;
let lastTouchAlpha = 0;
function getXYFromTouchOrPointer(e: TouchEvent | PointerEvent) {
let x = 'touches' in e
? (e as TouchEvent).touches[0].clientX
: (e as PointerEvent).clientX;
let y = 'touches' in e
? (e as TouchEvent).touches[0].clientY
: (e as PointerEvent).clientY;
return { x: x - centerX, y: y - centerY };
}
function onTouchStart(e: TouchEvent | PointerEvent) {
if (appState.pickerOpen) {
return;
}
let { x, y } = getXYFromTouchOrPointer(e);
onTouchMove(e);
touchInfo.down = true;
touchInfo.radius = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
lastTouchAlpha = touchInfo.alpha;
}
function onTouchMove(e: TouchEvent | PointerEvent) {
if (appState.pickerOpen) {
return;
}
let { x, y } = getXYFromTouchOrPointer(e);
touchInfo.alpha = Math.atan2(x, y);
e.preventDefault();
}
function touchEnd() {
if (appState.pickerOpen) {
return;
}
touchInfo.down = false;
}
function tick() {
requestAnimationFrame(() => {
if (touchInfo.down) {
if (touchInfo.radius > centerRadius) {
touchSpeed = touchInfo.alpha - lastTouchAlpha;
if (touchSpeed < -Math.PI) touchSpeed += 2 * Math.PI;
if (touchSpeed > Math.PI) touchSpeed -= 2 * Math.PI;
fidgetSpeed = touchSpeed;
lastTouchAlpha = touchInfo.alpha;
}
} else if (touchSpeed) {
fidgetSpeed = touchSpeed * touchInfo.radius / centerRadius;
touchSpeed = 0;
}
fidgetAlpha -= fidgetSpeed;
domElements.spinner.style.transform = `rotate(${fidgetAlpha}rad)`;
domElements.traceSlow.style.opacity = Math.abs(fidgetSpeed) > 0.2
? '1'
: '0.00001';
domElements.traceFast.style.opacity = Math.abs(fidgetSpeed) > 0.4
? '1'
: '0.00001';
stats();
// Slow down over time
fidgetSpeed = fidgetSpeed * 0.99;
fidgetSpeed =
Math.sign(fidgetSpeed) * Math.max(0, Math.abs(fidgetSpeed) - 2e-4);
const soundMagnitude = Math.abs(velocity * Math.PI / 60);
if (soundMagnitude && !touchInfo.down) {
spinSound(soundMagnitude);
spinSound2(soundMagnitude);
}
tick();
});
}
//
// Audio code
//
let endPlayTime = -1;
let endPlayTime2 = -1;
interface rangeArgs {
inputMin: number;
inputMax: number;
outputFloor: number;
outputCeil: number;
}
function generateRange(args: rangeArgs) {
return function(x: number): number {
const outputRange = args.outputCeil - args.outputFloor;
const inputPct = (x - args.inputMin) / (args.inputMax - args.inputMin);
return args.outputFloor + inputPct * outputRange;
};
}
const freqRange400_2000 = generateRange({
inputMin: 0,
inputMax: 80,
outputFloor: 400,
outputCeil: 2000
});
const freqRange300_1500 = generateRange({
inputMin: 0,
inputMax: 80,
outputFloor: 300,
outputCeil: 1500
});
const easeOutQuad = (t: number) => t * (2 - t);
// assume magnitude is between 0 and 1, though it can be a tad higher
function spinSound(magnitude: number) {
// automation start time
let time = ac.currentTime;
const freqMagnitude = magnitude;
magnitude = Math.min(1, magnitude / 10);
let x = easeOutQuad(magnitude) * 1.1 - (0.6 - 0.6 * easeOutQuad(magnitude));
if (time + x - easeOutQuad(magnitude) < endPlayTime) {
return;
}
const osc = ac.createOscillator();
const gain = ac.createGain();
// enforce range
magnitude = Math.min(1, Math.max(0, magnitude));
osc.type = 'triangle';
osc.connect(gain);
gain.connect(masterVolume);
// max of 40 boops
//const count = 6 + ( 1 * magnitude );
// decay constant for frequency between each boop
//const decay = 0.97;
// starting frequency (min of 400, max of 900)
let freq = freqRange400_2000(freqMagnitude);
// boop duration (longer for lower magnitude)
let dur = 0.1 * (1 - magnitude / 2);
osc.frequency.setValueAtTime(freq, time);
osc.frequency.linearRampToValueAtTime(freq * 1.8, (time += dur));
endPlayTime = time + dur;
// fade out the last boop
gain.gain.setValueAtTime(0.1, ac.currentTime);
gain.gain.linearRampToValueAtTime(0, endPlayTime);
// play it
osc.start(ac.currentTime);
osc.stop(endPlayTime);
}
function spinSound2(magnitude: number) {
// automation start time
let time = ac.currentTime;
const freqMagnitude = magnitude;
magnitude = Math.min(1, magnitude / 10);
let x = easeOutQuad(magnitude) * 1.1 - (0.3 - 0.3 * easeOutQuad(magnitude));
if (time + x - easeOutQuad(magnitude) < endPlayTime2) {
return;
}
const osc = ac.createOscillator();
const gain = ac.createGain();
// enforce range
magnitude = Math.min(1, Math.max(0, magnitude));
osc.type = 'sine';
osc.connect(gain);
gain.connect(masterVolume);
var freq = freqRange300_1500(freqMagnitude);
// boop duration (longer for lower magnitude)
var dur = 0.05 * (1 - magnitude / 2);
osc.frequency.setValueAtTime(freq, time);
osc.frequency.linearRampToValueAtTime(freq * 1.8, (time += dur));
endPlayTime2 = time + dur;
// fade out the last boop
gain.gain.setValueAtTime(0.15, ac.currentTime);
gain.gain.linearRampToValueAtTime(0, endPlayTime2);
// play it
osc.start(ac.currentTime);
osc.stop(endPlayTime2);
}
// Audio on IOS is very hard.
// http://www.holovaty.com/writing/ios9-web-audio/
// https://github.com/goldfire/howler.js/blob/8612912af28d6fb9f442c4f5a02827155bcf3464/src/howler.core.js#L278
function unlockAudio() {
function unlock() {
// Create an empty buffer.
const source = ac.createBufferSource();
source.buffer = ac.createBuffer(1, 1, 22050);
source.connect(ac.destination);
// Play the empty buffer.
if (typeof source.start === 'undefined') {
(source as any).noteOn(0);
} else {
source.start(0);
}
// Setup a timeout to check that we are unlocked on the next event loop.
source.onended = function() {
source.disconnect(0);
// Remove the touch start listener.
document.removeEventListener('touchend', unlock, true);
};
}
document.addEventListener('touchend', unlock, true);
}
function setMutedSideEffects(muted: boolean) {
domElements.toggleAudio.classList.toggle('muted', muted);
masterVolume.gain.setValueAtTime(appState.muted ? 0 : 1, ac.currentTime);
window.localStorage.setItem('fidget_muted', `${appState.muted}`);
}
function togglePicker() {
if (appState.pickerOpen !== true) {
appState.pickerOpen = !appState.pickerOpen;
history.pushState(appState, '', '#picker');
showPicker();
} else {
history.back();
}
}
function toggleAudio(e: Event) {
appState.muted = !appState.muted;
setMutedSideEffects(appState.muted);
// if something is spinning, we do not want to stop it if you touch the menu.
e.stopPropagation();
}
function changeSpinner(src: string) {
appState.spinner = src;
deferWork(() => window.localStorage.setItem('fidget_spinner', src));
for (let s of domElements.spinners) {
s.src = src;
}
}
function pickSpinner(e: Event) {
const target = e.target as HTMLElement;
if (target.tagName === 'IMG' && !target.classList.contains('locked')) {
changeSpinner((e.target as HTMLImageElement).src);
togglePicker();
}
}
function showPicker() {
domElements.pickerPane.innerHTML = '';
let toAppend = '';
for (let spinner of spinners) {
toAppend += `<li><p class="title">${spinner.name}</p>`;
if (spinner.unlockedAt >= appState.spins) {
toAppend += `<img width="300" height="300" class="locked" src="${spinner.path}"><p class="locked-info">Unlocks at ${spinner.unlockedAt} spins</p>`;
} else {
toAppend += `<img width="300" height="300" src="${spinner.path}">`;
}
toAppend += '</li>';
}
domElements.pickerPane.innerHTML = toAppend;
domElements.pickerPane.classList.remove('hidden');
domElements.pickerPane.scrollTop = 0;
}
(async () => {
setMutedSideEffects(appState.muted);
unlockAudio();
tick();
const listenFor = document.addEventListener as WhatWGAddEventListener;
domElements.pickerToggle.addEventListener(
USE_POINTER_EVENTS ? 'pointerdown' : 'touchstart',
togglePicker
);
domElements.pickerPane.addEventListener('click', pickSpinner);
domElements.toggleAudio.addEventListener(
USE_POINTER_EVENTS ? 'pointerdown' : 'touchstart',
toggleAudio
);
listenFor(USE_POINTER_EVENTS ? 'pointerdown' : 'touchstart', onTouchStart, {
passive: false
});
listenFor(USE_POINTER_EVENTS ? 'pointermove' : 'touchmove', onTouchMove, {
passive: false
});
listenFor(USE_POINTER_EVENTS ? 'pointerup' : 'touchend', touchEnd);
listenFor(USE_POINTER_EVENTS ? 'pointercancel' : 'touchcancel', touchEnd);
// Assume clean entry always.
history.replaceState(null, '', '/');
changeSpinner(appState.spinner);
window.onpopstate = (e: PopStateEvent) => {
// Assume if state is not set here picker is going to need to close.
if (e.state === null) {
appState.pickerOpen = false;
domElements.pickerPane.classList.add('hidden');
// Assume if state is set here picker is going to need to open.
} else if (e.state !== null) {
appState.pickerOpen = true;
showPicker();
}
};
})(); | the_stack |
import { rightOrThrow } from '@nexus/logger/dist/utils'
import Chalk from 'chalk'
import { stripIndent } from 'common-tags'
import { Either, isLeft, left, right } from 'fp-ts/lib/Either'
import * as FS from 'fs-jetpack'
import * as OS from 'os'
import * as Path from 'path'
import * as tsm from 'ts-morph'
import type { ParsedCommandLine } from 'typescript'
import { findFile, isEmptyDir } from '../../lib/fs'
import { rootLogger } from '../nexus-logger'
import * as PJ from '../package-json'
import * as PackageManager from '../package-manager'
import { exception, exceptionType } from '../utils'
import { BuildLayout, getBuildLayout } from './build'
import { saveDataForChildProcess } from './cache'
import { readOrScaffoldTsconfig } from './tsconfig'
const log = rootLogger.child('layout')
// todo allow user to configure these for their project
const CONVENTIONAL_ENTRYPOINT_MODULE_NAME = 'app'
const CONVENTIONAL_ENTRYPOINT_FILE_NAME = `${CONVENTIONAL_ENTRYPOINT_MODULE_NAME}.ts`
/**
* The part of layout data resulting from the dynamic file/folder inspection.
*/
export type ScanResult = {
app:
| {
exists: true
path: string
}
| {
exists: false
path: null
}
project: {
name: string
isAnonymous: boolean
}
sourceRoot: string
projectRoot: string
nexusModules: string[]
tsConfig: {
content: ParsedCommandLine
path: string
}
packageManagerType: PackageManager.PackageManager['type']
}
/**
* The combination of manual datums the user can specify about the layout plus
* the dynamic scan results.
*/
export type Data = ScanResult & {
build: BuildLayout
packageJson: null | {
dir: string
path: string
content: PJ.ValidPackageJson
}
}
/**
* Layout represents the important edges of the project to support things like
* scaffolding, build, and dev against the correct paths.
*/
export type Layout = Data & {
/**
* Property that aliases all the and only the data properties, makes it
* easy to e.g. serialize just the data.
*/
data: Data
projectRelative(filePath: string): string
projectPath(...subPaths: string[]): string
/**
* Like projectPath but treats absolute paths as passthrough.
*/
projectPathOrAbsolute(...subPaths: string[]): string
sourceRelative(filePath: string): string
sourcePath(...subPaths: string[]): string
update(options: UpdateableLayoutData): void
packageManager: PackageManager.PackageManager
}
interface UpdateableLayoutData {
nexusModules?: string[]
}
interface Options {
/**
* The place to output the build, relative to project root.
*/
buildOutputDir?: string
/**
* Path to the nexus entrypoint. Can be absolute or relative.
*/
entrypointPath?: string
/**
* Force the project root directory. Defaults to being detected automatically.
*/
projectRoot?: string
/**
* Whether the build should be outputted as a bundle
*/
asBundle?: boolean
/**
* Force the current working directory.
*
* @default
*
* process.cwd()
*
* @remarks
*
* Interplay between this and projectRoot option: When the projectRoot is not forced then the cwd is utilized for various logic.
*/
cwd?: string
}
/**
* Perform a layout scan and return results with attached helper functions.
*/
export async function create(options?: Options): Promise<Either<Error, Layout>> {
const cwd = options?.cwd ?? process.cwd()
/**
* Find the project root directory. This can be different than the source root
* directory. For example the classic project structure where there is a root
* `src` folder. `src` folder would be considered the "source root".
*
* Project root is considered to be the first package.json found from cwd upward
* to disk root. If not package.json is found then cwd is taken to be the
* project root.
*
*/
let projectRoot = options?.projectRoot
let packageJson: null | Data['packageJson'] = null
if (!projectRoot) {
const maybeErrPackageJson = PJ.findRecurisvelyUpwardSync({ cwd })
if (!maybeErrPackageJson) {
projectRoot = cwd
} else if (isLeft(maybeErrPackageJson.content)) {
return maybeErrPackageJson.content
} else {
projectRoot = maybeErrPackageJson.dir
packageJson = {
...maybeErrPackageJson,
content: maybeErrPackageJson.content.right,
}
}
}
const errNormalizedEntrypoint = normalizeEntrypoint(options?.entrypointPath, projectRoot)
if (isLeft(errNormalizedEntrypoint)) return errNormalizedEntrypoint
const normalizedEntrypoint = errNormalizedEntrypoint.right
const packageManagerType = await PackageManager.detectProjectPackageManager({ projectRoot })
const maybeAppModule = normalizedEntrypoint ?? findAppModule({ projectRoot })
const errTsConfig = await readOrScaffoldTsconfig({ projectRoot })
if (isLeft(errTsConfig)) return errTsConfig
const tsConfig = errTsConfig.right
const nexusModules = findNexusModules(tsConfig, maybeAppModule)
const project = packageJson
? {
name: packageJson.content.name,
isAnonymous: false,
}
: {
name: 'anonymous',
isAnonymous: true,
}
const scanResult = {
app:
maybeAppModule === null
? ({ exists: false, path: maybeAppModule } as const)
: ({ exists: true, path: maybeAppModule } as const),
projectRoot,
sourceRoot: Path.normalize(tsConfig.content.options.rootDir!),
nexusModules,
project,
tsConfig,
packageManagerType,
}
if (scanResult.app.exists === false && scanResult.nexusModules.length === 0) {
return left(noAppOrNexusModules({}))
}
const buildInfo = getBuildLayout(options?.buildOutputDir, scanResult, options?.asBundle)
log.trace('layout build info', { data: buildInfo })
const layout = createFromData({
...scanResult,
packageJson,
build: buildInfo,
})
/**
* Save the created layout in the env
*/
process.env = {
...process.env,
...saveDataForChildProcess(layout),
}
return right(layout)
}
/**
* Create a layout instance with given layout data. Useful for taking in serialized scan
* data from another process that would be wasteful to re-calculate.
*/
export function createFromData(layoutData: Data): Layout {
let layout: Layout = {
...layoutData,
data: layoutData,
projectRelative: Path.relative.bind(null, layoutData.projectRoot),
sourceRelative: Path.relative.bind(null, layoutData.sourceRoot),
sourcePath(...subPaths: string[]): string {
return Path.join(layoutData.sourceRoot, ...subPaths)
},
projectPath(...subPaths: string[]): string {
const joinedPath = Path.join(...subPaths)
return Path.join(layoutData.projectRoot, joinedPath)
},
projectPathOrAbsolute(...subPaths: string[]): string {
const joinedPath = Path.join(...subPaths)
if (Path.isAbsolute(joinedPath)) return joinedPath
return Path.join(layoutData.projectRoot, joinedPath)
},
packageManager: PackageManager.createPackageManager(layoutData.packageManagerType, {
projectRoot: layoutData.projectRoot,
}),
update(options) {
if (options.nexusModules) {
layout.nexusModules = options.nexusModules
layout.data.nexusModules = options.nexusModules
}
},
}
return layout
}
const checks = {
no_app_or_nexus_modules: {
code: 'no_app_or_schema_modules',
// prettier-ignore
explanations: {
problem: `We could not find any modules that imports 'nexus' or ${CONVENTIONAL_ENTRYPOINT_FILE_NAME} entrypoint`,
solution: stripIndent`
Please do one of the following:
1. Create a file, import { schema } from 'nexus' and write your GraphQL type definitions in it.
2. Create an ${Chalk.yellow(CONVENTIONAL_ENTRYPOINT_FILE_NAME)} file.
`,
}
},
}
const noAppOrNexusModules = exceptionType<'no_app_or_schema_modules', {}>(
'no_app_or_schema_modules',
checks.no_app_or_nexus_modules.explanations.problem +
OS.EOL +
checks.no_app_or_nexus_modules.explanations.solution
)
/**
* Find the (optional) app module in the user's project.
*/
export function findAppModule(opts: { projectRoot: string }): string | null {
log.trace('looking for app module')
const path = findFile(`./**/${CONVENTIONAL_ENTRYPOINT_FILE_NAME}`, { cwd: opts.projectRoot })
log.trace('done looking for app module', { path })
return path
}
/**
* Detect whether or not CWD is inside a nexus project. nexus project is
* defined as there being a package.json in or above CWD with nexus as a
* direct dependency.
*/
export async function scanProjectType(opts: {
cwd: string
}): Promise<
| { type: 'unknown' | 'new' }
| { type: 'malformed_package_json'; error: PJ.MalformedPackageJsonError }
| {
type: 'NEXUS_project' | 'node_project'
packageJson: {}
packageJsonLocation: { path: string; dir: string }
}
> {
const packageJson = PJ.findRecurisvelyUpwardSync(opts)
if (packageJson === null) {
if (await isEmptyDir(opts.cwd)) {
return { type: 'new' }
}
return { type: 'unknown' }
}
if (isLeft(packageJson.content)) {
return {
type: 'malformed_package_json',
error: packageJson.content.left,
}
}
const pjc = rightOrThrow(packageJson.content) // will never throw, check above
if (pjc.dependencies?.['nexus']) {
return {
type: 'NEXUS_project',
packageJson: packageJson,
packageJsonLocation: packageJson,
}
}
return {
type: 'node_project',
packageJson: packageJson,
packageJsonLocation: packageJson,
}
}
/**
* Validate the given entrypoint and normalize it into an absolute path.
*/
function normalizeEntrypoint(
entrypoint: string | undefined,
projectRoot: string
): Either<Error, string | undefined> {
if (!entrypoint) {
return right(undefined)
}
const absoluteEntrypoint = Path.isAbsolute(entrypoint) ? entrypoint : Path.join(projectRoot, entrypoint)
if (!absoluteEntrypoint.endsWith('.ts')) {
const error = exception('Entrypoint must be a .ts file', { path: absoluteEntrypoint })
return left(error)
}
if (!FS.exists(absoluteEntrypoint)) {
const error = exception('Entrypoint does not exist', { path: absoluteEntrypoint })
return left(error)
}
return right(absoluteEntrypoint)
}
/**
* Find the modules in the project that import nexus
*/
export function findNexusModules(tsConfig: Data['tsConfig'], maybeAppModule: string | null): string[] {
try {
log.trace('finding nexus modules')
const project = new tsm.Project({
addFilesFromTsConfig: false, // Prevent ts-morph from re-parsing the tsconfig
})
tsConfig.content.fileNames.forEach((f) => project.addSourceFileAtPath(f))
const modules = project
.getSourceFiles()
.filter((s) => {
// Do not add app module to nexus modules
// todo normalize because ts in windows is like "C:/.../.../" instead of "C:\...\..." ... why???
if (Path.normalize(s.getFilePath().toString()) === maybeAppModule) {
return false
}
return s.getImportDeclaration('nexus') !== undefined
})
.map((s) => {
// todo normalize because ts in windows is like "C:/.../.../" instead of "C:\...\..." ... why???
return Path.normalize(s.getFilePath().toString())
})
log.trace('done finding nexus modules', { modules })
return modules
} catch (error) {
// todo return left
log.error('We could not find your nexus modules', { error })
return []
}
} | the_stack |
import { ELineTypes, EToolName } from '@/constant/tool';
import { createSmoothCurvePointsFromPointList } from './polygonTool';
import PolygonUtils from './PolygonUtils';
import MathUtils from '../MathUtils';
export enum EStatus {
/** 正在创建 */
Create = 0,
/** 正在激活 */
Active = 1,
/** 正在编辑, 撤销与激活状态合并 */
Edit = 1,
/** 没有操作 */
None = 2,
}
export enum EColor {
ActiveArea = '#B3B8FF',
}
export interface IProps {
canvas: HTMLCanvasElement;
size: ISize;
historyChanged?: (undoEnabled: boolean, redoEnabled: boolean) => void;
}
/** 曲线分割点数 */
export const SEGMENT_NUMBER = 16;
export const LINE_ORDER_OFFSET = {
x: 0,
y: 20,
};
export interface IBasicLine {
pointA: IPoint;
pointB: IPoint;
}
/** 点半径 */
export const POINT_RADIUS = 3;
export const POINT_ACTIVE_RADIUS = 5;
/** 普通点内侧圆的半径 */
export const INNER_POINT_RADIUS = 2;
class LineToolUtils {
/** 为参考显示的线条设置样式 */
public static setSpecialEdgeStyle = (ctx: CanvasRenderingContext2D) => {
ctx.lineCap = 'butt';
ctx.setLineDash([10, 10]);
};
/** 设置特殊边样式 */
public static setReferenceCtx = (ctx: CanvasRenderingContext2D) => {
ctx.lineCap = 'butt';
ctx.setLineDash([6]);
};
/**
* 计算一条线跟多条线的交点,并找到最近距离最近的点
* @param pointList 点列表
* @param matchLine 需要计算交点的线条
* @param matchPoint 计算交点线条的起始点
* @param pointRadius 点的半径
*/
public static calcOptimalIntersection = (
pointList: IPoint[] | ILinePoint[],
matchLine: IBasicLine,
matchPoint: ICoordinate,
pointRadius: number,
zoom: number,
) => {
let optimalIntersection: IPoint | undefined;
let minDistance: number = Infinity;
let scopeIntersection: { point: IPoint; minDistance: number } | undefined;
const matchLineOnExistLine = pointList.find((p, index) => {
if (index === 0) {
return;
}
const pointAOnLine = LineToolUtils.isInLine(matchLine.pointA, p, pointList[index - 1]);
const pointBOnLine = LineToolUtils.isInLine(matchLine.pointB, p, pointList[index - 1]);
return pointAOnLine && pointBOnLine;
});
if (matchLineOnExistLine) {
return { point: matchPoint };
}
pointList.forEach((point, index) => {
if (index === 0) {
return;
}
const line2 = {
pointA: pointList[index - 1],
pointB: point,
};
const intersection = LineToolUtils.lineIntersection(matchLine, line2);
if (intersection && matchLine) {
const { onLine2, onLine1, x, y } = intersection;
const distance = LineToolUtils.calcDistance(matchPoint, intersection);
const matchPointInLine = LineToolUtils.isOnLine(
matchLine.pointB.x,
matchLine.pointB.y,
point.x,
point.y,
pointList[index - 1].x,
pointList[index - 1].y,
);
/** 点在线上 */
if (matchPointInLine) {
const intersectionDistance = LineToolUtils.calcDistance(matchPoint, intersection);
/** 交点和直线的起始点为一致 */
if (intersectionDistance < pointRadius / zoom) {
const cPoint = matchLine.pointB;
const { footPoint, length } = MathUtils.getFootOfPerpendicular(cPoint, line2.pointA, line2.pointB, true);
if (length !== undefined) {
const distPointA = LineToolUtils.calcDistance(line2.pointA, footPoint);
const distPointB = LineToolUtils.calcDistance(line2.pointB, footPoint);
scopeIntersection = {
point: footPoint,
minDistance: length,
};
if (length === Infinity) {
scopeIntersection.point = distPointA > distPointB ? line2.pointB : line2.pointA;
}
}
}
return;
}
if (distance < minDistance && onLine2 && onLine1) {
minDistance = distance;
optimalIntersection = {
x,
y,
};
}
}
});
if (optimalIntersection) {
return { point: optimalIntersection, minDistance };
}
if (scopeIntersection) {
return scopeIntersection;
}
return undefined;
};
public static lineIntersection = (lineA: IBasicLine, lineB: IBasicLine) => {
let onLine1: boolean = false;
let onLine2: boolean = false;
const lineADiff = LineToolUtils.getAxisDiff(lineA);
const lineBDiff = LineToolUtils.getAxisDiff(lineB);
const denominator = lineBDiff.y * lineADiff.x - lineBDiff.x * lineADiff.y;
if (denominator === 0) {
return false;
}
let a = lineA.pointA.y - lineB.pointA.y;
let b = lineA.pointA.x - lineB.pointA.x;
const numerator1 = (lineB.pointB.x - lineB.pointA.x) * a - (lineB.pointB.y - lineB.pointA.y) * b;
const numerator2 = (lineA.pointB.x - lineA.pointA.x) * a - (lineA.pointB.y - lineA.pointA.y) * b;
a = numerator1 / denominator;
b = numerator2 / denominator;
if (a > 0 && a < 1) {
onLine1 = true;
}
if (b > 0 && b < 1) {
onLine2 = true;
}
// 计算交点坐标
const x = lineA.pointA.x + a * (lineA.pointB.x - lineA.pointA.x);
const y = lineA.pointA.y + a * (lineA.pointB.y - lineA.pointA.y);
return { x, y, onLine1, onLine2 };
};
public static getAxisDiff = (line: IBasicLine) => {
return {
x: line.pointB.x - line.pointA.x,
y: line.pointB.y - line.pointA.y,
};
};
public static calcDistance = (point1: IPoint, point2: IPoint) => {
return Math.sqrt(Math.pow(Math.abs(point1.x - point2.x), 2) + Math.pow(Math.abs(point1.y - point2.y), 2));
};
public static drawCurveLine = (
ctx: any,
points: ILinePoint[],
config: any,
applyLineWidth: boolean = true,
isReference: boolean = false,
hoverEdgeIndex: number,
) => {
const pointList = createSmoothCurvePointsFromPointList(points, SEGMENT_NUMBER);
ctx.save();
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.strokeStyle = config.color;
if (applyLineWidth) {
ctx.lineWidth = config.lineWidth;
}
if (isReference) {
LineToolUtils.setReferenceCtx(ctx);
}
points.forEach((point: ILinePoint, index: number) => {
const specialEdge = (point as ILinePoint)?.specialEdge;
const curveLinePoints = pointList.splice(0, SEGMENT_NUMBER + 1);
ctx.save();
ctx.beginPath();
if (hoverEdgeIndex === index) {
ctx.lineWidth = 4;
}
curveLinePoints.forEach(({ x, y }: ILinePoint, pointIndex) => {
const fn = pointIndex > 0 ? 'lineTo' : 'moveTo';
if (specialEdge) {
LineToolUtils.setSpecialEdgeStyle(ctx);
}
ctx[fn](x, y);
});
ctx.stroke();
ctx.restore();
});
ctx.restore();
};
public static calcTwoPointDistance = (pointA: IPoint, pointB: IPoint) =>
Math.sqrt(Math.pow(pointA.x - pointB.x, 2) + Math.pow(pointA.y - pointB.y, 2));
/**
* 计算在依赖物体目标内与当前线段的交点。
* 支持的依赖工具: 多边形,矩形。
* @param axis 当前鼠标的点
* @param preAxis 上一个标注点
* @param {EDependPattern} dependPattern 依赖模式
* @param dependData 依赖工具的数据
* @param dependConfig 依赖工具的配置
* @param imageSize 图片尺寸
* @param pointRadius 点的半径
* @param zoom 缩放比例
* @param getRenderAxis 转化为渲染坐标
* @param getAbsAxis 转化为绝对坐标
*/
public static pointOverTarget = (
axis: ICoordinate,
preAxis: ICoordinate,
dependToolName: EToolName | undefined,
dependData: any,
dependConfig: any,
imageSize: ISize,
pointRadius: number,
zoom: number,
getRenderAxis: (coord: ICoordinate) => ICoordinate | ILinePoint,
getAbsAxis: (coord: ICoordinate) => ICoordinate | ILinePoint,
) => {
const absAxis = axis;
if (!preAxis) {
return axis;
}
if (dependToolName === EToolName.Polygon) {
const polygonPointList = LineToolUtils.getPolygonPointList(dependData, dependConfig);
if (polygonPointList.length === 0) {
return absAxis;
}
const inPolygon = PolygonUtils.isInPolygon(axis, polygonPointList);
if (inPolygon) {
return absAxis;
}
const pointList = polygonPointList.concat(polygonPointList[0]).map((i: any) => getRenderAxis(i));
const pointA = getRenderAxis(preAxis);
const pointB = getRenderAxis(axis);
const line1 = {
pointA,
pointB,
};
const intersection = LineToolUtils.calcOptimalIntersection(pointList, line1, pointA, pointRadius, zoom);
/** 判断交点,如果存在直接返回,否则返回上一个标注点 */
if (intersection) {
const intersectionAbsAxis = getAbsAxis(intersection?.point);
absAxis.x = intersectionAbsAxis.x;
absAxis.y = intersectionAbsAxis.y;
} else {
return preAxis;
}
return absAxis;
}
if (dependToolName === EToolName.Rect) {
const { x, y, width, height } = dependData;
absAxis.x = MathUtils.withinRange(absAxis.x, [x, x + width]);
absAxis.y = MathUtils.withinRange(absAxis.y, [y, y + height]);
return absAxis;
}
absAxis.x = MathUtils.withinRange(absAxis.x, [0, imageSize.width]);
absAxis.y = MathUtils.withinRange(absAxis.y, [0, imageSize.height]);
return absAxis;
};
/**
* 获取多边形的线段
* @param dependData 多边形数据
* @param dependConfig 多边形配置
*/
public static getPolygonPointList = (dependData: any, dependConfig: any) => {
const { pointList } = dependData;
const { lineType } = dependConfig;
return lineType === ELineTypes.Line
? pointList
: PolygonUtils.createSmoothCurvePoints(
pointList.reduce((acc: any[], cur: any) => {
return [...acc, cur.x, cur.y];
}, []),
0.5,
true,
20,
);
};
public static isInLine(checkPoint: ICoordinate, point1: IPoint, point2: IPoint, scope: number = 3) {
const { length } = MathUtils.getFootOfPerpendicular(checkPoint, point1, point2);
if (length < scope) {
return true;
}
return false;
}
public static isOnLine = (x: number, y: number, endX: number, endY: number, px: number, py: number) => {
const f = (someX: number) => {
return ((endY - y) / (endX - x)) * (someX - x) + y;
};
return Math.abs(f(px) - py) < 1e-6 && px >= x && px <= endX;
};
public static inArea = ({ top, left, right, bottom }: IRectArea, { x, y }: IPoint) =>
y >= top && y <= bottom && x >= left && x <= right;
/**
* 获取水平、垂直线的坐标点
* @param isStraight
* @param lastPoint
* @param nextPoint
* @param absNextPoint
* @param renderLastPoint
*/
public static getVHPoint = (
lastPoint: ICoordinate,
nextPoint: ICoordinate,
absNextPoint: ICoordinate,
renderLastPoint: ICoordinate,
) => {
const angle = LineToolUtils.getAngle(lastPoint, absNextPoint);
if (Math.abs(angle) < 45) {
return { ...nextPoint, y: renderLastPoint.y };
}
return { ...nextPoint, x: renderLastPoint.x };
};
public static getAngle = (startPoint: ICoordinate, endPoint: ICoordinate) => {
const diffX = endPoint.x - startPoint.x;
const diffY = endPoint.y - startPoint.y;
return (360 * Math.atan(diffY / diffX)) / (2 * Math.PI);
};
}
export default LineToolUtils; | the_stack |
import { /* FilesystemService, */ ProtocolService, UIResourceStatus } from '@airgap/angular-core'
import {
ICoinProtocol,
MainProtocolSymbols,
ProtocolNetwork,
TezosFA1p2Protocol,
TezosFA2Protocol,
TezosFA2ProtocolConfig,
TezosFA2ProtocolOptions,
TezosFAProtocolConfig,
TezosFAProtocolOptions,
TezosProtocolOptions
} from '@airgap/coinlib-core'
import { TezosContract } from '@airgap/coinlib-core/protocols/tezos/contract/TezosContract'
import { TezosProtocolNetwork } from '@airgap/coinlib-core/protocols/tezos/TezosProtocolOptions'
import { TezosContractMetadata } from '@airgap/coinlib-core/protocols/tezos/types/contract/TezosContractMetadata'
import { TezosFATokenMetadata } from '@airgap/coinlib-core/protocols/tezos/types/fa/TezosFATokenMetadata'
import { Injectable } from '@angular/core'
import { ComponentStore, tapResponse } from '@ngrx/component-store'
import { from, Observable, Subscriber } from 'rxjs'
import { repeat, switchMap, withLatestFrom } from 'rxjs/operators'
import { faProtocolSymbol } from '../../types/GenericProtocolSymbols'
import { TezosFAFormErrorType, TezosFAFormState, TokenDetailsInput, TokenInterface } from './tezos-fa-form.types'
import {
contractNotFoundError,
hasTokenInterface,
interfaceUnknownError,
isTezosFAFormError,
tokenMetadataMissingError,
tokenVaugeError,
unknownError
} from './tezos-fa-form.utils'
const initialState: TezosFAFormState = {
tokenInterface: { status: UIResourceStatus.IDLE, value: undefined },
tokenID: { status: UIResourceStatus.IDLE, value: undefined },
tokenInterfaces: [],
tokens: [],
networks: [],
protocol: { status: UIResourceStatus.IDLE, value: undefined },
errorDescription: undefined
}
@Injectable()
export class TezosFAFormStore extends ComponentStore<TezosFAFormState> {
private readonly contractMetadata: Record<string, TezosContractMetadata> = {}
private readonly tokenMetadata: Record<string, Record<number, TezosFATokenMetadata>> = {}
constructor(private readonly protocolService: ProtocolService /*, private readonly filesystemService: FilesystemService */) {
super(initialState)
}
public readonly onInit$ = this.effect(() => {
return from(this.initAsync()).pipe(
tapResponse(
(partialState) => this.updateWithValue(partialState),
(error) => this.updateWithError(error)
)
)
})
public readonly onTokenDetailsInput$ = this.effect((details$: Observable<TokenDetailsInput>) => {
return details$.pipe(
withLatestFrom(this.state$),
switchMap(([details, state]) => {
return this.fetchTokenDetails(state, details).pipe(
tapResponse(
(partialState) => this.updateWithValue(partialState),
(error) => this.updateWithError(error)
)
)
}),
repeat()
)
})
public selectFromState<K extends keyof TezosFAFormState>(key: K): Observable<TezosFAFormState[K]> {
return this.select((state) => state[key])
}
private updateWithValue = this.updater((state: TezosFAFormState, partialState: Partial<TezosFAFormState>) => {
return {
...state,
...partialState,
errorDescription: undefined
}
})
private updateWithError = this.updater((state: TezosFAFormState, error: unknown) => {
const tezosFAFormError = isTezosFAFormError(error) ? error : unknownError(error)
if (tezosFAFormError.type === TezosFAFormErrorType.UNKNOWN && tezosFAFormError.error) {
console.error(error)
}
return {
...state,
tokenInterface:
tezosFAFormError.type === TezosFAFormErrorType.INTERFACE_UNKNOWN
? { status: UIResourceStatus.ERROR, value: undefined }
: tezosFAFormError.type === TezosFAFormErrorType.CONTRACT_NOT_FOUND
? { status: UIResourceStatus.IDLE, value: undefined }
: state.tokenInterface,
tokenID:
tezosFAFormError.type === TezosFAFormErrorType.CONTRACT_NOT_FOUND
? { status: UIResourceStatus.IDLE, value: undefined }
: state.tokenID,
tokenInterfaces:
tezosFAFormError.type === TezosFAFormErrorType.INTERFACE_UNKNOWN
? tezosFAFormError.tokenInterfaces
: tezosFAFormError.type === TezosFAFormErrorType.CONTRACT_NOT_FOUND
? []
: state.tokenInterfaces,
tokens:
tezosFAFormError.type === TezosFAFormErrorType.TOKEN_VAGUE
? tezosFAFormError.tokens
: tezosFAFormError.type === TezosFAFormErrorType.CONTRACT_NOT_FOUND
? []
: state.tokens,
protocol: { status: UIResourceStatus.ERROR, value: state.protocol.value },
errorDescription: `tezos-fa-form.error.${tezosFAFormError.type}`
}
})
private async initAsync(): Promise<Partial<TezosFAFormState>> {
const networks = await this.protocolService.getNetworksForProtocol(MainProtocolSymbols.XTZ)
return {
networks: networks
}
}
private fetchTokenDetails(state: TezosFAFormState, inputDetails: TokenDetailsInput): Observable<Partial<TezosFAFormState>> {
return new Observable((subscriber: Subscriber<Partial<TezosFAFormState>>) => {
// tslint:disable-next-line: no-floating-promises
new Promise<void>(async (resolve, reject) => {
try {
this.emitLoading(subscriber)
const alreadySupported = await this.alreadySupported(inputDetails.address, inputDetails.networkIdentifier, inputDetails.tokenID)
if (alreadySupported) {
const handledAlreadySupported = await this.handleAlreadySupported(alreadySupported, inputDetails.tokenID)
await this.tapProtocol(handledAlreadySupported)
this.emitProtocol(handledAlreadySupported, inputDetails.tokenInterface, inputDetails.tokenID, subscriber)
resolve()
return
}
const network = state.networks.find((network: ProtocolNetwork) => network.identifier === inputDetails.networkIdentifier)
let contract: TezosContract | undefined
if (network && network instanceof TezosProtocolNetwork) {
contract = await this.getContract(inputDetails.address, network)
}
this.emitContract(contract, subscriber)
const tokenInterface: TokenInterface | undefined = await this.getTokenInterface(contract, inputDetails.tokenInterface)
this.emitTokenInterface(tokenInterface, subscriber)
let protocol: ICoinProtocol
switch (tokenInterface) {
case TokenInterface.FA1p2:
protocol = await this.getFA1p2TokenDetails(contract)
break
case TokenInterface.FA2:
protocol = await this.getFA2TokenDetails(contract, inputDetails.tokenID)
break
default:
throw interfaceUnknownError()
}
this.emitProtocol(protocol, inputDetails.tokenInterface, inputDetails.tokenID, subscriber)
} catch (error) {
reject(error)
}
})
.catch((error) => {
subscriber.error(error)
})
.finally(() => {
subscriber.complete()
})
})
}
private async alreadySupported(address: string, networkIdentifier: string, tokenID?: number): Promise<ICoinProtocol | undefined> {
const subProtocols = await this.protocolService.getSubProtocols(MainProtocolSymbols.XTZ)
const alreadySupportedProtocols = subProtocols.filter((protocol) => {
return protocol.contractAddress === address && (protocol.options as TezosProtocolOptions).network.identifier === networkIdentifier
})
const alreadySupportedToken = alreadySupportedProtocols.find((protocol) => {
return protocol instanceof TezosFA2Protocol && protocol.tokenID === tokenID
})
return alreadySupportedToken ?? alreadySupportedProtocols[0]
}
private async handleAlreadySupported(protocol: ICoinProtocol, tokenID?: number): Promise<ICoinProtocol> {
if (protocol instanceof TezosFA2Protocol) {
return this.handleFA2AlreadySupported(protocol, tokenID)
} else {
return protocol
}
}
private async handleFA2AlreadySupported(protocol: TezosFA2Protocol, customTokenID?: number): Promise<TezosFA2Protocol> {
if (customTokenID !== undefined && protocol.tokenID === customTokenID) {
return protocol
}
try {
return this.createFA2Protocol(protocol, customTokenID)
} catch (error) {
if (isTezosFAFormError(error) && error.type === TezosFAFormErrorType.TOKEN_METADATA_MISSING) {
return protocol
} else {
throw error
}
}
}
private async getContract(address: string, network: TezosProtocolNetwork): Promise<TezosContract | undefined> {
const contract = new TezosContract(address, network)
try {
// get contract's balance to verify if the address and network are valid
await contract.balance()
return contract
} catch {
return undefined
}
}
private async getTokenInterface(contract: TezosContract, tokenInterface?: TokenInterface): Promise<TokenInterface | undefined> {
if (!tokenInterface) {
const metadata = await this.getContractMetadata(contract)
if (!metadata) {
return undefined
}
if (hasTokenInterface(metadata, TokenInterface.FA1p2)) {
return TokenInterface.FA1p2
} else if (hasTokenInterface(metadata, TokenInterface.FA2)) {
return TokenInterface.FA2
}
}
return tokenInterface
}
private async getFA1p2TokenDetails(contract: TezosContract): Promise<TezosFA1p2Protocol> {
const genericFA1p2Protocol = new TezosFA1p2Protocol(
new TezosFAProtocolOptions(contract.network, new TezosFAProtocolConfig(contract.address, faProtocolSymbol('1.2', contract.address)))
)
const tokenMetadata = await this.getFA1p2TokenMetadata(genericFA1p2Protocol)
if (!tokenMetadata) {
throw tokenMetadataMissingError()
}
const protocol: TezosFA1p2Protocol = new TezosFA1p2Protocol(
new TezosFAProtocolOptions(
genericFA1p2Protocol.options.network,
new TezosFAProtocolConfig(
genericFA1p2Protocol.options.config.contractAddress,
faProtocolSymbol('1.2', contract.address),
tokenMetadata.symbol,
tokenMetadata.name,
tokenMetadata.symbol,
genericFA1p2Protocol.options.config.feeDefaults,
tokenMetadata.decimals
)
)
)
await this.tapProtocol(protocol, tokenMetadata)
return protocol
}
private async getFA2TokenDetails(contract: TezosContract, customTokenID: number | undefined): Promise<TezosFA2Protocol> {
const genericFA2Protocol = new TezosFA2Protocol(
new TezosFA2ProtocolOptions(
contract.network,
new TezosFA2ProtocolConfig(
contract.address,
faProtocolSymbol('2', contract.address, customTokenID),
undefined,
undefined,
undefined,
undefined,
undefined,
customTokenID
)
)
)
return this.createFA2Protocol(genericFA2Protocol, customTokenID)
}
private async createFA2Protocol(baseProtocol: TezosFA2Protocol, customTokenID: number | undefined): Promise<TezosFA2Protocol> {
const tokenMetadataRegistry = await this.getFA2TokenMetadata(baseProtocol)
if (!tokenMetadataRegistry) {
throw tokenMetadataMissingError()
}
const tokenMetadataRegistryEntries = Object.entries(tokenMetadataRegistry)
const [tokenID, tokenMetadata] =
customTokenID !== undefined
? [customTokenID, tokenMetadataRegistry[customTokenID]]
: tokenMetadataRegistryEntries.length === 1
? [parseInt(tokenMetadataRegistryEntries[0][0]), tokenMetadataRegistryEntries[0][1]]
: [undefined, undefined]
if (tokenID === undefined) {
throw tokenVaugeError(tokenMetadataRegistry)
}
if (tokenMetadata === undefined) {
throw tokenMetadataMissingError()
}
const protocol: TezosFA2Protocol = new TezosFA2Protocol(
new TezosFA2ProtocolOptions(
baseProtocol.options.network,
new TezosFA2ProtocolConfig(
baseProtocol.options.config.contractAddress,
faProtocolSymbol('2', baseProtocol.contractAddress, tokenID),
tokenMetadata.symbol,
tokenMetadata.name,
tokenMetadata.symbol,
baseProtocol.options.config.feeDefaults,
tokenMetadata.decimals,
tokenID
)
)
)
await this.tapProtocol(protocol, tokenMetadata)
return protocol
}
private emitLoading(subscriber: Subscriber<Partial<TezosFAFormState>>): void {
subscriber.next({
tokenID: { status: UIResourceStatus.LOADING, value: undefined },
tokenInterface: { status: UIResourceStatus.LOADING, value: undefined },
protocol: { status: UIResourceStatus.LOADING, value: undefined }
})
}
private emitProtocol(
protocol: ICoinProtocol,
tokenInterface: TokenInterface | undefined,
tokenID: number | undefined,
subscriber: Subscriber<Partial<TezosFAFormState>>
): void {
subscriber.next({
tokenID:
tokenID !== undefined
? { status: UIResourceStatus.SUCCESS, value: tokenID }
: protocol instanceof TezosFA2Protocol
? { status: UIResourceStatus.SUCCESS, value: protocol.tokenID }
: { status: UIResourceStatus.SUCCESS, value: 0 },
tokenInterface: {
status: UIResourceStatus.SUCCESS,
value:
protocol instanceof TezosFA1p2Protocol
? TokenInterface.FA1p2
: protocol instanceof TezosFA2Protocol
? TokenInterface.FA2
: undefined
},
protocol: { status: UIResourceStatus.SUCCESS, value: protocol },
...(tokenInterface === undefined ? { tokenInterfaces: [] } : {}),
...(tokenID === undefined ? { tokens: [] } : {})
})
}
private emitContract(contract: TezosContract | undefined, _subscriber: Subscriber<Partial<TezosFAFormState>>): void {
if (!contract) {
throw contractNotFoundError()
}
}
private emitTokenInterface(tokenInterface: TokenInterface | undefined, subscriber: Subscriber<Partial<TezosFAFormState>>): void {
if (!tokenInterface) {
throw interfaceUnknownError()
}
subscriber.next({
tokenInterface: { status: UIResourceStatus.SUCCESS, value: tokenInterface }
})
}
private async getContractMetadata(contract: TezosContract): Promise<TezosContractMetadata | undefined> {
if (!this.contractMetadata[contract.address]) {
const networks = await this.protocolService.getNetworksForProtocol(MainProtocolSymbols.XTZ)
this.contractMetadata[contract.address] = await contract.metadata((network: string) => {
return networks.find(
(protocolNetwork: ProtocolNetwork) =>
protocolNetwork instanceof TezosProtocolNetwork && protocolNetwork.extras.network === network
) as TezosProtocolNetwork
})
}
return this.contractMetadata[contract.address]
}
private async getFA1p2TokenMetadata(protocol: TezosFA1p2Protocol): Promise<TezosFATokenMetadata | undefined> {
const tokenMetadata = await this.getFATokenMetadata(protocol)
return tokenMetadata[0]
}
private async getFA2TokenMetadata(protocol: TezosFA2Protocol): Promise<Record<number, TezosFATokenMetadata> | undefined> {
if (!this.tokenMetadata[protocol.contractAddress]) {
const allTokenMetadata = await protocol.getAllTokenMetadata()
if (!allTokenMetadata) {
return undefined
}
await Promise.all(
Object.entries(allTokenMetadata).map(async ([tokenID, tokenMetadata]) => {
this.tokenMetadata[protocol.contractAddress] = Object.assign(this.tokenMetadata[protocol.contractAddress] ?? {}, {
[tokenID]: tokenMetadata
})
})
)
}
return this.tokenMetadata[protocol.contractAddress]
}
private async getFATokenMetadata(
protocol: TezosFA1p2Protocol | TezosFA2Protocol,
tokenID?: number
): Promise<Record<number, TezosFATokenMetadata> | undefined> {
tokenID = tokenID ?? ('tokenID' in protocol ? protocol.tokenID : 0)
if (!this.tokenMetadata[protocol.contractAddress] || !this.tokenMetadata[protocol.contractAddress][tokenID]) {
this.tokenMetadata[protocol.contractAddress] = Object.assign(this.tokenMetadata[protocol.contractAddress] ?? {}, {
[tokenID]: await protocol.getTokenMetadata()
})
}
return this.tokenMetadata[protocol.contractAddress]
}
private async tapProtocol(protocol: ICoinProtocol, tokenMetadata?: TezosFATokenMetadata): Promise<void> {
if (tokenMetadata === undefined) {
if (protocol instanceof TezosFA1p2Protocol) {
tokenMetadata = await protocol.getTokenMetadata()
} else if (protocol instanceof TezosFA2Protocol) {
tokenMetadata = await protocol.getTokenMetadata()
}
}
if (tokenMetadata) {
await this.tapTokenMetadata(protocol, tokenMetadata)
}
}
private async tapTokenMetadata(_protocol: ICoinProtocol, _tokenMetadata: TezosFATokenMetadata): Promise<void> {
// const thumbnailUri = tokenMetadata.thumbnailUri
// if (typeof thumbnailUri === 'string') {
// await this.filesystemService.writeLazyImage(`/images/symbols/${protocol.identifier}`, thumbnailUri.trim())
// }
}
} | the_stack |
import {
Component,
ElementRef,
EventEmitter,
Input,
OnInit,
Optional,
Output,
SimpleChanges,
ViewChild
} from '@angular/core';
import {WorkspaceVersion} from "../../models/workspace-version.model";
import {TestStep} from "../../models/test-step.model";
import {FormControl, FormGroup} from '@angular/forms';
import {Page} from "../../shared/models/page";
import {NaturalTextActions} from "../../models/natural-text-actions.model";
import {fromEvent} from "rxjs";
import {debounceTime, distinctUntilChanged, filter, tap} from "rxjs/operators";
import {ActionElementSuggestionComponent} from "./action-element-suggestion.component";
import {MatDialog, MatDialogRef} from '@angular/material/dialog';
import {TestStepService} from "../../services/test-step.service";
import {TestCase} from "../../models/test-case.model";
import {ActionTestDataFunctionSuggestionComponent} from "./action-test-data-function-suggestion.component";
import {TestDataType} from "../../enums/test-data-type.enum";
import {ActionTestDataParameterSuggestionComponent} from "./action-test-data-parameter-suggestion.component";
import {ActionTestDataEnvironmentSuggestionComponent} from "./action-test-data-environment-suggestion.component";
import {DefaultDataGeneratorService} from "../../services/default-data-generator.service";
import {TestStepType} from "../../enums/test-step-type.enum";
import {TestStepTestDataFunction} from "../../models/test-step-test-data-function.model";
import {DefaultDataGenerator} from "../../models/default-data-generator.model";
import {BaseComponent} from "../../shared/components/base.component";
import {AuthenticationGuard} from "../../shared/guards/authentication.guard";
import {NotificationsService} from 'angular2-notifications';
import {TranslateService} from '@ngx-translate/core';
import {ToastrService} from "ngx-toastr";
import {TestCaseService} from "../../services/test-case.service";
import {StepDetailsDataMap} from "../../models/step-details-data-map.model";
import {AddonNaturalTextAction} from "../../models/addon-natural-text-action.model";
import {AddonTestStepTestData} from "../../models/addon-test-step-test-data.model";
import {AddonElementData} from "../../models/addon-element-data.model";
import {Router} from "@angular/router";
import {TestStepConditionType} from "../../enums/test-step-condition-type.enum";
import {TestStepPriority} from "../../enums/test-step-priority.enum";
import {MobileRecorderEventService} from "../../services/mobile-recorder-event.service";
import {MobileStepRecorderComponent} from "../../agents/components/webcomponents/mobile-step-recorder.component";
import {ResultConstant} from "../../enums/result-constant.enum";
import {TestStepMoreActionFormComponent} from "./test-step-more-action-form.component";
import {ElementFormComponent} from "./element-form.component";
import {AddonTestDataFunctionService} from "../../services/addon-default-data-generator.service";
import {AddonTestDataFunction} from "../../models/addon-test-data-function.model";
import {AddonTestDataFunctionParameter} from "../../models/addon-test-data-function-parameter.model";
import {StepActionType} from "../../enums/step-action-type.enum";
@Component({
selector: 'app-action-step-form',
templateUrl: './action-step-form.component.html',
styles: [],
host: {
'(document:click)': 'onDocumentClick($event)',
},
})
export class ActionStepFormComponent extends BaseComponent implements OnInit {
@Input('version') version: WorkspaceVersion;
@Input('testStep') public testStep: TestStep;
@Input('testSteps') testSteps: Page<TestStep>;
@Input('testCase') testCase: TestCase;
@Input('testStepsLength') testStepsLength: number;
@Output('onCancel') onCancel = new EventEmitter<void>();
@Output('onSave') onSave = new EventEmitter<TestStep>();
@Input('stepForm') actionForm: FormGroup;
@Input('templates') templates: Page<NaturalTextActions>;
@Input('addonTemplates') addonTemplates?: Page<AddonNaturalTextAction>;
@Input('selectedTemplate') currentTemplate: NaturalTextActions;
@Input('testCaseResultId') testCaseResultId: number;
@Input('isDryRun') isDryRun: boolean;
@Optional() @Input('conditionTypeChange') conditionTypeChange: TestStepConditionType;
@ViewChild('searchInput') searchInput: ElementRef;
@ViewChild('replacer') replacer: ElementRef;
@ViewChild('actionsDropDownContainer') actionsDropDownContainer: ElementRef;
@ViewChild('displayNamesContainer') displayNamesContainer: ElementRef;
@ViewChild('dataTypesContainer') dataTypesContainer: ElementRef;
public currentFocusedIndex: number;
public filteredTemplates: NaturalTextActions[];
public filteredAddonTemplates: AddonNaturalTextAction[];
public animatedPlaceholder: string;
public formSubmitted: boolean;
public isFetching: Boolean = false;
public showTemplates: Boolean = false;
public showDataTypes: Boolean = false;
public showHelps: Boolean = false;
public showActions: Boolean = false;
public saving: boolean;
public displayNames: any;
public argumentList: any;
public currentDataTypeIndex: number;
public skipFocus: boolean;
private elementSuggestion: MatDialogRef<ActionElementSuggestionComponent>;
private StepMsg = ["Navigate to https://www.google.com/",
"Enter admin in the userName field",
"Enter 12345 in the password field",
"Click on LoginButton",
"Verify that the current page displays text Welcome"];
private stepMsgMobile = ["Launch App",
"Tap on Login button",
"Enter userName@gmail.com in the Enter Email field",
"Enter password123 in the Password field",
"Tap on next login",
"Verify that the current page displays text This email address is not registered on WordPress.com"];
private placeholders: any[];
private stepCreateArticles = {
"WebApplication": "https://testsigma.com/docs/test-cases/create-steps-recorder/web-apps/overview/",
"MobileWeb": "https://testsigma.com/docs/test-cases/create-steps-recorder/web-apps/overview/",
"AndroidNative": "https://testsigma.com/docs/test-cases/create-steps-recorder/android-apps/",
"IOSNative": "https://testsigma.com/docs/test-cases/create-steps-recorder/ios-apps/overview/",
"Rest": "https://testsigma.com/tutorials/getting-started/automate-rest-apis/"
}
public stepArticleUrl = "";
public navigateTemplate = [1044, 94, 10116, 10001]
private testDataFunctionSuggestion: MatDialogRef<ActionTestDataFunctionSuggestionComponent>;
private dataProfileSuggestion: MatDialogRef<ActionTestDataParameterSuggestionComponent>;
private environmentSuggestion: MatDialogRef<ActionTestDataEnvironmentSuggestionComponent>;
public localUrlVerifying: boolean;
public localUrlValid: number = -1;
public currentTestDataType: TestDataType;
public currentTestDataFunction: DefaultDataGenerator;
public isValidAttribute: Boolean;
public isValidElement: Boolean;
public isValidTestData: Boolean;
public isCurrentDataTypeRaw: boolean = false;
private currentStepDataMap: StepDetailsDataMap;
private lastActionNavigateUrl: string;
public currentAddonTemplate: AddonNaturalTextAction;
public currentDataItemIndex: number;
public currentAddonAllowedValues = [];
@Input() stepRecorderView?: boolean;
private eventEmitterAlreadySubscribed: Boolean = false;
private oldStepData: TestStep;
isAttachTestDataEvent: boolean = false;
get mobileStepRecorder(): MobileStepRecorderComponent {
return this.matModal.openDialogs.find(dialog => dialog.componentInstance instanceof MobileStepRecorderComponent).componentInstance;
}
get isTestDataRunTimeParameterType(){
return this.currentTestDataType && this.currentTestDataType == TestDataType.runtime;
}
get isTestDataRandomParameterType(){
return this.currentTestDataType && this.currentTestDataType == TestDataType.random;
}
public currentTestDataFunctionParameters: AddonTestDataFunctionParameter[];
public currentAddonTDF: AddonTestDataFunction;
constructor(
public authGuard: AuthenticationGuard,
public notificationsService: NotificationsService,
public translate: TranslateService,
public toastrService: ToastrService,
private testStepService: TestStepService,
private testDataFunctionService: DefaultDataGeneratorService,
private testCaseService: TestCaseService,
private addonTestDataFunctionService: AddonTestDataFunctionService,
private matModal: MatDialog,
private router: Router,
private _eref: ElementRef,
private mobileRecorderEventService: MobileRecorderEventService) {
super(authGuard, notificationsService, translate, toastrService);
}
get dataTypes() {
return Object.keys(TestDataType);
}
get isEdit() {
return this.testStep?.id;
}
ngOnInit(): void {
this.fetchSteps();
this.filter();
this.filterAddonAction()
this.placeholders = [...this.StepMsg];
if (this.version.workspace.isMobile) {
this.placeholders = [...this.stepMsgMobile]
}
if (this.testStep?.id) {
this.oldStepData = new TestStep().deserialize(this.testStep);
this.oldStepData.testDataVal = this.testStep.testDataVal;
this.testStep.conditionIf = Object.assign([], JSON.parse(JSON.stringify(this.testStep.conditionIf)));
}
this.actionForm.addControl('action', new FormControl(this.testStep.action, []))
this.isFetching = true;
this.attachContentEditableDivKeyEvent();
this.stepArticleUrl = this.stepCreateArticles[this.version.workspace.workspaceType];
this.resetValidation();
this.subscribeMobileRecorderEvents();
}
ngOnChanges(changes: SimpleChanges) {
this.clearSelection();
if (changes['currentTemplate'] && !changes['currentTemplate']?.firstChange) {
if (!this.testStep.isConditionalType)
this.currentTemplate = changes['currentTemplate']['currentValue'];
}
this.setTemplate(this.currentTemplate);
this.showTemplates = false;
}
getAddonTemplateAllowedValues(reference?) {
this.currentAddonAllowedValues = undefined;
this.currentAddonTemplate?.parameters.forEach(parameter => {
if (parameter?.reference == reference) {
this.currentAddonAllowedValues = parameter?.allowedValues?.length ? parameter?.allowedValues : undefined;
}
})
}
private resetValidation() {
this.isValidAttribute = true;
this.isValidTestData = true;
this.isValidElement = true;
}
showACTIONDropdown() {
if (this.skipFocus)
return;
this.showTemplates = true;
this.currentFocusedIndex = 0;
}
showDataDropdown() {
this.showDataTypes = true;
this.currentDataTypeIndex = 0;
this.showTemplates = false;
}
clearSelection(isClear?) {
this.currentTemplate = undefined;
if (this.replacer) {
this.replacer.nativeElement.innerHTML = "";
setTimeout(() => {
if (!this.testStep?.id)
this.replacer.nativeElement.focus()
}
,
100
)
;
}
this.filteredTemplates = this.filter();
this.filteredAddonTemplates = this.filterAddonAction();
if (this.testStep?.id) {
if (this.testStep.naturalTextActionId) {
this.testStep.template = this.filteredTemplates.find(item => item.id == this.testStep.naturalTextActionId);
delete this.testStep.addonTemplate;
}
if (this.testStep.addonActionId) {
this.testStep.addonTemplate = this.filteredAddonTemplates.find(item => item.id === this.testStep.addonActionId);
delete this.testStep.template;
}
// this.testStep.dataMap = new StepDetailsDataMap().deserialize(this.currentStepDataMap ? this.currentStepDataMap : this.testStep.dataMap);
}
this.showDataTypes = false;
this.currentDataTypeIndex = 0;
this.localUrlValid = -1;
this.resetCFArguments();
this.resetValidation();
this.currentTestDataFunctionParameters = null;
this.currentAddonTDF = null;
}
attachContentEditableDivKeyEvent() {
if (this.replacer && this.replacer.nativeElement) {
this.showHelps = true;
if (this.testStep.id) {
this.assignEditTemplate();
this.showDataTypes = false;
} else {
if (this.testStep.isConditionalIf || this.testStep.isConditionalElseIf || this.testStep.isConditionalWhileLoop) {
this.replacer.nativeElement.focus();
}
}
fromEvent(this.replacer.nativeElement, 'click')
.pipe(tap((event) => {
this.showDataTypes = false;
this.replacer.nativeElement.contentEditable = true;
if (this.testDataPlaceholder().length) {
this.testDataPlaceholder().forEach(item => {
item?.removeAttribute("contentEditable")
})
}
if (this.elementPlaceholder().length) {
this.elementPlaceholder().forEach(item => {
item?.removeAttribute("contentEditable")
})
}
this.attributePlaceholder()?.removeAttribute("contentEditable");
this.replacer.nativeElement.focus();
this.resetValidation();
console.log(event);
})).subscribe();
fromEvent(this.replacer.nativeElement, 'keyup')
.pipe(
filter(Boolean),
debounceTime(300),
distinctUntilChanged(),
tap((event: KeyboardEvent) => {
// Assuming the user is entering key in testData
if (this.testDataPlaceholder().length) {
let isEditTestData = false
this.testDataPlaceholder().forEach(item => {
if (item?.contentEditable != 'inherit' && item?.contentEditable)
isEditTestData = true;
})
if (isEditTestData)
return;
}
console.log(event);
if (["ArrowDown", "ArrowUp"].includes(event.key))
return;
if ("Backspace" == event.key)
delete this.currentTemplate
let htmlGrammar = this.replacer.nativeElement.innerHTML;
htmlGrammar = htmlGrammar.replace(/<br>/g, "");
if (htmlGrammar) {
htmlGrammar = htmlGrammar.replace(/<span class="element+(.*?)>(.*?)<\/span>/g, "Element")
.replace(/<span class="test_data+(.*?)>(.*?)<\/span>/g, "test data")
.replace(/<span class="selected_list+(.*?)>(.*?)<\/span>/g, this.currentTemplate?.extractTestDataString)
.replace(/<span class="attribute+(.*?)>(.*?)<\/span>/g, "attribute")
.replace(/ /g, "");
this.filter(htmlGrammar);
this.filterAddonAction(htmlGrammar)
} else {
this.filteredTemplates = this.filter();
this.filteredAddonTemplates = this.filterAddonAction();
}
})
)
.subscribe();
fromEvent(this.replacer.nativeElement, 'paste').pipe(tap((event) => {
const text = (event['originalEvent'] || event).clipboardData.getData('text/plain');
window.document.execCommand('insertText', false, text);
event['stopPropagation']();
event['preventDefault']();
return false;
})).subscribe()
this.swapPlaceholder();
this.preFillingSteps();
} else
setTimeout(() => {
this.attachContentEditableDivKeyEvent();
}, 100);
}
get actionTextLength() {
return this.replacer?.nativeElement?.textContent?.length;
}
private preFillingSteps() {
if (!this.testStep?.id && !this.testStepsLength) {
let templateSearchText = "Navigate to";
if (this.version.workspace.isMobileNative) {
templateSearchText = "Launch App";
}
this.filter(templateSearchText);
this.currentFocusedIndex = 0;
this.selectTemplate();
this.testDataPlaceholderText();
}
}
private testDataPlaceholderText() {
if (this.testDataPlaceholder()?.length) {
this.replacer.nativeElement.contentEditable = false;
let currentDataItemIndex = this.currentDataItemIndex || 0;
this.testDataPlaceholder()[currentDataItemIndex].contentEditable = true;
this.testDataPlaceholder()[currentDataItemIndex].innerHTML = "";
this.testDataPlaceholder()[currentDataItemIndex].classList.add('placeholder-test-animate');
this.testDataPlaceholder()[currentDataItemIndex].setAttribute("data-test-data-type", this.currentTestDataType);
this.testDataPlaceholder()[currentDataItemIndex].style.minWidth = "100px";
//this.testDataPlaceholder()?.focus();
this.showDataTypes = false;
} else {
setTimeout(() => {
this.testDataPlaceholderText()
})
}
}
filter(searchText?: string) {
this.filteredTemplates = [];
if (searchText && searchText.length) {
this.templates.content.forEach(template => {
if (template.searchableGrammar.toLowerCase().includes(searchText.toLowerCase()))
this.filteredTemplates.push(template)
})
this.filteredTemplates.sort((a: NaturalTextActions, b: NaturalTextActions) => {
return a.naturalText.toLowerCase().indexOf(searchText) - b.naturalText.toLowerCase().indexOf(searchText)
})
} else {
this.filteredTemplates = this.templates.content;
this.filteredTemplates.sort((a: NaturalTextActions, b: NaturalTextActions) => {
return a.displayOrder - b.displayOrder;
})
}
//this.filteredTemplates = this.filteredTemplates;
this.currentFocusedIndex = 0;
return this.filteredTemplates;
}
filterAddonAction(searchText?: string) {
if (this.addonTemplates?.content?.length) {
this.filteredAddonTemplates = [];
if (searchText && searchText.length) {
this.addonTemplates.content.forEach(template => {
if (template.searchableGrammar.toLowerCase().includes(searchText.toLowerCase()))
this.filteredAddonTemplates.push(template)
})
} else {
this.filteredAddonTemplates = this.addonTemplates.content;
}
return this.filteredAddonTemplates;
} else {
return [];
}
}
initNewTestStep(position: number, testCaseId): TestStep {
let testStep = this.testStep;
testStep.position = position;
testStep.testCaseId = testCaseId;
testStep.waitTime = 30;
testStep.priority = TestStepPriority.MAJOR;
testStep.type = TestStepType.ACTION_TEXT;
if (this.version.workspace.isRest)
testStep.type = TestStepType.REST_STEP;
return testStep
}
addWhileConditionStep(step: TestStep) {
this.testStep.conditionType = TestStepConditionType.LOOP_WHILE;
this.testStep.priority = TestStepPriority.MINOR;
this.testStep.parentId = step.id;
this.testStep.parentStep = step;
this.testStep.siblingStep = step;
this.testStep.position = step.position + 1;
this.testStep.stepDisplayNumber = step.stepDisplayNumber + ".1";
step.siblingStep = this.testStep;
step.isAfter = true;
// return afterStep;
}
public fetchSteps() {
let query = "testCaseId:" + this.testCase.id;
this.testStepService.findAll(query, 'position').subscribe(res => {
this.testSteps = res;
})
}
private createWhileStep() {
let whileStep = new TestStep();
whileStep.conditionIf = [];
whileStep.testCaseId = this.testCase.id;
whileStep.position = this.testStep.position;
if (this.testStep.parentId && !this.testStep?.getParentLoopId(this.testStep?.parentStep)) {
whileStep.parentId = this.testStep.parentId;
}
whileStep.waitTime = 30;
whileStep.priority = TestStepPriority.MINOR;
whileStep.type = TestStepType.WHILE_LOOP;
whileStep.ignoreStepResult = whileStep.ignoreStepResult === undefined ? true : whileStep.ignoreStepResult;
this.testStepService.create(whileStep).subscribe(res => {
this.testStep.parentId = res.id
this.testStep.position = res.position + 1;
this.testStep.parentStep = res;
this.testStep.siblingStep = res;
this.save(true);
}, error => {
this.translate.get('message.common.created.failure', {FieldName: 'Test Step'}).subscribe((res) => {
this.showAPIError(error, res);
})
})
}
save(isSkip?: boolean) {
if (this.testStep.isConditionalWhileLoop && !isSkip) {
this.createWhileStep();
} else {
this.formSubmitted = true;
if (this.validation()) {
this.saving = true;
this.testStepService.create(this.testStep).subscribe(step => this.afterSave(step), e => this.handleSaveFailure(e));
}
}
}
update(naturalTextActionId, addonActionId) {
this.formSubmitted = true;
if (this.validation()) {
this.saving = true;
if ((addonActionId && !this.testStep.naturalTextActionId) || (naturalTextActionId && this.testStep.addonActionId)) {
this.testStep.naturalTextActionId = undefined;
} else if ((naturalTextActionId && !this.testStep.addonActionId) || (addonActionId && this.testStep.naturalTextActionId)) {
this.testStep.addonActionId = undefined;
}
this.testStepService.update(this.testStep).subscribe((step) => this.afterSave(step), e => this.handleSaveFailure(e, true))
}
}
cancel() {
if (this.testStep.id) {
this.assignOldData();
}
this.clearSelection();
this.isAttachTestDataEvent = false;
this.showActions = false;
this.showTemplates = false;
this.replacer.nativeElement.blur();
this.onCancel.emit();
}
assignOldData() {
if (this.testStep.addonActionId) {
this.testStep.addonTestData = this.oldStepData.addonTestData;
this.testStep.addonElements = this.oldStepData.addonElements;
this.testStep.addonTDF = this.oldStepData.addonTDF;
} else if(this.testStep.naturalTextActionId) {
this.testStep.testDataVal = this.oldStepData.testDataVal;
this.testStep.attribute = this.oldStepData.attribute;
this.testStep.element = this.oldStepData.element;
this.testStep.testDataType = this.oldStepData.testDataType;
}
}
addonValidation() {
let dataMap = {};
if (this.elementPlaceholder().length) {
this.elementPlaceholder().forEach(item => {
let reference = item.dataset?.reference;
let value = item?.textContent?.replace(/ /g, "").trim();
if (value.length) {
dataMap[reference] = value
} else {
this.isValidElement = false
}
})
}
if (this.testDataPlaceholder().length) {
this.testDataPlaceholder().forEach(item => {
let reference = item.dataset?.reference;
let testDataType = TestDataType[item.dataset?.testDataType || 'raw'];
let value = item?.textContent?.replace(/ /g, "").trim();
['\@|', '\!|', '\~|', '\$|', '\*|', '\&|', '|'].some(type => {
value = value.replace(type, '').replace(/ /g, "");
});
if (value.length) {
if (this.testStep?.addonTestData) {
const testDataFunctionId = this.testStep?.addonTestData[reference]?.testDataFunctionId;
const isAddonFn = this.testStep?.addonTestData[reference]?.isAddonFn;
const args = this.testStep?.addonTestData[reference]?.testDataFunctionArguments;
dataMap[reference] = {
value: value,
type: testDataType,
testDataFunctionArguments: item.dataset?.testDataFunctionArguments ? JSON.parse(item.dataset?.testDataFunctionArguments) : args,
testDataFunctionId: testDataType === TestDataType.function ? item.dataset?.testDataFunctionId ? item.dataset?.testDataFunctionId : testDataFunctionId : undefined,
isAddonFn: item.dataset?.isAddonFn ? item.dataset?.isAddonFn : isAddonFn
}
} else {
dataMap[reference] = {
value: value,
type: testDataType,
testDataFunctionArguments: item.dataset?.testDataFunctionArguments ? JSON.parse(item.dataset?.testDataFunctionArguments) : undefined,
testDataFunctionId: testDataType === TestDataType.function && item.dataset?.testDataFunctionId ? item.dataset?.testDataFunctionId : undefined,
isAddonFn: item.dataset?.isAddonFn ? item.dataset?.isAddonFn : undefined
}
}
} else {
this.isValidTestData = false
}
})
}
let action = this.replacer.nativeElement.innerHTML;
let testData = new Map<string, AddonTestStepTestData>();
let elements = new Map<string, AddonElementData>();
if (this.testStep?.addonTemplate?.parameters) {
action = this.currentAddonTemplate.naturalText
this.testStep.addonTemplate.parameters.forEach(parameter => {
if (parameter.isTestData && dataMap[parameter.reference]) {
//action = action.replace(parameter.reference, dataMap[parameter.reference]['value']);
let data = new AddonTestStepTestData();
data.value = dataMap[parameter.reference]['value'];
data.type = dataMap[parameter.reference]['type'];
data.testDataFunctionArguments = dataMap[parameter.reference]['testDataFunctionArguments'];
data.isAddonFn = dataMap[parameter.reference]['isAddonFn'];
data.testDataFunctionId = dataMap[parameter.reference]['testDataFunctionId'];
testData[parameter.reference] = data;
} else if (parameter.isElement) {
//action = action.replace(parameter.reference, dataMap[parameter.reference]);
let element = new AddonElementData();
element.name = dataMap[parameter.reference];
elements[parameter.reference] = element;
}
})
}
if (action && action.length && this.isValidElement && this.isValidTestData && this.isValidAttribute) {
this.testStep.action = action;
this.testStep.addonActionId = this.currentAddonTemplate.id;
//this.testStep.addonNaturalTextActionData = new AddonNaturalTextActionDataModel();
this.testStep.addonTestData = testData;
this.testStep.addonElements = elements;
this.testStep.type = TestStepType.ACTION_TEXT;
this.testStep.addonTemplate = this.currentAddonTemplate;
this.testStep.deserializeCommonProperties(this.actionForm.getRawValue());
delete this.testStep.template;
delete this.testStep.naturalTextActionId;
delete this.testStep.testDataFunctionId;
delete this.testStep.testDataFunctionArgs;
delete this.testStep.testDataVal;
delete this.testStep.testDataType;
delete this.testStep.element;
delete this.testStep.attribute;
return true
} else {
return false;
}
}
validation() {
this.replacer.nativeElement.click();
this.showTemplates = false;
if (this.currentAddonTemplate) {
return this.addonValidation();
}
let elementValue = this.elementPlaceholder()[0]?.textContent?.replace(/ /g, "");
let testDataValue = this.testDataPlaceholder()[0]?.textContent?.replace(/ /g, "");
let attributeValue = this.attributePlaceholder()?.textContent?.replace(/ /g, "");
let action = this.replacer.nativeElement.innerHTML.replace(/<span class="element+(.*?)>(.*?)<\/span>/g, elementValue)
.replace(/<span class="test_data+(.*?)>(.*?)\|<\/span>/g, testDataValue)
.replace(/<span class="test_data+(.*?)>(.*?)<\/span>/g, testDataValue)
.replace(/<span class="selected_list+(.*?)>(.*?)<\/span>/g, testDataValue)
.replace(/<span class="attribute+(.*?)>(.*?)<\/span>/g, attributeValue)
.replace(/ /g, "");
if (testDataValue)
['\@|', '\!|', '\~|', '\$|', '\*|', '\&|'].some(type => {
if (testDataValue.startsWith(type))
testDataValue = testDataValue.replace(type, '').replace(/ /g, "");
});
testDataValue = testDataValue?.replace('|', '')?.replace(/ /g, "");
if (this.elementPlaceholder().length) {
this.elementPlaceholder().forEach(item => {
if (!item.textContent?.replace(/ /g, "").trim()?.length) {
this.isValidElement = false;
}
})
}
//this.isValidElement = this.elementPlaceholder() ? elementValue?.trim()?.length : true;
this.isValidTestData = this.testDataPlaceholder()[0] ? testDataValue?.trim().length : true;
this.isValidAttribute = this.attributePlaceholder() ? attributeValue?.trim().length : true;
if (action && action.length && this.isValidElement && this.isValidTestData && this.isValidAttribute) {
this.testStep.action = action;
this.testStep.naturalTextActionId = this.currentTemplate?.id;
this.testStep.type = TestStepType.ACTION_TEXT;
this.testStep.template = this.currentTemplate;
if (testDataValue) {
this.testStep.testDataVal = testDataValue.trim();
this.setDataMapValues();
}
if (this.elementPlaceholder().length) {
this.testStep.element = elementValue
}
if (attributeValue) {
this.testStep.attribute = attributeValue
}
this.testStep.deserializeCommonProperties(this.actionForm.getRawValue());
return true;
} else {
return false;
}
}
selectTemplate() {
let template = this.filteredTemplate[this.currentFocusedIndex];
if (template instanceof NaturalTextActions) {
//this.selectedTemplate = undefined;
if (this.testStep.id) {
this.resetDataMap();
}
this.currentTemplate = template;
this.testStep.template = template;
setTimeout(() => {
this.resetCFArguments();
this.showTemplates = false;
if (template instanceof NaturalTextActions)
this.setTemplate(template);
}, 100);
} else {
this.selectAddonTemplate(template)
}
}
setTemplate(template: NaturalTextActions) {
if (template) {
delete this.currentAddonTemplate;
this.resetDataMap();
this.replacer.nativeElement.innerHTML = template.htmlGrammar;
this.currentTemplate = template;
this.attachActionTemplatePlaceholderEvents();
}
}
selectAddonTemplate(template) {
delete this.currentTemplate;
//this.selectedTemplate = undefined;
if (this.testStep.id) {
//this.resetDataMap();
}
this.testStep.addonTemplate = template;
setTimeout(() => {
//this.resetCFArguments();
this.showTemplates = false;
this.setAddonTemplate(template);
}, 100);
}
setAddonTemplate(template: AddonNaturalTextAction) {
if (template) {
//this.resetDataMap();
this.currentAddonTemplate = template;
this.replacer.nativeElement.innerHTML = template.htmlGrammar;
this.attachActionTemplatePlaceholderEvents();
}
}
setLastChildFlex() {
let childNodes = this.replacer.nativeElement.childNodes
if (!(childNodes[childNodes.length - 1]?.nodeType == Node.TEXT_NODE)) {
let child = this.replacer.nativeElement.querySelectorAll('div.actiontext span');
child[child.length - 1]?.classList.add('action-flex-auto')
}
}
attachActionTemplatePlaceholderEvents() {
setTimeout(() => {
this.attachElementEvent();
this.attachTestDataEvent();
this.isAttachTestDataEvent = true;
this.attachAttributeEvent();
//this.appropriatePopup();
this.setCursorAtTestData();
this.setLastChildFlex();
}, 300);
}
elementPlaceholder() {
return this.replacer.nativeElement.querySelectorAll('div.actiontext span.element');
}
attachElementEvent() {
if (this.elementPlaceholder()?.length) {
this.elementPlaceholder().forEach(item => {
item.addEventListener('click', (event) => {
this.showTemplates = false;
this.resetValidation();
this.openElementsPopup(event?.target);
event.stopPropagation();
this.showTemplates = false;
});
item.addEventListener('paste', (event) => {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
const text = (event.originalEvent || event).clipboardData.getData('text/plain');
window.document.execCommand('insertText', false, text);
})
})
}
}
testDataPlaceholder() {
if (this.currentTemplate?.allowedValues) {
return this.replacer?.nativeElement?.querySelectorAll('div.actiontext span.selected_list');
} else {
return this.replacer?.nativeElement?.querySelectorAll('div.actiontext span.test_data');
}
}
attachTestDataEvent() {
if (this.testDataPlaceholder()?.length) {
this.currentTestDataType = this.testStep?.testDataType || this.currentTestDataType || TestDataType.raw;
console.log('attaching test data events');
this.currentAddonAllowedValues = undefined
this.testDataPlaceholder().forEach((item, index) => {
item.addEventListener('click', (event) => {
this.isCurrentDataTypeRaw = false;
console.log('test data click event triggered');
this.getAddonTemplateAllowedValues(item.dataset?.reference)
this.currentDataTypeIndex = 0;
item.contentEditable = true;
this.currentDataItemIndex = index;
this.replacer.nativeElement.contentEditable = false;
this.resetValidation();
if (!this.removeHtmlTags(item?.textContent).trim().length)
this.showDataDropdown();
else
this.showTemplates = false;
event.stopPropagation();
event.stopImmediatePropagation();
return false;
});
item.addEventListener('keydown', (event) => {
console.log('test data keydown event triggered');
this.getAddonTemplateAllowedValues(item.dataset?.reference);
let value = item?.textContent;
let testDataType = ['@|', '!|', '~|', '$|', '*|'].some(type => item?.textContent.includes(type))
if (["Escape", "Tab"].includes(event.key))
this.showDataTypes = false;
if (event.key == "ArrowUp" && this.currentDataTypeIndex != 0)
--this.currentDataTypeIndex;
if (event.key == "ArrowDown" && this.currentDataTypeIndex < this.dataTypes.length - 1)
++this.currentDataTypeIndex;
if (event.key == "Enter") {
this.currentDataItemIndex = index;
this.selectTestDataType(TestDataType[this.dataTypes[this.currentDataTypeIndex]]);
setTimeout(() => {
item.innerHTML = this.removeHtmlTags(item?.textContent);
}, 100)
}
if (value?.trim()?.length && testDataType &&
(value?.trim()?.match(/\|/g) || []).length == 1 &&
!(event.key == "Backspace" || event.key == "ArrowLeft" || event.key == "ArrowRight")) {
this.selectDataType(value)
}
this.localUrlValid = -1;
this.localUrlVerifying = false;
this.urlPatternError = false;
event.stopPropagation();
event.stopImmediatePropagation();
return false;
});
item.addEventListener('keyup', (event) => {
console.log('test data keyup event triggered');
this.getAddonTemplateAllowedValues(item.dataset?.reference);
this.urlPatternError = false;
let testDataType = ['@|', '!|', '~|', '$|', '*|'].some(type => item?.textContent.includes(type))
if (event.key == "Backspace") {
this.selectDataType(item?.textContent, true)
}
if ((!testDataType && this.removeHtmlTags(item?.textContent).trim().length) || (!(["Escape", "Tab", "Backspace", "ArrowLeft", "ArrowRight", "Enter", "ArrowUp", "ArrowDown", "Shift", "Control", "Meta", "Alt"].includes(event.key)) && item?.textContent)) {
this.showDataTypes = false;
} else if (!this.removeHtmlTags(item?.textContent).trim().length) {
this.showDataTypes = true;
}
if (event.key == "Backspace" && !this.removeHtmlTags(item?.textContent).trim().length) {
this.showDataDropdown();
}
event.stopPropagation();
event.stopImmediatePropagation();
return false;
})
// this.testDataPlaceholder().addEventListener('mouseleave', (event) => {
// if(this.testDataPlaceholder()?.textContent.length) {
// let testDataType = ['@|', '!|', '~|', '$|', '*|', '%|'].some(type => this.testDataPlaceholder()?.textContent.includes(type))
// if (this.currentTemplate && this.navigateTemplate.includes(this.currentTemplate.id) && !testDataType) {
// fromEvent(this.replacer.nativeElement, 'mouseleave')
// .pipe(tap((event) => {
// if(this.testDataPlaceholder()?.innerHTML?.length && this.currentTestDataType == TestDataType.raw)
// this.testDataPlaceholder().blur()
// })).subscribe()
//
// this.navigateUrlValidation();
// }
// }
// event.stopPropagation();
// event.stopImmediatePropagation();
// })
item.addEventListener('paste', (event) => {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
const text = (event.originalEvent || event).clipboardData.getData('text/plain');
window.document.execCommand('insertText', false, text);
})
item.addEventListener('dblclick', (event) => {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
this.currentDataItemIndex = index;
this.selectTestDataPlaceholder();
})
})
}
}
selectDataType(value, isSkipSelect?: boolean) {
let dataType = TestDataType.raw;
if (value?.trim()?.match(/@\|(.?)\||@\|(.+?)\|/g)) {
dataType = TestDataType.parameter;
} else if (value?.trim()?.match(/!\|(.?)\||!\|(.+?)\|/g)) {
dataType = TestDataType.function
} else if (value?.trim()?.match(/~\|(.?)\||~\|(.+?)\|/g)) {
dataType = TestDataType.random;
} else if (value?.trim()?.match(/\$\|(.?)\||\$\|(.+?)\|/g)) {
dataType = TestDataType.runtime;
}
this.selectTestDataType(dataType, false, isSkipSelect)
}
removeHtmlTags(value) {
return value.replace(/<br>/g, "").replace(/<div>/g, "").replace(/<\/div>/g, "")
}
scrollUpTemplateFocus() {
if (this.currentFocusedIndex)
--this.currentFocusedIndex;
let target = <HTMLElement>document.querySelector(".h-active");
target.parentElement.scrollTop = target.offsetTop - target.parentElement.offsetTop;
}
scrollDownTemplateFocus() {
if (this.currentFocusedIndex >= this.filteredTemplates.length - 1)
return;
++this.currentFocusedIndex;
let target = <HTMLElement>document.querySelector(".h-active");
target.parentElement.scrollTop = target.offsetTop - target.parentElement.offsetTop;
}
attributePlaceholder() {
return this.replacer.nativeElement.querySelector('div.actiontext span.attribute');
}
attachAttributeEvent() {
if (this.attributePlaceholder()) {
this.attributePlaceholder().addEventListener('click', (event) => {
this.attributePlaceholder().contentEditable = true;
this.replacer.nativeElement.contentEditable = false;
this.showDataTypes = false;
event.stopPropagation();
event.stopImmediatePropagation();
return false;
});
this.attributePlaceholder().addEventListener('keydown', (event) => {
if (event.key == "Enter") {
setTimeout(() => {
this.attributePlaceholder().innerHTML = this.removeHtmlTags(this.attributePlaceholder().textContent);
}, 100)
}
event.stopPropagation();
event.stopImmediatePropagation();
return false;
});
this.attributePlaceholder().addEventListener('paste', (event) => {
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
const text = (event.originalEvent || event).clipboardData.getData('text/plain');
window.document.execCommand('insertText', false, text);
})
}
}
inputType(displayName) {
let type = 'text';
if (displayName == 'int') {
type = 'number'
}
return type;
}
selectTestDataType(type, isFromHtml?: boolean, isSkipSelect?: boolean) {
this.resetCFArguments();
this.resetTestData();
this.currentTestDataFunction = undefined;
this.currentTestDataType = type;
this.showDataTypes = false;
this.isCurrentDataTypeRaw = false;
switch (type) {
case TestDataType.parameter:
this.assignDataValue("@| |")
if (!this.testCase.isStepGroup || this.testStep.getParentLoopDataId(this.testStep, this.testCase))
this.openSuggestionDataProfile()
else if (this.testCase.isStepGroup)
this.assignDataValue("@| |")
break;
case TestDataType.function:
this.assignDataValue("!| |")
this.openSuggestionTestDataFunction()
break;
case TestDataType.environment:
this.assignDataValue("*| |")
this.openSuggestionEnvironment()
break;
case TestDataType.raw:
if (isFromHtml)
this.isCurrentDataTypeRaw = true
this.assignDataValue("")
if (!isSkipSelect)
this.selectTestDataPlaceholder();
break;
case TestDataType.runtime:
this.assignDataValue("$| <span class='test_data_place'></span> |");
break;
case TestDataType.random:
this.assignDataValue("~| <span class='test_data_place'></span> |");
break;
}
}
selectAllowedValues(allowedValue, isFromHtml?: boolean, isSkipSelect?: boolean) {
this.resetCFArguments();
this.resetTestData();
this.currentTestDataType = TestDataType.raw;
this.assignDataValue(this.getDataTypeString(TestDataType.raw, allowedValue));
}
setCursorAtTestData() {
this.skipFocus = true;
let element = this.testDataPlaceholder()[this.currentDataItemIndex || 0];
if (!element) {
this.setCursorAtAttribute();
this.skipFocus = false;
return;
}
this.selectNodeAndFocus(element);
}
setCursorAtAttribute() {
this.skipFocus = true;
let element = this.attributePlaceholder();
if (!element) {
this.skipFocus = false;
return;
}
this.selectNodeAndFocus(element);
}
selectNodeAndFocus(node) {
try {
let range = document.createRange();
range.selectNodeContents(node);
let sel = window.getSelection();
sel.removeAllRanges();
range.setStart(node, 0);
range.setEnd(node, 1);
node.focus()
range.collapse(false);
sel.addRange(range);
this.skipFocus = false;
range.selectNodeContents(node);
node.click();
node.focus();
} catch (e) {
if (node.className.indexOf("test_data") > -1) {
node.focus();
}
this.skipFocus = false;
}
}
setTempPosition() {
let element = this.replacer.nativeElement.querySelector('div.actiontext span span.test_data_place');
this.replacer.nativeElement.contentEditable = false;
element.contentEditable = true;
this.setMeddlePosition(element);
}
setMeddlePosition(element) {
let range = document.createRange();
range.selectNodeContents(element);
let sel = window.getSelection();
sel.removeAllRanges();
range.setEnd(element, 0);
element.focus()
range.collapse(true);
sel.addRange(range);
}
selectTestDataPlaceholder() {
let range = document.createRange();
range.selectNodeContents(this.testDataPlaceholder()[this.currentDataItemIndex]);
let sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
this.testDataPlaceholder()[this.currentDataItemIndex].contentEditable = true;
this.replacer.nativeElement.contentEditable = false;
this.testDataPlaceholder()[this.currentDataItemIndex].focus();
}
private assignEditTemplate() {
if (this.testStep?.testDataType == TestDataType.function) {
if (this.testStep?.testDataFunctionId)
this.showTestDataCF(this.testStep?.testDataFunctionId);
else if (this.testStep?.testDataFunctionId) {
this.showAddonTDF(this.testStep?.testDataFunctionId);
this.editSerialize();
}
} else {
this.editSerialize()
}
}
showAddonTDF(id: number) {
this.addonTestDataFunctionService.show(id).subscribe(res => {
this.currentAddonTDF = res;
this.assignTDFData(res);
})
}
getAddonActionData(map: Map<string, any>) {
let result = [];
Object.keys(map).forEach(key => {
result.push(map[key]);
});
return result;
}
private editSerialize() {
if (this.testStep.addonTemplate) {
this.replacer.nativeElement.innerHTML = this.testStep?.parsedAddonStep;
this.setAddonTemplate(this.testStep.addonTemplate);
if (this.testStep.addonElements) {
const elementPlaceHolders = this.elementPlaceholder();
let index = 0;
for (const key in this.testStep.addonElements) {
this.assignElement(this.testStep.addonElements[key].name, elementPlaceHolders[index++]);
}
}
if (this.testStep.addonTestData) {
const testDataPlaceHolders = this.testDataPlaceholder();
let index = 0;
testDataPlaceHolders.forEach(item => {
let reference = item.dataset?.reference;
const dataName = this.getDataTypeString(this.testStep.addonTestData[reference].type, this.testStep.addonTestData[reference].value);
if (dataName) {
let item = testDataPlaceHolders[index++];
if (item?.contentEditable) {
item.innerHTML = dataName;
}
item.setAttribute("data-test-data-type", this.testStep.addonTestData[reference].type);
}
})
}
} else {
if (this.testStep?.template?.htmlGrammar) {
this.replacer.nativeElement.innerHTML = this.testStep?.template?.htmlGrammar;
this.showTemplates = false;
this.currentTemplate = this.testStep.template;
if (this.testStep?.element)
this.assignElement(this.testStep?.element, this.elementPlaceholder()[0]);
if (this.testStep?.testDataVal)
this.assignDataValue(this.getDataTypeString(this.testStep?.testDataType, this.testStep?.testDataVal));
if (this.attributePlaceholder())
this.attributePlaceholder().innerHTML = this.testStep?.attribute;
this.attachActionTemplatePlaceholderEvents();
}
else
this.replacer.nativeElement.innerHTML = this.testStep?.action;
}
}
private showTestDataCF(id) {
this.testDataFunctionService.show(id).subscribe(res => {
this.currentTestDataFunction = res
this.editSerialize();
this.assignCFData(res?.arguments, this.testStep?.testDataFunctionArgs)
})
}
swapPlaceholder() {
this.animatedPlaceholder = this.animatedPlaceholder ? this.animatedPlaceholder : this.placeholders[0];
setTimeout(() => {
this.replacer.nativeElement.classList.add('placeholder-animate');
}, 1500)
setTimeout(() => {
let placeholderChanged = false;
this.placeholders.forEach((placeholder, index) => {
if (this.animatedPlaceholder == placeholder && !placeholderChanged) {
this.replacer.nativeElement.classList.remove('placeholder-animate');
setTimeout(() => {
this.animatedPlaceholder = this.placeholders[index + 1];
placeholderChanged = true;
}, 100)
}
})
this.swapPlaceholder();
}, 3000)
}
// private appropriatePopup() {
// if (this.elementPlaceholder()) {
// this.elementPlaceholder().click();
// } else if (this.testDataPlaceholder()) {
// this.testDataPlaceholder().click();
// this.selectTestDataPlaceholder();
// } else if(this.attributePlaceholder()) {
// this.attributePlaceholder().click();
// }
// }
private openElementsPopup(targetElement?) {
if (this.popupsAlreadyOpen(ActionElementSuggestionComponent)) return;
this.elementSuggestion = this.matModal.open(ActionElementSuggestionComponent, {
height: "100vh",
width: '40%',
position: {top: '0', right: '0'},
panelClass: ['mat-dialog', 'rds-none'],
data: {
version: this.version,
testCase: this.testCase,
testCaseResultId: this.testCaseResultId,
isDryRun: this.isDryRun,
isStepRecordView: this.stepRecorderView
},
...this.alterStyleIfStepRecorder(),
});
let afterClose = (element) => {
if (element) {
let name = typeof element == "string" ? element : element.name;
this.assignElement(name, targetElement);
}
}
if (this.stepRecorderView) {
this.resetPositionAndSize(this.elementSuggestion, ActionElementSuggestionComponent, afterClose);
} else
this.elementSuggestion.afterClosed().subscribe(element => afterClose(element));
}
private assignElement(elementName, targetElement?) {
this.showTemplates = false;
if (elementName) {
if (elementName && elementName.length)
targetElement.innerHTML = elementName;
if (this.testDataPlaceholder()?.length && !this.isEdit) {
this.testDataPlaceholder()?.[this.currentDataItemIndex || 0]?.click();
this.selectTestDataPlaceholder();
}
}
}
private assignDataValue(dataName) {
this.showDataTypes = false;
const testDataPlaceHolders = this.testDataPlaceholder();
for (let i = 0; i < testDataPlaceHolders.length; i++) {
const content = testDataPlaceHolders[i].innerHTML;
if (testDataPlaceHolders[i]?.contentEditable && ((testDataPlaceHolders[i].getAttribute("data-test-data-type") == null) ||
((testDataPlaceHolders[i].getAttribute("data-test-data-type") != null && (content == '@| |' || content == '!| |' || content == '*| |'
|| content == "$| <span class='test_data_place'></span> |" || content == "~| <span class='test_data_place'></span> |" || content == "" || !this.removeHtmlTags(testDataPlaceHolders[i].textContent).trim().length))))) {
testDataPlaceHolders[i].innerHTML = dataName;
testDataPlaceHolders[i].setAttribute("data-test-data-type", this.currentTestDataType);
break;
}
}
if (dataName.startsWith('~|') || dataName.startsWith('$|')) {
this.setTempPosition()
}
}
private resetDataMap() {
this.resetTestData();
delete this.currentTestDataType;
this.resetTestDataValues();
delete this.testStep['attribute'];
delete this.testStep['element'];
delete this.testStep['addonElements'];
}
private resetTestData() {
delete this.testStep['testDataVal'];
delete this.testStep['testDataType'];
delete this.testStep['testDataFunctionId'];
delete this.testStep['testDataFunctionArgs'];
delete this.testStep['addonTestData'];
delete this.testStep['addonTDF'];
}
private resetCFArguments() {
this.argumentList = undefined;
this.displayNames = undefined;
}
private openSuggestionTestDataFunction() {
if (this.popupsAlreadyOpen(ActionTestDataFunctionSuggestionComponent)) return;
this.testDataFunctionSuggestion = this.matModal.open(ActionTestDataFunctionSuggestionComponent, {
height: "100vh",
width: '30%',
position: {top: '0', right: '0'},
panelClass: ['mat-dialog', 'rds-none'],
...this.alterStyleIfStepRecorder(),
data: {version: this.version?.id}
});
let afterClose = (data) => {
if (data) {
if (data instanceof AddonTestDataFunction) {
this.assignTDFData(data);
} else {
this.currentTestDataFunction = data;
this.assignCFData(data.arguments);
this.assignDataValue(this.getDataTypeString(TestDataType.function, data.classDisplayName + " :: " + data.displayName))
}
} else if (!data) {
delete this.currentTestDataType
this.showTestDataPopup()
}
}
if (this.stepRecorderView) {
this.resetPositionAndSize(this.testDataFunctionSuggestion, ActionTestDataFunctionSuggestionComponent, afterClose);
} else
this.testDataFunctionSuggestion.afterClosed().subscribe(data => afterClose(data));
}
addTDFControls(argumentList) {
const arr = Object.keys(this.actionForm.controls);
arr.forEach((con) => {
if (!(con == 'action')) {
this.actionForm.removeControl(con);
}
})
if (argumentList.length) {
argumentList.forEach(argument => {
this.actionForm.addControl(argument.reference, new FormControl(
this.testStep?.addonTestData ? this.testStep?.addonTestData[argument.reference] :
this.testStep?.addonTestData ? this.testStep?.testDataFunctionArgs[argument.reference] : undefined));
})
} else {
this.setAddonTestDataValues(this.currentAddonTDF.id)
}
}
isEmptyObject(obj) {
return obj && Object.keys(obj).length == 0;
}
private assignTDFData(data) {
this.currentAddonTDF = data;
this.currentTestDataFunctionParameters = data.parameters;
this.assignDataValue(this.getDataTypeString(TestDataType.function, data.displayName))
this.addTDFControls(data.parameters);
}
addCFControls(argumentList, values?) {
const arr = Object.keys(this.actionForm.controls);
arr.forEach((con) => {
if (!(con == 'action')) {
this.actionForm.removeControl(con);
}
})
let argumentKeys = Object.keys(argumentList);
argumentKeys.forEach(argument => {
this.actionForm.addControl(argument, new FormControl(values ? values[argument] : undefined));
})
}
private assignCFData(dataArguments, values?) {
this.addCFControls(dataArguments['display_names'], values);
this.argumentList = dataArguments['arg_types'];
this.displayNames = dataArguments['display_names'];
if (!this.isEmptyObject(this.argumentList))
this.setFocus();
else
this.setTestDataFunctionToDom();
}
setFocus() {
if (this.displayNamesContainer?.nativeElement) {
this.displayNamesContainer.nativeElement?.querySelector('div input.autofocus')?.focus();
} else {
setTimeout(() => {
this.setFocus()
}, 100)
}
}
private openSuggestionDataProfile() {
if (this.popupsAlreadyOpen(ActionTestDataParameterSuggestionComponent)) return;
this.dataProfileSuggestion = this.matModal.open(ActionTestDataParameterSuggestionComponent, {
height: "100vh",
width: '35%',
position: {top: '0', right: '0'},
panelClass: ['mat-dialog', 'rds-none'],
...this.alterStyleIfStepRecorder(),
data: {
dataProfileId: this.testStep.getParentLoopDataId(this.testStep, this.testCase),
versionId: this.version?.id,
testCaseId: this.testCase?.id,
stepRecorderView: Boolean(this.stepRecorderView),
}
});
let afterClose = (data) => {
if (data)
this.assignDataValue(this.getDataTypeString(TestDataType.parameter, data));
else {
this.currentTestDataType = TestDataType.raw;
this.showTestDataPopup()
}
}
if (this.stepRecorderView) {
this.resetPositionAndSize(this.dataProfileSuggestion, ActionTestDataParameterSuggestionComponent, afterClose);
} else
this.dataProfileSuggestion.afterClosed().subscribe(data => afterClose(data));
}
private openSuggestionEnvironment() {
if (this.popupsAlreadyOpen(ActionTestDataEnvironmentSuggestionComponent)) return;
this.environmentSuggestion = this.matModal.open(ActionTestDataEnvironmentSuggestionComponent, {
height: "100vh",
width: '30%',
position: {top: '0', right: '0'},
panelClass: ['mat-dialog', 'rds-none'],
data: {
versionId: this.version?.id,
stepRecorderView: Boolean(this.stepRecorderView),
}
});
let afterClose = (data) => {
data = data || ' ';
this.assignDataValue(this.getDataTypeString(TestDataType.environment, data));
if (data == ' ') {
this.showTestDataPopup()
}
}
if (this.stepRecorderView) {
this.resetPositionAndSize(this.environmentSuggestion, ActionTestDataEnvironmentSuggestionComponent, afterClose);
} else
this.environmentSuggestion.afterClosed().subscribe(data => afterClose(data));
}
private showTestDataPopup() {
this.showDataTypes = true;
this.testDataPlaceholder()[this.currentDataItemIndex].click();
this.testDataPlaceholder()[this.currentDataItemIndex].focus();
}
private getDataTypeString = (type, name) => {
let testDataString = name;
switch (type) {
case TestDataType.random:
testDataString = "~|<span class='test_data_place'>" + testDataString + "</span>|";
break;
case TestDataType.runtime:
testDataString = "$|<span class='test_data_place'>" + testDataString + "</span>|";
break;
case TestDataType.function:
testDataString = "!|" + testDataString + "|";
break;
case TestDataType.parameter:
testDataString = "@|" + testDataString + "|";
break;
case TestDataType.environment:
testDataString = "*|" + testDataString + "|";
break;
}
return testDataString;
};
public urlPatternError: boolean = false;
public navigateUrlValidation() {
this.currentDataItemIndex = this.currentDataItemIndex || 0;
if (
this.lastActionNavigateUrl != this.testDataPlaceholder()[this.currentDataItemIndex]?.textContent &&
this.currentTestDataType == TestDataType.raw &&
this.testDataPlaceholder()[this.currentDataItemIndex]?.innerHTML?.length &&
this.navigateTemplate.includes(this.currentTemplate?.id)) {
this.lastActionNavigateUrl = this.testDataPlaceholder()[this.currentDataItemIndex]?.textContent;
let cloudUrlExpression = /(?:^|\s)((https?:\/\/)?(?:localhost|[\w-]+(?:\.[\w-]+)+)(:\d+)?(\/\S*)?)/;
let localUrlExpression = /^(http[s]?:\/\/)[a-zA-Z0-9.\-:\/]?/;
if (cloudUrlExpression.test(this.testDataPlaceholder()[this.currentDataItemIndex]?.textContent)) {
this.localUrlValid = -1;
this.localUrlVerifying = true;
this.testCaseService.validateNavigationUrls(this.testCase.id, this.testDataPlaceholder()[this.currentDataItemIndex]?.textContent).subscribe(res => {
this.localUrlValid = res.length;
this.localUrlVerifying = false;
}, error => {
this.translate.get('action.step.message.localUrl.fetching_failed', {URL: this.testDataPlaceholder()[this.currentDataItemIndex]?.textContent}).subscribe((res) => {
this.showAPIError(error, res);
this.localUrlValid = -1;
this.localUrlVerifying = false;
})
})
} else if (!localUrlExpression.test(this.testDataPlaceholder()[this.currentDataItemIndex]?.textContent)) {
this.urlPatternError = true
}
}
}
public setAddonTestDataValues(customFunctionId) {
this.testDataPlaceholder().forEach((item, index) => {
if (this.currentDataItemIndex != index)
return
let formValue = this.actionForm.getRawValue();
if (item.getAttribute("data-test-data-type") || item.getAttribute('data-test-data-function-id')) {
item.setAttribute('data-test-data-function-id', customFunctionId)
let args: JSON = formValue;
let argsArray = new Map<String, String>();
delete formValue.action
for (let argsKey in args) {
argsArray[argsKey] = args[argsKey];
}
item.setAttribute('data-test-data-function-arguments', JSON.stringify(argsArray));
item.setAttribute('data-is-addon-fn', true);
}
});
this.currentTestDataFunctionParameters = null;
this.currentAddonTDF = null;
}
public setTestDataValues(customFunctionId) {
this.testDataPlaceholder().forEach((item, index) => {
if (this.currentDataItemIndex != index)
return
let formValue = this.actionForm.getRawValue();
if (item.getAttribute("data-test-data-type") || item.getAttribute('data-test-data-function-id')) {
item.setAttribute('data-test-data-function-id', customFunctionId)
let args: JSON = this.getArguments(formValue);
let argsArray = new Map<String, String>();
delete formValue.action
for (let argsKey in args) {
argsArray[argsKey] = args[argsKey];
}
item.setAttribute('data-test-data-function-arguments', JSON.stringify(argsArray));
item.setAttribute('data-is-addon-fn', false);
}
});
this.currentTestDataFunctionParameters = null;
this.currentAddonTDF = null;
this.resetCFArguments();
}
public resetTestDataValues() {
this.testDataPlaceholder().forEach((item) => {
item.removeAttribute('data-is-addon-fn');
item.removeAttribute('data-test-data-function-arguments');
item.removeAttribute('data-test-data-type');
item.removeAttribute('data-test-data-function-id');
})
}
public setTestDataFunctionToDom() {
this.setTestDataValues(this.currentTestDataFunction.id);
this.resetCFArguments();
}
private setDataMapValues() {
this.testStep.testDataType = this.currentTestDataType;
if (this.currentTestDataType && this.currentTestDataType == TestDataType.function && this.currentTestDataFunction) {
let formValue = this.actionForm.getRawValue();
delete formValue.action
let testDataFunction = new TestStepTestDataFunction();
testDataFunction.id = this.currentTestDataFunction.id;
testDataFunction.function = this.currentTestDataFunction.functionName;
testDataFunction.class = this.currentTestDataFunction.className;
testDataFunction.argsTypes = this.argumentList || {};
testDataFunction.args = this.getArguments(formValue);
testDataFunction.type = this.currentTestDataFunction.arguments['fun_type'];
testDataFunction.package = this.currentTestDataFunction.classPackage;
this.testStep.testDataFunctionId = this.currentTestDataFunction.id;
this.testStep.testDataFunctionArgs = this.getArguments(formValue);
} else if (this.currentTestDataType && this.currentTestDataType == TestDataType.function && this.currentAddonTDF) {
let formValue = this.actionForm.getRawValue();
delete formValue.action
let testData = new AddonTestStepTestData();
testData.testDataFunctionArguments = formValue;
testData.testDataFunctionId = this.currentAddonTDF.id;
testData.value = this.currentAddonTDF.displayName;
testData.type = this.currentTestDataType;
this.testStep.addonTDF = testData;
}
}
getArguments(formValue): JSON {
let returnObj = {};
Object.keys(formValue).forEach(item => {
if (item.includes('arg'))
returnObj[item] = formValue[item]
})
return <JSON>returnObj;
}
get inValidParameter() {
return !!!this.isValidTestData ? 'Test Data' : !!!this.isValidElement ? 'Element' : !!!this.isValidAttribute ? 'Attribute' : false;
}
get filteredTemplate() {
this.filteredTemplates = this.filteredTemplates.filter(template => template.displayName !== 'breakLoop' && template.displayName !== 'continueLoop');
let returnData = [...this.filteredTemplates, ...this.filteredAddonTemplates];
if (this.testStep.conditionType === TestStepConditionType.CONDITION_IF ||
this.testStep.conditionType === TestStepConditionType.CONDITION_ELSE_IF) {
returnData = returnData.filter(template => template.stepActionType === StepActionType.IF_CONDITION);
} else if (this.testStep.conditionType === TestStepConditionType.LOOP_WHILE) {
returnData = returnData.filter(template => template.stepActionType === StepActionType.WHILE_LOOP);
} else {
returnData = returnData.filter(template => !(template.stepActionType === StepActionType.WHILE_LOOP ||
template.stepActionType === StepActionType.IF_CONDITION));
}
return returnData;
}
onDocumentClick(event) {
if (this._eref.nativeElement.contains(event.target))
return;
this.showTemplates = false;
this.currentFocusedIndex = 0;
this.showDataTypes = false;
if ((!this.currentTestDataType || this.currentTestDataType == TestDataType.raw) && !this.isCurrentDataTypeRaw && this.testDataPlaceholder()?.length && !this.testDataPlaceholder()[this.currentDataItemIndex]?.innerHTML?.length) {
this.testDataPlaceholder()[this.currentDataItemIndex || 0].innerHTML = "test data";
}
}
subscribeMobileRecorderEvents() {
if (this.stepRecorderView) {
this.mobileRecorderEventService.getStepRecorderEmitter().subscribe(res => {
this.populateAndSaveFromRecorder(res)
});
}
}
private populateAndSaveFromRecorder(testStep: TestStep) {
if (this.eventEmitterAlreadySubscribed ||
(this.mobileStepRecorder.stepList.editedStep && this.mobileStepRecorder.stepList.editedStep.id != this.testStep.parentId)) return;
let currentStep: TestStep = new TestStep();
Object.assign(currentStep, this.testStep);
if (this.testStep.position == 0) {
testStep.testCaseId = currentStep.testCaseId;
testStep.position = testStep.position || currentStep.position;
testStep.testCaseId = this.testCase.id;
testStep.conditionIf = this.actionForm.getRawValue()?.conditionIf ? this.actionForm.getRawValue()?.conditionIf : [ResultConstant.SUCCESS];
this.saveFromRecorder(testStep);
} else {
testStep.conditionIf = this.actionForm.getRawValue()?.conditionIf ? this.actionForm.getRawValue()?.conditionIf : [ResultConstant.SUCCESS];
this.testStep = testStep;
this.testStep.position = testStep.position || currentStep.position;
this.testStep.testCaseId = this.testCase.id;
this.saveFromRecorder(this.testStep)
}
this.eventEmitterAlreadySubscribed = true;
}
private saveFromRecorder(testStep: TestStep) {
this.formSubmitted = true;
this.saving = true; // TODO - step in the list , should be the assigned this value // this.testStep = Object.assign(this.testStep, step);//new TestStep().deserialize(step.serialize());
this.testStepService.create(testStep).subscribe(step => this.afterSave(step), e => this.handleSaveFailure(e));
}
private afterSave(step: TestStep) {
if (step.addonActionId) {
step.addonTemplate = this.testStep.addonTemplate
} else {
step.template = this.testStep.template;
}
step.parentStep = this.testStep.parentStep;
step.siblingStep = this.testStep.siblingStep;
step.action = this.testStep.action;
step.stepDisplayNumber = this.testStep.stepDisplayNumber;
if (Boolean(this.stepRecorderView)) {
this.matModal.openDialogs?.find(dialog => dialog.componentInstance instanceof TestStepMoreActionFormComponent)?.close();
}
this.actionForm.reset();
this.onSave.emit(step);
this.saving = false;
this.addActionStepAfterSwitch();
}
addActionStepAfterSwitch() {
setTimeout(() => {
if (Boolean(this.stepRecorderView) && this.mobileStepRecorder.addActionStepAfterSwitch) {
this.mobileStepRecorder.createStep(this.mobileStepRecorder.actionStep, true);
this.mobileStepRecorder.addActionStepAfterSwitch = false;
}
}, 1000)
}
private handleSaveFailure(err, isUpdate?) {
let msgKey = Boolean(isUpdate) ? 'message.common.update.failure' : 'message.common.created.failure';
this.showAPIError(err, this.translate.instant(msgKey, {FieldName: 'Test Step'}));
this.saving = false;
}
alterStyleIfStepRecorder() {
if (!this.stepRecorderView) return {};
let mobileStepRecorderComponent: MobileStepRecorderComponent = this.matModal.openDialogs.find(dialog => dialog.componentInstance instanceof MobileStepRecorderComponent).componentInstance;
let clients = {
height: mobileStepRecorderComponent.customDialogContainerH50.nativeElement.clientHeight + 'px',
width: mobileStepRecorderComponent.customDialogContainerH50.nativeElement.clientWidth + 'px',
position: {
top: mobileStepRecorderComponent.customDialogContainerH50.nativeElement.getBoundingClientRect().top + 'px',
left: mobileStepRecorderComponent.customDialogContainerH50.nativeElement.getBoundingClientRect().left + 'px'
},
hasBackdrop: false,
panelClass: ['modal-shadow-none', 'px-10']
}
return clients;
}
private resetPositionAndSize(matDialog: MatDialogRef<any>, dialogComponent: any, afterClose: (res?) => void) {
setTimeout(() => {
if (matDialog._containerInstance._config.height == '0px') {
let alterStyleIfStepRecorder = this.alterStyleIfStepRecorder();
matDialog.close();
matDialog = this.matModal.open(dialogComponent, {
...matDialog._containerInstance._config,
...alterStyleIfStepRecorder
});
matDialog.afterClosed().subscribe(res => afterClose(res));
} else {
matDialog.afterClosed().subscribe(res => afterClose(res));
}
}, 200)
}
private popupsAlreadyOpen(currentPopup) {
if (!Boolean(this.stepRecorderView)) return false;
this?.matModal?.openDialogs?.forEach(dialog => {
if ((dialog.componentInstance instanceof ActionElementSuggestionComponent ||
dialog.componentInstance instanceof ActionTestDataFunctionSuggestionComponent ||
dialog.componentInstance instanceof ActionTestDataParameterSuggestionComponent ||
dialog.componentInstance instanceof ActionTestDataEnvironmentSuggestionComponent ||
dialog.componentInstance instanceof TestStepMoreActionFormComponent ||
(dialog.componentInstance instanceof ActionElementSuggestionComponent &&
!(currentPopup instanceof ElementFormComponent)))
&& !(dialog.componentInstance instanceof currentPopup)) {
dialog.close();
}
})
return Boolean(this?.matModal?.openDialogs?.find(dialog => dialog.componentInstance instanceof currentPopup));
}
ngOnDestroy() {
this.eventEmitterAlreadySubscribed = true;
}
} | the_stack |
import "reflect-metadata";
type Constructor<T> = new (...args) => T;
type BeanId<T> = string | Constructor<T>;
type BeanDefinition = {
id?: BeanId<any>; // bean id
target: Constructor<any>; // 类
field?: string; // 字段名
method?: string; // 方法名
}
type AutowiredInfo = {
id: BeanId<any>; // 注入
target: Constructor<any>;
field?: string; // 字段名(如果@Autowired修饰类成员)
fieldType?: any; // 字段类型(如果@Autowired修饰类成员)
method?: string; // 方法名(如果@Autowired修饰方法参数)
paramIndex?: number; // 方法参数index(如果@Autowired修饰方法参数)
paramName?: string; // 方法参数名(如果@Autowired修饰方法参数)
paramType?: any; // 方法参数类型(如果@Autowired修饰方法参数)
}
export interface AfterInit {
afterInit();
}
function idStr(id: BeanId<any>) {
return typeof id === "string" ? id : id.name;
}
const beanDefinitions = new Map<BeanId<any>, BeanDefinition>();
function addBeanDefinition(beanDefinition: BeanDefinition) {
let id = beanDefinition.id;
if (id == null) {
if (beanDefinition.method != null) {
id = beanDefinition.method;
}
else if (beanDefinition.field != null) {
id = beanDefinition.field;
}
else {
id = beanDefinition.target;
}
}
beanDefinition.id = id;
const existedBeanDefinition = beanDefinitions.get(id);
if (existedBeanDefinition) {
if (existedBeanDefinition.id !== beanDefinition.id
|| existedBeanDefinition.target !== beanDefinition.target
|| existedBeanDefinition.field !== beanDefinition.field
|| existedBeanDefinition.method !== beanDefinition.method) {
throw new Error("duplicate Bean(" + idStr(id) + ")");
}
}
else {
beanDefinitions.set(id, beanDefinition);
}
}
export function Bean(id?: string) {
return function (target: any, fieldOrMethod?: string, descriptor?: any) {
if (target.constructor.name === "function") {
throw new Error("cannot decorate static field/method with Bean");
}
if (descriptor) {
// 方法
addBeanDefinition({
id: id,
target: target.constructor,
method: fieldOrMethod
});
return descriptor;
}
else if (fieldOrMethod) {
// 字段
addBeanDefinition({
id: id,
target: target.constructor,
field: fieldOrMethod
});
}
else {
// 类
addBeanDefinition({
id: id,
target: target
});
}
};
}
const autowiredInfos = new Map<Constructor<any>, AutowiredInfo[]>();
function addAutowiredInfo(autowiredInfo: AutowiredInfo) {
let id = autowiredInfo.id;
if (id == null) {
autowiredInfo.id = autowiredInfo.field || autowiredInfo.paramName;
}
let targetDepends = autowiredInfos.get(autowiredInfo.target);
if (!targetDepends) {
targetDepends = [];
autowiredInfos.set(autowiredInfo.target, targetDepends);
}
targetDepends.push(autowiredInfo);
}
export function Autowired(id?: BeanId<any>) {
return function (target: any, fieldOrMethod: string, paramIndex?: number) {
if (target.constructor.name === "function") {
throw new Error("cannot decorate static field with Autowired");
}
else if (fieldOrMethod == null || (target.prototype != null && typeof target.prototype[fieldOrMethod] == "function")) {
throw new Error("cannot decorate class or method with Autowired");
}
if (typeof paramIndex === "number") {
const methodDesc = target[fieldOrMethod].toString();
const params = methodDesc.substring(fieldOrMethod.length + 1, methodDesc.indexOf(") {")).split(", ");
const paramTypes = Reflect.getMetadata('design:paramtypes', target, fieldOrMethod);
addAutowiredInfo({
id: id,
target: target.constructor,
method: fieldOrMethod,
paramIndex: paramIndex,
paramName: params[paramIndex],
paramType:paramTypes[paramIndex]
});
}
else {
const fieldType = Reflect.getMetadata('design:type', target, fieldOrMethod);
addAutowiredInfo({
id: id,
target: target.constructor,
field: fieldOrMethod,
fieldType: fieldType
});
}
};
}
const beans = new Map<BeanId<any>, any>();
export function getBean<T>(id: BeanId<T>, createBeanDefinitionIfNotExisted: boolean = false): T {
let bean = beans.get(id);
if (bean === undefined) {
if (beanDefinitions.has(id)) {
bean = initBean(id);
}
else if (createBeanDefinitionIfNotExisted && typeof id === "function") {
addBeanDefinition({
id: id,
target: id
});
bean = initBean(id);
}
else {
throw new Error("Bean(" + idStr(id) + ") is not defined");
}
}
return bean;
}
export function findBean<T>(id: BeanId<T>, type: any) {
// 首先通过id去查找
try {
const beanIns = getBean(id, true);
if (beanIns) {
return beanIns;
}
}
catch (e) {
}
// 如果没有找到,通过 type 匹配 beanDefinitions,如果匹配到多个,抛出异常
const beanDefinitionsForType: BeanDefinition[] = [];
for (let entry of beanDefinitions.entries()) {
const beanDefinition = entry[1];
if (beanDefinition.target == type && !beanDefinition.field && !beanDefinition.method) {
beanDefinitionsForType.push(beanDefinition);
}
}
if (beanDefinitionsForType.length == 1) {
return getBean(beanDefinitionsForType[0].id);
}
else if (beanDefinitionsForType.length == 0) {
throw new Error(`bean definition is not found for type ${type.name}`);
}
else {
throw new Error(`${beanDefinitionsForType.length} bean definitions are found for type ${type.name}`);
}
}
function initBean<T>(id: BeanId<T>): T {
let beanDefinition = beanDefinitions.get(id);
if (beanDefinition.method || beanDefinition.field) {
// 方法或字段
// 获取所在类的实例
let targetIns = null;
for (let entry of beanDefinitions.entries()) {
const tempId = entry[0];
const tempDefinition = entry[1];
if (id !== tempId
&& tempDefinition.target === beanDefinition.target
&& tempDefinition.method === undefined
&& tempDefinition.field === undefined) {
targetIns = getBean(tempId);
break;
}
}
if (targetIns == null) {
throw new Error(beanDefinition.target.name + " is not decorated with @Bean");
}
if (beanDefinition.field) {
return targetIns[beanDefinition.field];
}
else {
return targetIns[beanDefinition.method]();
}
}
else {
const ins = new beanDefinition.target();
beans.set(id, ins);
// 处理该类 @Autowired 装饰信息
let autowiredArr = autowiredInfos.get(beanDefinition.target);
if (autowiredArr) {
let methodParamAutowiredMap: {[methodName: string]: AutowiredInfo[]} = {};
for (let autowiredInfo of autowiredArr) {
if (autowiredInfo.paramIndex == null) {
// 字段
Object.defineProperty(ins, autowiredInfo.field, {
get: () => findBean(autowiredInfo.id, autowiredInfo.fieldType)
});
}
else {
// 方法
let methodParamAutowired = methodParamAutowiredMap[autowiredInfo.method];
if (!methodParamAutowired) {
methodParamAutowiredMap[autowiredInfo.method] = methodParamAutowired = [];
}
while (methodParamAutowired.length <= autowiredInfo.paramIndex) {
methodParamAutowired.push(null);
}
methodParamAutowired[autowiredInfo.paramIndex] = autowiredInfo;
}
}
for (let methodName of Object.keys(methodParamAutowiredMap)) {
const methodParamAutowire = methodParamAutowiredMap[methodName];
const oldM = ins[methodName];
ins[methodName] = (...args) => {
if (args == null) {
args = [];
}
const newArgs = new Array(Math.max(args.length, methodParamAutowire.length));
for (let i = 0, len = newArgs.length; i < len; i++) {
const oldArg = args[i];
if (oldArg === undefined) {
const paramAutowire = methodParamAutowire[i];
if (paramAutowire) {
newArgs[i] = findBean(paramAutowire.id, paramAutowire.paramType);
}
}
else {
newArgs[i] = oldArg;
}
}
return oldM.call(ins, ...newArgs);
};
}
}
// 处理 Bean 注解
for (let entry of beanDefinitions.entries()) {
const tempDefinition = entry[1];
if (tempDefinition.target === beanDefinition.target) {
if (tempDefinition.field) {
registeBean(tempDefinition.id, ins[tempDefinition.field], null, true);
Object.defineProperty(ins, tempDefinition.field, {
get: () => getBean(tempDefinition.id),
set: value => beans.set(tempDefinition.id, value)
});
}
else if (tempDefinition.method) {
const oldM = ins[tempDefinition.method];
let _cachedValue = undefined;
ins[tempDefinition.method] = (...args) => {
if (_cachedValue === undefined) {
_cachedValue = oldM.call(ins, ...args);
registeBean(tempDefinition.id, _cachedValue, null, true);
}
return _cachedValue;
};
}
}
}
if (typeof ins["afterInit"] === "function") {
ins["afterInit"]();
}
return ins;
}
}
export function existBean(id: BeanId<any>) {
return beans.has(id);
}
export function registeBean<T>(id: BeanId<T>, ins: T, beanDefinition?: BeanDefinition, ignoreIfExisted = false) {
if (!beans.has(id)) {
if (!beanDefinitions.has(id)) {
addBeanDefinition(beanDefinition || {
id: id,
target: ins.constructor as Constructor<T>
});
}
beans.set(id, ins);
}
else if (!ignoreIfExisted) {
throw new Error("Bean(" + idStr(id) + ") existed");
}
} | the_stack |
import { check, CheckBlockSymbolTable, CheckHandle, CheckOption, CheckOr } from '@glimmer/debug';
import { DEBUG } from '@glimmer/env';
import {
BlockArguments,
BlockSymbolTable,
BlockValue,
CapturedArguments,
CapturedBlockArguments,
CapturedNamedArguments,
CapturedPositionalArguments,
CompilableBlock,
Dict,
NamedArguments,
Option,
PositionalArguments,
Scope,
ScopeBlock,
VMArguments,
} from '@glimmer/interfaces';
import {
createDebugAliasRef,
Reference,
UNDEFINED_REFERENCE,
valueForRef,
} from '@glimmer/reference';
import { dict, emptyArray, EMPTY_STRING_ARRAY } from '@glimmer/util';
import { CONSTANT_TAG, Tag } from '@glimmer/validator';
import { $sp } from '@glimmer/vm';
import { CheckCompilableBlock, CheckReference, CheckScope } from '../compiled/opcodes/-debug-strip';
import { REGISTERS } from '../symbols';
import { EvaluationStack } from './stack';
/*
The calling convention is:
* 0-N block arguments at the bottom
* 0-N positional arguments next (left-to-right)
* 0-N named arguments next
*/
export class VMArgumentsImpl implements VMArguments {
private stack: Option<EvaluationStack> = null;
public positional = new PositionalArgumentsImpl();
public named = new NamedArgumentsImpl();
public blocks = new BlockArgumentsImpl();
empty(stack: EvaluationStack): this {
let base = stack[REGISTERS][$sp] + 1;
this.named.empty(stack, base);
this.positional.empty(stack, base);
this.blocks.empty(stack, base);
return this;
}
setup(
stack: EvaluationStack,
names: readonly string[],
blockNames: readonly string[],
positionalCount: number,
atNames: boolean
) {
this.stack = stack;
/*
| ... | blocks | positional | named |
| ... | b0 b1 | p0 p1 p2 p3 | n0 n1 |
index | ... | 4/5/6 7/8/9 | 10 11 12 13 | 14 15 |
^ ^ ^ ^
bbase pbase nbase sp
*/
let named = this.named;
let namedCount = names.length;
let namedBase = stack[REGISTERS][$sp] - namedCount + 1;
named.setup(stack, namedBase, namedCount, names, atNames);
let positional = this.positional;
let positionalBase = namedBase - positionalCount;
positional.setup(stack, positionalBase, positionalCount);
let blocks = this.blocks;
let blocksCount = blockNames.length;
let blocksBase = positionalBase - blocksCount * 3;
blocks.setup(stack, blocksBase, blocksCount, blockNames);
}
get base(): number {
return this.blocks.base;
}
get length(): number {
return this.positional.length + this.named.length + this.blocks.length * 3;
}
at(pos: number): Reference {
return this.positional.at(pos);
}
realloc(offset: number) {
let { stack } = this;
if (offset > 0 && stack !== null) {
let { positional, named } = this;
let newBase = positional.base + offset;
let length = positional.length + named.length;
for (let i = length - 1; i >= 0; i--) {
stack.copy(i + positional.base, i + newBase);
}
positional.base += offset;
named.base += offset;
stack[REGISTERS][$sp] += offset;
}
}
capture(): CapturedArguments {
let positional = this.positional.length === 0 ? EMPTY_POSITIONAL : this.positional.capture();
let named = this.named.length === 0 ? EMPTY_NAMED : this.named.capture();
return { named, positional } as CapturedArguments;
}
clear(): void {
let { stack, length } = this;
if (length > 0 && stack !== null) stack.pop(length);
}
}
const EMPTY_REFERENCES = emptyArray<Reference>();
export class PositionalArgumentsImpl implements PositionalArguments {
public base = 0;
public length = 0;
private stack: EvaluationStack = null as any;
private _references: Option<readonly Reference[]> = null;
empty(stack: EvaluationStack, base: number) {
this.stack = stack;
this.base = base;
this.length = 0;
this._references = EMPTY_REFERENCES;
}
setup(stack: EvaluationStack, base: number, length: number) {
this.stack = stack;
this.base = base;
this.length = length;
if (length === 0) {
this._references = EMPTY_REFERENCES;
} else {
this._references = null;
}
}
at(position: number): Reference {
let { base, length, stack } = this;
if (position < 0 || position >= length) {
return UNDEFINED_REFERENCE;
}
return check(stack.get(position, base), CheckReference);
}
capture(): CapturedPositionalArguments {
return this.references as CapturedPositionalArguments;
}
prepend(other: Reference[]) {
let additions = other.length;
if (additions > 0) {
let { base, length, stack } = this;
this.base = base = base - additions;
this.length = length + additions;
for (let i = 0; i < additions; i++) {
stack.set(other[i], i, base);
}
this._references = null;
}
}
private get references(): readonly Reference[] {
let references = this._references;
if (!references) {
let { stack, base, length } = this;
references = this._references = stack.slice<Reference>(base, base + length);
}
return references;
}
}
export class NamedArgumentsImpl implements NamedArguments {
public base = 0;
public length = 0;
private stack!: EvaluationStack;
private _references: Option<readonly Reference[]> = null;
private _names: Option<readonly string[]> = EMPTY_STRING_ARRAY;
private _atNames: Option<readonly string[]> = EMPTY_STRING_ARRAY;
empty(stack: EvaluationStack, base: number) {
this.stack = stack;
this.base = base;
this.length = 0;
this._references = EMPTY_REFERENCES;
this._names = EMPTY_STRING_ARRAY;
this._atNames = EMPTY_STRING_ARRAY;
}
setup(
stack: EvaluationStack,
base: number,
length: number,
names: readonly string[],
atNames: boolean
) {
this.stack = stack;
this.base = base;
this.length = length;
if (length === 0) {
this._references = EMPTY_REFERENCES;
this._names = EMPTY_STRING_ARRAY;
this._atNames = EMPTY_STRING_ARRAY;
} else {
this._references = null;
if (atNames) {
this._names = null;
this._atNames = names;
} else {
this._names = names;
this._atNames = null;
}
}
}
get names(): readonly string[] {
let names = this._names;
if (!names) {
names = this._names = this._atNames!.map(this.toSyntheticName);
}
return names!;
}
get atNames(): readonly string[] {
let atNames = this._atNames;
if (!atNames) {
atNames = this._atNames = this._names!.map(this.toAtName);
}
return atNames!;
}
has(name: string): boolean {
return this.names.indexOf(name) !== -1;
}
get(name: string, atNames = false): Reference {
let { base, stack } = this;
let names = atNames ? this.atNames : this.names;
let idx = names.indexOf(name);
if (idx === -1) {
return UNDEFINED_REFERENCE;
}
let ref = stack.get<Reference>(idx, base);
if (DEBUG) {
return createDebugAliasRef!(atNames ? name : `@${name}`, ref);
} else {
return ref;
}
}
capture(): CapturedNamedArguments {
let { names, references } = this;
let map = dict<Reference>();
for (let i = 0; i < names.length; i++) {
let name = names[i];
if (DEBUG) {
map[name] = createDebugAliasRef!(`@${name}`, references[i]);
} else {
map[name] = references[i];
}
}
return map as CapturedNamedArguments;
}
merge(other: Record<string, Reference>) {
let keys = Object.keys(other);
if (keys.length > 0) {
let { names, length, stack } = this;
let newNames = names.slice();
for (let i = 0; i < keys.length; i++) {
let name = keys[i];
let idx = newNames.indexOf(name);
if (idx === -1) {
length = newNames.push(name);
stack.push(other[name]);
}
}
this.length = length;
this._references = null;
this._names = newNames;
this._atNames = null;
}
}
private get references(): readonly Reference[] {
let references = this._references;
if (!references) {
let { base, length, stack } = this;
references = this._references = stack.slice<Reference>(base, base + length);
}
return references;
}
private toSyntheticName(this: void, name: string): string {
return name.slice(1);
}
private toAtName(this: void, name: string): string {
return `@${name}`;
}
}
function toSymbolName(name: string): string {
return `&${name}`;
}
const EMPTY_BLOCK_VALUES = emptyArray<BlockValue>();
export class BlockArgumentsImpl implements BlockArguments {
private stack!: EvaluationStack;
private internalValues: Option<readonly BlockValue[]> = null;
private _symbolNames: Option<readonly string[]> = null;
public internalTag: Option<Tag> = null;
public names: readonly string[] = EMPTY_STRING_ARRAY;
public length = 0;
public base = 0;
empty(stack: EvaluationStack, base: number) {
this.stack = stack;
this.names = EMPTY_STRING_ARRAY;
this.base = base;
this.length = 0;
this._symbolNames = null;
this.internalTag = CONSTANT_TAG;
this.internalValues = EMPTY_BLOCK_VALUES;
}
setup(stack: EvaluationStack, base: number, length: number, names: readonly string[]) {
this.stack = stack;
this.names = names;
this.base = base;
this.length = length;
this._symbolNames = null;
if (length === 0) {
this.internalTag = CONSTANT_TAG;
this.internalValues = EMPTY_BLOCK_VALUES;
} else {
this.internalTag = null;
this.internalValues = null;
}
}
get values(): readonly BlockValue[] {
let values = this.internalValues;
if (!values) {
let { base, length, stack } = this;
values = this.internalValues = stack.slice<BlockValue>(base, base + length * 3);
}
return values;
}
has(name: string): boolean {
return this.names!.indexOf(name) !== -1;
}
get(name: string): Option<ScopeBlock> {
let idx = this.names!.indexOf(name);
if (idx === -1) {
return null;
}
let { base, stack } = this;
let table = check(stack.get(idx * 3, base), CheckOption(CheckBlockSymbolTable));
let scope = check(stack.get(idx * 3 + 1, base), CheckOption(CheckScope));
let handle = check(
stack.get(idx * 3 + 2, base),
CheckOption(CheckOr(CheckHandle, CheckCompilableBlock))
);
return handle === null ? null : ([handle, scope!, table!] as ScopeBlock);
}
capture(): CapturedBlockArguments {
return new CapturedBlockArgumentsImpl(this.names, this.values);
}
get symbolNames(): readonly string[] {
let symbolNames = this._symbolNames;
if (symbolNames === null) {
symbolNames = this._symbolNames = this.names.map(toSymbolName);
}
return symbolNames;
}
}
class CapturedBlockArgumentsImpl implements CapturedBlockArguments {
public length: number;
constructor(public names: readonly string[], public values: readonly Option<BlockValue>[]) {
this.length = names.length;
}
has(name: string): boolean {
return this.names.indexOf(name) !== -1;
}
get(name: string): Option<ScopeBlock> {
let idx = this.names.indexOf(name);
if (idx === -1) return null;
return [
this.values[idx * 3 + 2] as CompilableBlock,
this.values[idx * 3 + 1] as Scope,
this.values[idx * 3] as BlockSymbolTable,
];
}
}
export function createCapturedArgs(named: Dict<Reference>, positional: Reference[]) {
return {
named,
positional,
} as CapturedArguments;
}
export function reifyNamed(named: CapturedNamedArguments) {
let reified = dict();
for (let key in named) {
reified[key] = valueForRef(named[key]);
}
return reified;
}
export function reifyPositional(positional: CapturedPositionalArguments) {
return positional.map(valueForRef);
}
export function reifyArgs(args: CapturedArguments) {
return {
named: reifyNamed(args.named),
positional: reifyPositional(args.positional),
};
}
export const EMPTY_NAMED = Object.freeze(Object.create(null)) as CapturedNamedArguments;
export const EMPTY_POSITIONAL = EMPTY_REFERENCES as CapturedPositionalArguments;
export const EMPTY_ARGS = createCapturedArgs(EMPTY_NAMED, EMPTY_POSITIONAL); | the_stack |
import { SpecialAbilitySelectOptionL10n } from "../../../../../app/Database/Schema/SpecialAbilities/SpecialAbilities.l10n"
import { SelectOptionCategoryUniv, SpecialAbilitySelectOptionUniv } from "../../../../../app/Database/Schema/SpecialAbilities/SpecialAbilities.univ"
import { Either, Left, Right } from "../../../../Data/Either"
import { flip, ident } from "../../../../Data/Function"
import { fromArray, List, notNull } from "../../../../Data/List"
import { ensure, Just, Maybe, Nothing } from "../../../../Data/Maybe"
import { foldr, insert, OrderedMap, toMap } from "../../../../Data/OrderedMap"
import { Record } from "../../../../Data/Record"
import { Blessing } from "../../../Models/Wiki/Blessing"
import { Cantrip } from "../../../Models/Wiki/Cantrip"
import { CombatTechnique } from "../../../Models/Wiki/CombatTechnique"
import { LiturgicalChant } from "../../../Models/Wiki/LiturgicalChant"
import { Skill } from "../../../Models/Wiki/Skill"
import { Spell } from "../../../Models/Wiki/Spell"
import { SelectOption } from "../../../Models/Wiki/sub/SelectOption"
import { pipe, pipe_ } from "../../pipe"
import { toErrata } from "./ToErrata"
import { toPrerequisites } from "./ToPrerequisites"
import { toSourceRefs } from "./ToSourceRefs"
type InsertMap = ident<OrderedMap<string, Record<SelectOption>>>
const blessingToSelectOption : (attr : Record<Blessing>) => Record<SelectOption>
= x => SelectOption ({
id: Blessing.A.id (x),
name: Blessing.A.name (x),
src: Blessing.A.src (x),
errata: Blessing.A.errata (x),
})
const resolveBlessings : (blessings : OrderedMap<string, Record<Blessing>>)
=> InsertMap
= flip (foldr (x => pipe_ (
x,
blessingToSelectOption,
insert (Blessing.A.id (x))
)))
const cantripToSelectOption : (cantrip : Record<Cantrip>) => Record<SelectOption>
= x => SelectOption ({
id: Cantrip.A.id (x),
name: Cantrip.A.name (x),
src: Cantrip.A.src (x),
errata: Cantrip.A.errata (x),
})
const resolveCantrips : (cantrips : OrderedMap<string, Record<Cantrip>>)
=> InsertMap
= flip (foldr (x => pipe_ (
x,
cantripToSelectOption,
insert (Cantrip.A.id (x))
)))
const ctToSelectOption : (combatTechnique : Record<CombatTechnique>) => Record<SelectOption>
= x => SelectOption ({
id: CombatTechnique.A.id (x),
name: CombatTechnique.A.name (x),
cost: Just (CombatTechnique.A.ic (x)),
src: CombatTechnique.A.src (x),
errata: CombatTechnique.A.errata (x),
})
const resolveCombatTechniques : (gr : number[] | undefined)
=> (combatTechniques : OrderedMap<string, Record<CombatTechnique>>)
=> InsertMap
= gr => gr === undefined
? flip (foldr ((x : Record<CombatTechnique>) =>
pipe_ (
x,
ctToSelectOption,
insert (CombatTechnique.A.id (x))
)))
: flip (foldr ((x : Record<CombatTechnique>) =>
gr.includes (CombatTechnique.A.gr (x))
? pipe_ (
x,
ctToSelectOption,
insert (CombatTechnique.A.id (x))
)
: ident as InsertMap))
const lcToSelectOption : (liturgicalChant : Record<LiturgicalChant>) => Record<SelectOption>
= x => SelectOption ({
id: LiturgicalChant.A.id (x),
name: LiturgicalChant.A.name (x),
cost: Just (LiturgicalChant.A.ic (x)),
src: LiturgicalChant.A.src (x),
errata: LiturgicalChant.A.errata (x),
})
const resolveLiturgicalChants : (gr : number[] | undefined)
=> (liturgicalChants : OrderedMap<string, Record<LiturgicalChant>>)
=> InsertMap
= gr => gr === undefined
? flip (foldr ((x : Record<LiturgicalChant>) =>
pipe_ (
x,
lcToSelectOption,
insert (LiturgicalChant.A.id (x))
)))
: flip (foldr ((x : Record<LiturgicalChant>) =>
gr.includes (LiturgicalChant.A.gr (x))
? pipe_ (
x,
lcToSelectOption,
insert (LiturgicalChant.A.id (x))
)
: ident as InsertMap))
const skillToSelectOption : (skill : Record<Skill>) => Record<SelectOption>
= x => SelectOption ({
id: Skill.A.id (x),
name: Skill.A.name (x),
cost: Just (Skill.A.ic (x)),
applications: Just (Skill.A.applications (x)),
applicationInput: Skill.A.applicationsInput (x),
src: Skill.A.src (x),
errata: Skill.A.errata (x),
})
const resolveSkills : (gr : number[] | undefined)
=> (skills : OrderedMap<string, Record<Skill>>)
=> InsertMap
= gr => gr === undefined
? flip (foldr ((x : Record<Skill>) =>
pipe_ (
x,
skillToSelectOption,
insert (Skill.A.id (x))
)))
: flip (foldr ((x : Record<Skill>) =>
gr.includes (Skill.A.gr (x))
? pipe_ (
x,
skillToSelectOption,
insert (Skill.A.id (x))
)
: ident as InsertMap))
const spellToSelectOption : (spell : Record<Spell>) => Record<SelectOption>
= x => SelectOption ({
id: Spell.A.id (x),
name: Spell.A.name (x),
cost: Just (Spell.A.ic (x)),
src: Spell.A.src (x),
errata: Spell.A.errata (x),
})
const resolveSpells : (gr : number[] | undefined)
=> (spells : OrderedMap<string, Record<Spell>>)
=> InsertMap
= gr => gr === undefined
? flip (foldr ((x : Record<Spell>) =>
pipe_ (
x,
spellToSelectOption,
insert (Spell.A.id (x))
)))
: flip (foldr ((x : Record<Spell>) =>
gr.includes (Spell.A.gr (x))
? pipe_ (
x,
spellToSelectOption,
insert (Spell.A.id (x))
)
: ident as InsertMap))
/**
* Takes an array of select option categories and resolves them into a list of
* select options.
*/
export const resolveSOCats : (blessings : OrderedMap<string, Record<Blessing>>)
=> (cantrips : OrderedMap<string, Record<Cantrip>>)
=> (combatTechniques : OrderedMap<string, Record<CombatTechnique>>)
=> (liturgicalChants : OrderedMap<string, Record<LiturgicalChant>>)
=> (skills : OrderedMap<string, Record<Skill>>)
=> (spells : OrderedMap<string, Record<Spell>>)
=> (categories : SelectOptionCategoryUniv[] | undefined)
=> OrderedMap<string, Record<SelectOption>>
= bs => cas => cts => lcs => sks => sps =>
pipe (
xs => xs === undefined ? [] : xs,
fromArray,
List.foldr ((cat : SelectOptionCategoryUniv) =>
cat.category === "BLESSINGS"
? resolveBlessings (bs)
: cat.category === "CANTRIPS"
? resolveCantrips (cas)
: cat.category === "COMBAT_TECHNIQUES"
? resolveCombatTechniques (cat.groups) (cts)
: cat.category === "LITURGICAL_CHANTS"
? resolveLiturgicalChants (cat.groups) (lcs)
: cat.category === "SKILLS"
? resolveSkills (cat.groups) (sks)
: resolveSpells (cat.groups) (sps))
(OrderedMap.empty),
)
const l10nSelectOptionToRecord : (l10n : SpecialAbilitySelectOptionL10n) => Record<SelectOption>
= l10n => SelectOption ({
id: l10n.id,
name: l10n.name,
description: Maybe (l10n.description),
specializations: l10n.specializations === undefined
? Nothing
: Just (
fromArray (l10n.specializations)
),
specializationInput: Maybe (l10n.specializationInput),
src: toSourceRefs (l10n.src),
errata: toErrata (l10n.errata),
})
const mergeUnivIntoL10n : (univ : SpecialAbilitySelectOptionUniv) => ident<Record<SelectOption>>
= univ => l10n => SelectOption ({
id: SelectOption.A.id (l10n),
name: SelectOption.A.name (l10n),
description: SelectOption.A.description (l10n),
specializations: SelectOption.A.specializations (l10n),
specializationInput:
SelectOption.A.specializationInput (l10n),
continent: Maybe (univ.continent),
cost: Maybe (univ.cost),
isExtinct: Maybe (univ.isExtinct),
isSecret: Maybe (univ.isSecret),
languages: typeof univ.languages === "object"
? Just (fromArray (univ.languages))
: Nothing,
prerequisites: ensure (notNull)
(toPrerequisites (univ)),
level: Maybe (univ.animalLevel),
gr: Maybe (univ.animalGr),
src: SelectOption.A.src (l10n),
errata: SelectOption.A.errata (l10n),
})
export const mergeSOs : (sosL10n : SpecialAbilitySelectOptionL10n[] | undefined)
=> (sosUniv : SpecialAbilitySelectOptionUniv[] | undefined)
=> (soCatMap : OrderedMap<string, Record<SelectOption>>)
=> Either<Error[], List<Record<SelectOption>>>
= sosL10n => sosUniv => soCatMap => {
const mp : Map<string | number, Record<SelectOption>>
= new Map (toMap (soCatMap))
const errs : Error[] = []
if (sosL10n !== undefined) {
for (const so of sosL10n) {
if (mp.has (so.id)) {
errs.push (new Error (`mergeSOs: Key ${so.id} already in use`))
}
else {
mp.set (so.id, l10nSelectOptionToRecord (so))
}
}
}
if (sosUniv !== undefined) {
for (const so of sosUniv) {
const v = mp.get (so.id)
if (v !== undefined) {
mp.set (so.id, mergeUnivIntoL10n (so) (v))
}
}
}
if (errs.length > 0) {
return Left (errs)
}
return Right (List (...mp.values ()))
} | the_stack |
import { TypeAssertion,
ValidationContext } from '../types';
import { validate,
getType } from '../validator';
import { compile } from '../compiler';
import { serialize,
deserialize } from '../serializer';
describe("compiler-4", function() {
it("compiler-exported-types-1", function() {
const schema = compile(`
export type Foo = string | number;
type Bar = string | number;
`);
{
expect(Array.from(schema.keys())).toEqual([
'Foo', 'Bar',
]);
}
{
const rhs: TypeAssertion = {
name: 'Foo',
typeName: 'Foo',
kind: 'one-of',
oneOf: [{
kind: 'primitive',
primitiveName: 'string',
}, {
kind: 'primitive',
primitiveName: 'number',
}],
};
// const ty = getType(schema, 'Foo');
for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Foo')?.exported).toEqual(true);
}
}
{
const rhs: TypeAssertion = {
name: 'Bar',
typeName: 'Bar',
kind: 'one-of',
oneOf: [{
kind: 'primitive',
primitiveName: 'string',
}, {
kind: 'primitive',
primitiveName: 'number',
}],
};
// const ty = getType(schema, 'Bar');
for (const ty of [getType(deserialize(serialize(schema)), 'Bar'), getType(schema, 'Bar')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Bar')?.exported).toEqual(false);
}
}
});
it("compiler-exported-types-2", function() {
const schema = compile(`
export interface Foo {}
interface Bar {}
`);
{
expect(Array.from(schema.keys())).toEqual([
'Foo', 'Bar',
]);
}
{
const rhs: TypeAssertion = {
name: 'Foo',
typeName: 'Foo',
kind: 'object',
members: [],
};
// const ty = getType(schema, 'Foo');
for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Foo')?.exported).toEqual(true);
}
}
{
const rhs: TypeAssertion = {
name: 'Bar',
typeName: 'Bar',
kind: 'object',
members: [],
};
// const ty = getType(schema, 'Bar');
for (const ty of [getType(deserialize(serialize(schema)), 'Bar'), getType(schema, 'Bar')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Bar')?.exported).toEqual(false);
}
}
});
it("compiler-exported-types-3", function() {
const schema = compile(`
export enum Foo {}
enum Bar {}
`);
{
expect(Array.from(schema.keys())).toEqual([
'Foo', 'Bar',
]);
}
{
const rhs: TypeAssertion = {
name: 'Foo',
typeName: 'Foo',
kind: 'enum',
values: [],
};
// const ty = getType(schema, 'Foo');
for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Foo')?.exported).toEqual(true);
}
}
{
const rhs: TypeAssertion = {
name: 'Bar',
typeName: 'Bar',
kind: 'enum',
values: [],
};
// const ty = getType(schema, 'Bar');
for (const ty of [getType(deserialize(serialize(schema)), 'Bar'), getType(schema, 'Bar')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Bar')?.exported).toEqual(false);
}
}
});
it("compiler-doc-comments-1", function() {
const schema = compile(`
/* comment1 */
export type Foo = string | number;
/*
* comment2
*/
type Bar = string | number;
`);
{
expect(Array.from(schema.keys())).toEqual([
'Foo', 'Bar',
]);
}
{
const rhs: TypeAssertion = {
name: 'Foo',
typeName: 'Foo',
kind: 'one-of',
oneOf: [{
kind: 'primitive',
primitiveName: 'string',
}, {
kind: 'primitive',
primitiveName: 'number',
}],
};
// const ty = getType(schema, 'Foo');
for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Foo')?.exported).toEqual(true);
}
}
{
const rhs: TypeAssertion = {
name: 'Bar',
typeName: 'Bar',
kind: 'one-of',
oneOf: [{
kind: 'primitive',
primitiveName: 'string',
}, {
kind: 'primitive',
primitiveName: 'number',
}],
};
// const ty = getType(schema, 'Bar');
for (const ty of [getType(deserialize(serialize(schema)), 'Bar'), getType(schema, 'Bar')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Bar')?.exported).toEqual(false);
}
}
});
it("compiler-doc-comments-2", function() {
const schema = compile(`
/** comment1 */
export type Foo = string | number;
/**
* comment2
*/
type Bar = string | number;
`);
{
expect(Array.from(schema.keys())).toEqual([
'Foo', 'Bar',
]);
}
{
const rhs: TypeAssertion = {
name: 'Foo',
typeName: 'Foo',
kind: 'one-of',
oneOf: [{
kind: 'primitive',
primitiveName: 'string',
}, {
kind: 'primitive',
primitiveName: 'number',
}],
docComment: 'comment1',
};
// const ty = getType(schema, 'Foo');
for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Foo')?.exported).toEqual(true);
}
}
{
const rhs: TypeAssertion = {
name: 'Bar',
typeName: 'Bar',
kind: 'one-of',
oneOf: [{
kind: 'primitive',
primitiveName: 'string',
}, {
kind: 'primitive',
primitiveName: 'number',
}],
docComment: '* comment2',
};
// const ty = getType(schema, 'Bar');
for (const ty of [getType(deserialize(serialize(schema)), 'Bar'), getType(schema, 'Bar')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Bar')?.exported).toEqual(false);
}
}
});
it("compiler-doc-comments-3", function() {
const schema = compile(`
/** comment X */
type X = string;
/** comment Foo */
export interface Foo {
/** comment Foo.a */
a: number;
/** comment Foo.b */
b: X;
c: X;
/** comment Foo.d */
d: string;
/** comment Foo.propNames */
[propNames: string]: string;
}
/** comment Bar */
interface Bar extends Foo {
/** comment Bar.e */
e: number;
/** comment Bar.propNames */
[propNames: number]: number;
}
`);
{
expect(Array.from(schema.keys())).toEqual([
'X', 'Foo', 'Bar',
]);
}
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'primitive',
primitiveName: 'string',
docComment: 'comment X',
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(schema.get('X')?.exported).toEqual(false);
}
}
{
const rhs: TypeAssertion = {
name: 'Foo',
typeName: 'Foo',
kind: 'object',
members: [
['a',
{name: 'a', kind: 'primitive', primitiveName: 'number'},
false, 'comment Foo.a',
],
['b',
{name: 'b', typeName: 'X', kind: 'primitive', primitiveName: 'string', docComment: 'comment X'},
false, 'comment Foo.b',
],
['c',
{name: 'c', typeName: 'X', kind: 'primitive', primitiveName: 'string', docComment: 'comment X'},
],
['d',
{name: 'd', kind: 'primitive', primitiveName: 'string'},
false, 'comment Foo.d',
],
],
additionalProps: [
[['string'], {kind: 'primitive', primitiveName: 'string'}, false, 'comment Foo.propNames'],
],
docComment: 'comment Foo',
};
// const ty = getType(schema, 'Foo');
for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Foo')?.exported).toEqual(true);
}
}
{
const rhs: TypeAssertion = {
name: 'Bar',
typeName: 'Bar',
kind: 'object',
members: [
['e',
{name: 'e', kind: 'primitive', primitiveName: 'number'},
false, 'comment Bar.e',
],
['a',
{name: 'a', kind: 'primitive', primitiveName: 'number'},
true, 'comment Foo.a',
],
['b',
{name: 'b', typeName: 'X', kind: 'primitive', primitiveName: 'string', docComment: 'comment X'},
true, 'comment Foo.b',
],
['c',
{name: 'c', typeName: 'X', kind: 'primitive', primitiveName: 'string', docComment: 'comment X'},
true,
],
['d',
{name: 'd', kind: 'primitive', primitiveName: 'string'},
true, 'comment Foo.d',
],
],
additionalProps: [
[['string'], {kind: 'primitive', primitiveName: 'string'}, true, 'comment Foo.propNames'],
[['number'], {kind: 'primitive', primitiveName: 'number'}, false, 'comment Bar.propNames'], // TODO: concat order
],
baseTypes: [getType(schema, 'Foo') as any],
docComment: 'comment Bar',
};
// const ty = getType(schema, 'Bar');
for (const ty of [getType(deserialize(serialize(schema)), 'Bar'), getType(schema, 'Bar')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Bar')?.exported).toEqual(false);
}
}
});
it("compiler-doc-comments-4", function() {
const schema = compile(`
/** comment Foo */
export enum Foo {
/** comment Foo.A */
A,
/** comment Foo.B */
B = 'bbb',
}
`);
{
expect(Array.from(schema.keys())).toEqual([
'Foo',
]);
}
{
const rhs: TypeAssertion = {
name: 'Foo',
typeName: 'Foo',
kind: 'enum',
values: [
['A', 0, 'comment Foo.A'],
['B', 'bbb', 'comment Foo.B'],
],
docComment: 'comment Foo',
};
// const ty = getType(schema, 'Foo');
for (const ty of [getType(deserialize(serialize(schema)), 'Foo'), getType(schema, 'Foo')]) {
expect(ty).toEqual(rhs);
expect(schema.get('Foo')?.exported).toEqual(true);
}
}
});
it("compiler-array-length-1", function() {
const schemas = [compile(`
type X = string[3..5];
`), compile(`
type X = Array<string, 3..5>;
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
expect(Array.from(schemas[1].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'repeated',
min: 3,
max: 5,
repeated: {
kind: 'primitive',
primitiveName: 'string',
},
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>(['1'], ty)).toEqual(null);
expect(validate<any>(['1', '2'], ty)).toEqual(null);
expect(validate<any>(['1', '2', '3'], ty)).toEqual({value: ['1', '2', '3']});
expect(validate<any>(['1', '2', '3', '4'], ty)).toEqual({value: ['1', '2', '3', '4']});
expect(validate<any>(['1', '2', '3', '4', '5'], ty)).toEqual({value: ['1', '2', '3', '4', '5']});
expect(validate<any>(['1', '2', '3', '4', '5', '6'], ty)).toEqual(null);
}
}
}
});
it("compiler-array-length-2", function() {
const schemas = [compile(`
type X = string[..5];
`), compile(`
type X = Array<string, ..5>;
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
expect(Array.from(schemas[1].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'repeated',
min: null,
max: 5,
repeated: {
kind: 'primitive',
primitiveName: 'string',
},
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual({value: []});
expect(validate<any>(['1'], ty)).toEqual({value: ['1']});
expect(validate<any>(['1', '2'], ty)).toEqual({value: ['1', '2']});
expect(validate<any>(['1', '2', '3'], ty)).toEqual({value: ['1', '2', '3']});
expect(validate<any>(['1', '2', '3', '4'], ty)).toEqual({value: ['1', '2', '3', '4']});
expect(validate<any>(['1', '2', '3', '4', '5'], ty)).toEqual({value: ['1', '2', '3', '4', '5']});
expect(validate<any>(['1', '2', '3', '4', '5', '6'], ty)).toEqual(null);
}
}
}
});
it("compiler-array-length-3", function() {
const schemas = [compile(`
type X = string[3..];
`), compile(`
type X = Array<string, 3..>;
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
expect(Array.from(schemas[1].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'repeated',
min: 3,
max: null,
repeated: {
kind: 'primitive',
primitiveName: 'string',
},
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>(['1'], ty)).toEqual(null);
expect(validate<any>(['1', '2'], ty)).toEqual(null);
expect(validate<any>(['1', '2', '3'], ty)).toEqual({value: ['1', '2', '3']});
expect(validate<any>(['1', '2', '3', '4'], ty)).toEqual({value: ['1', '2', '3', '4']});
expect(validate<any>(['1', '2', '3', '4', '5'], ty)).toEqual({value: ['1', '2', '3', '4', '5']});
expect(validate<any>(['1', '2', '3', '4', '5', '6'], ty)).toEqual({value: ['1', '2', '3', '4', '5', '6']});
}
}
}
});
it("compiler-array-length-4a", function() {
const schemas = [compile(`
type X = string[3];
`), compile(`
type X = Array<string, 3>;
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
expect(Array.from(schemas[1].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'repeated',
min: 3,
max: 3,
repeated: {
kind: 'primitive',
primitiveName: 'string',
},
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>(['1'], ty)).toEqual(null);
expect(validate<any>(['1', '2'], ty)).toEqual(null);
expect(validate<any>(['1', '2', '3'], ty)).toEqual({value: ['1', '2', '3']});
expect(validate<any>(['1', '2', '3', '4'], ty)).toEqual(null);
expect(validate<any>(['1', '2', '3', '4', '5'], ty)).toEqual(null);
expect(validate<any>(['1', '2', '3', '4', '5', '6'], ty)).toEqual(null);
}
}
}
});
it("compiler-array-length-4b", function() {
const schemas = [compile(`
type X = string[];
`), compile(`
type X = Array<string>;
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
expect(Array.from(schemas[1].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'repeated',
min: null,
max: null,
repeated: {
kind: 'primitive',
primitiveName: 'string',
},
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual({value: []});
expect(validate<any>(['1'], ty)).toEqual({value: ['1']});
expect(validate<any>(['1', '2'], ty)).toEqual({value: ['1', '2']});
expect(validate<any>(['1', '2', '3'], ty)).toEqual({value: ['1', '2', '3']});
expect(validate<any>(['1', '2', '3', '4'], ty)).toEqual({value: ['1', '2', '3', '4']});
expect(validate<any>(['1', '2', '3', '4', '5'], ty)).toEqual({value: ['1', '2', '3', '4', '5']});
expect(validate<any>(['1', '2', '3', '4', '5', '6'], ty)).toEqual({value: ['1', '2', '3', '4', '5', '6']});
}
}
}
});
it("compiler-spread-length-1", function() {
const schemas = [compile(`
type X = [number, ...<string, 3..5>, boolean];
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'sequence',
sequence: [{
kind: 'primitive',
primitiveName: 'number',
}, {
kind: 'spread',
min: 3,
max: 5,
spread: {
kind: 'primitive',
primitiveName: 'string',
},
}, {
kind: 'primitive',
primitiveName: 'boolean',
}],
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>([0, false], ty)).toEqual(null);
expect(validate<any>([0, '1', false], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', false], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', '3', false], ty)).toEqual({value: [0, '1', '2', '3', false]});
expect(validate<any>([0, '1', '2', '3', '4', false], ty)).toEqual({value: [0, '1', '2', '3', '4', false]});
expect(validate<any>([0, '1', '2', '3', '4', '5', false], ty)).toEqual({value: [0, '1', '2', '3', '4', '5', false]});
expect(validate<any>([0, '1', '2', '3', '4', '5', '6', false], ty)).toEqual(null);
}
}
}
});
it("compiler-spread-length-2", function() {
const schemas = [compile(`
type X = [number, ...<string, ..5>, boolean];
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'sequence',
sequence: [{
kind: 'primitive',
primitiveName: 'number',
}, {
kind: 'spread',
min: null,
max: 5,
spread: {
kind: 'primitive',
primitiveName: 'string',
},
}, {
kind: 'primitive',
primitiveName: 'boolean',
}],
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>([0, false], ty)).toEqual({value: [0, false]});
expect(validate<any>([0, '1', false], ty)).toEqual({value: [0, '1', false]});
expect(validate<any>([0, '1', '2', false], ty)).toEqual({value: [0, '1', '2', false]});
expect(validate<any>([0, '1', '2', '3', false], ty)).toEqual({value: [0, '1', '2', '3', false]});
expect(validate<any>([0, '1', '2', '3', '4', false], ty)).toEqual({value: [0, '1', '2', '3', '4', false]});
expect(validate<any>([0, '1', '2', '3', '4', '5', false], ty)).toEqual({value: [0, '1', '2', '3', '4', '5', false]});
expect(validate<any>([0, '1', '2', '3', '4', '5', '6', false], ty)).toEqual(null);
}
}
}
});
it("compiler-spread-length-3", function() {
const schemas = [compile(`
type X = [number, ...<string, 3..>, boolean];
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'sequence',
sequence: [{
kind: 'primitive',
primitiveName: 'number',
}, {
kind: 'spread',
min: 3,
max: null,
spread: {
kind: 'primitive',
primitiveName: 'string',
},
}, {
kind: 'primitive',
primitiveName: 'boolean',
}],
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>([0, false], ty)).toEqual(null);
expect(validate<any>([0, '1', false], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', false], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', '3', false], ty)).toEqual({value: [0, '1', '2', '3', false]});
expect(validate<any>([0, '1', '2', '3', '4', false], ty)).toEqual({value: [0, '1', '2', '3', '4', false]});
expect(validate<any>([0, '1', '2', '3', '4', '5', false], ty)).toEqual({value: [0, '1', '2', '3', '4', '5', false]});
expect(validate<any>([0, '1', '2', '3', '4', '5', '6', false], ty)).toEqual({value: [0, '1', '2', '3', '4', '5', '6', false]});
}
}
}
});
it("compiler-spread-length-4a", function() {
const schemas = [compile(`
type X = [number, ...<string, 3>, boolean];
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'sequence',
sequence: [{
kind: 'primitive',
primitiveName: 'number',
}, {
kind: 'spread',
min: 3,
max: 3,
spread: {
kind: 'primitive',
primitiveName: 'string',
},
}, {
kind: 'primitive',
primitiveName: 'boolean',
}],
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>([0, false], ty)).toEqual(null);
expect(validate<any>([0, '1', false], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', false], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', '3', false], ty)).toEqual({value: [0, '1', '2', '3', false]});
expect(validate<any>([0, '1', '2', '3', '4', false], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', '3', '4', '5', false], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', '3', '4', '5', '6', false], ty)).toEqual(null);
}
}
}
});
it("compiler-spread-length-4b", function() {
const schemas = [compile(`
type X = [number, ...<string>, boolean];
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'sequence',
sequence: [{
kind: 'primitive',
primitiveName: 'number',
}, {
kind: 'spread',
min: null,
max: null,
spread: {
kind: 'primitive',
primitiveName: 'string',
},
}, {
kind: 'primitive',
primitiveName: 'boolean',
}],
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>([0, false], ty)).toEqual({value: [0, false]});
expect(validate<any>([0, '1', false], ty)).toEqual({value: [0, '1', false]});
expect(validate<any>([0, '1', '2', false], ty)).toEqual({value: [0, '1', '2', false]});
expect(validate<any>([0, '1', '2', '3', false], ty)).toEqual({value: [0, '1', '2', '3', false]});
expect(validate<any>([0, '1', '2', '3', '4', false], ty)).toEqual({value: [0, '1', '2', '3', '4', false]});
expect(validate<any>([0, '1', '2', '3', '4', '5', false], ty)).toEqual({value: [0, '1', '2', '3', '4', '5', false]});
expect(validate<any>([0, '1', '2', '3', '4', '5', '6', false], ty)).toEqual({value: [0, '1', '2', '3', '4', '5', '6', false]});
}
}
}
});
it("compiler-spread-length-5", function() {
const schemas = [compile(`
type X = [number, ...<string, 3..5>];
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'sequence',
sequence: [{
kind: 'primitive',
primitiveName: 'number',
}, {
kind: 'spread',
min: 3,
max: 5,
spread: {
kind: 'primitive',
primitiveName: 'string',
},
}],
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>([0], ty)).toEqual(null);
expect(validate<any>([0, '1'], ty)).toEqual(null);
expect(validate<any>([0, '1', '2'], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', '3'], ty)).toEqual({value: [0, '1', '2', '3']});
expect(validate<any>([0, '1', '2', '3', '4'], ty)).toEqual({value: [0, '1', '2', '3', '4']});
expect(validate<any>([0, '1', '2', '3', '4', '5'], ty)).toEqual({value: [0, '1', '2', '3', '4', '5']});
expect(validate<any>([0, '1', '2', '3', '4', '5', '6'], ty)).toEqual(null);
}
}
}
});
it("compiler-spread-length-6", function() {
const schemas = [compile(`
type X = [number, ...<string, ..5>];
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'sequence',
sequence: [{
kind: 'primitive',
primitiveName: 'number',
}, {
kind: 'spread',
min: null,
max: 5,
spread: {
kind: 'primitive',
primitiveName: 'string',
},
}],
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>([0], ty)).toEqual({value: [0]});
expect(validate<any>([0, '1'], ty)).toEqual({value: [0, '1']});
expect(validate<any>([0, '1', '2'], ty)).toEqual({value: [0, '1', '2']});
expect(validate<any>([0, '1', '2', '3'], ty)).toEqual({value: [0, '1', '2', '3']});
expect(validate<any>([0, '1', '2', '3', '4'], ty)).toEqual({value: [0, '1', '2', '3', '4']});
expect(validate<any>([0, '1', '2', '3', '4', '5'], ty)).toEqual({value: [0, '1', '2', '3', '4', '5']});
expect(validate<any>([0, '1', '2', '3', '4', '5', '6'], ty)).toEqual(null);
}
}
}
});
it("compiler-spread-length-7", function() {
const schemas = [compile(`
type X = [number, ...<string, 3..>];
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'sequence',
sequence: [{
kind: 'primitive',
primitiveName: 'number',
}, {
kind: 'spread',
min: 3,
max: null,
spread: {
kind: 'primitive',
primitiveName: 'string',
},
}],
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>([0], ty)).toEqual(null);
expect(validate<any>([0, '1'], ty)).toEqual(null);
expect(validate<any>([0, '1', '2'], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', '3'], ty)).toEqual({value: [0, '1', '2', '3']});
expect(validate<any>([0, '1', '2', '3', '4'], ty)).toEqual({value: [0, '1', '2', '3', '4']});
expect(validate<any>([0, '1', '2', '3', '4', '5'], ty)).toEqual({value: [0, '1', '2', '3', '4', '5']});
expect(validate<any>([0, '1', '2', '3', '4', '5', '6'], ty)).toEqual({value: [0, '1', '2', '3', '4', '5', '6']});
}
}
}
});
it("compiler-spread-length-8", function() {
const schemas = [compile(`
type X = [number, ...<string>];
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'sequence',
sequence: [{
kind: 'primitive',
primitiveName: 'number',
}, {
kind: 'spread',
min: null,
max: null,
spread: {
kind: 'primitive',
primitiveName: 'string',
},
}],
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>([0], ty)).toEqual({value: [0]});
expect(validate<any>([0, '1'], ty)).toEqual({value: [0, '1']});
expect(validate<any>([0, '1', '2'], ty)).toEqual({value: [0, '1', '2']});
expect(validate<any>([0, '1', '2', '3'], ty)).toEqual({value: [0, '1', '2', '3']});
expect(validate<any>([0, '1', '2', '3', '4'], ty)).toEqual({value: [0, '1', '2', '3', '4']});
expect(validate<any>([0, '1', '2', '3', '4', '5'], ty)).toEqual({value: [0, '1', '2', '3', '4', '5']});
expect(validate<any>([0, '1', '2', '3', '4', '5', '6'], ty)).toEqual({value: [0, '1', '2', '3', '4', '5', '6']});
}
}
}
});
it("compiler-spread-optional-length-1", function() {
const schemas = [compile(`
type X = [number, string?, boolean?];
`)];
{
expect(Array.from(schemas[0].keys())).toEqual([
'X',
]);
}
for (const schema of schemas) {
{
const rhs: TypeAssertion = {
name: 'X',
typeName: 'X',
kind: 'sequence',
sequence: [{
kind: 'primitive',
primitiveName: 'number',
}, {
kind: 'optional',
optional: {
kind: 'primitive',
primitiveName: 'string',
},
}, {
kind: 'optional',
optional: {
kind: 'primitive',
primitiveName: 'boolean',
},
}],
};
// const ty = getType(schema, 'X');
for (const ty of [getType(deserialize(serialize(schema)), 'X'), getType(schema, 'X')]) {
expect(ty).toEqual(rhs);
expect(validate<any>([], ty)).toEqual(null);
expect(validate<any>([0], ty)).toEqual({value: [0]});
expect(validate<any>([0, '1'], ty)).toEqual({value: [0, '1']});
expect(validate<any>([0, '1', '2'], ty)).toEqual(null);
expect(validate<any>([0, false], ty)).toEqual(null);
expect(validate<any>([0, '1', false], ty)).toEqual({value: [0, '1', false]});
expect(validate<any>([0, '1', '2', false], ty)).toEqual(null);
expect(validate<any>([0, false, true], ty)).toEqual(null);
expect(validate<any>([0, '1', false, true], ty)).toEqual(null);
expect(validate<any>([0, '1', '2', false, true], ty)).toEqual(null);
}
}
}
});
}); | the_stack |
import { createElement } from '@syncfusion/ej2-base';
import { CircularGauge } from '../../../src/circular-gauge/circular-gauge';
import { ILoadedEventArgs } from '../../../src/circular-gauge/model/interface';
import { profile, inMB, getMemoryProfile } from '../../common.spec';
describe('Circular-Gauge 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;
}
});
describe('Gauge direct properties and its behavior', () => {
let gauge: CircularGauge;
let ele: HTMLElement;
let svg: HTMLElement;
let value: string | number;
beforeAll((): void => {
ele = createElement('div', { id: 'container' });
document.body.appendChild(ele);
gauge = new CircularGauge({
enablePersistence: true
});
gauge.appendTo('#container');
});
afterAll((): void => {
gauge.destroy();
ele.remove();
});
it('Checking with empty options', () => {
let className: string = document.getElementById('container').className;
expect(className.indexOf('e-control') > -1).toBe(true);
});
it('Checking gauge instance creation', (done: Function) => {
gauge.loaded = (args: ILoadedEventArgs): void => {
expect(gauge != null).toBe(true);
done();
};
gauge.refresh();
});
it('Checking module name', () => {
expect(gauge.getModuleName()).toBe('circulargauge');
});
it('Checking the border properties of the gauge', () => {
expect(gauge.border != null).toBe(true);
expect(gauge.border.color == 'transparent').toBe(true);
expect(gauge.border.width == 0).toBe(true);
});
it('Checking the height of the gauge', (done: Function) => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_svg');
expect(svg.getAttribute('height')).toEqual('250');
done();
};
gauge.height = '250';
gauge.dataBind();
});
it('Checking the height of the gauge with percentage', (done: Function) => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_svg');
//expect(svg.getAttribute('height')).toEqual('200');
done();
};
ele.style.height = '400px';
gauge.height = '50%';
gauge.dataBind();
});
it('Checking the width of the gauge', (done: Function) => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_svg');
expect(svg.getAttribute('width')).toEqual('250');
done();
};
gauge.width = '250';
gauge.dataBind();
});
it('Checking the null width of the gauge', (done: Function) => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_svg');
// expect(svg.getAttribute('width')).toEqual('600');
done();
};
gauge.width = null;
ele.setAttribute('style', 'width:0px');
gauge.dataBind();
});
it('Checking the width of the gauge with percentage', (done: Function) => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_svg');
// expect(svg.getAttribute('width')).toEqual('200');
done();
};
ele.style.width = '400px';
gauge.width = '50%';
gauge.dataBind();
});
it('Checking the load event of the gauge', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_svg');
expect(value != '100').toBe(true);
expect(svg.getAttribute('width')).toEqual('100');
gauge.load = null;
done();
};
gauge.load = (args: ILoadedEventArgs): void => {
args.gauge.width = '100';
};
gauge.refresh();
});
it('Checking the gauge border width', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeBorder');
expect(svg != null).toBe(true);
expect(svg.getAttribute('stroke-width') == '2').toBe(true);
gauge.load = null;
done();
};
gauge.border.width = 2;
gauge.dataBind();
});
it('Checking the gauge border width and color', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeBorder');
expect(svg.getAttribute('stroke-width') == '2').toBe(true);
expect(svg.getAttribute('stroke') == 'red').toBe(true);
gauge.load = null;
done();
};
gauge.border.color = 'red';
gauge.dataBind();
});
it('Checking the gauge background and title', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeBorder');
expect(svg.getAttribute('stroke-width') == '2').toBe(true);
expect(svg.getAttribute('fill') == 'violet').toBe(true);
svg = document.getElementById('container_CircularGaugeTitle');
expect(svg == null).toBe(true);
done();
};
gauge.background = 'violet';
gauge.dataBind();
});
it('Checking the gauge title', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeTitle');
expect(svg != null).toBe(true);
expect(svg.textContent == 'This is circular-gauge').toBe(true);
expect(svg.getAttribute('aria-label')).toBe('This is circular-gauge');
done();
};
gauge.title = 'This is circular-gauge';
gauge.dataBind();
});
it('Checking the gauge title with description', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeTitle');
expect(svg != null).toBe(true);
expect(svg.textContent == 'circular-gauge').toBe(true);
expect(svg.getAttribute('aria-label')).toBe('this is title');
done();
};
gauge.description = 'this is title';
gauge.title = 'circular-gauge';
gauge.dataBind();
});
it('Checking the gauge title-style', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeTitle');
expect(svg != null).toBe(true);
expect(svg.getAttribute('fill') == 'green').toBe(true);
expect(svg.style.fontSize == '20px').toBe(true);
done();
};
gauge.titleStyle.color = 'green';
gauge.titleStyle.size = '20px';
gauge.dataBind();
});
it('Checking the gauge title with top margin', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeTitle');
expect(svg != null).toBe(true);
expect(svg.style.fontSize == '12px').toBe(true);
expect(svg.getAttribute('y') == '12' || svg.getAttribute('y') == '11.25').toBe(true);
done();
};
gauge.titleStyle.color = 'green';
gauge.titleStyle.size = '12px';
gauge.margin.top = 0;
gauge.dataBind();
});
it('Checking the data bind method - title style - fill', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeTitle');
expect(svg != null).toBe(true);
expect(svg.style.fontSize == '12px').toBe(true);
expect(svg.getAttribute('fill') == 'red').toBe(true);
done();
};
gauge.titleStyle.color = 'red';
gauge.dataBind();
});
it('Checking the data bind method - title style - font size', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeTitle');
expect(svg != null).toBe(true);
expect(svg.style.fontSize == '14px').toBe(true);
expect(svg.getAttribute('y') != '11.25').toBe(true);
expect(svg.getAttribute('fill') == 'red').toBe(true);
done();
};
gauge.titleStyle.color = 'red';
gauge.titleStyle.size = '14px';
gauge.margin.top = 0;
gauge.dataBind();
});
it('Checking the data bind method - width, height and margin', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_svg');
expect(svg.getAttribute('height')).toEqual('500');
expect(svg.getAttribute('width')).toEqual('500');
done();
};
gauge.width = '500';
gauge.height = '500';
gauge.margin = {
top: 0, left: 0, bottom: 0, right: 0
};
gauge.dataBind();
});
it('Checking the data bind method - center x and center y', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_Axis_0_Pointer_NeedleCap_0');
expect(svg.getAttribute('cx')).toEqual('350');
expect(svg.getAttribute('cy')).toEqual('250');
done();
};
gauge.centerX = '70%';
gauge.centerY = '50%';
gauge.dataBind();
});
it('Checking the gauge background as null with border 0', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeBorder');
expect(svg != null).toBe(true);
done();
};
gauge.background = null;
gauge.border.width = 0;
gauge.dataBind();
});
it('Checking the gauge background as transparent with border 0', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeBorder');
expect(svg != null).toBe(true);
done();
};
gauge.background = 'transparent';
gauge.border.width = 0;
gauge.dataBind();
});
it('Checking the gauge background as transparent with border as value', (done: Function) => {
value = gauge.width;
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeBorder');
expect(svg != null).toBe(true);
done();
};
gauge.theme = 'MaterialDark';
gauge.background = 'transparent';
gauge.border.width = 2;
gauge.refresh();
});
it('Checking touch resize event', (done: Function) => {
gauge.loaded = (args: ILoadedEventArgs): void => {
gauge.loaded = null;
expect(document.getElementById('container_svg').getAttribute('width') == '500').toBe(true);
done();
};
gauge.gaugeResize(<Event>{});
});
it('Checking center x and center y with empty string', (done: Function) => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_AxisLine_0');
let path = svg.getAttribute('d');
expect(path.indexOf('NaN') == -1).toBe(true);
done();
};
gauge.centerX = '';
gauge.centerY = '';
gauge.refresh();
});
});
describe('Checking theme support', () => {
let gauge: CircularGauge;
let element: HTMLElement;
let svg: HTMLElement;
beforeAll((): void => {
element = createElement('div', { id: 'container' });
document.body.appendChild(element);
gauge = new CircularGauge();
gauge.appendTo('#container');
});
afterAll((): void => {
// timeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
element.remove();
});
it('gauge theme support - highcontrast', (done: Function): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeTitle');
expect(svg != null).toBe(true);
svg = document.getElementById('container_Axis_Major_TickLine_0_20');
expect(svg.getAttribute('stroke')).toEqual('#FFFFFF');
done();
};
gauge.titleStyle.color = '';
gauge.theme = 'HighContrast';
gauge.title = 'circular gauge';
gauge.axes[0].majorTicks.width = 5;
gauge.refresh();
});
it('gauge theme support - bootstrap4', (done: Function): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeTitle');
expect(svg != null).toBe(true);
svg = document.getElementById('container_Axis_Major_TickLine_0_20');
expect(svg.getAttribute('stroke')).toEqual('#ADB5BD');
done();
};
gauge.theme = 'Bootstrap4';
gauge.refresh();
});
it('gauge theme support - Dark', (done: Function): void => {
gauge.loaded = (args: ILoadedEventArgs): void => {
svg = document.getElementById('container_CircularGaugeTitle');
expect(svg != null).toBe(true);
svg = document.getElementById('container_Axis_Major_TickLine_0_20');
expect(svg.getAttribute('stroke')).toEqual('#C8C8C8');
done();
};
gauge.axes[0].pointers[0].type = 'Needle';
gauge.axes[0].labelStyle.font.color = '';
gauge.axes[0].majorTicks.color = '';
gauge.axes[0].minorTicks.color = '';
gauge.axes[0].pointers[0].color = '';
gauge.axes[0].pointers[0].needleTail.color = '';
gauge.axes[0].pointers[0].needleTail.border.color = '';
gauge.axes[0].pointers[0].cap.color = '';
gauge.axes[0].pointers[0].cap.border.color = '';
gauge.theme = 'FabricDark';
gauge.title = 'Circular gauge';
gauge.axes[0].majorTicks.width = 5;
gauge.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 * as React from "react";
import CONSTANTS from "../../constants";
import accessibility from "./Accessibility_utils";
import CPX_SVG from "./Cpx_svg";
import * as SvgStyle from "./Cpx_svg_style";
import svg from "./Svg_utils";
interface IProps {
pixels: number[][];
red_led: boolean;
brightness: number;
switch: boolean;
on: boolean;
onKeyEvent: (event: KeyboardEvent, active: boolean) => void;
onMouseUp: (button: HTMLElement, event: Event) => void;
onMouseDown: (button: HTMLElement, event: Event) => void;
onMouseLeave: (button: HTMLElement, event: Event) => void;
}
export class CpxImage extends React.Component<IProps, any> {
componentDidMount() {
const svgElement = window.document.getElementById("cpx_svg");
if (svgElement) {
initSvgStyle(svgElement, this.props.brightness);
setupButtons(this.props);
setupPins(this.props);
this.setupKeyPresses(this.props.onKeyEvent);
setupSwitch(this.props);
this.updateImage();
}
}
componentWillUnmount() {
window.document.removeEventListener("keydown", this.handleKeyDown);
window.document.removeEventListener("keyup", this.handleKeyUp);
}
componentDidUpdate() {
this.updateImage();
}
setupKeyPresses = (
onKeyEvent: (event: KeyboardEvent, active: boolean) => void
) => {
window.document.addEventListener("keydown", this.handleKeyDown);
window.document.addEventListener("keyup", this.handleKeyUp);
};
handleKeyDown = (event: KeyboardEvent) => {
const keyEvents = [event.key, event.code];
// Don't listen to keydown events for the switch, run button, restart button and enter key
if (
!(
keyEvents.includes(CONSTANTS.KEYBOARD_KEYS.S) ||
keyEvents.includes(CONSTANTS.KEYBOARD_KEYS.CAPITAL_F) ||
keyEvents.includes(CONSTANTS.KEYBOARD_KEYS.CAPITAL_R) ||
keyEvents.includes(CONSTANTS.KEYBOARD_KEYS.ENTER)
)
) {
this.props.onKeyEvent(event, true);
}
};
handleKeyUp = (event: KeyboardEvent) => {
this.props.onKeyEvent(event, false);
};
render() {
return CPX_SVG;
}
private updateImage() {
updateNeopixels(this.props);
updateRedLED(this.props.red_led);
updatePowerLED(this.props.on);
updateSwitch(this.props.switch);
}
}
const makeButton = (
g: SVGElement,
left: number,
top: number,
id: string
): { outer: SVGElement; inner: SVGElement } => {
const buttonCornerRadius = SvgStyle.BUTTON_CORNER_RADIUS;
const buttonWidth = SvgStyle.BUTTON_WIDTH;
const buttonCircleRadius = SvgStyle.BUTTON_CIRCLE_RADIUS;
const btng = svg.child(g, "g", { class: "sim-button-group" });
svg.child(btng, "rect", {
fill: SvgStyle.BUTTON_OUTER,
height: buttonWidth,
id: id + "_OUTER",
rx: buttonCornerRadius,
ry: buttonCornerRadius,
width: buttonWidth,
x: left,
y: top,
});
const outer = btng;
const inner = svg.child(btng, "circle", {
id: id + "_INNER",
cx: left + buttonWidth / 2,
cy: top + buttonWidth / 2,
r: buttonCircleRadius,
fill: SvgStyle.BUTTON_NEUTRAL,
});
return { outer, inner };
};
const initSvgStyle = (svgElement: HTMLElement, brightness: number): void => {
const style: SVGStyleElement = svg.child(
svgElement,
"style",
{}
) as SVGStyleElement;
style.textContent = SvgStyle.SVG_STYLE;
// Filters for the glow effect (Adapted from : https://github.com/microsoft/pxt-adafruit/blob/master/sim/visuals/board.ts)
const defs: SVGDefsElement = svg.child(
svgElement,
"defs",
{}
) as SVGDefsElement;
const g = svg.createElement("g") as SVGElement;
svgElement.appendChild(g);
const glow = svg.child(defs, "filter", {
height: "120%",
id: "filterglow",
width: "120%",
x: "-5%",
y: "-5%",
});
svg.child(glow, "feGaussianBlur", { stdDeviation: "5", result: "glow" });
const merge = svg.child(glow, "feMerge", {});
for (let i = 0; i < 3; ++i) {
svg.child(merge, "feMergeNode", { in: "glow" });
}
const neopixelglow = svg.child(defs, "filter", {
height: "600%",
id: "neopixelglow",
width: "600%",
x: "-300%",
y: "-300%",
});
svg.child(neopixelglow, "feGaussianBlur", {
result: "coloredBlur",
stdDeviation: "4.3",
});
const neopixelmerge = svg.child(neopixelglow, "feMerge", {});
svg.child(neopixelmerge, "feMergeNode", { in: "coloredBlur" });
svg.child(neopixelmerge, "feMergeNode", { in: "coloredBlur" });
svg.child(neopixelmerge, "feMergeNode", { in: "SourceGraphic" });
// Brightness
const neopixelfeComponentTransfer = svg.child(
neopixelglow,
"feComponentTransfer",
{}
);
svg.child(neopixelfeComponentTransfer, "feFuncR", {
id: "brightnessFilterR",
type: "linear",
slope: brightness,
});
svg.child(neopixelfeComponentTransfer, "feFuncG", {
id: "brightnessFilterG",
slope: brightness,
type: "linear",
});
svg.child(neopixelfeComponentTransfer, "feFuncB", {
id: "brightnessFilterB",
slope: brightness,
type: "linear",
});
// BTN A+B
const outerBtn = (left: number, top: number, label: string) => {
return makeButton(g, left, top, "BTN_AB");
};
const ab = outerBtn(165, SvgStyle.MB_HEIGHT - 15, "A+B");
const abtext = svg.child(ab.outer, "text", {
class: "sim-text-outside",
x: SvgStyle.BUTTON_TEXT_BASELINE,
y: SvgStyle.MB_HEIGHT - 18,
}) as SVGTextElement;
abtext.textContent = "A+B";
};
const updateNeopixels = (props: IProps): void => {
for (let i = 0; i < props.pixels.length; i++) {
const led = window.document.getElementById(`NEOPIXEL_${i}`);
if (led) {
setNeopixel(led, props.pixels[i], props.brightness);
}
}
};
const updateRedLED = (propsRedLED: boolean): void => {
const redLED = window.document.getElementById("SERIAL_LED");
if (redLED) {
redLED.style.fill = propsRedLED
? SvgStyle.RED_LED_ON
: SvgStyle.RED_LED_OFF;
}
};
const updatePowerLED = (propsPowerLED: boolean): void => {
const powerLED = window.document.getElementById("PWR_LED");
if (powerLED) {
powerLED.style.fill = propsPowerLED
? SvgStyle.POWER_LED_ON
: SvgStyle.POWER_LED_OFF;
}
};
const setNeopixel = (
led: HTMLElement,
pixValue: number[],
brightness: number
): void => {
if (isLightOn(pixValue) && brightness > 0) {
// Neopixels style (Adapted from : https://github.com/microsoft/pxt-adafruit/blob/master/sim/visuals/board.ts)
changeBrightness("brightnessFilterR", brightness);
changeBrightness("brightnessFilterG", brightness);
changeBrightness("brightnessFilterB", brightness);
let [hue, sat, lum] = SvgStyle.rgbToHsl([
pixValue[0],
pixValue[1],
pixValue[2],
]);
const innerLum = Math.max(
lum * SvgStyle.INTENSITY_FACTOR,
SvgStyle.MIN_INNER_LUM
);
lum = (lum * 90) / 100 + 10; // at least 10% luminosity for the stroke
led.style.filter = `url(#neopixelglow)`;
led.style.fill = `hsl(${hue}, ${sat}%, ${innerLum}%)`;
led.style.stroke = `hsl(${hue}, ${sat}%, ${Math.min(
lum * 3,
SvgStyle.MAX_STROKE_LUM
)}%)`;
led.style.strokeWidth = `1.5`;
} else {
led.style.fill = SvgStyle.OFF_COLOR;
led.style.filter = `none`;
led.style.stroke = `none`;
}
};
const isLightOn = (pixValue: number[]): boolean => {
return !pixValue.every(val => {
return val === 0;
});
};
const changeBrightness = (filterID: string, brightness: number): void => {
const brightnessFilter: HTMLElement | null = window.document.getElementById(
filterID
);
if (brightnessFilter) {
brightnessFilter.setAttribute("slope", brightness.toString());
}
};
const setupButtons = (props: IProps): void => {
const outButtons = ["A_OUTER", "B_OUTER", "AB_OUTER"];
const inButtons = ["A_INNER", "B_INNER", "AB_INNER"];
outButtons.forEach(buttonName => {
const button = window.document.getElementById("BTN_" + buttonName);
if (button) {
setupButton(button, "sim-button-outer", props);
}
});
inButtons.forEach(buttonName => {
const button = window.document.getElementById("BTN_" + buttonName);
if (button) {
setupButton(button, "sim-button", props);
}
});
};
const setupPins = (props: IProps): void => {
const pins = [
"PIN_A1",
"PIN_A2",
"PIN_A3",
"PIN_A4",
"PIN_A5",
"PIN_A6",
"PIN_A7",
];
pins.forEach(pinName => {
const pin = window.document.getElementById(pinName);
if (pin) {
const svgPin = (pin as unknown) as SVGElement;
svg.addClass(svgPin, `sim-${pinName}-touch`);
accessibility.makeFocusable(svgPin);
svgPin.onmouseup = e => props.onMouseUp(pin, e);
svgPin.onkeyup = e => props.onKeyEvent(e, false);
svgPin.onmousedown = e => props.onMouseDown(pin, e);
svgPin.onkeydown = e => props.onKeyEvent(e, true);
accessibility.setAria(
svgPin,
"button",
`Touch pin ${pinName.substr(pinName.length - 2)}`
);
}
});
};
const addButtonLabels = (button: HTMLElement) => {
let label = "";
if (button.id.match(/AB/) !== null) {
label = "a+b";
} else if (button.id.match(/A/) !== null) {
label = "a";
} else if (button.id.match(/B/) !== null) {
label = "b";
}
accessibility.setAria(button, "button", label);
};
const setupButton = (button: HTMLElement, className: string, props: IProps) => {
const svgButton = (button as unknown) as SVGElement;
svg.addClass(svgButton, className);
addButtonLabels(button);
if (className.match(/outer/) !== null) {
accessibility.makeFocusable(svgButton);
}
svgButton.onmousedown = e => props.onMouseDown(button, e);
svgButton.onmouseup = e => props.onMouseUp(button, e);
svgButton.onkeydown = e => {
// ensure that the keydown is enter.
// Or else, if the key is a shortcut instead,
// it may register shortcuts twice
if (e.key === CONSTANTS.KEYBOARD_KEYS.ENTER) {
props.onKeyEvent(e, true);
}
};
svgButton.onkeyup = e => props.onKeyEvent(e, false);
svgButton.onmouseleave = e => props.onMouseLeave(button, e);
};
const setupSwitch = (props: IProps): void => {
const switchElement = window.document.getElementById("SWITCH");
const swInnerElement = window.document.getElementById("SWITCH_INNER");
const swHousingElement = window.document.getElementById("SWITCH_HOUSING");
if (switchElement && swInnerElement && swHousingElement) {
const svgSwitch: SVGElement = (switchElement as unknown) as SVGElement;
const svgSwitchInner: SVGElement = (swInnerElement as unknown) as SVGElement;
const svgSwitchHousing: SVGElement = (swHousingElement as unknown) as SVGElement;
svg.addClass(svgSwitch, "sim-slide-switch");
svgSwitch.onmouseup = e => props.onMouseUp(switchElement, e);
svgSwitchInner.onmouseup = e => props.onMouseUp(swInnerElement, e);
svgSwitchHousing.onmouseup = e => props.onMouseUp(swHousingElement, e);
svgSwitch.onkeyup = e => props.onKeyEvent(e, false);
accessibility.makeFocusable(svgSwitch);
accessibility.setAria(svgSwitch, "button", "On/Off Switch");
}
};
export const updateSwitch = (switchState: boolean): void => {
const switchElement = window.document.getElementById("SWITCH");
const switchInner = (window.document.getElementById(
"SWITCH_INNER"
) as unknown) as SVGElement;
if (switchElement && switchInner) {
svg.addClass(switchInner, "sim-slide-switch-inner");
if (!switchState) {
svg.addClass(switchInner, "on");
switchInner.setAttribute("transform", "translate(-5,0)");
} else {
svg.removeClass(switchInner, "on");
switchInner.removeAttribute("transform");
}
switchElement.setAttribute("aria-pressed", switchState.toString());
}
};
export const updatePinTouch = (pinState: boolean, id: string): void => {
console.log(`updating ${id} with ${pinState}`);
const pinElement = window.document.getElementById(id);
const pinSvg: SVGElement = (pinElement as unknown) as SVGElement;
if (pinElement && pinSvg) {
pinElement.setAttribute("aria-pressed", pinState.toString());
pinState
? svg.addClass(pinSvg, "pin-pressed")
: svg.removeClass(pinSvg, "pin-pressed");
}
};
export default CpxImage; | the_stack |
import { TestBed, fakeAsync, tick, flush } from '@angular/core/testing';
import { Component, Type } from '@angular/core';
import { DefaultFocusState } from '@material/menu';
import { LIST_DIRECTIVES } from '../list/mdc.list.directive';
import { MENU_SURFACE_DIRECTIVES } from '../menu-surface/mdc.menu-surface.directive';
import { MENU_DIRECTIVES, MdcMenuDirective } from '../menu/mdc.menu.directive';
import { simulateKey } from '../../testutils/page.test';
import { By } from '@angular/platform-browser';
describe('mdcMenu', () => {
@Component({
template: `
<a href="javascript:void(0)">before</a>
<div id="anchor" mdcMenuAnchor>
<button id="trigger" [mdcMenuTrigger]="menu">Open Menu</button>
<div mdcMenu #menu="mdcMenu" id="surface"
[(open)]="open" (pick)="notify('pick', $event)">
<ul mdcList>
<li mdcListItem><span mdcListItemText>A Menu Item</span></li>
<li mdcListItem [disabled]="item2disabled"><span mdcListItemText>Another Menu Item</span></li>
</ul>
</div>
</div>
<a href="javascript:void(0)">after</a>
`,
styles: [`
#anchor {
left: 150px;
top: 150px;
width: 80px;
height: 20px;
}`
]
})
class TestComponent {
notifications = [];
open = null;
openFrom = null;
fixed = null;
item2disabled = null;
notify(name: string, value: any) {
let notification = {};
notification[name] = value;
this.notifications.push(notification);
}
}
it('open with ArrowDown', fakeAsync(() => {
const { fixture, trigger } = setup();
validateOpenBy(fixture, () => {
simulateKey(trigger, 'ArrowDown');
});
expect(document.activeElement).toBe(listElement(fixture, 0));
}));
it('open with ArrowUp', fakeAsync(() => {
const { fixture, trigger } = setup();
validateOpenBy(fixture, () => {
simulateKey(trigger, 'ArrowUp');
});
expect(document.activeElement).toBe(listElement(fixture, 1));
}));
it('open with Enter', fakeAsync(() => {
const { fixture, trigger } = setup();
validateOpenBy(fixture, () => {
simulateKey(trigger, 'Enter');
trigger.click();
simulateKey(trigger, 'Enter', 'keyup');
});
expect(document.activeElement).toBe(listElement(fixture, 0));
}));
it('open with Space', fakeAsync(() => {
const { fixture, trigger } = setup();
validateOpenBy(fixture, () => {
simulateKey(trigger, 'Space');
trigger.click();
simulateKey(trigger, 'Space', 'keyup');
});
expect(document.activeElement).toBe(listElement(fixture, 0));
}));
it('open with click', fakeAsync(() => {
const { fixture, trigger, list } = setup();
validateOpenBy(fixture, () => {
trigger.click();
});
expect(document.activeElement).toBe(list);
}));
it('close restores focus', fakeAsync(() => {
const { fixture, surface, before, trigger, list } = setup();
before.focus();
validateOpenBy(fixture, () => trigger.click());
expect(document.activeElement).toBe(list);
validateCloseBy(fixture, () => simulateKey(surface, 'Escape'));
expect(document.activeElement).toBe(before);
}));
it('close with tab key does not restore focus', fakeAsync(() => {
const { fixture, surface, list, before, trigger, testComponent } = setup();
before.focus();
validateOpenBy(fixture, () => trigger.click());
expect(document.activeElement).toBe(list);
validateCloseBy(fixture, () => simulateKey(surface, 'Tab'));
// focus is unchanged from open state - (when a user presses the Tab key, focus will be changed to the next element)
expect(document.activeElement).toBe(list);
// no menu item picked:
expect(testComponent.notifications).toEqual([]);
}));
it('close with picking a menu item restores focus', fakeAsync(() => {
const { fixture, before, testComponent } = setup();
before.focus();
validateCloseBy(fixture, () => listElement(fixture, 1).click());
expect(document.activeElement).toBe(before);
expect(testComponent.notifications).toEqual([
{pick: {index: 1, value: null}}
]);
}));
it('menu list has role=menu; items have role=menuitem', fakeAsync(() => {
const { list, items } = setup();
expect(list.getAttribute('role')).toBe('menu');
items.forEach(item => expect(item.getAttribute('role')).toBe('menuitem'));
}));
it('menu list aria attributes and tabindex', fakeAsync(() => {
const { fixture, surface, list, trigger } = setup();
expect(list.getAttribute('tabindex')).toBe('-1');
expect(list.getAttribute('aria-hidden')).toBe('true');
expect(list.getAttribute('aria-orientation')).toBe('vertical');
validateOpenBy(fixture, () => trigger.click());
expect(list.hasAttribute('aria-hidden')).toBeFalse();
validateCloseBy(fixture, () => simulateKey(surface, 'Escape'));
expect(list.getAttribute('aria-orientation')).toBe('vertical');
}));
it('disabled menu item', fakeAsync(() => {
const { fixture, testComponent } = setup();
testComponent.item2disabled = true;
fixture.detectChanges();
const items = [...fixture.nativeElement.querySelectorAll('li')];
expect(items[0].classList).not.toContain('mdc-list-item--disabled');
expect(items[0].hasAttribute('aria-disabled')).toBeFalse();
expect(items[1].classList).toContain('mdc-list-item--disabled');
expect(items[1].getAttribute('aria-disabled')).toBe('true');
}));
@Component({
template: `
<div mdcMenuAnchor>
<button [mdcMenuTrigger]="menu">Open Menu</button>
<div mdcMenu #menu="mdcMenu">
<ul *ngIf="firstList" mdcList id="list1">
<li mdcListItem><span mdcListItemText>1 - 1</span></li>
</ul>
<ul *ngIf="!firstList" mdcList id="list2">
<li mdcListItem><span mdcListItemText>2 - 1</span></li>
<li mdcListItem><span mdcListItemText>2 - 2</span></li>
</ul>
</div>
</div>
<a href="javascript:void(0)">after</a>
`
})
class TestChangeListComponent {
firstList = true;
}
it('underlying list can be changed', fakeAsync(() => {
let { fixture, list, items, trigger, testComponent } = setup(TestChangeListComponent);
expect(list.id).toBe('list1');
expect(list.getAttribute('role')).toBe('menu');
items.forEach(item => expect(item.getAttribute('role')).toBe('menuitem'));
expect(list.getAttribute('tabindex')).toBe('-1');
testComponent.firstList = false;
fixture.detectChanges(); tick();
list = fixture.nativeElement.querySelector('ul');
items = [...fixture.nativeElement.querySelectorAll('li')];
expect(list.id).toBe('list2');
expect(list.getAttribute('role')).toBe('menu');
items.forEach(item => expect(item.getAttribute('role')).toBe('menuitem'));
expect(list.getAttribute('tabindex')).toBe('-1');
validateOpenBy(fixture, () => trigger.click(), TestChangeListComponent);
}));
@Component({
template: `
<div mdcMenuAnchor>
<button [mdcMenuTrigger]="menu">Open Menu</button>
<div mdcMenu #menu="mdcMenu">
<ul mdcList>
<li *ngFor="let item of items" mdcListItem [value]="item.value">
<span mdcListItemText>{{item.text}}</span>
</li>
</ul>
</div>
</div>
`
})
class TestListItemNgForComponent {
items = [
{value: 'item1', text: 'First Item'},
{value: 'item2', text: 'Second Item'}
];
}
it('menu items in ngFor', fakeAsync(() => {
let { fixture, list, items, trigger, testComponent } = setup(TestListItemNgForComponent);
expect(list.getAttribute('role')).toBe('menu');
expect(items.length).toBe(2);
items.forEach(item => expect(item.getAttribute('role')).toBe('menuitem'));
expect(list.getAttribute('tabindex')).toBe('-1');
testComponent.items.push({value: 'item3', text: 'Third Item'});
// this would previously throw ExpressionChangedAfterItHasBeenCheckedError;
// fixed by calling ChangeDetectorRef.detectChanges after child components are
// updated in MdcListDirective.ngAfterContentInit:
fixture.detectChanges(); tick();
list = fixture.nativeElement.querySelector('ul');
items = [...fixture.nativeElement.querySelectorAll('li')];
expect(list.getAttribute('role')).toBe('menu');
expect(items.length).toBe(3);
items.forEach(item => expect(item.getAttribute('role')).toBe('menuitem'));
expect(list.getAttribute('tabindex')).toBe('-1');
validateOpenBy(fixture, () => trigger.click(), TestListItemNgForComponent);
}));
function validateOpenBy(fixture, doOpen: () => void, compType: Type<any> = TestComponent) {
const { surface } = getElements(fixture, compType);
expect(surface.classList).not.toContain('mdc-menu-surface--open');
doOpen();
animationCycle(fixture);
expect(surface.classList).toContain('mdc-menu-surface--open');
validateDefaultFocusState(fixture);
}
function validateCloseBy(fixture, doClose: () => void, compType: Type<any> = TestComponent) {
const { surface } = getElements(fixture, compType);
doClose();
animationCycle(fixture);
expect(surface.classList).not.toContain('mdc-menu-surface--open');
}
function setup(compType: Type<any> = TestComponent) {
const fixture = TestBed.configureTestingModule({
declarations: [...LIST_DIRECTIVES, ...MENU_SURFACE_DIRECTIVES, ...MENU_DIRECTIVES, ...LIST_DIRECTIVES, compType]
}).createComponent(compType);
fixture.detectChanges(); tick();
return getElements(fixture, compType);
}
function getElements(fixture, compType: Type<any> = TestComponent) {
const testComponent = fixture.debugElement.injector.get(compType);
const menuDirective = fixture.debugElement.query(By.directive(MdcMenuDirective)).injector.get(MdcMenuDirective);
const anchor: HTMLElement = fixture.nativeElement.querySelector('.mdc-menu-surface--anchor');
const surface: HTMLElement = fixture.nativeElement.querySelector('.mdc-menu-surface');
const trigger: HTMLElement = fixture.nativeElement.querySelector('button');
const list: HTMLElement = fixture.nativeElement.querySelector('ul');
const before: HTMLAnchorElement = fixture.nativeElement.querySelectorAll('a').item(0);
const after: HTMLAnchorElement = fixture.nativeElement.querySelectorAll('a').item(1);
const items: HTMLElement[] = [...fixture.nativeElement.querySelectorAll('li')];
return { fixture, anchor, surface, trigger, list, testComponent, menuDirective, before, after, items };
}
function listElement(fixture, index) {
return fixture.nativeElement.querySelectorAll('li').item(index);
}
function validateDefaultFocusState(fixture) {
const menuDirective = fixture.debugElement.query(By.directive(MdcMenuDirective)).injector.get(MdcMenuDirective);
// default focus state should always NONE when not currently handling an open/close:
expect(menuDirective['foundation']['defaultFocusState_']).toBe(DefaultFocusState.NONE);
}
});
describe('mdcMenuTrigger', () => {
@Component({
template: `
<div mdcMenuAnchor>
<a href="javascript:void(0)" id="trigger1" [mdcMenuTrigger]="menu1">Open Menu1</a>
<div mdcMenu #menu1="mdcMenu" id="surface1"
[(open)]="open[0]">
<ul mdcList>
<li mdcListItem><span mdcListItemText>A Menu Item</span></li>
<li mdcListItem><span mdcListItemText>Another Menu Item</span></li>
</ul>
</div>
</div>
<div mdcMenuAnchor>
<button [mdcMenuTrigger]="menu2">Open Menu2</button>
<div mdcMenu #menu2="mdcMenu" [(open)]="open[1]">
<ul mdcList>
<li mdcListItem><span mdcListItemText>A Menu Item</span></li>
<li mdcListItem><span mdcListItemText>Another Menu Item</span></li>
</ul>
</div>
</div>
<button [mdcMenuTrigger]="">Whatever</button>
`,
styles: [`
#anchor {
left: 150px;
top: 150px;
width: 80px;
height: 20px;
}`
]
})
class TestComponent {
open = [false, false, false];
}
it('accessibility attributes mdcMenuTrigger', fakeAsync(() => {
const { fixture, triggers, surfaces } = setup();
// anchor element as menuTrigger; template assigned id:
expect(surfaces[0].id).toBe('surface1');
expect(triggers[0].getAttribute('role')).toBe('button');
expect(triggers[0].getAttribute('aria-haspopup')).toBe('menu');
expect(triggers[0].getAttribute('aria-controls')).toBe('surface1');
expect(triggers[0].hasAttribute('aria-expanded')).toBeFalse();
// button as menuTrigger, unique id assigned by menu:
expect(surfaces[1].id).toMatch(/mdc-menu-.*/);
expect(triggers[1].hasAttribute('role')).toBeFalse();
expect(triggers[1].getAttribute('aria-haspopup')).toBe('menu');
expect(triggers[1].getAttribute('aria-controls')).toBe(surfaces[1].id);
expect(triggers[1].hasAttribute('aria-expanded')).toBeFalse();
// not attached to a menu:
expect(triggers[2].hasAttribute('role')).toBeFalse();
expect(triggers[2].hasAttribute('aria-haspopup')).toBeFalse();
expect(triggers[2].hasAttribute('aria-controls')).toBeFalse();
expect(triggers[2].hasAttribute('aria-expanded')).toBeFalse();
// open:
triggers[0].click();
animationCycle(fixture);
expect(triggers[0].getAttribute('aria-expanded')).toBe('true');
// close:
simulateKey(surfaces[0], 'Escape');
animationCycle(fixture);
expect(triggers[0].hasAttribute('aria-expanded')).toBeFalse();
}));
function setup(compType: Type<any> = TestComponent) {
const fixture = TestBed.configureTestingModule({
declarations: [...LIST_DIRECTIVES, ...MENU_SURFACE_DIRECTIVES, ...MENU_DIRECTIVES, ...LIST_DIRECTIVES, compType]
}).createComponent(compType);
fixture.detectChanges();
return getElements(fixture);
}
function getElements(fixture, compType: Type<any> = TestComponent) {
const testComponent = fixture.debugElement.injector.get(compType);
const surfaces: HTMLElement[] = [...fixture.nativeElement.querySelectorAll('.mdc-menu-surface')];
const triggers: HTMLElement[] = [...fixture.nativeElement.querySelectorAll('a,button')];
return { fixture, surfaces, triggers, testComponent };
}
});
function animationCycle(fixture) {
fixture.detectChanges(); tick(300); flush();
} | the_stack |
import type {Mutable, Class} from "@swim/util";
import {Affinity, MemberFastenerClass, Property} from "@swim/component";
import {AnyLength, Length, R2Box} from "@swim/math";
import {AnyExpansion, Expansion} from "@swim/style";
import {Look, ThemeAnimator, ExpansionThemeAnimator, ThemeConstraintAnimator} from "@swim/theme";
import {
PositionGestureInput,
ViewContextType,
ViewContext,
ViewFlags,
ViewCreator,
View,
ViewRef,
} from "@swim/view";
import {HtmlView} from "@swim/dom";
import {AnyTableLayout, TableLayout} from "../layout/TableLayout";
import type {CellView} from "../cell/CellView";
import {LeafView} from "../leaf/LeafView";
import type {RowViewObserver} from "./RowViewObserver";
import type {TableViewContext} from "../table/TableViewContext";
import {TableView} from "../"; // forward reference
/** @public */
export class RowView extends HtmlView {
constructor(node: HTMLElement) {
super(node);
this.visibleFrame = new R2Box(0, 0, window.innerWidth, window.innerHeight);
this.initRow();
}
protected initRow(): void {
this.addClass("row");
this.position.setState("relative", Affinity.Intrinsic);
}
override readonly observerType?: Class<RowViewObserver>;
override readonly contextType?: Class<TableViewContext>;
@Property({type: TableLayout, inherits: true, value: null, updateFlags: View.NeedsLayout})
readonly layout!: Property<this, TableLayout | null, AnyTableLayout | null>;
@Property<RowView, number>({
type: Number,
inherits: true,
value: 0,
updateFlags: View.NeedsLayout,
didSetValue(newDepth: number, oldDepth: number): void {
const treeView = this.owner.tree.view;
if (treeView !== null) {
treeView.depth.setValue(newDepth + 1, Affinity.Intrinsic);
}
},
})
readonly depth!: Property<this, number>;
@ThemeConstraintAnimator({type: Length, inherits: true, value: null, updateFlags: View.NeedsLayout})
readonly rowSpacing!: ThemeConstraintAnimator<this, Length | null, AnyLength | null>;
@ThemeConstraintAnimator({type: Length, inherits: true, value: null, updateFlags: View.NeedsLayout})
readonly rowHeight!: ThemeConstraintAnimator<this, Length | null, AnyLength | null>;
@Property({type: Boolean, inherits: true, value: false})
readonly hovers!: Property<this, boolean>;
@Property({type: Boolean, inherits: true, value: true})
readonly glows!: Property<this, boolean>;
getCell<F extends abstract new (...args: any) => CellView>(key: string, cellViewClass: F): InstanceType<F> | null;
getCell(key: string): CellView | null;
getCell(key: string, cellViewClass?: abstract new (...args: any) => CellView): CellView | null {
const leafView = this.leaf.view;
return leafView !== null ? leafView.getCell(key, cellViewClass!) : null;
}
getOrCreateCell<F extends ViewCreator<F, CellView>>(key: string, cellViewClass: F): InstanceType<F> {
const leafView = this.leaf.insertView();
if (leafView === null) {
throw new Error("no leaf view");
}
return leafView.getOrCreateCell(key, cellViewClass);
}
setCell(key: string, cellView: CellView): void {
const leafView = this.leaf.insertView();
if (leafView === null) {
throw new Error("no leaf view");
}
leafView.setCell(key, cellView);
}
@ViewRef<RowView, LeafView>({
key: true,
type: LeafView,
binds: true,
observes: true,
initView(leafView: LeafView): void {
leafView.display.setState("none", Affinity.Intrinsic);
leafView.position.setState("absolute", Affinity.Intrinsic);
leafView.left.setState(0, Affinity.Intrinsic);
leafView.top.setState(0, Affinity.Intrinsic);
const layout = this.owner.layout.value;
leafView.width.setState(layout !== null ? layout.width : null, Affinity.Intrinsic);
leafView.zIndex.setState(1, Affinity.Intrinsic);
},
willAttachView(leafView: LeafView): void {
this.owner.callObservers("viewWillAttachLeaf", leafView, this.owner);
},
didDetachView(leafView: LeafView): void {
this.owner.callObservers("viewDidDetachLeaf", leafView, this.owner);
},
viewWillHighlight(leafView: LeafView): void {
this.owner.callObservers("viewWillHighlightLeaf", leafView, this.owner);
},
viewDidHighlight(leafView: LeafView): void {
this.owner.callObservers("viewDidHighlightLeaf", leafView, this.owner);
},
viewWillUnhighlight(leafView: LeafView): void {
this.owner.callObservers("viewWillUnhighlightLeaf", leafView, this.owner);
},
viewDidUnhighlight(leafView: LeafView): void {
this.owner.callObservers("viewDidUnhighlightLeaf", leafView, this.owner);
},
viewDidEnter(leafView: LeafView): void {
this.owner.callObservers("viewDidEnterLeaf", leafView, this.owner);
},
viewDidLeave(leafView: LeafView): void {
this.owner.callObservers("viewDidLeaveLeaf", leafView, this.owner);
},
viewDidPress(input: PositionGestureInput, event: Event | null, leafView: LeafView): void {
this.owner.callObservers("viewDidPressLeaf", input, event, leafView, this.owner);
},
viewDidLongPress(input: PositionGestureInput, leafView: LeafView): void {
this.owner.callObservers("viewDidLongPressLeaf", input, leafView, this.owner);
},
})
readonly leaf!: ViewRef<this, LeafView>;
static readonly leaf: MemberFastenerClass<RowView, "leaf">;
@ViewRef<RowView, HtmlView>({
key: true,
type: HtmlView,
binds: true,
initView(headView: HtmlView): void {
headView.addClass("head");
headView.display.setState("none", Affinity.Intrinsic);
headView.position.setState("absolute", Affinity.Intrinsic);
headView.left.setState(0, Affinity.Intrinsic);
headView.top.setState(this.owner.rowHeight.state, Affinity.Intrinsic);
const layout = this.owner.layout.value;
headView.width.setState(layout !== null ? layout.width : null, Affinity.Intrinsic);
headView.height.setState(this.owner.rowSpacing.state, Affinity.Intrinsic);
headView.backgroundColor.setLook(Look.accentColor, Affinity.Intrinsic);
headView.opacity.setState(this.owner.disclosing.phase, Affinity.Intrinsic);
headView.zIndex.setState(1, Affinity.Intrinsic);
},
})
readonly head!: ViewRef<this, HtmlView>;
static readonly head: MemberFastenerClass<RowView, "head">;
@ViewRef<RowView, TableView>({
key: true,
// avoid cyclic static reference to type: TableView
binds: true,
initView(treeView: TableView): void {
treeView.addClass("tree");
treeView.display.setState(this.owner.disclosure.collapsed ? "none" : "block", Affinity.Intrinsic);
treeView.position.setState("absolute", Affinity.Intrinsic);
treeView.left.setState(0, Affinity.Intrinsic);
const layout = this.owner.layout.value;
treeView.width.setState(layout !== null ? layout.width : null, Affinity.Intrinsic);
treeView.zIndex.setState(0, Affinity.Intrinsic);
treeView.depth.setValue(this.owner.depth.value + 1, Affinity.Intrinsic);
},
willAttachView(treeView: TableView): void {
this.owner.callObservers("viewWillAttachTree", treeView, this.owner);
},
didDetachView(treeView: TableView): void {
this.owner.callObservers("viewDidDetachTree", treeView, this.owner);
},
createView(): TableView {
return TableView.create();
},
})
readonly tree!: ViewRef<this, TableView>;
static readonly tree: MemberFastenerClass<RowView, "tree">;
@ViewRef<RowView, HtmlView>({
key: true,
type: HtmlView,
binds: true,
initView(footView: HtmlView): void {
footView.addClass("foot");
footView.display.setState("none", Affinity.Intrinsic);
footView.position.setState("absolute", Affinity.Intrinsic);
footView.left.setState(0, Affinity.Intrinsic);
footView.top.setState(this.owner.rowHeight.state, Affinity.Intrinsic);
const layout = this.owner.layout.value;
footView.width.setState(layout !== null ? layout.width : null, Affinity.Intrinsic);
footView.height.setState(this.owner.rowSpacing.state, Affinity.Intrinsic);
footView.backgroundColor.setLook(Look.borderColor, Affinity.Intrinsic);
footView.opacity.setState(this.owner.disclosing.phase, Affinity.Intrinsic);
footView.zIndex.setState(1, Affinity.Intrinsic);
},
})
readonly foot!: ViewRef<this, HtmlView>;
static readonly foot: MemberFastenerClass<RowView, "foot">;
@ThemeAnimator<RowView, Expansion>({
type: Expansion,
value: Expansion.collapsed(),
willExpand(): void {
this.owner.callObservers("viewWillExpand", this.owner);
const treeView = this.owner.tree.view;
if (treeView !== null) {
treeView.display.setState("block", Affinity.Intrinsic);
}
},
didExpand(): void {
this.owner.callObservers("viewDidExpand", this.owner);
},
willCollapse(): void {
this.owner.callObservers("viewWillCollapse", this.owner);
},
didCollapse(): void {
const treeView = this.owner.tree.view;
if (treeView !== null) {
treeView.display.setState("none", Affinity.Intrinsic);
}
this.owner.callObservers("viewDidCollapse", this.owner);
},
didSetValue(newDisclosure: Expansion, oldDisclosure: Expansion): void {
if (newDisclosure.direction !== 0) {
this.owner.disclosing.setState(newDisclosure, Affinity.Intrinsic);
} else {
this.owner.disclosing.setState(null, Affinity.Intrinsic);
this.owner.disclosing.setAffinity(Affinity.Transient);
}
const tableView = this.owner.getBase(TableView);
if (tableView !== null) {
tableView.requireUpdate(View.NeedsLayout);
}
},
})
readonly disclosure!: ExpansionThemeAnimator<this, Expansion, AnyExpansion>;
@ThemeAnimator({type: Expansion, inherits: true, value: null, updateFlags: View.NeedsLayout})
readonly disclosing!: ExpansionThemeAnimator<this, Expansion | null, AnyExpansion | null>;
/** @internal */
readonly visibleFrame!: R2Box;
protected detectVisibleFrame(viewContext: ViewContext): R2Box {
const xBleed = 0;
const yBleed = this.rowHeight.getValueOr(Length.zero()).pxValue();
const parentVisibleFrame = (viewContext as TableViewContext).visibleFrame as R2Box | undefined;
if (parentVisibleFrame !== void 0) {
let left: Length | number | null = this.left.state;
left = left instanceof Length ? left.pxValue() : 0;
let top: Length | number | null = this.top.state;
top = top instanceof Length ? top.pxValue() : 0;
return new R2Box(parentVisibleFrame.xMin - left - xBleed, parentVisibleFrame.yMin - top - yBleed,
parentVisibleFrame.xMax - left + xBleed, parentVisibleFrame.yMax - top + yBleed);
} else {
const bounds = this.node.getBoundingClientRect();
const xMin = -bounds.x - xBleed;
const yMin = -bounds.y - yBleed;
const xMax = window.innerWidth - bounds.x + xBleed;
const yMax = window.innerHeight - bounds.y + yBleed;
return new R2Box(xMin, yMin, xMax, yMax);
}
}
override extendViewContext(viewContext: ViewContext): ViewContextType<this> {
const treeViewContext = Object.create(viewContext);
treeViewContext.visibleFrame = this.visibleFrame;
return treeViewContext;
}
protected override onProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): void {
super.onProcess(processFlags, viewContext);
const visibleFrame = this.detectVisibleFrame(Object.getPrototypeOf(viewContext));
(this as Mutable<this>).visibleFrame = visibleFrame;
(viewContext as Mutable<ViewContextType<this>>).visibleFrame = this.visibleFrame;
}
protected override needsProcess(processFlags: ViewFlags, viewContext: ViewContextType<this>): ViewFlags {
if ((processFlags & View.NeedsResize) !== 0) {
processFlags |= View.NeedsScroll;
}
return processFlags;
}
protected override onDisplay(displayFlags: ViewFlags, viewContext: ViewContextType<this>): void {
super.onDisplay(displayFlags, viewContext);
const visibleFrame = this.detectVisibleFrame(Object.getPrototypeOf(viewContext));
(this as Mutable<this>).visibleFrame = visibleFrame;
(viewContext as Mutable<ViewContextType<this>>).visibleFrame = this.visibleFrame;
}
protected override onLayout(viewContext: ViewContextType<this>): void {
super.onLayout(viewContext);
this.resizeRow();
const leafView = this.leaf.view;
if (leafView !== null) {
this.layoutLeaf(leafView);
}
}
protected resizeRow(): void {
const oldLayout = !this.layout.inherited ? this.layout.value : null;
if (oldLayout !== null) {
const superLayout = this.layout.superValue;
let width: Length | number | null = null;
if (superLayout !== void 0 && superLayout !== null && superLayout.width !== null) {
width = superLayout.width.pxValue();
}
if (width === null) {
width = this.width.state;
width = width instanceof Length ? width.pxValue() : this.node.offsetWidth;
}
const newLayout = oldLayout.resized(width, 0, 0);
this.layout.setValue(newLayout);
}
}
protected layoutLeaf(leafView: LeafView): void {
const layout = this.layout.value;
const width = layout !== null ? layout.width : null;
const timing = this.getLook(Look.timing);
leafView.top.setState(0, timing, Affinity.Intrinsic);
leafView.width.setState(width, Affinity.Intrinsic);
}
protected override didLayout(viewContext: ViewContextType<this>): void {
this.layoutRow();
super.didLayout(viewContext);
}
protected layoutRow(): void {
const layout = this.layout.value;
const width = layout !== null ? layout.width : null;
const rowSpacing = this.rowSpacing.getValueOr(Length.zero()).pxValue();
const disclosure = this.disclosure.getValue();
const disclosingPhase = this.disclosing.getPhaseOr(1);
let leafHeightValue: Length | number | null = 0;
let leafHeightState: Length | number | null = 0;
const leafView = this.leaf.view;
if (leafView !== null) {
leafView.width.setState(width, Affinity.Intrinsic);
leafView.display.setState("flex", Affinity.Intrinsic);
leafHeightValue = leafView.height.value;
leafHeightValue = leafHeightValue instanceof Length ? leafHeightValue.pxValue() : leafView.node.offsetHeight;
leafHeightState = leafView.height.state;
leafHeightState = leafHeightState instanceof Length ? leafHeightState.pxValue() : leafHeightValue;
}
const headView = this.head.view;
if (headView !== null) {
if (!disclosure.collapsed) {
headView.top.setState(leafHeightValue, Affinity.Intrinsic);
headView.width.setState(width, Affinity.Intrinsic);
headView.height.setState(rowSpacing * disclosingPhase, Affinity.Intrinsic);
headView.opacity.setState(disclosingPhase, Affinity.Intrinsic);
headView.display.setState("block", Affinity.Intrinsic);
} else {
headView.display.setState("none", Affinity.Intrinsic);
}
}
let treeHeightValue: Length | number | null = 0;
let treeHeightState: Length | number | null = 0;
const treeView = this.tree.view;
if (treeView !== null) {
if (!disclosure.collapsed) {
treeView.top.setState((leafHeightValue + rowSpacing) * disclosingPhase, Affinity.Intrinsic);
treeView.width.setState(width, Affinity.Intrinsic);
treeView.display.setState("block", Affinity.Intrinsic);
treeHeightValue = treeView.height.value;
treeHeightValue = treeHeightValue instanceof Length ? treeHeightValue.pxValue() : treeView.node.offsetHeight;
treeHeightValue += rowSpacing;
treeHeightState = treeView.height.state;
treeHeightState = treeHeightState instanceof Length ? treeHeightState.pxValue() : treeHeightValue;
treeHeightState += rowSpacing;
} else {
treeView.display.setState("none", Affinity.Intrinsic);
}
}
const footView = this.foot.view;
if (footView !== null) {
if (!disclosure.collapsed) {
footView.top.setState(leafHeightValue + treeHeightValue, Affinity.Intrinsic);
footView.width.setState(width, Affinity.Intrinsic);
footView.height.setState(rowSpacing * disclosingPhase, Affinity.Intrinsic);
footView.opacity.setState(disclosingPhase, Affinity.Intrinsic);
footView.display.setState("block", Affinity.Intrinsic);
} else {
footView.display.setState("none", Affinity.Intrinsic);
}
}
if (this.height.hasAffinity(Affinity.Intrinsic)) {
const heightValue = leafHeightValue + treeHeightValue * disclosingPhase;
const heightState = leafHeightState + treeHeightState;
this.height.setInterpolatedValue(Length.px(heightValue), Length.px(heightState));
}
}
protected override onCull(): void {
super.onCull();
this.display.setState("none", Affinity.Intrinsic);
}
protected override onUncull(): void {
super.onUncull();
this.display.setState("block", Affinity.Intrinsic);
}
} | the_stack |
export const mockChatLogs = [
{
items: [
{
payload: {
level: 0,
text: 'Emulator listening on http://localhost:60002',
},
type: 'text',
},
],
timestamp: 1561995656213,
},
{
items: [
{
payload: {
level: 0,
text: 'ngrok not configured (only needed when connecting to remotely hosted bots)',
},
type: 'text',
},
],
timestamp: 1561995656213,
},
{
items: [
{
payload: {
hyperlink: 'https://aka.ms/cnjvpo',
text: 'Connecting to bots hosted remotely',
},
type: 'external-link',
},
],
timestamp: 1561995656213,
},
{
items: [
{
payload: {
text: 'Edit ngrok settings',
},
type: 'open-app-settings',
},
],
timestamp: 1561995656214,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: '9dcd6cd0-9c16-11e9-a2fc-f170e382beae',
label: 'Command',
localTimestamp: '2019-07-01T08:40:56-07:00',
locale: 'en-US',
name: 'Command',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
replyToId: '9dcc5b62-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:40:56.221Z',
type: 'trace',
value: '/INSPECT attach d40aac28-2948-7d20-0b45-218e4e3aac47',
valueType: 'https://www.botframework.com/schemas/command',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: '9dcd6cd0-9c16-11e9-a2fc-f170e382beae',
label: 'Command',
localTimestamp: '2019-07-01T08:40:56-07:00',
locale: 'en-US',
name: 'Command',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
replyToId: '9dcc5b62-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:40:56.221Z',
type: 'trace',
value: '/INSPECT attach d40aac28-2948-7d20-0b45-218e4e3aac47',
valueType: 'https://www.botframework.com/schemas/command',
},
},
type: 'summary-text',
},
],
timestamp: 1561995656222,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a3ead300-9c16-11e9-a2fc-f170e382beae',
label: 'Received Activity',
localTimestamp: '2019-07-01T08:41:06-07:00',
locale: 'en-US',
name: 'ReceivedActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:06.480Z',
type: 'trace',
value: {
channelData: {
clientActivityID: '15619956664690.bduatnj3x2',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a3e9e8a0-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:06.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Hi',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:06.474Z',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a3ead300-9c16-11e9-a2fc-f170e382beae',
label: 'Received Activity',
localTimestamp: '2019-07-01T08:41:06-07:00',
locale: 'en-US',
name: 'ReceivedActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:06.480Z',
type: 'trace',
value: {
channelData: {
clientActivityID: '15619956664690.bduatnj3x2',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a3e9e8a0-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:06.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Hi',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:06.474Z',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
},
type: 'summary-text',
},
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelData: {
clientActivityID: '15619956664690.bduatnj3x2',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a3e9e8a0-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:06.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Hi',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:06.474Z',
type: 'message',
},
text: 'message',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelData: {
clientActivityID: '15619956664690.bduatnj3x2',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a3e9e8a0-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:06.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Hi',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:06.474Z',
type: 'message',
},
},
type: 'summary-text',
},
],
timestamp: 1561995666480,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a3ebe470-9c16-11e9-a2fc-f170e382beae',
label: 'Sent Activity',
localTimestamp: '2019-07-01T08:41:06-07:00',
locale: 'en-US',
name: 'SentActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:06.487Z',
type: 'trace',
value: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a3ebe470-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a3e9e8a0-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your first name.',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a3ebe470-9c16-11e9-a2fc-f170e382beae',
label: 'Sent Activity',
localTimestamp: '2019-07-01T08:41:06-07:00',
locale: 'en-US',
name: 'SentActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:06.487Z',
type: 'trace',
value: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a3ebe470-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a3e9e8a0-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your first name.',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
},
type: 'summary-text',
},
{
payload: {
level: 0,
text: '-> ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a3ebe470-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a3e9e8a0-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your first name.',
type: 'message',
},
text: 'message',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a3ebe470-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a3e9e8a0-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your first name.',
type: 'message',
},
},
type: 'summary-text',
},
],
timestamp: 1561995666487,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a3ed6b10-9c16-11e9-a2fc-f170e382beae',
label: 'Bot State',
localTimestamp: '2019-07-01T08:41:06-07:00',
locale: 'en-US',
name: 'BotState',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:06.497Z',
type: 'trace',
value: {
conversationState: {
dialogState: {
dialogStack: [
{
id: 'root',
state: {
options: {},
stepIndex: 0,
values: {
instanceId: '6e732f12-4b0e-1b19-95c6-50213cd9ec1d',
},
},
},
{
id: 'slot-dialog',
state: {
slot: 'fullname',
values: {},
},
},
{
id: 'fullname',
state: {
slot: 'first',
values: {},
},
},
{
id: 'text',
state: {
options: {
prompt: 'Please enter your first name.',
},
state: {},
},
},
],
},
eTag: '*',
},
userState: {},
},
valueType: 'https://www.botframework.com/schemas/botState',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a3ed6b10-9c16-11e9-a2fc-f170e382beae',
label: 'Bot State',
localTimestamp: '2019-07-01T08:41:06-07:00',
locale: 'en-US',
name: 'BotState',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:06.497Z',
type: 'trace',
value: {
conversationState: {
dialogState: {
dialogStack: [
{
id: 'root',
state: {
options: {},
stepIndex: 0,
values: {
instanceId: '6e732f12-4b0e-1b19-95c6-50213cd9ec1d',
},
},
},
{
id: 'slot-dialog',
state: {
slot: 'fullname',
values: {},
},
},
{
id: 'fullname',
state: {
slot: 'first',
values: {},
},
},
{
id: 'text',
state: {
options: {
prompt: 'Please enter your first name.',
},
state: {},
},
},
],
},
eTag: '*',
},
userState: {},
},
valueType: 'https://www.botframework.com/schemas/botState',
},
},
type: 'summary-text',
},
],
timestamp: 1561995666497,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a5c6bef0-9c16-11e9-a2fc-f170e382beae',
label: 'Received Activity',
localTimestamp: '2019-07-01T08:41:09-07:00',
locale: 'en-US',
name: 'ReceivedActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:09.599Z',
type: 'trace',
value: {
channelData: {
clientActivityID: '15619956695770.qysf656hq9o',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a5c5d490-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:09.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Joe',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:09.593Z',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a5c6bef0-9c16-11e9-a2fc-f170e382beae',
label: 'Received Activity',
localTimestamp: '2019-07-01T08:41:09-07:00',
locale: 'en-US',
name: 'ReceivedActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:09.599Z',
type: 'trace',
value: {
channelData: {
clientActivityID: '15619956695770.qysf656hq9o',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a5c5d490-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:09.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Joe',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:09.593Z',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
},
type: 'summary-text',
},
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelData: {
clientActivityID: '15619956695770.qysf656hq9o',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a5c5d490-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:09.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Joe',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:09.593Z',
type: 'message',
},
text: 'message',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelData: {
clientActivityID: '15619956695770.qysf656hq9o',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a5c5d490-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:09.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Joe',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:09.593Z',
type: 'message',
},
},
type: 'summary-text',
},
],
timestamp: 1561995669599,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a5c7a950-9c16-11e9-a2fc-f170e382beae',
label: 'Sent Activity',
localTimestamp: '2019-07-01T08:41:09-07:00',
locale: 'en-US',
name: 'SentActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:09.605Z',
type: 'trace',
value: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a5c7a950-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a5c5d490-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your last name.',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a5c7a950-9c16-11e9-a2fc-f170e382beae',
label: 'Sent Activity',
localTimestamp: '2019-07-01T08:41:09-07:00',
locale: 'en-US',
name: 'SentActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:09.605Z',
type: 'trace',
value: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a5c7a950-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a5c5d490-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your last name.',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
},
type: 'summary-text',
},
{
payload: {
level: 0,
text: '-> ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a5c7a950-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a5c5d490-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your last name.',
type: 'message',
},
text: 'message',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a5c7a950-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a5c5d490-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your last name.',
type: 'message',
},
},
type: 'summary-text',
},
],
timestamp: 1561995669605,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a5c95700-9c16-11e9-a2fc-f170e382beae',
label: 'Bot State',
localTimestamp: '2019-07-01T08:41:09-07:00',
locale: 'en-US',
name: 'BotState',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:09.616Z',
type: 'trace',
value: {
conversationState: {
dialogState: {
dialogStack: [
{
id: 'root',
state: {
options: {},
stepIndex: 0,
values: {
instanceId: '6e732f12-4b0e-1b19-95c6-50213cd9ec1d',
},
},
},
{
id: 'slot-dialog',
state: {
slot: 'fullname',
values: {},
},
},
{
id: 'fullname',
state: {
slot: 'last',
values: {
first: 'Joe',
},
},
},
{
id: 'text',
state: {
options: {
prompt: 'Please enter your last name.',
},
state: {},
},
},
],
},
eTag: '*',
},
userState: {},
},
valueType: 'https://www.botframework.com/schemas/botState',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a5c95700-9c16-11e9-a2fc-f170e382beae',
label: 'Bot State',
localTimestamp: '2019-07-01T08:41:09-07:00',
locale: 'en-US',
name: 'BotState',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:09.616Z',
type: 'trace',
value: {
conversationState: {
dialogState: {
dialogStack: [
{
id: 'root',
state: {
options: {},
stepIndex: 0,
values: {
instanceId: '6e732f12-4b0e-1b19-95c6-50213cd9ec1d',
},
},
},
{
id: 'slot-dialog',
state: {
slot: 'fullname',
values: {},
},
},
{
id: 'fullname',
state: {
slot: 'last',
values: {
first: 'Joe',
},
},
},
{
id: 'text',
state: {
options: {
prompt: 'Please enter your last name.',
},
state: {},
},
},
],
},
eTag: '*',
},
userState: {},
},
valueType: 'https://www.botframework.com/schemas/botState',
},
},
type: 'summary-text',
},
],
timestamp: 1561995669616,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a7f27890-9c16-11e9-a2fc-f170e382beae',
label: 'Received Activity',
localTimestamp: '2019-07-01T08:41:13-07:00',
locale: 'en-US',
name: 'ReceivedActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:13.241Z',
type: 'trace',
value: {
channelData: {
clientActivityID: '15619956732300.j0slyoyawej',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a7f16720-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:13.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Schmo',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:13.234Z',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a7f27890-9c16-11e9-a2fc-f170e382beae',
label: 'Received Activity',
localTimestamp: '2019-07-01T08:41:13-07:00',
locale: 'en-US',
name: 'ReceivedActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:13.241Z',
type: 'trace',
value: {
channelData: {
clientActivityID: '15619956732300.j0slyoyawej',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a7f16720-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:13.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Schmo',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:13.234Z',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
},
type: 'summary-text',
},
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelData: {
clientActivityID: '15619956732300.j0slyoyawej',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a7f16720-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:13.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Schmo',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:13.234Z',
type: 'message',
},
text: 'message',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelData: {
clientActivityID: '15619956732300.j0slyoyawej',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'a7f16720-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:13.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: 'Schmo',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:13.234Z',
type: 'message',
},
},
type: 'summary-text',
},
],
timestamp: 1561995673241,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a7f362f0-9c16-11e9-a2fc-f170e382beae',
label: 'Sent Activity',
localTimestamp: '2019-07-01T08:41:13-07:00',
locale: 'en-US',
name: 'SentActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:13.247Z',
type: 'trace',
value: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a7f362f0-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a7f16720-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your age.',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a7f362f0-9c16-11e9-a2fc-f170e382beae',
label: 'Sent Activity',
localTimestamp: '2019-07-01T08:41:13-07:00',
locale: 'en-US',
name: 'SentActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:13.247Z',
type: 'trace',
value: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a7f362f0-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a7f16720-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your age.',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
},
type: 'summary-text',
},
{
payload: {
level: 0,
text: '-> ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a7f362f0-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a7f16720-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your age.',
type: 'message',
},
text: 'message',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-a7f362f0-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'a7f16720-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your age.',
type: 'message',
},
},
type: 'summary-text',
},
],
timestamp: 1561995673247,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a7f4e990-9c16-11e9-a2fc-f170e382beae',
label: 'Bot State',
localTimestamp: '2019-07-01T08:41:13-07:00',
locale: 'en-US',
name: 'BotState',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:13.257Z',
type: 'trace',
value: {
conversationState: {
dialogState: {
dialogStack: [
{
id: 'root',
state: {
options: {},
stepIndex: 0,
values: {
instanceId: '6e732f12-4b0e-1b19-95c6-50213cd9ec1d',
},
},
},
{
id: 'slot-dialog',
state: {
slot: 'age',
values: {
fullname: {
slot: 'last',
values: {
first: 'Joe',
last: 'Schmo',
},
},
},
},
},
{
id: 'number',
state: {
options: {
prompt: 'Please enter your age.',
},
state: {},
},
},
],
},
eTag: '*',
},
userState: {},
},
valueType: 'https://www.botframework.com/schemas/botState',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a7f4e990-9c16-11e9-a2fc-f170e382beae',
label: 'Bot State',
localTimestamp: '2019-07-01T08:41:13-07:00',
locale: 'en-US',
name: 'BotState',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:13.257Z',
type: 'trace',
value: {
conversationState: {
dialogState: {
dialogStack: [
{
id: 'root',
state: {
options: {},
stepIndex: 0,
values: {
instanceId: '6e732f12-4b0e-1b19-95c6-50213cd9ec1d',
},
},
},
{
id: 'slot-dialog',
state: {
slot: 'age',
values: {
fullname: {
slot: 'last',
values: {
first: 'Joe',
last: 'Schmo',
},
},
},
},
},
{
id: 'number',
state: {
options: {
prompt: 'Please enter your age.',
},
state: {},
},
},
],
},
eTag: '*',
},
userState: {},
},
valueType: 'https://www.botframework.com/schemas/botState',
},
},
type: 'summary-text',
},
],
timestamp: 1561995673257,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'aa680c70-9c16-11e9-a2fc-f170e382beae',
label: 'Received Activity',
localTimestamp: '2019-07-01T08:41:17-07:00',
locale: 'en-US',
name: 'ReceivedActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:17.367Z',
type: 'trace',
value: {
channelData: {
clientActivityID: '15619956773390.fiog39rlqcl',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'aa672210-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:17.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: '21',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:17.361Z',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'aa680c70-9c16-11e9-a2fc-f170e382beae',
label: 'Received Activity',
localTimestamp: '2019-07-01T08:41:17-07:00',
locale: 'en-US',
name: 'ReceivedActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:17.367Z',
type: 'trace',
value: {
channelData: {
clientActivityID: '15619956773390.fiog39rlqcl',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'aa672210-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:17.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: '21',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:17.361Z',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
},
type: 'summary-text',
},
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelData: {
clientActivityID: '15619956773390.fiog39rlqcl',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'aa672210-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:17.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: '21',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:17.361Z',
type: 'message',
},
text: 'message',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelData: {
clientActivityID: '15619956773390.fiog39rlqcl',
},
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
id: 'aa672210-9c16-11e9-a2fc-f170e382beae',
localTimestamp: '2019-07-01T15:41:17.000Z',
locale: 'en-US',
recipient: {
id: '123',
name: 'Bot',
role: 'bot',
},
serviceUrl: 'http://localhost:60002',
text: '21',
textFormat: 'plain',
timestamp: '2019-07-01T15:41:17.361Z',
type: 'message',
},
},
type: 'summary-text',
},
],
timestamp: 1561995677367,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'aa69ba20-9c16-11e9-a2fc-f170e382beae',
label: 'Sent Activity',
localTimestamp: '2019-07-01T08:41:17-07:00',
locale: 'en-US',
name: 'SentActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:17.378Z',
type: 'trace',
value: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-aa69ba20-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'aa672210-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your shoe size.',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'aa69ba20-9c16-11e9-a2fc-f170e382beae',
label: 'Sent Activity',
localTimestamp: '2019-07-01T08:41:17-07:00',
locale: 'en-US',
name: 'SentActivity',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:17.378Z',
type: 'trace',
value: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-aa69ba20-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'aa672210-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your shoe size.',
type: 'message',
},
valueType: 'https://www.botframework.com/schemas/activity',
},
},
type: 'summary-text',
},
{
payload: {
level: 0,
text: '-> ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-aa69ba20-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'aa672210-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your shoe size.',
type: 'message',
},
text: 'message',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '6a3c96c1-9c16-11e9-b530-d5773e50965f|livechat',
},
from: {
id: '123',
name: 'Bot',
role: 'bot',
},
id: 'emulator-required-id-aa69ba20-9c16-11e9-a2fc-f170e382beae',
inputHint: 'expectingInput',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
name: 'User',
role: 'user',
},
replyToId: 'aa672210-9c16-11e9-a2fc-f170e382beae',
serviceUrl: 'http://localhost:60002',
text: 'Please enter your shoe size.',
type: 'message',
},
},
type: 'summary-text',
},
],
timestamp: 1561995677378,
},
{
items: [
{
payload: {
level: 0,
text: '<- ',
},
type: 'text',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'aa6b67d0-9c16-11e9-a2fc-f170e382beae',
label: 'Bot State',
localTimestamp: '2019-07-01T08:41:17-07:00',
locale: 'en-US',
name: 'BotState',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:17.389Z',
type: 'trace',
value: {
conversationState: {
dialogState: {
dialogStack: [
{
id: 'root',
state: {
options: {},
stepIndex: 0,
values: {
instanceId: '6e732f12-4b0e-1b19-95c6-50213cd9ec1d',
},
},
},
{
id: 'slot-dialog',
state: {
slot: 'shoesize',
values: {
age: 21,
fullname: {
slot: 'last',
values: {
first: 'Joe',
last: 'Schmo',
},
},
},
},
},
{
id: 'shoesize',
state: {
options: {
prompt: 'Please enter your shoe size.',
retryPrompt: 'You must enter a size between 0 and 16. Half sizes are acceptable.',
},
state: {},
},
},
],
},
eTag: '*',
},
userState: {},
},
valueType: 'https://www.botframework.com/schemas/botState',
},
text: 'trace',
},
type: 'inspectable-object',
},
{
payload: {
obj: {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'aa6b67d0-9c16-11e9-a2fc-f170e382beae',
label: 'Bot State',
localTimestamp: '2019-07-01T08:41:17-07:00',
locale: 'en-US',
name: 'BotState',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:17.389Z',
type: 'trace',
value: {
conversationState: {
dialogState: {
dialogStack: [
{
id: 'root',
state: {
options: {},
stepIndex: 0,
values: {
instanceId: '6e732f12-4b0e-1b19-95c6-50213cd9ec1d',
},
},
},
{
id: 'slot-dialog',
state: {
slot: 'shoesize',
values: {
age: 21,
fullname: {
slot: 'last',
values: {
first: 'Joe',
last: 'Schmo',
},
},
},
},
},
{
id: 'shoesize',
state: {
options: {
prompt: 'Please enter your shoe size.',
retryPrompt: 'You must enter a size between 0 and 16. Half sizes are acceptable.',
},
state: {},
},
},
],
},
eTag: '*',
},
userState: {},
},
valueType: 'https://www.botframework.com/schemas/botState',
},
},
type: 'summary-text',
},
],
timestamp: 1561995677389,
},
];
export const mockDiff0 = {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a5c95700-9c16-11e9-a2fc-f170e382beae',
label: 'Bot State',
localTimestamp: '2019-07-01T08:41:09-07:00',
locale: 'en-US',
name: 'BotState',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:09.616Z',
type: 'trace',
value: {
conversationState: {
dialogState: {
dialogStack: {
'0': {
id: 'root',
state: {
options: {},
stepIndex: 0,
values: {
instanceId: '6e732f12-4b0e-1b19-95c6-50213cd9ec1d',
},
},
},
'1': {
id: 'slot-dialog',
state: {
slot: 'fullname',
values: {},
},
},
'2': {
id: 'fullname',
state: {
'+slot': 'last',
'-slot': 'first',
values: {
'+first': 'Joe',
},
},
},
'3': {
id: 'text',
state: {
options: {
'+prompt': 'Please enter your last name.',
'-prompt': 'Please enter your first name.',
},
state: {},
},
},
},
},
eTag: '*',
},
userState: {},
},
valueType: 'https://www.botframework.com/schemas/diff',
};
export const mockDiff1 = {
channelId: 'emulator',
conversation: {
id: '9dc7ee90-9c16-11e9-a2fc-f170e382beae|livechat',
},
from: {
id: '552539a0-9c15-11e9-b530-d5773e50965f',
name: 'Bot',
role: 'bot',
},
id: 'a7f4e990-9c16-11e9-a2fc-f170e382beae',
label: 'Bot State',
localTimestamp: '2019-07-01T08:41:13-07:00',
locale: 'en-US',
name: 'BotState',
recipient: {
id: '99b60ee8-3ffc-45c0-88cc-59b598641827',
role: 'user',
},
serviceUrl: 'http://localhost:60002',
timestamp: '2019-07-01T15:41:13.257Z',
type: 'trace',
value: {
conversationState: {
dialogState: {
dialogStack: {
'0': {
id: 'root',
state: {
options: {},
stepIndex: 0,
values: {
instanceId: '6e732f12-4b0e-1b19-95c6-50213cd9ec1d',
},
},
},
'1': {
id: 'slot-dialog',
state: {
'+slot': 'age',
'-slot': 'fullname',
values: {
fullname: {
slot: 'last',
values: {
first: 'Joe',
last: 'Schmo',
},
},
},
},
},
'2': {
'+id': 'number',
'-id': 'fullname',
state: {
'-slot': 'last',
'-values': {
first: 'Joe',
},
options: {
prompt: 'Please enter your age.',
},
state: {},
},
},
'-3': {
id: 'text',
state: {
options: {
prompt: 'Please enter your last name.',
},
state: {},
},
},
},
},
eTag: '*',
},
userState: {},
},
valueType: 'https://www.botframework.com/schemas/diff',
}; | the_stack |
import { TextureFont, Texture } from "./t";
import {
CustomSprite,
Sprite,
CustomSpriteProps,
NativeSpriteImplementation,
NativeSpriteUtils,
PureSprite,
PureCustomSprite,
Context,
} from "./sprite";
import { Device, DeviceSize, preloadFiles, cleanupFiles } from "./device";
import { SpriteBaseProps, getDefaultProps, mutateBaseProps } from "./props";
import { ContextValue } from "./context";
/**
* The props type a game should take.
*/
export interface GameProps {
id: "Game";
size: GameSize;
defaultFont?: TextureFont;
/**
* Default `"white"`
*/
backgroundColor?: string;
}
/**
* The size of a game
*/
export type GameSize =
// Orientation calculated by ratio of width and height
| GameOrientationSize
// Support both portrait and landscape
| {
portrait: GameOrientationSize;
landscape: GameOrientationSize;
};
/**
* Type representing the game orientation
*/
export interface GameOrientationSize {
width: number;
height: number;
/**
* The minimum width of device in px for XL render methods to be used. Omit to
* not use XL.
*/
minWidthXL?: number;
/**
* The minimum height of device in px for XL render methods to be used. Omit
* to not use XL.
*/
minHeightXL?: number;
/**
* The max allowed margin on left and right of game in game coordinates.
* @default 0
*/
maxWidthMargin?: number;
/**
* The max allowed margin on top and bottom of game in game coordinates.
* @default 0
*/
maxHeightMargin?: number;
}
/**
* Interface a platform that implements Replay must fit.
*/
export interface ReplayPlatform<I> {
/**
* Get the inputs for an individual sprite
*/
getInputs: (
getLocalCoords: (globalCoords: {
x: number;
y: number;
}) => { x: number; y: number }
) => I;
/**
* Returns a device instance that's shared between all Sprites and mutated by
* the platform to update it
*/
mutDevice: Device;
render: PlatformRender;
}
export type PlatformRender = {
newFrame: () => void;
startRenderSprite: (baseProps: SpriteBaseProps) => void;
endRenderSprite: () => void;
renderTexture: (texture: Texture) => void;
};
export type NativeSpriteMap = Record<
string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
NativeSpriteImplementation<any, any> | undefined
>;
export function replayCore<S, I>(
platform: ReplayPlatform<I>,
nativeSpriteSettings: NativeSpriteSettings,
gameSprite: CustomSprite<GameProps, S, I>,
/**
* Optionally specify a game size when you want to override the
* `gameSprite` prop
*/
gameSizeArg?: GameSize
): {
runNextFrame: (time: number, resetInputs: () => void) => void;
} {
const globalToGameCoords = ({ x, y }: { x: number; y: number }) => ({ x, y });
const { mutDevice, getInputs: getInputsPlatform } = platform;
const gameContainer = createCustomSpriteContainer(
gameSprite,
mutDevice,
() => getInputsPlatform(globalToGameCoords),
0,
gameSprite.props.id,
[]
);
const gameSize = gameSizeArg || gameSprite.props.size;
const initRenderMethod = getRenderMethod(mutDevice.size, gameSize);
let prevTime = 0;
let currentLag = 0;
platform.render.newFrame();
traverseCustomSpriteContainer<GameProps, I>(
gameContainer,
gameSprite.props,
mutDevice,
getInputsPlatform,
globalToGameCoords,
true,
initRenderMethod,
0,
gameSprite.props.id,
nativeSpriteSettings,
platform.render,
[]
);
const emptyRender: PlatformRender = {
newFrame: () => null,
startRenderSprite: () => null,
endRenderSprite: () => null,
renderTexture: () => null,
};
return {
runNextFrame(time, resetInputs) {
const timeSinceLastCall = time - prevTime;
prevTime = time;
currentLag += timeSinceLastCall;
let framesToCatchup = Math.floor(currentLag / REPLAY_TIME_PER_UPDATE_MS);
while (framesToCatchup > 0) {
currentLag -= REPLAY_TIME_PER_UPDATE_MS;
framesToCatchup--;
const extrapolateFactor = currentLag / REPLAY_TIME_PER_UPDATE_MS;
const renderMethod = getRenderMethod(mutDevice.size, gameSize);
// Only draw on last frame
const platformRender =
framesToCatchup === 0 ? platform.render : emptyRender;
platformRender.newFrame();
traverseCustomSpriteContainer<GameProps, I>(
gameContainer,
gameSprite.props,
mutDevice,
getInputsPlatform,
globalToGameCoords,
false,
renderMethod,
extrapolateFactor,
gameSprite.props.id,
nativeSpriteSettings,
platformRender,
[]
);
// reset inputs after each update
resetInputs();
}
},
};
}
/**
* A game is a tree of sprites. This function recursively traverses the tree of
* sprites to update a tree of sprite containers, or create / destroy containers
* as appropriate.
*/
function traverseCustomSpriteContainer<P, I>(
customSpriteContainer: CustomSpriteContainer<P, unknown, I>,
spriteProps: CustomSpriteProps<P>,
mutDevice: Device,
getInputsPlatform: ReplayPlatform<I>["getInputs"],
getParentCoords: (globalCoords: {
x: number;
y: number;
}) => { x: number; y: number },
initCreation: boolean,
renderMethod: RenderMethod,
extrapolateFactor: number,
parentGlobalId: string,
nativeSpriteSettings: NativeSpriteSettings,
platformRender: PlatformRender,
contextValues: ContextValue[]
) {
const { baseProps } = customSpriteContainer;
mutateBaseProps(baseProps, spriteProps);
const getLocalCoords = (globalCoords: { x: number; y: number }) => {
const parentCoords = getParentCoords(globalCoords);
const getParentToLocalCoords = getLocalCoordsForSprite(baseProps);
return getParentToLocalCoords(parentCoords);
};
// Cache in case called in multiple sprite methods
let cachedInputs: I | null = null;
const getInputs = () => {
if (!cachedInputs) {
cachedInputs = getInputsPlatform(getLocalCoords);
}
return cachedInputs;
};
const sprites = customSpriteContainer.getSprites(
spriteProps,
getInputs,
initCreation,
renderMethod,
extrapolateFactor,
contextValues
);
const unusedChildIds = customSpriteContainer.prevChildIdsSet;
// Reuse original array to reduce GC
const childIds = customSpriteContainer.prevChildIds;
let childIdIndex = 0;
const addChildId = (id: string) => {
childIds[childIdIndex] = id;
childIdIndex++;
unusedChildIds.delete(id);
};
platformRender.startRenderSprite(baseProps);
handleSprites(
sprites,
customSpriteContainer,
mutDevice,
getInputsPlatform,
renderMethod,
extrapolateFactor,
parentGlobalId,
nativeSpriteSettings,
platformRender,
contextValues,
addChildId,
getInputs,
getLocalCoords
);
platformRender.endRenderSprite();
nativeSpriteSettings.nativeSpriteUtils.didResize = false;
if (childIdIndex < childIds.length) {
childIds.length = childIdIndex;
}
unusedChildIds.forEach((id) => {
// Run cleanup of Sprites on all the removed child containers
const recursiveSpriteCleanup = (
containers: { [id: string]: SpriteContainer<unknown, unknown, I> },
containerParentGlobalId: string
) => {
Object.entries(containers).forEach(([containerId, container]) => {
if (container.type === "custom") {
const containerGlobalId = `${containerParentGlobalId}--${containerId}`;
recursiveSpriteCleanup(container.childContainers, containerGlobalId);
container.cleanup(getInputs);
if (container.loadFilesPromise) {
container.loadFilesPromise.then(() => {
// Only cleanup once the initial load is complete
cleanupFiles(containerGlobalId, mutDevice.assetUtils);
});
}
} else if (container.type === "native") {
container.cleanup({
state: container.state,
parentGlobalId,
});
}
});
};
const spriteContainer = customSpriteContainer.childContainers[id];
recursiveSpriteCleanup({ [id]: spriteContainer }, parentGlobalId);
delete customSpriteContainer.childContainers[id];
});
customSpriteContainer.prevChildIdsSet = new Set(childIds);
if (customSpriteContainer.prevChildIdsSet.size < childIds.length) {
const duplicate = childIds.find(
(item, index) => childIds.indexOf(item) !== index
);
throw Error(`Duplicate Sprite id ${duplicate}`);
}
}
function handleSprites<P, I>(
sprites: Sprite[],
customSpriteContainer: CustomSpriteContainer<P, unknown, I>,
mutDevice: Device,
getInputsPlatform: ReplayPlatform<I>["getInputs"],
renderMethod: RenderMethod,
extrapolateFactor: number,
parentGlobalId: string,
nativeSpriteSettings: NativeSpriteSettings,
platformRender: PlatformRender,
contextValues: ContextValue[],
addChildId: (id: string) => void,
getInputs: () => I,
getLocalCoords: (globalCoords: {
x: number;
y: number;
}) => { x: number; y: number }
) {
for (let i = 0; i < sprites.length; i++) {
const sprite = sprites[i];
if (!sprite) continue;
if (sprite.type === "context") {
handleSprites(
sprite.sprites,
customSpriteContainer,
mutDevice,
getInputsPlatform,
renderMethod,
extrapolateFactor,
parentGlobalId,
nativeSpriteSettings,
platformRender,
// Adding the context value to nested sprites here
[...contextValues, sprite],
addChildId,
getInputs,
getLocalCoords
);
} else if (sprite.type === "native") {
addChildId(sprite.props.id);
const { nativeSpriteMap, nativeSpriteUtils } = nativeSpriteSettings;
const nativeSpriteImplementation = nativeSpriteMap[sprite.name];
if (!nativeSpriteImplementation) {
throw Error(`Cannot find Native Sprite "${sprite.name}"`);
}
let lookupNativeSpriteContainer =
customSpriteContainer.childContainers[sprite.props.id];
if (
!lookupNativeSpriteContainer ||
lookupNativeSpriteContainer.type !== "native"
) {
// Create a native container
const newContainer: NativeSpriteContainer<UnknownObject> = {
type: "native",
state: nativeSpriteImplementation.create({
props: sprite.props,
parentGlobalId,
getState: () => newContainer.state,
updateState: (mergeState) => {
newContainer.state = {
...newContainer.state,
...mergeState,
};
},
utils: nativeSpriteUtils,
}),
cleanup: nativeSpriteImplementation.cleanup,
};
customSpriteContainer.childContainers[sprite.props.id] = newContainer;
lookupNativeSpriteContainer = newContainer;
}
lookupNativeSpriteContainer.state = nativeSpriteImplementation.loop({
props: sprite.props,
state: lookupNativeSpriteContainer.state,
parentGlobalId,
utils: nativeSpriteUtils,
});
} else if (sprite.type === "pure") {
addChildId(sprite.props.id);
let lookupPureCustomSpriteContainer =
customSpriteContainer.childContainers[sprite.props.id];
if (
!lookupPureCustomSpriteContainer ||
lookupPureCustomSpriteContainer.type !== "pure"
) {
lookupPureCustomSpriteContainer = createPureCustomSpriteContainer(
sprite
);
customSpriteContainer.childContainers[
sprite.props.id
] = lookupPureCustomSpriteContainer;
}
traversePureCustomSpriteContainer(
lookupPureCustomSpriteContainer,
sprite.props,
mutDevice.size,
nativeSpriteSettings.nativeSpriteUtils.didResize, // conveniently get this from native utils
renderMethod,
platformRender
);
} else if (sprite.type === "custom") {
addChildId(sprite.props.id);
let spriteInitCreation = false;
let lookupCustomSpriteContainer =
customSpriteContainer.childContainers[sprite.props.id];
const globalId = `${parentGlobalId}--${sprite.props.id}`;
if (
!lookupCustomSpriteContainer ||
lookupCustomSpriteContainer.type !== "custom"
) {
spriteInitCreation = true;
lookupCustomSpriteContainer = createCustomSpriteContainer(
sprite,
mutDevice,
getInputs,
customSpriteContainer.prevTime,
globalId,
contextValues
);
customSpriteContainer.childContainers[
sprite.props.id
] = lookupCustomSpriteContainer;
}
traverseCustomSpriteContainer(
lookupCustomSpriteContainer,
sprite.props,
mutDevice,
getInputsPlatform,
getLocalCoords,
spriteInitCreation,
renderMethod,
extrapolateFactor,
globalId,
nativeSpriteSettings,
platformRender,
contextValues
);
} else {
platformRender.renderTexture(sprite);
}
}
}
/**
* Replay will update at this frame rate on all platforms.
*/
const REPLAY_TIME_PER_UPDATE_MS = 1000 * (1 / 60);
/**
* Returns a container of the state of the sprite. Should only be called once
* per creation of sprite.
*/
function createCustomSpriteContainer<P, S, I>(
sprite: CustomSprite<P, S, I>,
mutDevice: Device,
getInitInputs: () => I,
currentTime: number,
globalId: string,
contextValues: ContextValue[]
): CustomSpriteContainer<P, S, I> {
const { spriteObj, props: initProps } = sprite;
// Use a queue so state is updated after rendering
const updateStateQueue: ((state: S) => S)[] = [];
const updateState = (update: (state: S) => S) => {
updateStateQueue.push(update);
};
let spriteContainer: null | CustomSpriteContainer<P, S, I> = null;
let initState;
let loadFilesPromise: null | Promise<void> = null;
if (spriteObj.init) {
initState = spriteObj.init({
props: initProps,
getState: () => {
if (!spriteContainer) {
throw Error("Cannot call getState synchronously in init");
}
return spriteContainer.state;
},
device: mutDevice,
getInputs: getInitInputs,
updateState,
getContext: <T>(context: Context<T>): T => {
const contextValue = contextValues.find((c) => c.context === context);
if (!contextValue) {
throw Error("No context setup");
}
return contextValue.value as T;
},
preloadFiles: async (assets) => {
const loadFiles = preloadFiles(globalId, assets, mutDevice.assetUtils);
if (spriteContainer) {
spriteContainer.loadFilesPromise = loadFiles;
} else {
// Was called synchronously
loadFilesPromise = loadFiles;
}
await loadFiles;
},
});
}
const runUpdateStateCallbacks = () => {
let queueIndex = 0;
// Use a while loop in case nested updateStates add to the array during
// loop
while (queueIndex < updateStateQueue.length) {
const update = updateStateQueue[queueIndex];
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
spriteContainer!.state = update(spriteContainer!.state);
queueIndex++;
}
updateStateQueue.length = 0;
};
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const getState = () => spriteContainer!.state;
spriteContainer = {
type: "custom",
// WARNING: types are a bit tricky here, need to cast.
// If a sprite does not set an init state, this will simply pass undefined
state: initState as S,
baseProps: getDefaultProps(initProps),
childContainers: {},
prevChildIds: [],
prevChildIdsSet: new Set(),
prevTime: currentTime,
currentLag: 0,
loadFilesPromise,
getSprites(
props,
getInputs,
initCreation,
renderMethod,
extrapolateFactor,
contextValues
) {
// Run any updateState from callbacks in other sprites last render
runUpdateStateCallbacks();
const getContext = <T>(context: Context<T>): T => {
const contextValue = contextValues.find((c) => c.context === context);
if (!contextValue) {
throw Error("No context setup");
}
return contextValue.value as T;
};
// Do not run loop on init creation of sprites
if (!initCreation && spriteObj.loop) {
this.state = spriteObj.loop({
props,
state: this.state,
device: mutDevice,
getInputs,
updateState,
getState,
getContext,
});
}
// Run any updateState from callbacks in loop
runUpdateStateCallbacks();
let render = spriteObj[renderMethod];
if (!render) {
// default to other renderXL or render method if not defined by user
render =
renderMethod === "renderPXL" && spriteObj.renderXL
? spriteObj.renderXL
: spriteObj.render;
}
const sprites = render({
props,
state: this.state,
device: mutDevice,
getInputs,
updateState,
getState,
getContext,
extrapolateFactor,
});
// Run any updateState from callbacks in render
runUpdateStateCallbacks();
return sprites;
},
cleanup(getInputs) {
spriteObj.cleanup?.({
state: this.state,
device: mutDevice,
getInputs,
});
},
};
return spriteContainer;
}
type RenderMethod = "render" | "renderP" | "renderXL" | "renderPXL";
/**
* If the user did not specify portrait and landscape, then it is calculated by
* the game dimensions. Otherwise, it is assumed `render` is for landscape and
* `renderP` for portrait.
*/
function getRenderMethod(
deviceSize: DeviceSize,
gameSize: GameSize
): RenderMethod {
const isPortrait = deviceSize.deviceHeight > deviceSize.deviceWidth;
let supportsLandscapeAndPortrait = false;
let gameOrientationSize;
if ("portrait" in gameSize) {
gameOrientationSize = isPortrait ? gameSize.portrait : gameSize.landscape;
supportsLandscapeAndPortrait = true;
} else {
gameOrientationSize = gameSize;
}
const useXL =
(gameOrientationSize.minHeightXL &&
deviceSize.deviceHeight >= gameOrientationSize.minHeightXL) ||
(gameOrientationSize.minWidthXL &&
deviceSize.deviceWidth >= gameOrientationSize.minWidthXL);
if (useXL) {
return supportsLandscapeAndPortrait && isPortrait
? "renderPXL"
: "renderXL";
}
return supportsLandscapeAndPortrait && isPortrait ? "renderP" : "render";
}
type SpriteContainer<P, S, I> =
| CustomSpriteContainer<P, S, I>
| PureCustomSpriteContainer<P>
| NativeSpriteContainer<S>;
type CustomSpriteContainer<P, S, I> = {
type: "custom";
state: S;
childContainers: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[id: string]: SpriteContainer<unknown, any, I>;
};
// stored for memory pooling
baseProps: SpriteBaseProps;
prevChildIds: string[];
prevChildIdsSet: Set<string>;
prevTime: number;
currentLag: number;
loadFilesPromise: null | Promise<void>;
getSprites: (
props: CustomSpriteProps<P>,
getInputs: () => I,
initCreation: boolean,
renderMethod: RenderMethod,
time: number,
contextValues: ContextValue[]
) => Sprite[];
cleanup: (getInputs: () => I) => void;
};
type PureCustomSpriteContainer<P> = {
type: "pure";
childContainers: {
[id: string]: PureCustomSpriteContainer<unknown>;
};
prevChildIds: string[];
prevChildIdsSet: Set<string>;
baseProps: SpriteBaseProps;
cache?: PureSpriteCache;
prevProps?: P;
getSprites: (
props: CustomSpriteProps<P>,
size: DeviceSize,
didResize: boolean,
renderMethod: RenderMethod
) => { type: "pureSprites"; sprites: PureSprite[] } | PureSpriteCache;
};
type PureSpriteCache = {
type: "cache";
baseProps: SpriteBaseProps;
items: (PureSpriteCache | Texture)[];
};
function createPureCustomSpriteContainer<P>(
sprite: PureCustomSprite<P>
): PureCustomSpriteContainer<P> {
const { spriteObj } = sprite;
return {
type: "pure",
childContainers: {},
prevChildIds: [],
prevChildIdsSet: new Set(),
baseProps: getDefaultProps(sprite.props),
getSprites(props, size, didResize, renderMethod) {
if (
this.prevProps &&
this.cache &&
!spriteObj.shouldRerender(this.prevProps, props) &&
!didResize
) {
this.prevProps = props;
return this.cache;
}
let render = spriteObj[renderMethod];
if (!render) {
// default to other renderXL or render method if not defined by user
render =
renderMethod === "renderPXL" && spriteObj.renderXL
? spriteObj.renderXL
: spriteObj.render;
}
// Cache will be updated outside of this function
this.prevProps = props;
return {
type: "pureSprites",
sprites: render({
props,
size,
}),
};
},
};
}
function traversePureCustomSpriteContainer<P>(
pureSpriteContainer: PureCustomSpriteContainer<P>,
spriteProps: CustomSpriteProps<P>,
deviceSize: DeviceSize,
didResize: boolean,
renderMethod: RenderMethod,
platformRender: PlatformRender
): PureSpriteCache {
const { baseProps } = pureSpriteContainer;
mutateBaseProps(baseProps, spriteProps);
const spritesResult = pureSpriteContainer.getSprites(
spriteProps,
deviceSize,
didResize,
renderMethod
);
if (spritesResult.type === "cache") {
// Need to traverse to apply base props of nested Sprites
traversePureSpriteCache(spritesResult, platformRender);
return spritesResult;
}
return traversePureCustomSpriteContainerNotCached(
pureSpriteContainer,
spritesResult.sprites,
deviceSize,
didResize,
renderMethod,
platformRender
);
}
function traversePureCustomSpriteContainerNotCached<P>(
pureSpriteContainer: PureCustomSpriteContainer<P>,
sprites: PureSprite<unknown>[],
deviceSize: DeviceSize,
didResize: boolean,
renderMethod: RenderMethod,
platformRender: PlatformRender
): PureSpriteCache {
const { baseProps } = pureSpriteContainer;
const unusedChildIds = pureSpriteContainer.prevChildIdsSet;
// Mutate original to reduce GC
const childIds = pureSpriteContainer.prevChildIds;
let childIdIndex = 0;
platformRender.startRenderSprite(baseProps);
const cacheItems = new Array<PureSpriteCache | Texture>(sprites.length);
let cacheItemIndex = 0;
for (let i = 0; i < sprites.length; i++) {
const sprite = sprites[i];
if (!sprite) continue;
if (sprite.type === "pure") {
childIds[childIdIndex] = sprite.props.id;
childIdIndex++;
unusedChildIds.delete(sprite.props.id);
let lookupPureCustomSpriteContainer =
pureSpriteContainer.childContainers[sprite.props.id];
if (
!lookupPureCustomSpriteContainer ||
lookupPureCustomSpriteContainer.type !== "pure"
) {
lookupPureCustomSpriteContainer = createPureCustomSpriteContainer(
sprite
);
pureSpriteContainer.childContainers[
sprite.props.id
] = lookupPureCustomSpriteContainer;
}
cacheItems[cacheItemIndex] = traversePureCustomSpriteContainer(
lookupPureCustomSpriteContainer,
sprite.props,
deviceSize,
didResize,
renderMethod,
platformRender
);
cacheItemIndex++;
} else {
platformRender.renderTexture(sprite);
cacheItems[cacheItemIndex] = sprite;
cacheItemIndex++;
}
}
if (cacheItemIndex < cacheItems.length) {
cacheItems.length = cacheItemIndex;
}
platformRender.endRenderSprite();
unusedChildIds.forEach((id) => {
delete pureSpriteContainer.childContainers[id];
});
const cache: PureSpriteCache = {
type: "cache",
baseProps,
items: cacheItems,
};
// Update cache
pureSpriteContainer.cache = cache;
if (childIdIndex < childIds.length) {
childIds.length = childIdIndex;
}
pureSpriteContainer.prevChildIdsSet = new Set(childIds);
if (pureSpriteContainer.prevChildIdsSet.size < childIds.length) {
const duplicate = childIds.find(
(item, index) => childIds.indexOf(item) !== index
);
throw Error(`Duplicate Sprite id ${duplicate}`);
}
return cache;
}
function traversePureSpriteCache(
cache: PureSpriteCache,
platformRender: PlatformRender
) {
platformRender.startRenderSprite(cache.baseProps);
for (let i = 0; i < cache.items.length; i++) {
const item = cache.items[i];
if (item.type === "cache") {
traversePureSpriteCache(item, platformRender);
} else {
platformRender.renderTexture(item);
}
}
platformRender.endRenderSprite();
}
type NativeSpriteContainer<S> = {
type: "native";
state: S;
cleanup: (params: { state: S; parentGlobalId: string }) => void;
};
export type NativeSpriteSettings = {
/**
* A map of Native Sprite names and their platform's implementation
*/
nativeSpriteMap: NativeSpriteMap;
nativeSpriteUtils: NativeSpriteUtils;
};
/**
* A mapping of the parent Sprite's (x, y) coordinate to local Sprite
* coordinates
*/
export function getLocalCoordsForSprite(baseProps: SpriteBaseProps) {
const toRad = Math.PI / 180;
const rotation = -(baseProps.rotation || 0) * toRad;
return ({ x, y }: { x: number; y: number }) => {
// This explains the equation for rotating: https://www.youtube.com/watch?v=AAx8JON4KeQ
const relativeX = x - baseProps.x;
const relativeY = y - baseProps.y;
const rotatedX =
relativeX * Math.cos(rotation) + relativeY * Math.sin(rotation);
const rotatedY =
-relativeX * Math.sin(rotation) + relativeY * Math.cos(rotation);
const scaledX = rotatedX / baseProps.scaleX;
const scaledY = rotatedY / baseProps.scaleY;
const anchoredX = scaledX + baseProps.anchorX;
const anchoredY = scaledY + baseProps.anchorY;
return { x: anchoredX, y: anchoredY };
};
}
type UnknownObject = Record<string, unknown>; | the_stack |
import * as pulumi from "@pulumi/pulumi";
import { input as inputs, output as outputs } from "../types";
import * as utilities from "../utilities";
/**
* A game server config resource. Configs are global and immutable.
*
* To get more information about GameServerConfig, see:
*
* * [API documentation](https://cloud.google.com/game-servers/docs/reference/rest/v1beta/projects.locations.gameServerDeployments.configs)
* * How-to Guides
* * [Official Documentation](https://cloud.google.com/game-servers/docs)
*
* ## Example Usage
* ### Game Service Config Basic
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as gcp from "@pulumi/gcp";
*
* const defaultGameServerDeployment = new gcp.gameservices.GameServerDeployment("defaultGameServerDeployment", {
* deploymentId: "tf-test-deployment",
* description: "a deployment description",
* });
* const defaultGameServerConfig = new gcp.gameservices.GameServerConfig("defaultGameServerConfig", {
* configId: "tf-test-config",
* deploymentId: defaultGameServerDeployment.deploymentId,
* description: "a config description",
* fleetConfigs: [{
* name: "something-unique",
* fleetSpec: JSON.stringify({
* replicas: 1,
* scheduling: "Packed",
* template: {
* metadata: {
* name: "tf-test-game-server-template",
* },
* spec: {
* ports: [{
* name: "default",
* portPolicy: "Dynamic",
* containerPort: 7654,
* protocol: "UDP",
* }],
* template: {
* spec: {
* containers: [{
* name: "simple-udp-server",
* image: "gcr.io/agones-images/udp-server:0.14",
* }],
* },
* },
* },
* },
* }),
* }],
* scalingConfigs: [{
* name: "scaling-config-name",
* fleetAutoscalerSpec: JSON.stringify({
* policy: {
* type: "Webhook",
* webhook: {
* service: {
* name: "autoscaler-webhook-service",
* namespace: "default",
* path: "scale",
* },
* },
* },
* }),
* selectors: [{
* labels: {
* one: "two",
* },
* }],
* schedules: [{
* cronJobDuration: "3.500s",
* cronSpec: "0 0 * * 0",
* }],
* }],
* });
* ```
*
* ## Import
*
* GameServerConfig can be imported using any of these accepted formats
*
* ```sh
* $ pulumi import gcp:gameservices/gameServerConfig:GameServerConfig default projects/{{project}}/locations/{{location}}/gameServerDeployments/{{deployment_id}}/configs/{{config_id}}
* ```
*
* ```sh
* $ pulumi import gcp:gameservices/gameServerConfig:GameServerConfig default {{project}}/{{location}}/{{deployment_id}}/{{config_id}}
* ```
*
* ```sh
* $ pulumi import gcp:gameservices/gameServerConfig:GameServerConfig default {{location}}/{{deployment_id}}/{{config_id}}
* ```
*/
export class GameServerConfig extends pulumi.CustomResource {
/**
* Get an existing GameServerConfig 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?: GameServerConfigState, opts?: pulumi.CustomResourceOptions): GameServerConfig {
return new GameServerConfig(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'gcp:gameservices/gameServerConfig:GameServerConfig';
/**
* Returns true if the given object is an instance of GameServerConfig. 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 GameServerConfig {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === GameServerConfig.__pulumiType;
}
/**
* A unique id for the deployment config.
*/
public readonly configId!: pulumi.Output<string>;
/**
* A unique id for the deployment.
*/
public readonly deploymentId!: pulumi.Output<string>;
/**
* The description of the game server config.
*/
public readonly description!: pulumi.Output<string | undefined>;
/**
* The fleet config contains list of fleet specs. In the Single Cloud, there
* will be only one.
* Structure is documented below.
*/
public readonly fleetConfigs!: pulumi.Output<outputs.gameservices.GameServerConfigFleetConfig[]>;
/**
* Set of labels to group by.
*/
public readonly labels!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* Location of the Deployment.
*/
public readonly location!: pulumi.Output<string | undefined>;
/**
* The name of the ScalingConfig
*/
public /*out*/ readonly name!: pulumi.Output<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
public readonly project!: pulumi.Output<string>;
/**
* Optional. This contains the autoscaling settings.
* Structure is documented below.
*/
public readonly scalingConfigs!: pulumi.Output<outputs.gameservices.GameServerConfigScalingConfig[] | undefined>;
/**
* Create a GameServerConfig 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: GameServerConfigArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: GameServerConfigArgs | GameServerConfigState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as GameServerConfigState | undefined;
inputs["configId"] = state ? state.configId : undefined;
inputs["deploymentId"] = state ? state.deploymentId : undefined;
inputs["description"] = state ? state.description : undefined;
inputs["fleetConfigs"] = state ? state.fleetConfigs : undefined;
inputs["labels"] = state ? state.labels : undefined;
inputs["location"] = state ? state.location : undefined;
inputs["name"] = state ? state.name : undefined;
inputs["project"] = state ? state.project : undefined;
inputs["scalingConfigs"] = state ? state.scalingConfigs : undefined;
} else {
const args = argsOrState as GameServerConfigArgs | undefined;
if ((!args || args.configId === undefined) && !opts.urn) {
throw new Error("Missing required property 'configId'");
}
if ((!args || args.deploymentId === undefined) && !opts.urn) {
throw new Error("Missing required property 'deploymentId'");
}
if ((!args || args.fleetConfigs === undefined) && !opts.urn) {
throw new Error("Missing required property 'fleetConfigs'");
}
inputs["configId"] = args ? args.configId : undefined;
inputs["deploymentId"] = args ? args.deploymentId : undefined;
inputs["description"] = args ? args.description : undefined;
inputs["fleetConfigs"] = args ? args.fleetConfigs : undefined;
inputs["labels"] = args ? args.labels : undefined;
inputs["location"] = args ? args.location : undefined;
inputs["project"] = args ? args.project : undefined;
inputs["scalingConfigs"] = args ? args.scalingConfigs : undefined;
inputs["name"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(GameServerConfig.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering GameServerConfig resources.
*/
export interface GameServerConfigState {
/**
* A unique id for the deployment config.
*/
configId?: pulumi.Input<string>;
/**
* A unique id for the deployment.
*/
deploymentId?: pulumi.Input<string>;
/**
* The description of the game server config.
*/
description?: pulumi.Input<string>;
/**
* The fleet config contains list of fleet specs. In the Single Cloud, there
* will be only one.
* Structure is documented below.
*/
fleetConfigs?: pulumi.Input<pulumi.Input<inputs.gameservices.GameServerConfigFleetConfig>[]>;
/**
* Set of labels to group by.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Location of the Deployment.
*/
location?: pulumi.Input<string>;
/**
* The name of the ScalingConfig
*/
name?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Optional. This contains the autoscaling settings.
* Structure is documented below.
*/
scalingConfigs?: pulumi.Input<pulumi.Input<inputs.gameservices.GameServerConfigScalingConfig>[]>;
}
/**
* The set of arguments for constructing a GameServerConfig resource.
*/
export interface GameServerConfigArgs {
/**
* A unique id for the deployment config.
*/
configId: pulumi.Input<string>;
/**
* A unique id for the deployment.
*/
deploymentId: pulumi.Input<string>;
/**
* The description of the game server config.
*/
description?: pulumi.Input<string>;
/**
* The fleet config contains list of fleet specs. In the Single Cloud, there
* will be only one.
* Structure is documented below.
*/
fleetConfigs: pulumi.Input<pulumi.Input<inputs.gameservices.GameServerConfigFleetConfig>[]>;
/**
* Set of labels to group by.
*/
labels?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* Location of the Deployment.
*/
location?: pulumi.Input<string>;
/**
* The ID of the project in which the resource belongs.
* If it is not provided, the provider project is used.
*/
project?: pulumi.Input<string>;
/**
* Optional. This contains the autoscaling settings.
* Structure is documented below.
*/
scalingConfigs?: pulumi.Input<pulumi.Input<inputs.gameservices.GameServerConfigScalingConfig>[]>;
} | the_stack |
import { expect } from 'chai'
import { RECORD_STORE_ADD } from '../../../src/extension/public/RecordStoreActions'
import ActionType from '../../../src/tracker/public/ActionType'
import OwnerManager from '../../../src/tracker/private/OwnerManager'
import * as utils from './utils'
/* this test is based on dom tracker initialized in__init__.ts */
describe('HTML DOM API tracker', () => {
// const receiver = new utils.TrackerMessageReceiver(window)
const receiver = new utils.RecordStoreMessageCatcher(window, RECORD_STORE_ADD)
const svgns = 'http://www.w3.org/2000/svg'
before(() => {
receiver.setup()
})
after(() => {
receiver.teardown()
})
beforeEach(() => {
receiver.reset()
})
describe('Window', () => {
it('should have owner \'window-info\' element on page', () => {
const windowInfoElement = document.getElementsByTagName('window-info')[0]
const ownerElement = OwnerManager.getOwnerElement(window)
expect(windowInfoElement).to.be.not.undefined
expect(ownerElement).to.equal(windowInfoElement)
})
it('should track method call (e.g., addEventListener) as from window given no explicit target', () => {
addEventListener('click', () => { })
const loc = utils.createSourceLocationWith(-2, 7)
const data = utils.createActionData('1', ActionType.Event)
const ownerID = OwnerManager.getTrackIDFromItsOwner(window)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
})
describe('Document', () => {
it('should have owner \'document-info\' element on page', () => {
const documentInfoElement = document.getElementsByTagName('document-info')[0]
const ownerElement = OwnerManager.getOwnerElement(document)
expect(documentInfoElement).to.be.not.undefined
expect(ownerElement).to.equal(documentInfoElement)
})
})
describe('DocumentFragment', () => {
it('should not track any action on fragment', () => {
const div = document.createElement('div')
const fragment = document.createDocumentFragment()
fragment.appendChild(div)
receiver.verifyNoMessage()
})
it('should track other element appending a fragment', () => {
const div = document.createElement('div')
const fragment = document.createDocumentFragment()
div.appendChild(fragment)
const loc = utils.createSourceLocationWith(-2, 11)
const data = utils.createActionData('1', ActionType.Node)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
})
describe('HTMLElement', () => {
it('should track its property assignment', () => {
const div = document.createElement('div')
div.accessKey = 'accessKey'
const loc = utils.createSourceLocationWith(-2, 20)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
/* anomalies */
it('should track behavior (e.g., click, focus) and actions triggered by it properly', () => {
const div1 = document.createElement('div')
const div2 = document.createElement('div')
div2.addEventListener('click', () => {
div1.style.color = 'red'
})
receiver.reset()
const loc1 = utils.createSourceLocationWith(-4, 25)
const data1 = utils.createActionData('2', ActionType.Style)
div2.click()
const loc2 = utils.createSourceLocationWith(-2, 12)
const data2 = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div1.style)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div2)
expect(ownerID1).to.equal(data1.trackid)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContain([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 },
])
})
})
describe('SVGElement', () => {
it('should track its property assignment', () => {
const svg = document.createElementNS(svgns, 'svg');
(<any>svg).tabIndex = 1
const loc = utils.createSourceLocationWith(-2, 26)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(svg)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track its method call', () => {
const svg = document.createElementNS(svgns, 'svg');
(<any>svg).focus()
const loc = utils.createSourceLocationWith(-2, 18)
const data = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID = OwnerManager.getTrackIDFromItsOwner(svg)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
})
describe('Element', () => {
it('should track its property assignment', () => {
const div = document.createElement('div')
div.id = 'id'
const loc = utils.createSourceLocationWith(-2, 13)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track its method call', () => {
const div = document.createElement('div')
const div2 = document.createElement('div')
div.insertAdjacentElement('afterbegin', div2)
const loc = utils.createSourceLocationWith(-2, 11)
const data = utils.createActionData('1', ActionType.Node)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
/* composite actions */
describe('set/removeAttribute', () => {
it('should track setAttribute', () => {
const div = document.createElement('div')
div.setAttribute('id', 'id')
const loc = utils.createSourceLocationWith(-2, 13)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track removeAttribute', () => {
const div = document.createElement('div')
div.setAttribute('id', 'id')
receiver.reset()
div.removeAttribute('id')
const loc = utils.createSourceLocationWith(-2, 13)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track removeAttributeNode', () => {
const div = document.createElement('div')
div.setAttribute('id', 'id')
receiver.reset()
div.removeAttributeNode(div.getAttributeNode('id'))
const loc = utils.createSourceLocationWith(-2, 13)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
})
/* anomalies */
describe('setAttributeNode{NS}', () => {
// @NOTE: setAttributeNode & NS are identical, only test Node here
it('should track setAttributeNode{NS} (basic scenario)', () => {
const div = document.createElement('div')
const idAttr = document.createAttribute('id')
div.setAttributeNode(idAttr)
const loc = utils.createSourceLocationWith(-2, 13)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track setAttributeNode{NS} (merge scenario)', () => {
const div = document.createElement('div')
const idAttr = document.createAttribute('id')
idAttr.value = 'id' // trackid 1 attach to shadow element
receiver.reset()
div.setAttributeNode(idAttr) // trackid 2 attach to div
const loc = utils.createSourceLocationWith(-2, 13)
const data = utils.createActionData('2', ActionType.Attr, '1')
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track setAttributeNode{NS} (attr has no value scenario)', () => {
const div = document.createElement('div')
const idAttr = document.createAttribute('id')
// pre-set trackid on div, for more details, please checkout
// [src/tracker/trackers/dom/trackerHelpers.ts] decorators.setAttributeNode
div.accessKey = 'accessKey'
receiver.reset()
// test set no owner attribute
div.setAttributeNode(idAttr)
const loc1 = utils.createSourceLocationWith(-2, 13)
const data1 = utils.createActionData('1', ActionType.Attr)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID1).to.equal(data1.trackid)
receiver.verifyMessagesContain({ loc: loc1, data: data1 })
receiver.reset()
// test set value after attach to element
idAttr.value = 'id'
const loc2 = utils.createSourceLocationWith(-2, 21)
const data2 = utils.createActionData('1', ActionType.Attr)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(idAttr)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContain({ loc: loc2, data: data2 })
})
it('should not track setAttributeNode{NS} (error scenario)', () => {
const div = document.createElement('div')
const div2 = document.createElement('div')
div.id = 'id'
receiver.reset()
const error = () => {
div2.setAttributeNode(div.attributes[0])
}
expect(error).to.throw()
receiver.verifyNoMessage()
})
})
})
describe('Node', () => {
it('should track its property assignment', () => {
const div = document.createElement('div')
div.textContent = 'content'
const loc = utils.createSourceLocationWith(-2, 22)
const data = utils.createActionData('1', ActionType.Attr | ActionType.Node)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track its method call', () => {
const div = document.createElement('div')
const div2 = document.createElement('div')
div.appendChild(div2)
const loc = utils.createSourceLocationWith(-2, 11)
const data = utils.createActionData('1', ActionType.Node)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
})
describe('EventTarget', () => {
it('should track its method call', () => {
const div = document.createElement('div')
div.addEventListener('click', () => { })
const loc = utils.createSourceLocationWith(-2, 11)
const data = utils.createActionData('1', ActionType.Event)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
/* anomalies */
it('should track dispatchEvent and actions triggered by it properly', () => {
const div = document.createElement('div')
div.addEventListener('click', () => {
div.style.color = 'red'
})
const loc1 = utils.createSourceLocationWith(-2, 24)
const data1 = utils.createActionData('1', ActionType.Style)
receiver.reset()
div.dispatchEvent(new Event('click'))
const loc2 = utils.createSourceLocationWith(-2, 11)
const data2 = utils.createActionData('1', ActionType.Behav | ActionType.Event)
const ownerID1 = OwnerManager.getTrackIDFromItsOwner(div.style)
const ownerID2 = OwnerManager.getTrackIDFromItsOwner(div)
expect(ownerID1).to.equal(data1.trackid)
expect(ownerID2).to.equal(data2.trackid)
receiver.verifyMessagesContain([
{ loc: loc1, data: data1 },
{ loc: loc2, data: data2 }
])
})
})
describe('Attr', () => {
it('should track its property assignment', () => {
const idAttr = document.createAttribute('id')
idAttr.value = 'id'
const loc = utils.createSourceLocationWith(-2, 19)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(idAttr)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
})
describe('CSSStyleDeclaration', () => {
it('should set HTMLElement owner properly', () => {
const div = document.createElement('div')
expect(
OwnerManager.getOwnerElement(div.style)
).to.equal(div)
})
it('should set SVGElement owner properly', () => {
const svg = document.createElementNS(svgns, 'svg')
expect(
OwnerManager.getOwnerElement(svg.style)
).to.equal(svg)
})
it('should track HTMLElement owner style property assignment', () => {
const div = document.createElement('div')
div.style.color = 'red'
const loc = utils.createSourceLocationWith(-2, 22)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div.style)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track SVGElement owner style property assignment', () => {
const svg = document.createElementNS(svgns, 'svg')
svg.style.color = 'red'
const loc = utils.createSourceLocationWith(-2, 22)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(svg.style)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
})
describe('DOMStringMap', () => {
it('should set its owner properly', () => {
const div = document.createElement('div')
expect(
OwnerManager.getOwnerElement(div.dataset)
).to.equal(div)
})
it('should track its property assignment', () => {
const div = document.createElement('div')
div.dataset.data = 'data'
const loc = utils.createSourceLocationWith(-2, 23)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div.dataset)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
})
describe('DOMTokenList', () => {
it('should set owner properly', () => {
const div = document.createElement('div')
expect(
OwnerManager.getOwnerElement(div.classList)
).to.equal(div)
})
it('should track its value property assignment', () => {
const div = document.createElement('div')
div.classList.value = 'class'
const loc = utils.createSourceLocationWith(-2, 26)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div.classList)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track its methods', () => {
const div = document.createElement('div')
div.classList.add('class')
const loc = utils.createSourceLocationWith(-2, 21)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div.classList)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
})
describe('NamedNodeMap', () => {
it('should set its owner properly', () => {
const div = document.createElement('div')
expect(
OwnerManager.getOwnerElement(div.attributes)
).to.equal(div)
})
it('should track removeNamedItem (attr scenario)', () => {
const div = document.createElement('div')
div.id = 'id'
receiver.reset()
div.attributes.removeNamedItem('id')
const loc = utils.createSourceLocationWith(-2, 22)
const data = utils.createActionData('1', ActionType.Attr)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div.attributes)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track removeNamedItem (style scenario)', () => {
const div = document.createElement('div')
div.style.color = 'red'
receiver.reset()
div.attributes.removeNamedItem('style')
const loc = utils.createSourceLocationWith(-2, 22)
const data = utils.createActionData('1', ActionType.Style)
const ownerID = OwnerManager.getTrackIDFromItsOwner(div.attributes)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
/* anomalies */
it('should track setNamedItem (attr scenario)', () => {
const div = document.createElement('div')
const id = document.createAttribute('id')
id.value = 'id' // trackid 1 attach to shadow element
receiver.reset()
div.attributes.setNamedItem(id) // trackid 2 attach to owner of attributes
const loc = utils.createSourceLocationWith(-2, 22)
const data = utils.createActionData('2', ActionType.Attr, '1')
const ownerID = OwnerManager.getTrackIDFromItsOwner(div.attributes)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
it('should track setNamedItem (style scenario)', () => {
const div = document.createElement('div')
const style = document.createAttribute('style')
style.value = 'color: red' // trackid 1 attach to shadow element
receiver.reset()
div.attributes.setNamedItem(style) // trackid 2 attach to owner of attributes
const loc = utils.createSourceLocationWith(-2, 22)
const data = utils.createActionData('2', ActionType.Style, '1')
const ownerID = OwnerManager.getTrackIDFromItsOwner(div.attributes)
expect(ownerID).to.equal(data.trackid)
receiver.verifyMessagesContain({ loc, data })
})
})
}) | the_stack |
import { Picker, View } from "@tarojs/components";
import Taro, { useState, useMemo } from "@tarojs/taro";
import { classNames, getNowDate, isAliPay } from "../../lib";
import { IProps } from "../../../@types/select";
import { getAreaData } from "../../lib/area";
import "./index.scss"
import AlipayMutiSelect from "./components/alipay/mutiSelector";
function ClSelect(props: IProps) {
const selector = {
range: (props.selector && props.selector.range) || [],
value: (props.selector && props.selector.value) || 0,
rangeKey: (props.selector && props.selector.rangeKey) || undefined
};
const mutiSelector = {
range: (props.multiSelector && props.multiSelector.range) || [],
value: (props.multiSelector && props.multiSelector.value) || [0, 0],
rangeKey: (props.multiSelector && props.multiSelector.rangeKey) || undefined
};
const timeSelector = {
value: (props.time && props.time.value) || "00:00",
start: (props.time && props.time.start) || "00:00",
end: (props.time && props.time.end) || "23:59"
};
const dateSelector = {
value:
(props.date && props.date.value) ||
getNowDate((props.date && props.date.fields) || "day"),
fields: (props.date && props.date.fields) || "day",
start: (props.date && props.date.start) || "",
end: (props.date && props.date.end) || ""
};
const getRegionData = (
province?: { key: string; value: string },
city?: { key: string; value: string }
) => {
const regionObjData = getAreaData(province, city);
const provinceArr = regionObjData.province.map(item => ({
key: item[0],
value: item[1]
}));
const cityArr = regionObjData.city.map(item => ({
key: item[0],
value: item[1] as string
}));
const districtArr = regionObjData.district.map(item => ({
key: item[0],
value: item[1] as string
}));
return [provinceArr, cityArr, districtArr];
};
const regionSelector = {
value:
(props.region && props.region.value) ||
getRegionData().map(item => item[0])
};
// 单选
const getSelectorValue = index =>
selector.rangeKey
? selector.range[index][selector.rangeKey]
: selector.range[index];
const [selected, setSelected] = useState(() =>
getSelectorValue(selector.value)
);
const setSelect = index => {
const value: string = getSelectorValue(index);
setSelected(value);
};
// 多选
const getMutiSelectorValue = mutiIndex => {
const value: any[] = [];
mutiSelector.range.forEach((item, index) => {
const rangeValue = mutiIndex[index];
const temp = mutiSelector.rangeKey
? item[rangeValue][mutiSelector.rangeKey]
: item[rangeValue];
value.push(temp);
});
return value.join(",");
};
const [mutiSelected, setMutiSelected] = useState(() =>
getMutiSelectorValue(mutiSelector.value)
);
const setMutiSelect = index => {
setMutiSelected(getMutiSelectorValue(index));
};
// 时间选择
const getTimeSelectorValue = value => value;
const [timeSelected, setTimeSelected] = useState(() =>
getTimeSelectorValue(timeSelector.value)
);
const setTimeSelect = value => {
setTimeSelected(getTimeSelectorValue(value));
};
// 日期选择
const getDateSelectorValue = value => value;
const [dateSelected, setDateSelected] = useState(() =>
getDateSelectorValue(dateSelector.value)
);
const setDateSelect = value => {
setDateSelected(getDateSelectorValue(value));
};
// 地区选择
const [areaData, setAreaData] = useState(
getRegionData(...regionSelector.value)
);
const getRegionSelectorValue = (value: any[]) =>
value.map(item => item.value).join(",");
const [regionSelected, setRegionSelected] = useState(() =>
getRegionSelectorValue(regionSelector.value)
);
const [confirmRegion, setConfirmRegion] = useState(regionSelector.value);
const [originAreaData, setOriginAreaData] = useState(areaData);
const setRegionSelect = value => {
setRegionSelected(getRegionSelectorValue(value));
};
// 单选触发
const onSelectorChange = (e: any) => {
const index = e.detail.value;
setSelect(index);
props.onChange && props.onChange(index);
};
// 多选触发
const onMutiSelectorChange = (e: any) => {
const index = e.detail.value;
setMutiSelect(index);
props.onChange && props.onChange(index);
};
// 多选滚动触发
const onMutiSelectorColumChange = (e: any) => {
props.onColumnChange && props.onColumnChange(e.detail);
};
// 时间触发
const onTimeSelectorChange = (e: any) => {
const index = e.detail.value;
setTimeSelect(index);
props.onChange && props.onChange(index);
};
// 日期触发
const onDateSelectorChange = (e: any) => {
const index = e.detail.value;
setDateSelect(index);
props.onChange && props.onChange(index);
};
const origin = regionSelector.value.map((item, index) =>
originAreaData[index].findIndex(obj => obj.key === item.key)
);
const onCancel = (e: any) => {
setAreaData(originAreaData);
setTempSelect(
confirmRegion.map((item, index) =>
originAreaData[index].findIndex(origin => origin.key === item.key)
)
);
props.onCancel && props.onCancel(e);
};
// 地区触发
const onRegionSelectorChange = (e: any) => {
const detail = e.detail.value;
const dataSelected = detail.map((key, index) => areaData[index][key]);
setRegionSelect(dataSelected);
setOriginAreaData(areaData);
setConfirmRegion(dataSelected);
props.onChange && props.onChange(dataSelected);
};
const [tempSelect, setTempSelect] = useState(origin);
const onRegionMutiSelectorColumChange = (e: any) => {
const detail = e.detail;
const column = detail.column;
const index = e.detail.value;
tempSelect[column] = index;
if (column !== 2) {
if (column === 0) {
tempSelect[1] = 0;
tempSelect[2] = 0;
setAreaData(getRegionData(areaData[0][tempSelect[0]]));
}
if (column === 1) {
tempSelect[2] = 0;
setAreaData(
getRegionData(areaData[0][tempSelect[0]], areaData[1][tempSelect[1]])
);
}
}
setTempSelect(tempSelect);
};
useMemo(() => {
switch (props.mode) {
case "selector": {
setSelected(getSelectorValue(selector.value));
break;
}
case "multiSelector": {
setMutiSelected(getMutiSelectorValue(mutiSelector.value));
break;
}
case "region": {
setRegionSelected(getRegionSelectorValue(regionSelector.value));
const area = getRegionData(...regionSelector.value);
setAreaData(area);
const origin = regionSelector.value.map((item, index) =>
area[index].findIndex(obj => obj.key === item.key)
);
setTempSelect(origin);
break;
}
case "date": {
setDateSelected(getDateSelectorValue(dateSelector.value));
break;
}
case "time": {
setTimeSelected(getTimeSelectorValue(timeSelector.value));
break;
}
default: {
}
}
}, [
props.selector,
props.region,
props.date,
props.time,
props.multiSelector
]);
// 单选组件
const selectorComponent = (
<Picker
mode="selector"
range={selector.range}
rangeKey={selector.rangeKey}
value={selector.value || 0}
onChange={onSelectorChange}
onCancel={onCancel}
disabled={props.disabled}
className='longSelect'
>
<View className="picker">{selected}</View>
</Picker>
);
// 多选组件
const mutiSelectorComponent = (
<Picker
mode="multiSelector"
range={mutiSelector.range}
rangeKey={mutiSelector.rangeKey}
value={mutiSelector.value}
onChange={onMutiSelectorChange}
onColumnChange={onMutiSelectorColumChange}
onCancel={onCancel}
disabled={props.disabled}
className='longSelect'
>
<View className="picker">{mutiSelected}</View>
</Picker>
);
// alipay 多选
const alipayMutiSelectorComponent = <AlipayMutiSelect {...props} />;
// 时间选择组件
const timeSelectorComponent = (
<Picker
mode="time"
value={timeSelector.value}
start={timeSelector.start}
end={timeSelector.end}
onChange={onTimeSelectorChange}
onCancel={onCancel}
disabled={props.disabled}
className='longSelect'
>
<View className="picker">{timeSelected}</View>
</Picker>
);
// 日期选择组件
const dateSelectorComponent = (
<Picker
mode="date"
value={dateSelector.value}
start={dateSelector.start}
end={dateSelector.end}
fields={dateSelector.fields}
onCancel={onCancel}
onChange={onDateSelectorChange}
className='longSelect'
>
<View className="picker">{dateSelected}</View>
</Picker>
);
// 地区选择组件
const regionSelectorComponent = (
<Picker
mode="multiSelector"
range={areaData}
rangeKey={"value"}
value={tempSelect}
onChange={onRegionSelectorChange}
onColumnChange={onRegionMutiSelectorColumChange}
onCancel={onCancel}
disabled={props.disabled}
className='longSelect'
>
<View className="picker">{regionSelected}</View>
</Picker>
);
const title = props.title;
return (
<View
className={classNames(
`cu-form-group ${props.disabled ? "text-gray" : ""}`,
props.className
)}
style={Object.assign({}, props.style)}
>
<View className="title">{title || ""}</View>
{props.mode === "selector" ? selectorComponent : ""}
{props.mode === "multiSelector" && !isAliPay ? mutiSelectorComponent : ""}
{props.mode === "multiSelector" && isAliPay
? alipayMutiSelectorComponent
: ""}
{props.mode === "time" ? timeSelectorComponent : ""}
{props.mode === "date" ? dateSelectorComponent : ""}
{props.mode === "region" ? regionSelectorComponent : ""}
</View>
);
}
ClSelect.options = {
addGlobalClass: true
};
ClSelect.defaultProps = {
mode: "selector",
selector: [],
multiSelector: [],
time: [],
date: [],
region: []
} as IProps;
export default ClSelect; | the_stack |
* @title: 2D Physics callbacks
* @description:
* This sample shows how to use 2D physics contact callbacks
* (preSolve, begin and progress) to implement one-way platforms and
* destruction based on collision strength.
* Left click to pick up and move the rigid bodies and right click to add new ones.
*/
/*{{ javascript("jslib/observer.js") }}*/
/*{{ javascript("jslib/requesthandler.js") }}*/
/*{{ javascript("jslib/utilities.js") }}*/
/*{{ javascript("jslib/services/turbulenzservices.js") }}*/
/*{{ javascript("jslib/services/turbulenzbridge.js") }}*/
/*{{ javascript("jslib/services/gamesession.js") }}*/
/*{{ javascript("jslib/services/mappingtable.js") }}*/
/*{{ javascript("jslib/shadermanager.js") }}*/
/*{{ javascript("jslib/physics2ddevice.js") }}*/
/*{{ javascript("jslib/draw2d.js") }}*/
/*{{ javascript("jslib/boxtree.js") }}*/
/*{{ javascript("jslib/physics2ddebugdraw.js") }}*/
/*{{ javascript("jslib/textureeffects.js") }}*/
/*global TurbulenzEngine: true */
/*global TurbulenzServices: false */
/*global RequestHandler: false */
/*global Physics2DDevice: false */
/*global Physics2DDebugDraw: false */
/*global Draw2D: false */
TurbulenzEngine.onload = function onloadFn()
{
//==========================================================================
// Turbulenz Initialization
//==========================================================================
var graphicsDevice = TurbulenzEngine.createGraphicsDevice({});
var mathDevice = TurbulenzEngine.createMathDevice({});
var requestHandler = RequestHandler.create({});
var gameSession;
function sessionCreated()
{
TurbulenzServices.createMappingTable(
requestHandler,
gameSession,
function (/* table */) { }
);
}
gameSession = TurbulenzServices.createGameSession(requestHandler, sessionCreated);
//==========================================================================
// Phys2D/Draw2D
//==========================================================================
// set up.
var phys2D = Physics2DDevice.create();
// size of physics stage.
var stageWidth = 30; // m
var stageHeight = 22; // m
var draw2D = Draw2D.create({
graphicsDevice : graphicsDevice
});
var debug = Physics2DDebugDraw.create({
graphicsDevice : graphicsDevice
});
// Configure draw2D viewport to the physics stage.
// As well as the physics2D debug-draw viewport.
draw2D.configure({
viewportRectangle : [0, 0, stageWidth, stageHeight],
scaleMode : 'scale'
});
debug.setPhysics2DViewport([0, 0, stageWidth, stageHeight]);
var world = phys2D.createWorld({
gravity : [0, 20] // 20 m/s/s
});
// group that objects breakable by spikes are given
// for filtering event listeners.
var breakGroup = 4;
var shapeSize = 2;
var boxShape = phys2D.createPolygonShape({
vertices : phys2D.createBoxVertices(shapeSize, shapeSize),
userData : {
breakCount : 3,
shapeSize : shapeSize
},
group : breakGroup
});
// Create a static body at (0, 0) with no rotation
// Which we add to the world to use as the first body
// In hand constraint. We set anchor for this body
// as the cursor position in physics coordinates.
var handReferenceBody = phys2D.createRigidBody({
type : 'static'
});
world.addRigidBody(handReferenceBody);
var handConstraint = null;
// Generate event listener for one-way platforms
// given a direction of permitted movement through body.
function oneWayListener(direction)
{
return function (arbiter /*, otherShape */)
{
var normal = arbiter.getNormal();
// May need to flip directional logic if shapeA is not 'this'
// as normals always point from shapeA to shapeB.
var flip = (arbiter.shapeA !== this);
if ((mathDevice.v2Dot(normal, direction) < 0) === flip)
{
// Ignore interaction, and make action persistent 'till
// objects seperate.
arbiter.setAcceptedState(false);
arbiter.setPersistentState(true);
}
};
}
// Event listener used for teleporter at bottom of stage.
function teleportListener(arbiter, otherShape)
{
var otherBody = otherShape.body;
// Teleport to top of screen.
var pos = otherBody.getPosition();
pos[1] = -1;
otherBody.setPosition(pos);
}
// Event listener used for spikes to break apart objects.
function spikeListener(arbiter, otherShape)
{
// Shape may have hit more than one spike, ensure we don't break it again
// once already broken.
var otherBody = otherShape.body;
if (!otherBody.world)
{
return;
}
// Assert that the impact was strong enough for spikes to break the box.
var impulse = arbiter.getImpulseForBody(otherBody);
if (mathDevice.v2Length(impulse) < (5 * otherBody.getMass()))
{
return;
}
world.removeRigidBody(otherBody);
var shapeSize = (otherShape.userData.shapeSize / 2);
var breakCount = (otherShape.userData.breakCount - 1);
if (breakCount === 0)
{
// Object simply destroyed instead.
return;
}
// Break shape into a 2x2 grid of smaller parts.
// We only created square shapes, so this is easy
var x, y;
for (x = 0; x < 2; x += 1)
{
for (y = 0; y < 2; y += 1)
{
var localPosition = [
(shapeSize / 2) * ((2 * x) - 1),
(shapeSize / 2) * ((2 * y) - 1)
];
var burstVelocity = otherBody.transformLocalVectorToWorld(localPosition);
var newBody = phys2D.createRigidBody({
position : otherBody.transformLocalPointToWorld(localPosition),
rotation : otherBody.getRotation(),
velocity : mathDevice.v2AddScalarMul(otherBody.getVelocity(), burstVelocity, 10),
angularVelocity : otherBody.getAngularVelocity()
});
var newShape = otherShape.clone();
newShape.scale(1 / 2);
newBody.addShape(newShape);
// Set up for next level of breaking!
newShape.userData = {
breakCount : breakCount,
shapeSize : shapeSize
};
newShape.setGroup(breakGroup);
world.addRigidBody(newBody);
}
}
}
function lightTunnelListener(position, direction)
{
return function (arbiter, otherShape)
{
var otherBody = otherShape.body;
// Counteract gravity force on world.
// 60 because our time step is (1 / 60) and gravity is a force.
var mass = otherBody.getMass();
var gravityImpulse = mathDevice.v2ScalarMul(world.getGravity(), -mass / 60);
// Tunnel direction impulses.
var tunnelImpulse = mathDevice.v2ScalarMul(direction, mass);
// Impulse to guide body to centre of tunnel.
var amount = mathDevice.v2PerpDot(mathDevice.v2Sub(otherBody.getPosition(), position), direction) * mass;
var directionX = direction[0];
var directionY = direction[1];
var guideImpulse = mathDevice.v2Build(-directionY * amount, directionX * amount);
// Add a velocity dampener.
mathDevice.v2AddScalarMul(guideImpulse, otherBody.getVelocity(), -mass * 0.1, guideImpulse);
otherBody.applyImpulse(gravityImpulse);
otherBody.applyImpulse(tunnelImpulse);
otherBody.applyImpulse(guideImpulse);
// Dampen angular velocity too.
otherBody.setAngularVelocity(otherBody.getAngularVelocity() * 0.95);
};
}
function reset()
{
// Remove all bodies and constraints from world.
world.clear();
handConstraint = null;
// Create border body.
var thickness = 0.01; // 1 cm
var border = phys2D.createRigidBody({
type : 'static',
shapes : [
phys2D.createPolygonShape({
vertices : phys2D.createRectangleVertices(0, 0, thickness, stageHeight)
}),
phys2D.createPolygonShape({
vertices : phys2D.createRectangleVertices((stageWidth - thickness), 0, stageWidth, stageHeight)
}),
phys2D.createPolygonShape({
vertices : phys2D.createRectangleVertices(stageWidth - 2, (stageHeight - thickness - 1), stageWidth, stageHeight)
}),
phys2D.createPolygonShape({
vertices : phys2D.createRectangleVertices(0, (stageHeight - thickness - 1), stageWidth - 8, stageHeight)
})
]
});
// Set up top bar of border with preSolve handler allowing one-way motion
// from the top down.
var topBar = phys2D.createPolygonShape({
vertices : phys2D.createRectangleVertices(0, 1, stageWidth, thickness + 1)
});
border.addShape(topBar);
// Set as a deterministic handler operating on all objects (undefined mask).
topBar.addEventListener('preSolve', oneWayListener(mathDevice.v2Build(0, 1)), undefined, true);
// Set up sensor bar at bottom of border to teleport bodies.
var sensorBar = phys2D.createPolygonShape({
vertices : phys2D.createRectangleVertices(stageWidth - 8, (stageHeight - 0.5), stageWidth - 2, stageHeight),
sensor : true
});
border.addShape(sensorBar);
// Unspecified mask means operate on all objects.
sensorBar.addEventListener('begin', teleportListener);
world.addRigidBody(border);
var spikes = function spikesFn(x: number, y: number,
directionX: number, directionY: number,
count: number, startIndex?: number)
{
var spikeBody = phys2D.createRigidBody({
type : 'static'
});
// Create set of spikes.
var spikeWidth = 0.5;
var spikeHeight = 0.5;
var i;
startIndex = (startIndex || 0);
for (i = startIndex; i < (startIndex + count); i += 1)
{
var posX = x - (directionY * spikeWidth * i);
var posY = y + (directionX * spikeWidth * i);
var spike = phys2D.createPolygonShape({
vertices : [
[ posX,
posY ],
[ posX - (spikeWidth * directionY / 2) + (spikeHeight * directionX),
posY + (spikeWidth * directionX / 2) + (spikeHeight * directionY) ],
[ posX - (spikeWidth * directionY),
posY + (spikeWidth * directionX) ]
]
});
// Don't invoke listener on shapes we don't want to break.
// Set event listener for 'begin' and 'progress' so we can also
// cause boxes to break by pushing them into the spikes.
spike.addEventListener('begin', spikeListener, breakGroup);
spike.addEventListener('progress', spikeListener, breakGroup);
spikeBody.addShape(spike);
}
world.addRigidBody(spikeBody);
};
// Horizontal spikes (facing up [0, -1]) at bottom-left of border.
spikes(2, stageHeight - 1, 0, -1, 8);
// Vertical spikes (facing right [1, 0]) at mid-point of left of border.
spikes(0, stageHeight / 4, 1, 0, 8, -4);
// Light tunnel.
var lightShape = phys2D.createPolygonShape({
vertices : phys2D.createRectangleVertices(0, stageHeight / 4 - 1, stageWidth, stageHeight / 4 + 1),
sensor : true
});
// light tunnel in left direction [-1, 0]
var listener = lightTunnelListener(mathDevice.v2Build(0, stageHeight / 4), mathDevice.v2Build(-1, 0));
lightShape.addEventListener('begin', listener);
lightShape.addEventListener('progress', listener);
var lightBody = phys2D.createRigidBody({
shapes : [lightShape],
type : 'static'
});
world.addRigidBody(lightBody);
// Middle platform with one-way tunnel
var platform = phys2D.createRigidBody({
type : 'static',
shapes : [
phys2D.createPolygonShape({
vertices : [
[ 9, 11 ],
[ 11, 11 ],
[ 11, 15 ]
]
}),
phys2D.createPolygonShape({
vertices : [
[ 17, 11 ],
[ 19, 11 ],
[ 17, 15 ]
]
}),
// Arrow
phys2D.createPolygonShape({
vertices : [
[ 14, 12.5 ],
[ 14.4, 13 ],
[ 13.6, 13 ]
],
sensor : true
}),
phys2D.createPolygonShape({
vertices : [
[ 14.1, 13 ],
[ 14.1, 13.5 ],
[ 13.9, 13.5 ],
[ 13.9, 13 ]
],
sensor : true
})
]
});
thickness = 0.1;
topBar = phys2D.createPolygonShape({
vertices : phys2D.createRectangleVertices(11, 11, 17, 11 + thickness)
});
platform.addShape(topBar);
// Set as a deterministic handler operating on all objects (undefined mask).
topBar.addEventListener('preSolve', oneWayListener(mathDevice.v2Build(0, -1)), undefined, true);
var bottomBar = phys2D.createPolygonShape({
vertices : phys2D.createRectangleVertices(11, 15 - thickness, 17, 15)
});
platform.addShape(bottomBar);
// Set as a deterministic handler operating on all objects (undefined mask).
bottomBar.addEventListener('preSolve', oneWayListener(mathDevice.v2Build(0, -1)), undefined, true);
world.addRigidBody(platform);
// Set up some initial objects.
var generate = function generateFn(x: number, y: number,
scale: number, breakCount: number)
{
var shape = boxShape.clone();
shape.scale(scale);
shape.userData = {
shapeSize : (shapeSize * scale),
breakCount : breakCount
};
var body = phys2D.createRigidBody({
shapes : [shape],
position : [x, y]
});
world.addRigidBody(body);
};
generate(15, 14, 1, 3);
generate(13.5, 14.5, 0.5, 2);
generate(12.75, 14.75, 0.25, 1);
generate(4, 15, 1, 3);
generate(4, 13, 1, 3);
generate(4, 11, 1, 3);
generate(stageWidth - 5, 15, 1, 3);
}
reset();
//==========================================================================
// Mouse/Keyboard controls
//==========================================================================
var inputDevice = TurbulenzEngine.createInputDevice({});
var keyCodes = inputDevice.keyCodes;
var mouseCodes = inputDevice.mouseCodes;
var mouseX = 0;
var mouseY = 0;
var onMouseOver = function mouseOverFn(x, y)
{
mouseX = x;
mouseY = y;
};
inputDevice.addEventListener('mouseover', onMouseOver);
var onKeyUp = function onKeyUpFn(keynum)
{
if (keynum === keyCodes.R) // 'r' key
{
reset();
}
};
inputDevice.addEventListener('keyup', onKeyUp);
var onMouseDown = function onMouseDownFn(code, x, y)
{
mouseX = x;
mouseY = y;
if (handConstraint)
{
return;
}
var point = draw2D.viewportMap(x, y);
var body;
if (code === mouseCodes.BUTTON_0) // Left button
{
if (handConstraint)
{
world.removeConstraint(handConstraint);
handConstraint = null;
}
var bodies = [];
var numBodies = world.bodyPointQuery(point, bodies);
var i;
for (i = 0; i < numBodies; i += 1)
{
body = bodies[i];
if (body.isDynamic())
{
handConstraint = phys2D.createPointConstraint({
bodyA : handReferenceBody,
bodyB : body,
anchorA : point,
anchorB : body.transformWorldPointToLocal(point),
stiff : false,
maxForce : 1e5
});
world.addConstraint(handConstraint);
break;
}
}
}
else if (code === mouseCodes.BUTTON_1) // Right button
{
body = phys2D.createRigidBody({
shapes : [boxShape.clone()],
position : point
});
world.addRigidBody(body);
}
};
inputDevice.addEventListener('mousedown', onMouseDown);
var onMouseLeaveUp = function onMouseLeaveUpFn()
{
if (handConstraint)
{
world.removeConstraint(handConstraint);
handConstraint = null;
}
};
inputDevice.addEventListener('mouseleave', onMouseLeaveUp);
inputDevice.addEventListener('mouseup', onMouseLeaveUp);
//==========================================================================
// Main loop.
//==========================================================================
var realTime = 0;
var prevTime = TurbulenzEngine.time;
function mainLoop()
{
if (!graphicsDevice.beginFrame())
{
return;
}
inputDevice.update();
graphicsDevice.clear([0.3, 0.3, 0.3, 1.0]);
if (handConstraint)
{
handConstraint.setAnchorA(draw2D.viewportMap(mouseX, mouseY));
var body = handConstraint.bodyB;
// Additional angular dampening of body being dragged.
// Helps it to settle quicker instead of spinning around
// the cursor.
body.setAngularVelocity(body.getAngularVelocity() * 0.9);
}
var curTime = TurbulenzEngine.time;
var timeDelta = (curTime - prevTime);
// Prevent trying to simulate too much time at once!
if (timeDelta > (1 / 20))
{
timeDelta = (1 / 20);
}
realTime += timeDelta;
prevTime = curTime;
while (world.simulatedTime < realTime)
{
world.step(1 / 60);
}
// physics2D debug drawing.
debug.setScreenViewport(draw2D.getScreenSpaceViewport());
debug.begin();
debug.drawWorld(world);
debug.end();
graphicsDevice.endFrame();
}
var intervalID = TurbulenzEngine.setInterval(mainLoop, (1000 / 60));
// Create a scene destroy callback to run when the window is closed
TurbulenzEngine.onunload = function destroyScene()
{
if (mainLoop)
{
TurbulenzEngine.clearInterval(intervalID);
}
if (gameSession)
{
gameSession.destroy();
gameSession = null;
}
};
}; | the_stack |
import { assert } from '../common/debug';
import { DiagnosticAddendum } from '../common/diagnostic';
import { Localizer } from '../localization/localize';
import { DeclarationType } from './declaration';
import { assignProperty } from './properties';
import { TypeEvaluator } from './typeEvaluatorTypes';
import {
ClassType,
isClassInstance,
isFunction,
isInstantiableClass,
isOverloadedFunction,
isTypeSame,
maxTypeRecursionCount,
ModuleType,
Type,
UnknownType,
} from './types';
import {
applySolvedTypeVars,
AssignTypeFlags,
buildTypeVarContextFromSpecializedClass,
ClassMember,
containsLiteralType,
getTypeVarScopeId,
lookUpClassMember,
partiallySpecializeType,
populateTypeVarContextForSelfType,
removeParamSpecVariadicsFromSignature,
specializeForBaseClass,
} from './typeUtils';
import { TypeVarContext } from './typeVarContext';
interface ProtocolAssignmentStackEntry {
srcType: ClassType;
destType: ClassType;
}
const protocolAssignmentStack: ProtocolAssignmentStackEntry[] = [];
// If treatSourceAsInstantiable is true, we're comparing the class object against the
// protocol. If it's false, we're comparing the class instance against the protocol.
export function assignClassToProtocol(
evaluator: TypeEvaluator,
destType: ClassType,
srcType: ClassType,
diag: DiagnosticAddendum | undefined,
destTypeVarContext: TypeVarContext | undefined,
srcTypeVarContext: TypeVarContext | undefined,
flags: AssignTypeFlags,
treatSourceAsInstantiable: boolean,
recursionCount: number
): boolean {
if (recursionCount > maxTypeRecursionCount) {
return true;
}
recursionCount++;
// Use a stack of pending protocol class evaluations to detect recursion.
// This can happen when a protocol class refers to itself.
if (
protocolAssignmentStack.some((entry) => {
return isTypeSame(entry.srcType, srcType) && isTypeSame(entry.destType, destType);
})
) {
return true;
}
// See if we've already determined that this class is compatible with this protocol.
if (
!treatSourceAsInstantiable &&
destType.details.typeParameters.length === 0 &&
srcType.details.typeParameters.length === 0 &&
srcType.details.compatibleProtocols?.has(destType.details.fullName)
) {
return true;
}
protocolAssignmentStack.push({ srcType, destType });
let isCompatible = true;
try {
isCompatible = assignClassToProtocolInternal(
evaluator,
destType,
srcType,
diag,
destTypeVarContext,
srcTypeVarContext,
flags,
treatSourceAsInstantiable,
recursionCount
);
} catch (e) {
// We'd normally use "finally" here, but the TS debugger does such
// a poor job dealing with finally, we'll use a catch instead.
protocolAssignmentStack.pop();
throw e;
}
protocolAssignmentStack.pop();
// If the destination protocol is not generic and the source type is not
// generic and the two are compatible, cache that information so we can
// skip the check next time.
if (
isCompatible &&
!treatSourceAsInstantiable &&
destType.details.typeParameters.length === 0 &&
srcType.details.typeParameters.length === 0
) {
if (!srcType.details.compatibleProtocols) {
srcType.details.compatibleProtocols = new Set<string>();
}
srcType.details.compatibleProtocols.add(destType.details.fullName);
}
return isCompatible;
}
function assignClassToProtocolInternal(
evaluator: TypeEvaluator,
destType: ClassType,
srcType: ClassType,
diag: DiagnosticAddendum | undefined,
destTypeVarContext: TypeVarContext | undefined,
srcTypeVarContext: TypeVarContext | undefined,
flags: AssignTypeFlags,
treatSourceAsInstantiable: boolean,
recursionCount: number
): boolean {
if ((flags & AssignTypeFlags.EnforceInvariance) !== 0) {
return isTypeSame(destType, srcType);
}
// Strip the type arguments off the dest protocol if they are provided.
const genericDestType = ClassType.cloneForSpecialization(destType, undefined, /* isTypeArgumentExplicit */ false);
const genericDestTypeVarContext = new TypeVarContext(getTypeVarScopeId(destType));
const selfTypeVarContext = new TypeVarContext(getTypeVarScopeId(destType));
populateTypeVarContextForSelfType(selfTypeVarContext, destType, srcType);
// If the source is a TypedDict, use the _TypedDict placeholder class
// instead. We don't want to use the TypedDict members for protocol
// comparison.
if (ClassType.isTypedDictClass(srcType)) {
const typedDictClassType = evaluator.getTypedDictClassType();
if (typedDictClassType && isInstantiableClass(typedDictClassType)) {
srcType = typedDictClassType;
}
}
let typesAreConsistent = true;
const checkedSymbolSet = new Set<string>();
const srcClassTypeVarContext = buildTypeVarContextFromSpecializedClass(srcType);
const assignTypeFlags = containsLiteralType(srcType, /* includeTypeArgs */ true)
? AssignTypeFlags.RetainLiteralsForTypeVar
: AssignTypeFlags.Default;
destType.details.mro.forEach((mroClass) => {
if (!isInstantiableClass(mroClass) || !ClassType.isProtocolClass(mroClass)) {
return;
}
// If we've already determined that the types are not consistent and the caller
// hasn't requested detailed diagnostic output, we can shortcut the remainder.
if (!typesAreConsistent && !diag) {
return;
}
mroClass.details.fields.forEach((symbol, name) => {
// If we've already determined that the types are not consistent and the caller
// hasn't requested detailed diagnostic output, we can shortcut the remainder.
if (!typesAreConsistent && !diag) {
return;
}
if (symbol.isClassMember() && !symbol.isIgnoredForProtocolMatch() && !checkedSymbolSet.has(name)) {
let isMemberFromMetaclass = false;
let srcMemberInfo: ClassMember | undefined;
// Special-case the `__class_getitem__` for normal protocol comparison.
// This is a convention agreed upon by typeshed maintainers.
if (!treatSourceAsInstantiable && name === '__class_getitem__') {
return;
}
// Special-case the `__slots__` entry for all protocol comparisons.
// This is a convention agreed upon by typeshed maintainers.
if (name === '__slots__') {
return;
}
// Note that we've already checked this symbol. It doesn't need to
// be checked again even if it is declared by a subclass.
checkedSymbolSet.add(name);
// Look in the metaclass first if we're treating the source as an instantiable class.
if (
treatSourceAsInstantiable &&
srcType.details.effectiveMetaclass &&
isInstantiableClass(srcType.details.effectiveMetaclass)
) {
srcMemberInfo = lookUpClassMember(srcType.details.effectiveMetaclass, name);
if (srcMemberInfo) {
srcClassTypeVarContext.addSolveForScope(getTypeVarScopeId(srcType.details.effectiveMetaclass));
isMemberFromMetaclass = true;
}
}
if (!srcMemberInfo) {
srcMemberInfo = lookUpClassMember(srcType, name);
}
if (!srcMemberInfo) {
diag?.addMessage(Localizer.DiagnosticAddendum.protocolMemberMissing().format({ name }));
typesAreConsistent = false;
} else {
let destMemberType = evaluator.getDeclaredTypeOfSymbol(symbol);
if (destMemberType) {
// Partially specialize the type of the symbol based on the MRO class.
// We can skip this if it's the dest class because it is already
// specialized.
if (!ClassType.isSameGenericClass(mroClass, destType)) {
destMemberType = partiallySpecializeType(destMemberType, mroClass);
}
let srcMemberType: Type;
if (isInstantiableClass(srcMemberInfo.classType)) {
const symbolType = evaluator.getEffectiveTypeOfSymbol(srcMemberInfo.symbol);
// If this is a function, infer its return type prior to specializing it.
if (isFunction(symbolType)) {
evaluator.inferReturnTypeIfNecessary(symbolType);
}
srcMemberType = partiallySpecializeType(symbolType, srcMemberInfo.classType, srcType);
} else {
srcMemberType = UnknownType.create();
}
if (isFunction(srcMemberType) || isOverloadedFunction(srcMemberType)) {
if (isMemberFromMetaclass) {
const boundSrcFunction = evaluator.bindFunctionToClassOrObject(
srcType,
srcMemberType,
/* memberClass */ undefined,
/* errorNode */ undefined,
recursionCount,
/* treatConstructorAsClassMember */ false,
srcType
);
if (boundSrcFunction) {
srcMemberType = removeParamSpecVariadicsFromSignature(boundSrcFunction);
}
if (isFunction(destMemberType) || isOverloadedFunction(destMemberType)) {
const boundDeclaredType = evaluator.bindFunctionToClassOrObject(
srcType,
destMemberType,
/* memberClass */ undefined,
/* errorNode */ undefined,
recursionCount,
/* treatConstructorAsClassMember */ false,
srcType
);
if (boundDeclaredType) {
destMemberType = removeParamSpecVariadicsFromSignature(boundDeclaredType);
}
}
} else if (isInstantiableClass(srcMemberInfo.classType)) {
// Replace any "Self" TypeVar within the dest with the source type.
destMemberType = applySolvedTypeVars(destMemberType, selfTypeVarContext);
const boundSrcFunction = evaluator.bindFunctionToClassOrObject(
treatSourceAsInstantiable ? srcType : ClassType.cloneAsInstance(srcType),
srcMemberType,
srcMemberInfo.classType,
/* errorNode */ undefined,
recursionCount
);
if (boundSrcFunction) {
srcMemberType = removeParamSpecVariadicsFromSignature(boundSrcFunction);
}
if (isFunction(destMemberType) || isOverloadedFunction(destMemberType)) {
const boundDeclaredType = evaluator.bindFunctionToClassOrObject(
ClassType.cloneAsInstance(srcType),
destMemberType,
srcMemberInfo.classType,
/* errorNode */ undefined,
recursionCount
);
if (boundDeclaredType) {
destMemberType = removeParamSpecVariadicsFromSignature(boundDeclaredType);
}
}
}
} else {
// Replace any "Self" TypeVar within the dest with the source type.
destMemberType = applySolvedTypeVars(destMemberType, selfTypeVarContext);
}
const subDiag = diag?.createAddendum();
// Properties require special processing.
if (isClassInstance(destMemberType) && ClassType.isPropertyClass(destMemberType)) {
if (
isClassInstance(srcMemberType) &&
ClassType.isPropertyClass(srcMemberType) &&
!treatSourceAsInstantiable
) {
if (
!assignProperty(
evaluator,
ClassType.cloneAsInstantiable(destMemberType),
ClassType.cloneAsInstantiable(srcMemberType),
mroClass,
srcType,
subDiag?.createAddendum(),
genericDestTypeVarContext,
selfTypeVarContext,
recursionCount
)
) {
if (subDiag) {
subDiag.addMessage(
Localizer.DiagnosticAddendum.memberTypeMismatch().format({ name })
);
}
typesAreConsistent = false;
}
} else {
// Extract the property type from the property class.
const getterType = evaluator.getGetterTypeFromProperty(
destMemberType,
/* inferTypeIfNeeded */ true
);
if (
!getterType ||
!evaluator.assignType(
getterType,
srcMemberType,
subDiag?.createAddendum(),
genericDestTypeVarContext,
/* srcTypeVarContext */ undefined,
assignTypeFlags,
recursionCount
)
) {
if (subDiag) {
subDiag.addMessage(
Localizer.DiagnosticAddendum.memberTypeMismatch().format({ name })
);
}
typesAreConsistent = false;
}
}
} else {
// Class and instance variables that are mutable need to
// enforce invariance.
const primaryDecl = symbol.getDeclarations()[0];
const isInvariant = primaryDecl?.type === DeclarationType.Variable && !primaryDecl.isFinal;
if (
!evaluator.assignType(
destMemberType,
srcMemberType,
subDiag?.createAddendum(),
genericDestTypeVarContext,
/* srcTypeVarContext */ undefined,
isInvariant ? assignTypeFlags | AssignTypeFlags.EnforceInvariance : assignTypeFlags,
recursionCount
)
) {
if (subDiag) {
if (isInvariant) {
subDiag.addMessage(
Localizer.DiagnosticAddendum.memberIsInvariant().format({ name })
);
}
subDiag.addMessage(
Localizer.DiagnosticAddendum.memberTypeMismatch().format({ name })
);
}
typesAreConsistent = false;
}
}
const isDestFinal = symbol
.getTypedDeclarations()
.some((decl) => decl.type === DeclarationType.Variable && !!decl.isFinal);
const isSrcFinal = srcMemberInfo.symbol
.getTypedDeclarations()
.some((decl) => decl.type === DeclarationType.Variable && !!decl.isFinal);
if (isDestFinal !== isSrcFinal) {
if (isDestFinal) {
if (subDiag) {
subDiag.addMessage(
Localizer.DiagnosticAddendum.memberIsFinalInProtocol().format({ name })
);
}
} else {
if (subDiag) {
subDiag.addMessage(
Localizer.DiagnosticAddendum.memberIsNotFinalInProtocol().format({ name })
);
}
}
typesAreConsistent = false;
}
}
if (symbol.isClassVar() && !srcMemberInfo.symbol.isClassMember()) {
diag?.addMessage(Localizer.DiagnosticAddendum.protocolMemberClassVar().format({ name }));
typesAreConsistent = false;
}
}
}
});
});
// If the dest protocol has type parameters, make sure the source type arguments match.
if (typesAreConsistent && destType.details.typeParameters.length > 0 && destType.typeArguments) {
// Create a specialized version of the protocol defined by the dest and
// make sure the resulting type args can be assigned.
const specializedDestProtocol = applySolvedTypeVars(genericDestType, genericDestTypeVarContext) as ClassType;
if (
!evaluator.verifyTypeArgumentsAssignable(
destType,
specializedDestProtocol,
diag,
destTypeVarContext,
srcTypeVarContext,
flags,
recursionCount
)
) {
typesAreConsistent = false;
}
}
return typesAreConsistent;
}
export function assignModuleToProtocol(
evaluator: TypeEvaluator,
destType: ClassType,
srcType: ModuleType,
diag: DiagnosticAddendum | undefined,
typeVarContext: TypeVarContext | undefined,
flags: AssignTypeFlags,
recursionCount: number
): boolean {
if (recursionCount > maxTypeRecursionCount) {
return true;
}
recursionCount++;
let typesAreConsistent = true;
const checkedSymbolSet = new Set<string>();
// Strip the type arguments off the dest protocol if they are provided.
const genericDestType = ClassType.cloneForSpecialization(destType, undefined, /* isTypeArgumentExplicit */ false);
const genericDestTypeVarContext = new TypeVarContext(getTypeVarScopeId(destType));
destType.details.mro.forEach((mroClass) => {
if (!isInstantiableClass(mroClass) || !ClassType.isProtocolClass(mroClass)) {
return;
}
mroClass.details.fields.forEach((symbol, name) => {
if (symbol.isClassMember() && !symbol.isIgnoredForProtocolMatch() && !checkedSymbolSet.has(name)) {
// Note that we've already checked this symbol. It doesn't need to
// be checked again even if it is declared by a subclass.
checkedSymbolSet.add(name);
const memberSymbol = srcType.fields.get(name);
if (!memberSymbol) {
diag?.addMessage(Localizer.DiagnosticAddendum.protocolMemberMissing().format({ name }));
typesAreConsistent = false;
} else {
let destMemberType = evaluator.getDeclaredTypeOfSymbol(symbol);
if (destMemberType) {
destMemberType = partiallySpecializeType(destMemberType, destType);
const srcMemberType = evaluator.getEffectiveTypeOfSymbol(memberSymbol);
if (isFunction(srcMemberType) || isOverloadedFunction(srcMemberType)) {
if (isFunction(destMemberType) || isOverloadedFunction(destMemberType)) {
const boundDeclaredType = evaluator.bindFunctionToClassOrObject(
ClassType.cloneAsInstance(destType),
destMemberType,
destType,
/* errorNode */ undefined,
recursionCount
);
if (boundDeclaredType) {
destMemberType = boundDeclaredType;
}
}
}
const subDiag = diag?.createAddendum();
if (
!evaluator.assignType(
destMemberType,
srcMemberType,
subDiag?.createAddendum(),
genericDestTypeVarContext,
/* srcTypeVarContext */ undefined,
AssignTypeFlags.Default,
recursionCount
)
) {
if (subDiag) {
subDiag.addMessage(Localizer.DiagnosticAddendum.memberTypeMismatch().format({ name }));
}
typesAreConsistent = false;
}
}
}
}
});
});
// If the dest protocol has type parameters, make sure the source type arguments match.
if (typesAreConsistent && destType.details.typeParameters.length > 0 && destType.typeArguments) {
// Create a specialized version of the protocol defined by the dest and
// make sure the resulting type args can be assigned.
const specializedSrcProtocol = applySolvedTypeVars(genericDestType, genericDestTypeVarContext) as ClassType;
if (
!evaluator.verifyTypeArgumentsAssignable(
destType,
specializedSrcProtocol,
diag,
typeVarContext,
/* srcTypeVarContext */ undefined,
flags,
recursionCount
)
) {
typesAreConsistent = false;
}
}
return typesAreConsistent;
}
// This function is used to validate the variance of type variables
// within a protocol class.
export function assignProtocolClassToSelf(
evaluator: TypeEvaluator,
destType: ClassType,
srcType: ClassType,
recursionCount = 0
): boolean {
assert(ClassType.isProtocolClass(destType));
assert(ClassType.isProtocolClass(srcType));
assert(ClassType.isSameGenericClass(destType, srcType));
assert(destType.details.typeParameters.length > 0);
const diag = new DiagnosticAddendum();
const typeVarContext = new TypeVarContext();
let isAssignable = true;
destType.details.fields.forEach((symbol, name) => {
if (isAssignable && symbol.isClassMember() && !symbol.isIgnoredForProtocolMatch()) {
const memberInfo = lookUpClassMember(srcType, name);
assert(memberInfo !== undefined);
let destMemberType = evaluator.getDeclaredTypeOfSymbol(symbol);
if (destMemberType) {
const srcMemberType = evaluator.getTypeOfMember(memberInfo!);
destMemberType = partiallySpecializeType(destMemberType, destType);
// Properties require special processing.
if (
isClassInstance(destMemberType) &&
ClassType.isPropertyClass(destMemberType) &&
isClassInstance(srcMemberType) &&
ClassType.isPropertyClass(srcMemberType)
) {
if (
!assignProperty(
evaluator,
ClassType.cloneAsInstantiable(destMemberType),
ClassType.cloneAsInstantiable(srcMemberType),
destType,
srcType,
diag,
typeVarContext,
/* selfTypeVarContext */ undefined,
recursionCount
)
) {
isAssignable = false;
}
} else {
const primaryDecl = symbol.getDeclarations()[0];
// Class and instance variables that are mutable need to
// enforce invariance.
const flags =
primaryDecl?.type === DeclarationType.Variable && !primaryDecl.isFinal
? AssignTypeFlags.EnforceInvariance
: AssignTypeFlags.Default;
if (
!evaluator.assignType(
destMemberType,
srcMemberType,
diag,
typeVarContext,
/* srcTypeVarContext */ undefined,
flags,
recursionCount
)
) {
isAssignable = false;
}
}
}
}
});
// Now handle generic base classes.
destType.details.baseClasses.forEach((baseClass) => {
if (
isInstantiableClass(baseClass) &&
ClassType.isProtocolClass(baseClass) &&
!ClassType.isBuiltIn(baseClass, 'object') &&
!ClassType.isBuiltIn(baseClass, 'Protocol') &&
baseClass.details.typeParameters.length > 0
) {
const specializedDestBaseClass = specializeForBaseClass(destType, baseClass);
const specializedSrcBaseClass = specializeForBaseClass(srcType, baseClass);
if (
!assignProtocolClassToSelf(evaluator, specializedDestBaseClass, specializedSrcBaseClass, recursionCount)
) {
isAssignable = false;
}
}
});
return isAssignable;
} | the_stack |
import assert from 'assert';
import {
CallbackObject,
ComponentsObject,
ExampleObject,
HeaderObject,
ISpecificationExtension,
LinkObject,
OpenAPIObject,
OperationObject,
ParameterObject,
ReferenceObject,
RequestBodyObject,
ResponseObject,
SchemaObject,
SecuritySchemeObject,
} from 'openapi3-ts';
/**
* Create a new instance of OpenApiSpecBuilder.
*
* @param basePath - The base path on which the API is served.
*/
export function anOpenApiSpec() {
return new OpenApiSpecBuilder();
}
/**
* Create a new instance of OperationSpecBuilder.
*/
export function anOperationSpec() {
return new OperationSpecBuilder();
}
/**
* Create a new instance of ComponentsSpecBuilder.
*/
export function aComponentsSpec() {
return new ComponentsSpecBuilder();
}
export class BuilderBase<T extends ISpecificationExtension> {
protected _spec: T;
constructor(initialSpec: T) {
this._spec = initialSpec;
}
/**
* Add a custom (extension) property to the spec object.
*
* @param key - The property name starting with "x-".
* @param value - The property value.
*/
withExtension(
key: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any,
): this {
assert(
key.startsWith('x-'),
`Invalid extension ${key}, extension keys must be prefixed with "x-"`,
);
// `this._spec[key] = value;` is broken in TypeScript 3.5
// See https://github.com/microsoft/TypeScript/issues/31661
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(this._spec as Record<string, any>)[key] = value;
return this;
}
/**
* Build the spec object.
*/
build(): T {
// TODO(bajtos): deep-clone
return this._spec;
}
}
/**
* A builder for creating OpenApiSpec documents.
*/
export class OpenApiSpecBuilder extends BuilderBase<OpenAPIObject> {
/**
* @param basePath - The base path on which the API is served.
*/
constructor() {
super({
openapi: '3.0.0',
info: {
title: 'LoopBack Application',
version: '1.0.0',
},
paths: {},
servers: [{url: '/'}],
});
}
/**
* Define a new OperationObject at the given path and verb (method).
*
* @param verb - The HTTP verb.
* @param path - The path relative to basePath.
* @param spec - Additional specification of the operation.
*/
withOperation(
verb: string,
path: string,
spec: OperationObject | OperationSpecBuilder,
): this {
if (spec instanceof OperationSpecBuilder) spec = spec.build();
if (!this._spec.paths[path]) this._spec.paths[path] = {};
this._spec.paths[path][verb] = spec;
return this;
}
/**
* Define a new operation that returns a string response.
*
* @param verb - The HTTP verb.
* @param path - The path relative to basePath.
* @param operationName - The name of the controller method implementing
* this operation (`x-operation-name` field).
*/
withOperationReturningString(
verb: string,
path: string,
operationName?: string,
): this {
const spec = anOperationSpec().withStringResponse(200);
if (operationName) spec.withOperationName(operationName);
return this.withOperation(verb, path, spec);
}
/**
* Define a new ComponentsObject.
*
* @param spec - Specification of the components.
*/
withComponents(spec: ComponentsObject | ComponentsSpecBuilder): this {
if (spec instanceof ComponentsSpecBuilder) spec = spec.build();
if (!this._spec.components) this._spec.components = spec;
return this;
}
}
/**
* A builder for creating OperationObject specifications.
*/
export class OperationSpecBuilder extends BuilderBase<OperationObject> {
constructor() {
super({
responses: {'200': {description: 'An undocumented response body.'}},
});
}
/**
* Describe a response for a given HTTP status code.
* @param status - HTTP status code or string "default"
* @param responseSpec - Specification of the response
*/
withResponse(status: number | 'default', responseSpec: ResponseObject): this {
// OpenAPI spec uses string indices, i.e. 200 OK uses "200" as the index
this._spec.responses[status.toString()] = responseSpec;
return this;
}
withStringResponse(status: number | 'default' = 200): this {
return this.withResponse(status, {
description: 'The string result.',
content: {
'text/plain': {
schema: {type: 'string'},
},
},
});
}
/**
* Describe one more parameters accepted by the operation.
* Note that parameters are positional in OpenAPI Spec, therefore
* the first call of `withParameter` defines the first parameter,
* the second call defines the second parameter, etc.
* @param parameterSpecs
*/
withParameter(...parameterSpecs: ParameterObject[]): this {
if (!this._spec.parameters) this._spec.parameters = [];
this._spec.parameters.push(...parameterSpecs);
return this;
}
withRequestBody(requestBodySpec: RequestBodyObject): this {
this._spec.requestBody = requestBodySpec;
return this;
}
/**
* Define the operation name (controller method name).
*
* @param name - The name of the controller method implementing this operation.
*/
withOperationName(name: string): this {
this.withExtension('x-operation-name', name);
this.setupOperationId();
return this;
}
/**
* Define the controller name (controller name).
*
* @param name - The name of the controller containing this operation.
*/
withControllerName(name: string): this {
this.withExtension('x-controller-name', name);
this.setupOperationId();
return this;
}
/**
* Set up the `operationId` if not configured
*/
private setupOperationId() {
if (this._spec.operationId) return;
const controllerName = this._spec['x-controller-name'];
const operationName = this._spec['x-operation-name'];
if (controllerName && operationName) {
// Build the operationId as `<controllerName>.<operationName>`
// Please note API explorer (https://github.com/swagger-api/swagger-js/)
// will normalize it as `<controllerName>_<operationName>`
this._spec.operationId = controllerName + '.' + operationName;
}
}
/**
* Define the operationId
* @param operationId - Operation id
*/
withOperationId(operationId: string): this {
this._spec.operationId = operationId;
return this;
}
/**
* Describe tags associated with the operation
* @param tags
*/
withTags(tags: string | string[]): this {
if (!this._spec.tags) this._spec.tags = [];
if (typeof tags === 'string') tags = [tags];
this._spec.tags.push(...tags);
return this;
}
}
/**
* A builder for creating ComponentsObject specifications.
*/
export class ComponentsSpecBuilder extends BuilderBase<ComponentsObject> {
constructor() {
super({});
}
/**
* Define a component schema.
*
* @param name - The name of the schema
* @param schema - Specification of the schema
*
*/
withSchema(name: string, schema: SchemaObject | ReferenceObject): this {
if (!this._spec.schemas) this._spec.schemas = {};
this._spec.schemas[name] = schema;
return this;
}
/**
* Define a component response.
*
* @param name - The name of the response
* @param response - Specification of the response
*
*/
withResponse(name: string, response: ResponseObject | ReferenceObject): this {
if (!this._spec.responses) this._spec.responses = {};
this._spec.responses[name] = response;
return this;
}
/**
* Define a component parameter.
*
* @param name - The name of the parameter
* @param parameter - Specification of the parameter
*
*/
withParameter(
name: string,
parameter: ParameterObject | ReferenceObject,
): this {
if (!this._spec.parameters) this._spec.parameters = {};
this._spec.parameters[name] = parameter;
return this;
}
/**
* Define a component example.
*
* @param name - The name of the example
* @param example - Specification of the example
*
*/
withExample(name: string, example: ExampleObject | ReferenceObject): this {
if (!this._spec.examples) this._spec.examples = {};
this._spec.examples[name] = example;
return this;
}
/**
* Define a component request body.
*
* @param name - The name of the request body
* @param requestBody - Specification of the request body
*
*/
withRequestBody(
name: string,
requestBody: RequestBodyObject | ReferenceObject,
): this {
if (!this._spec.requestBodies) this._spec.requestBodies = {};
this._spec.requestBodies[name] = requestBody;
return this;
}
/**
* Define a component header.
*
* @param name - The name of the header
* @param header - Specification of the header
*
*/
withHeader(name: string, header: HeaderObject | ReferenceObject): this {
if (!this._spec.headers) this._spec.headers = {};
this._spec.headers[name] = header;
return this;
}
/**
* Define a component security scheme.
*
* @param name - The name of the security scheme
* @param securityScheme - Specification of the security scheme
*
*/
withSecurityScheme(
name: string,
securityScheme: SecuritySchemeObject | ReferenceObject,
): this {
if (!this._spec.securitySchemes) this._spec.securitySchemes = {};
this._spec.securitySchemes[name] = securityScheme;
return this;
}
/**
* Define a component link.
*
* @param name - The name of the link
* @param link - Specification of the link
*
*/
withLink(name: string, link: LinkObject | ReferenceObject): this {
if (!this._spec.links) this._spec.links = {};
this._spec.links[name] = link;
return this;
}
/**
* Define a component callback.
*
* @param name - The name of the callback
* @param callback - Specification of the callback
*
*/
withCallback(name: string, callback: CallbackObject | ReferenceObject): this {
if (!this._spec.callbacks) this._spec.callbacks = {};
this._spec.callbacks[name] = callback;
return this;
}
} | the_stack |
import { MnemonicLanguages } from '@celo/base/lib/account'
import * as bip39 from 'bip39'
import {
generateKeys,
generateMnemonic,
getAllLanguages,
invalidMnemonicWords,
MnemonicStrength,
normalizeMnemonic,
suggestMnemonicCorrections,
validateMnemonic,
} from './account'
describe('AccountUtils', () => {
describe('.generateMnemonic()', () => {
it('should generate 24 word mnemonic', async () => {
const mnemonic: string = await generateMnemonic()
expect(mnemonic.split(/\s+/g).length).toEqual(24)
})
it('should generate 12 word mnemonic', async () => {
const mnemonic: string = await generateMnemonic(MnemonicStrength.s128_12words)
expect(mnemonic.split(/\s+/g).length).toEqual(12)
})
for (const language of getAllLanguages()) {
const languageName = MnemonicLanguages[language]
it(`should generate a valid mnemonic in ${languageName}}`, async () => {
const mnemonic = await generateMnemonic(undefined, language)
expect(mnemonic.split(/\s+/g).length).toEqual(24)
// This validates against all languages
expect(validateMnemonic(mnemonic)).toBeTruthy()
// This validates using a specific wordlist
expect(bip39.validateMnemonic(mnemonic, bip39.wordlists[languageName])).toBeTruthy()
})
}
})
describe('.validateMnemonic()', () => {
const testMnemonics = {
[MnemonicLanguages.chinese_simplified]:
'唐 即 驶 橡 钙 六 码 卸 擦 批 培 拒 磨 励 累 栏 砍 霞 弃 卫 中 空 罩 尘',
[MnemonicLanguages.chinese_traditional]:
'微 款 輩 除 雕 將 鑽 蕭 奇 波 掃 齒 弱 誣 氫 兩 證 漸 堡 亦 攝 了 坯 材',
[MnemonicLanguages.english]:
'grid dove lift rib rose grit comfort delay moon crumble sell adapt rule food pull loan puppy okay palace predict grass hint repair napkin',
[MnemonicLanguages.french]:
'texte succès lexique frégate sévir oiseau lanceur souvenir mythique onirique pélican opérer foulure enfouir maintien vexer relief aérer citerne ligoter arbitre gomme sénateur dénouer',
[MnemonicLanguages.italian]:
'leone sinistro nicchia mole tromba celebre parcella pillola golf voga ostacolo relazione peso unificato tristezza brezza merenda trasloco pinolo persuaso querela pomice onere premere',
[MnemonicLanguages.japanese]:
'へきが けねん したうけ せんさい けいさつ めんきょ せりふ ひびく せあぶら たいむ そこう うさぎ つながる はんろん むいか せはば すべる りりく はいれつ たいる りかい さたん はっかく ひしょ',
[MnemonicLanguages.korean]:
'보장 검사 장기간 문득 먼저 현지 쇼핑 재정 예금 녹화 연세 도덕 정말 불빛 사생활 재능 활동 불빛 경험 소형 고등학생 철저히 공원 증세',
[MnemonicLanguages.spanish]:
'cordón soplar santo teoría arpa ducha secreto margen brisa anciano maldad colgar atún catre votar órgano bebida ecuador rabia maduro tubo faja avaro vivero',
[MnemonicLanguages.portuguese]:
'cheiro lealdade duplo oposto vereador acessar lanche regra prefeito apego ratazana piedade alarme marmita subsolo brochura honrado viajar magnata canoa sarjeta terno cimento prezar',
}
for (const language of getAllLanguages()) {
const languageName = MnemonicLanguages[language]
it(`should validate a mnemonic in ${languageName}`, () => {
const mnemonic = testMnemonics[language]
expect(mnemonic).toBeDefined()
// This validates against all languages
expect(validateMnemonic(mnemonic)).toBeTruthy()
// This validates using a specific wordlist
expect(bip39.validateMnemonic(mnemonic, bip39.wordlists[languageName])).toBeTruthy()
})
}
})
describe('.generateKeys()', () => {
it('should generate an expected private key for a mnemonic', async () => {
// 3 random mnemonic
const mnemonics = [
'language quiz proud sample canoe trend topic upper coil rack choice engage noodle panda mutual grab shallow thrive forget trophy pull pool mask height',
'law canoe elegant tuna core tired flag scissors shy expand drum often output result exotic busy smooth dumb world obtain nominee easily conduct increase',
'second inside foot legend direct bridge human diesel exotic regular silent trigger multiply prosper involve bulb swarm oppose police forest tooth ankle hungry diesel',
]
const expectedPrivateKeys = [
{
derivation0: {
address: '0xe13E391f19193DB38AeA975a30193E50fBff381f',
privateKey: '9b20170cd294190efb2eb1d406a51e6705461cb540e777784565c1d8342016d7',
publicKey: '0257780786b4ba7bf47b3be6082f65069f552012735a17c2080648de67cfb440c1',
},
derivation1: {
address: '0x9a85EBC698647895a1e12544E9B1751Aed57f9F4',
privateKey: '29c025cda952cb59d8504cca390bcdbc2cc3706ca5bfb65a5b6f5dd5dc5176dd',
publicKey: '029c90f394bea3d46c46896b0bd1b36119b031a6da498b49a32aad77f10ce1f672',
},
password: {
address: '0x1546D345F7A5Cf533290fd54833de1Ce0552A2d7',
privateKey: '92956ef74d530224029380385ca556240be042b7e5592ffece5945286f1562c3',
publicKey: '0331003f16d42ea996da1bc91188ff170ea451570a9bed4779682dd27da1892303',
},
},
{
derivation0: {
address: '0xCA388713E3741d9Bf938D6370a94F80766A22530',
privateKey: 'eb0fea0b0aab13e4115939e2af62a5f136cdeefa1f0480c5550b93550339857d',
publicKey: '0279548f9e2b8fbbeb91865068257de240fa307d479c94926a32e33f8707c70497',
},
derivation1: {
address: '0x5bA0350E8a681b0fe3D939633B5514A9A6152f81',
privateKey: 'cd2aa97d2bf6ddac4f00513eb08de8d40dcff4106508d18ea995ffbff8166420',
publicKey: '03e4784248f6c4b3bacf8090f67d002e58f4da448bb9b993432fe226abdcd5c83f',
},
password: {
address: '0x9A78acd4C77c796C3d657f17F3D05cd46eFCC5bE',
privateKey: '62c928058f72e5a04abcf5e46035d5f0933f996285ec25b3bc9d2b9fc907dc56',
publicKey: '0240d5adc5c0ce46f3488401e3ea78a261de1cd8a8e6a1d9e55386c6c4881b70ec',
},
},
{
derivation0: {
address: '0x64265716715822ff47025B0c06478C0FADaf9c6E',
privateKey: 'bfc514b7a895cade755f65196b4807a0635381ee16195b33e22b919ecaedf553',
publicKey: '034ca1fb554b952b6794da020c8d101527a2a91884dbab671211ce77b2ec3f1a3e',
},
derivation1: {
address: '0xff1ef005f5A11426343D3492d73e94bad169d900',
privateKey: '074e6edfc31f8ccfd93427d204da5ada15124a25fde119b7f65b54ff283b6207',
publicKey: '03606b5f63932b2a896c3fb3aa7f60f0f5aa9cd7ce8310199cae2c06514159f799',
},
password: {
address: '0xb73C6AaDb67238323d811469A95E8e2B92cC0B4A',
privateKey: '743594169177ae8ab3dd08a6e22842a2ac43dbe886a73eebc33cd21e73175661',
publicKey: '03aa657da15ceb192b73a3aa3a36512a765d9c9751763dd7801585fba8d10f7467',
},
},
]
expect(mnemonics.length).toEqual(expectedPrivateKeys.length)
for (let i = 0; i < mnemonics.length; ++i) {
expect(validateMnemonic(mnemonics[i])).toBe(true)
const derivation0 = await generateKeys(mnemonics[i])
const derivation1 = await generateKeys(mnemonics[i], undefined, 0, 1)
const password = await generateKeys(mnemonics[i], 'password')
expect({ derivation0, derivation1, password }).toEqual(expectedPrivateKeys[i])
}
})
})
describe('.normalizeMnemonic()', () => {
it('should normalize phrases with and without accents', () => {
const spanishMnemonics = [
'yerno obvio niñez pierna bebé pomelo retorno flujo sacar odio oxígeno rabo', // Correctly accented.
'yerno obvio niñez pierna bebé pomelo retorno flujo sacar odio oxigeno rabo', // Missing 1 accent.
'yerno obvio niñez pierna bebe pomelo retorno flujo sacar odio oxígeno rabo', // Missing 1 accent.
'yerno obvio ninez pierna bebe pomelo retorno flujo sacar odio oxígeno rabo', // Missing 2 accents.
'yerno obvio ninez pierna bebe pomelo retorno flujo sacar odio oxigeno rabo', // Missing all 3 accents.
'yérno obvio ninez pierña bebe pomelo retorno flujo sacar odio oxigéno rabo', // Incorrect accents.
]
const expectedMnemonic = spanishMnemonics[0]
for (const mnemonic of spanishMnemonics) {
expect(normalizeMnemonic(mnemonic)).toEqual(expectedMnemonic)
}
})
it('should not normalize accents when the word is from a different language', () => {
// Cases include French mnemonic, missing one accent, and a single Spanish word mixed in, without proper accent.
const cases = [
{
mnemonic:
'declarer effrayer estime carbone bebe danger déphaser junior buisson ériger morceau cintrer',
language: undefined,
expected:
'déclarer effrayer estime carbone bebe danger déphaser junior buisson ériger morceau cintrer',
},
{
mnemonic:
'declarer effrayer estime carbone bebe danger déphaser junior buisson ériger morceau cintrer',
language: MnemonicLanguages.french,
expected:
'déclarer effrayer estime carbone bebe danger déphaser junior buisson ériger morceau cintrer',
},
// Expect that it will not try to normalize accents for words not in the given language.
{
mnemonic:
'declarer effrayer estime carbone bebe danger déphaser junior buisson ériger morceau cintrer',
language: MnemonicLanguages.spanish,
expected:
'declarer effrayer estime carbone bebé danger déphaser junior buisson ériger morceau cintrer',
},
]
for (const { mnemonic, language, expected } of cases) {
expect(normalizeMnemonic(mnemonic, language)).toEqual(expected)
}
})
it('should normalize capitalized words to lowercase', () => {
const mnemonic =
'female cousin RAPID exotic ribbon level equiP LeGal fuN RIVER hotel duTy TRIP youth rebel'
const expected =
'female cousin rapid exotic ribbon level equip legal fun river hotel duty trip youth rebel'
expect(normalizeMnemonic(mnemonic)).toEqual(expected)
})
it('should normalize extra and non-standard whitespace', () => {
const mnemonic =
' \tfemale cousin rapid exotic\nribbon level\u3000equip legal fun river hotel duty trip youth rebel'
const expected =
'female cousin rapid exotic ribbon level equip legal fun river hotel duty trip youth rebel'
expect(normalizeMnemonic(mnemonic)).toEqual(expected)
})
it('should normalize extra and non-standard whitespace', () => {
const mnemonic =
' \tfemale cousin rapid exotic\nribbon level\u3000equip legal fun river hotel duty trip youth rebel'
const expected =
'female cousin rapid exotic ribbon level equip legal fun river hotel duty trip youth rebel'
expect(normalizeMnemonic(mnemonic)).toEqual(expected)
})
it('should normalize whitespace of Japanese mnemonics using ideographic spaces', () => {
const mnemonic =
' せけん まなぶ せんえい ねっしん はくしゅ うなずく いがく ひこく\nにちようび いがく なふだ ばかり どんぶり\tせきらんうん きかく '
const expected =
'せけん まなぶ せんえい ねっしん はくしゅ うなずく いがく ひこく にちようび いがく なふだ ばかり どんぶり せきらんうん きかく'
expect(normalizeMnemonic(mnemonic)).toEqual(expected)
})
for (const language of getAllLanguages()) {
it(`should pass through newly generated mnemonics in ${MnemonicLanguages[language]}`, async () => {
const mnemonic = await generateMnemonic(MnemonicStrength.s256_24words, language)
expect(normalizeMnemonic(mnemonic)).toEqual(mnemonic)
})
}
})
describe('.invalidMnemonicWords()', () => {
it('should return list of invalid words in a phrase with errors', () => {
const mnemonic =
'salute roayl possible rare dufbuty wabnt ynfikd oik cabbage labor approbe winner claw conduct spider velvet buyer level second adult payment blish inject draw'
const invalidWords = ['roayl', 'dufbuty', 'wabnt', 'ynfikd', 'oik', 'approbe', 'blish']
expect(invalidMnemonicWords(mnemonic)).toEqual(invalidWords)
})
it('should return an empty list when given a correct phrase', () => {
const mnemonic =
'salute royal possible rare dignity want unfold oil cabbage labor approve winner claw conduct spider velvet buyer level second adult payment blush inject draw'
expect(invalidMnemonicWords(mnemonic)).toEqual([])
})
it('should return undefined when the language is undetermined', () => {
// A specially crafted phrase with equal numbers of english and spanish words, one of each being invalid.
const mnemonic =
'oil sponsor unlock diet aprove trim usual ethics tip prepare twist hunt neto sanidad tregua cuneta cazar tirón trueno enredo tauro pan torpedo húmedo'
expect(invalidMnemonicWords(mnemonic)).not.toBeDefined()
})
})
describe('.suggestMnemonicCorrections()', () => {
it('should correct a single simple typo on the first suggestion', () => {
const cases = [
{
mnemonic: 'crush hollow differ mean easy ostrihc almost cherry route hurt inner bless',
corrected: 'crush hollow differ mean easy ostrich almost cherry route hurt inner bless',
},
{
mnemonic: 'monster note endless discover tilt glide girl wing spstial imitate mad ridge',
corrected: 'monster note endless discover tilt glide girl wing spatial imitate mad ridge',
},
{
mnemonic: 'mimo musgo efecto danza tariot gente gavilán visor sala imán madre potencia',
corrected: 'mimo musgo efecto danza tarot gente gavilán visor sala imán madre potencia',
},
{
mnemonic:
'linéaire marron dosage déborder spiral farine faibvlir virtuose risible géomètre ivresse pinceau',
corrected:
'linéaire marron dosage déborder spiral farine faiblir virtuose risible géomètre ivresse pinceau',
},
{
mnemonic:
'leme malandro depurar coperoi sovado extrato explanar vilarejo resolver garrafa inverno pergunta',
corrected:
'leme malandro depurar copeiro sovado extrato explanar vilarejo resolver garrafa inverno pergunta',
},
]
for (const { mnemonic, corrected } of cases) {
expect(suggestMnemonicCorrections(mnemonic).next().value).toEqual(corrected)
}
})
it('should quickly offer the corect suggestion for a phrase with a few typos', () => {
// First 5 phrases were quickly copied on a keyboard to produce typos.
const cases = [
{
mnemonic:
'whear poitdoor cup shoulder diret broccoli fragile donate legend slogan crew between secrety recall asset',
corrected:
'wheat outdoor cup shoulder dirt broccoli fragile donate legend slogan crew between secret recall asset',
},
{
mnemonic:
'inner lottery artist cintage climb corn theroty cronze tot segement squirrel south ordinatu assume congress',
corrected:
'inner lottery artist vintage climb corn theory bronze toy segment squirrel south ordinary assume congress',
},
{
mnemonic:
'note evidence bubble dog style master region prosper input amazing moviuew adain awrite drisagree glasre',
corrected:
'note evidence bubble dog style master region prosper input amazing movie again write disagree glare',
},
{
// Note: "rent" (typo) and "tent" are both in the BIP-39 English word list.
mnemonic:
'cruise arom apology bracket demimnar another vorrow csninn finish walnut rural rent pledge fasgion alarm',
corrected:
'cruise atom apology bracket seminar another borrow cabin finish walnut rural tent pledge fashion alarm',
},
{
mnemonic:
'wisgh animal bracket stand enroll purchase wave quantuim film polar rare fury time great time',
corrected:
'wish animal bracket stand enroll purchase wave quantum film polar rare fury time great time',
},
{
mnemonic:
'debat connect bid lend opkay decreaser library balcony claw become squeeze usage reseccue jazzz segment dinosaur cushion sing markvle iundo depth bag object trash',
corrected:
'debate connect bid lend okay decrease library balcony claw become squeeze usage rescue jazz segment dinosaur cushion sing marble undo depth bag object trash',
},
{
mnemonic:
'salute roayl possible rare dufbuty wabnt ynfikd oik cabbage labor approbe winner claw conduct spider velvet buyer level second adult payment blish inject draw',
corrected:
'salute royal possible rare dignity want unfold oil cabbage labor approve winner claw conduct spider velvet buyer level second adult payment blush inject draw',
},
{
mnemonic:
'frame mmarkety oak dissmiss bried theme avocade wgaon rabbit latin angry kind pitch wild trune chornic lamp cault into prioisty gues review parent add',
corrected:
'frame market oak dismiss brief theme avocado wagon rabbit latin angry kind pitch wild tube chronic lamp vault into priority guess review parent add',
},
]
for (const { mnemonic, corrected } of cases) {
let attempts = 0
for (const suggestion of suggestMnemonicCorrections(mnemonic)) {
attempts++
if (suggestion === corrected) {
// Enable the following log statement to see how many attempts each phrase takes.
// console.log(`Phrase '${mnemonic}' corrected in ${attempts} attempt(s)`)
break
}
if (attempts >= 25) {
throw new Error(`Phrase '${mnemonic}' was not corrected within 100 attempts`)
}
}
}
})
it('should never return an invalid mnemonic', () => {
const mnemonic =
'frame mmarkety oak dissmiss bried theme avocade wgaon rabbit latin angry kind pitch wild trune'
let trials = 0
for (const suggestion of suggestMnemonicCorrections(mnemonic)) {
trials++
expect(validateMnemonic(suggestion)).toBe(true)
if (trials >= 100) {
break
}
}
})
it('should never return the same suggestion twice', () => {
const mnemonic =
'frame mmarkety oak dissmiss bried theme avocade wgaon rabbit latin angry kind pitch wild trune'
const seen = new Set<string>()
for (const suggestion of suggestMnemonicCorrections(mnemonic)) {
expect(seen.has(suggestion)).toBe(false)
seen.add(suggestion)
if (seen.size >= 100) {
break
}
}
})
})
}) | the_stack |
import { host, optionsController, telemetry, themeController } from '../main';
import { i18n } from '../model/i18n';
import { Tabulator } from 'tabulator-tables';
import { Dic, Utils, _, __ } from '../helpers/utils';
import { Doc, DocType, MeasureStatus } from '../model/doc';
import { strings } from '../model/strings';
import { Alert } from './alert';
import { FormattedMeasure, TabularMeasure, daxName } from '../model/tabular';
import { ContextMenu } from '../helpers/contextmenu';
import { Loader } from '../helpers/loader';
import * as sanitizeHtml from 'sanitize-html';
import { DocScene } from './scene-doc';
import { LoaderScene } from './scene-loader';
import { ErrorScene } from './scene-error';
import { FormatDaxRequest, FormatDaxRequestOptions, UpdatePBICloudDatasetRequest, UpdatePBIDesktopReportRequest } from '../controllers/host';
import { SuccessScene } from './scene-success';
import { AppError, AppProblem } from '../model/exceptions';
import { ClientOptionsFormattingRegion, DaxFormatterLineStyle, DaxFormatterSpacingStyle } from '../controllers/options';
import { PageType } from '../controllers/page';
import { MultiViewPane, MultiViewPaneMode, ViewPane } from './multiview-pane';
import { DaxEditor } from './dax-editor';
import { Confirm } from './confirm';
import { DialogResponse } from './dialog';
export class DaxFormatterScene extends DocScene {
table: Tabulator;
previewContainer: HTMLElement;
previewOverlay: HTMLElement;
previewPane: MultiViewPane;
formattedEditor: DaxEditor;
currentEditor: DaxEditor;
searchBox: HTMLInputElement;
formatButton: HTMLElement;
activeMeasure: TabularMeasure;
previewing: Dic<boolean> = {};
showMeasuresWithErrorsOnly = false;
get formattableMeasures(): TabularMeasure[] {
if (!optionsController.options.customOptions.formatting.daxFormatter.includeTimeIntelligence) {
return this.doc.measures.filter(measure => !measure.isManageDatesTimeIntelligence);
}
return this.doc.measures;
}
get canFormat(): boolean {
return this.canEdit;
}
constructor(id: string, container: HTMLElement, doc: Doc, type: PageType) {
super(id, container, [doc.name, i18n(strings.DaxFormatter)], doc, type, true);
this.element.classList.add("dax-formatter");
}
updateEditor(editor: DaxEditor, measure?: TabularMeasure | FormattedMeasure) {
editor.removeErrors();
if (measure && measure.expression) {
editor.value = measure.expression;
const errors = (<FormattedMeasure>measure).errors;
if (errors)
editor.highlightErrors(errors);
} else {
editor.value = "";
}
}
render() {
if (!super.render()) return false;
let html = `
<div class="summary">
<p></p>
</div>
<div class="cols">
<div class="col coll browser">
<div class="toolbar">
<div class="search">
<input type="search" placeholder="${i18n(strings.searchMeasurePlaceholder)}" class="disable-if-empty">
</div>
<div class="filter-measures-with-errors toggle icon-filter-errors disable-if-empty" title="${i18n(strings.filterMeasuresWithErrorsCtrlTitle)}" disabled></div>
</div>
<div class="table"></div>
</div>
<div class="col colr">
<div class="preview" hidden></div>
</div>
</div>
<div class="scene-action">
<div class="privacy-explanation">
<div class="icon icon-privacy"></div>
<p>${i18n(strings.daxFormatterAgreement)}
<span class="show-data-usage link">${i18n(strings.dataUsageLink)}</span>
</p>
</div>
<div class="do-format button disable-on-syncing enable-if-editable" disabled>${i18n(!this.canFormat && this.doc.type == DocType.vpax ? strings.daxFormatterFormatDisabled : strings.daxFormatterFormat)}</div>
</div>
`;
this.body.insertAdjacentHTML("beforeend", html);
this.previewContainer = _(".preview", this.body);
this.previewPane = new MultiViewPane(Utils.DOM.uniqueId(), _(".preview", this.body), <Dic<ViewPane>>{
"current": {
name: i18n(strings.daxFormatterOriginalCode),
onRender: element => {
this.currentEditor = new DaxEditor(Utils.DOM.uniqueId(), element, optionsController.options.customOptions.editor.zoom, optionsController.options.customOptions.editor.wrapping, optionsController.options.customOptions.editor.whitespaces);
},
onChange: element => {
if (this.currentEditor)
this.updateEditor(this.currentEditor, this.activeMeasure);
}
},
"formatted": {
name: i18n(strings.daxFormatterFormattedCode),
onRender: element => {
this.formattedEditor = new DaxEditor(Utils.DOM.uniqueId(), element, optionsController.options.customOptions.editor.zoom, optionsController.options.customOptions.editor.wrapping, optionsController.options.customOptions.editor.whitespaces, [
{
className: ["refresh", "disable-on-syncing"],
icon: "refresh",
title: i18n(strings.refreshPreviewCtrlTitle),
onClick: (e) => {
this.generateFormattedPreview(this.formattableMeasures);
}
},
{
className: ["open-with-dax-formatter", "disable-on-syncing"],
icon: "send-to-dax-formatter",
title: i18n(strings.openWithDaxFormatterCtrlTitle),
onClick: (e) => {
this.formatWithDaxFormatter();
}
}
]);
},
onChange: element => {
if (this.formattedEditor) {
if (this.activeMeasure) {
const key = daxName(this.activeMeasure.tableName, this.activeMeasure.name);
if (key in this.doc.formattedMeasures) {
this.togglePreviewOverlay(false);
this.updateEditor(this.formattedEditor, this.doc.formattedMeasures[key]);
} else if (key in this.previewing) {
this.updateEditor(this.formattedEditor);
this.renderPreviewLoading();
} else {
this.updateEditor(this.formattedEditor);
this.renderPreviewOverlay();
}
}
}
}
}
}, optionsController.options.customOptions.formatting.previewLayout, optionsController.options.customOptions.sizes.formatDax);
this.previewOverlay = document.createElement("div");
this.previewOverlay.classList.add("preview-overlay");
_("#body-formatted", this.body).append(this.previewOverlay);
this.searchBox = <HTMLInputElement>_(".search input", this.body);
this.formatButton = _(".do-format", this.body);
this.update();
this.listen();
}
renderPreviewOverlay() {
let html = `
<div class="gen-preview-action">
${i18n(strings.daxFormatterPreviewDesc)}
<span class="show-data-usage link hide-if-editable">${i18n(strings.dataUsageLink)}</span>
<div class="gen-preview-ctrl">
<span class="gen-preview button button-alt">${i18n(strings.daxFormatterPreviewButton)}</span>
<span class="gen-preview-all button button-alt">${i18n(strings.daxFormatterPreviewAllButton)}</span>
</div>
<label class="switch"><input type="checkbox" id="gen-preview-auto-option" ${optionsController.options.customOptions.formatting.preview ? "checked" : ""}><span class="slider"></span></label> <label for="gen-preview-auto-option">${i18n(strings.daxFormatterAutoPreviewOption)}</label>
</div>
`;
this.previewOverlay.innerHTML = html;
this.togglePreviewOverlay(true);
}
renderPreviewError(error: AppError, retry?: () => void) {
this.previewing = {};
const retryId = Utils.DOM.uniqueId();
this.previewOverlay.innerHTML = `
<div class="notice">
<div>
<p>${error.toString()}</p>
<p><span class="copy-error link">${i18n(strings.copyErrorDetails)}</span></p>
${ retry ? `
<div id="${retryId}" class="button button-alt">${i18n(strings.errorRetry)}</div>
` : ""}
</div>
</div>
`;
this.togglePreviewOverlay(true);
_(".copy-error", this.element).addEventListener("click", e =>{
e.preventDefault();
navigator.clipboard.writeText(error.toString(true, true, true));
let ctrl = <HTMLElement>e.currentTarget;
ctrl.innerText = i18n(strings.copiedErrorDetails);
window.setTimeout(() => {
ctrl.innerText = i18n(strings.copyErrorDetails);
}, 1500);
});
if (retry) {
_(`#${retryId}`, this.element).addEventListener("click", e => {
e.preventDefault();
retry();
});
}
}
togglePreviewOverlay(toggle: boolean) {
if (this.previewOverlay) {
this.previewOverlay.toggle(toggle)
}
}
renderPreviewLoading() {
new Loader(this.previewOverlay, false);
this.togglePreviewOverlay(true);
}
maybeAutoGenerateFormattedPreview() {
if (optionsController.options.customOptions.formatting.preview) {
this.generateFormattedPreview(this.formattableMeasures);
}
}
generateFormattedPreview(measures: TabularMeasure[]) {
if (!measures.length || !measures[0]) return;
this.renderPreviewLoading();
measures.forEach(measure => {
this.previewing[daxName(measure.tableName, measure.name)] = true;
});
this.updateMeasuresStatus();
host.formatDax(this.getFormatDaxRequest(measures))
.then(formattedMeasures => {
formattedMeasures.forEach(measure => {
let measureKey = daxName(measure.tableName, measure.name);
this.doc.formattedMeasures[measureKey] = measure;
delete this.previewing[measureKey];
if (this.activeMeasure && measureKey == daxName(this.activeMeasure.tableName, this.activeMeasure.name)) {
this.togglePreviewOverlay(false);
this.updateEditor(this.formattedEditor, measure);
}
});
this.togglePreviewOverlay(false);
})
.catch((error: AppError) => {
this.renderPreviewError(error, ()=>{
this.generateFormattedPreview(measures);
});
})
.finally(() => {
this.updateMeasuresStatus();
this.updateSummary();
});
}
togglePreview(toggle: boolean) {
this.previewContainer.toggle(toggle);
if (toggle)
this.previewPane.updateLayout();
}
deselectMeasures() {
if (this.table) {
this.table.deselectRow();
__(".row-active", this.table.element).forEach((el: HTMLElement) => {
el.classList.remove("row-active");
});
}
this.activeMeasure = null;
this.togglePreview(false);
this.formatButton.toggleAttr("disabled", true);
}
updateMeasuresStatus() {
let canFilter = false;
if (this.table) {
// If the table is not initialized yet it could raise an error
try {
this.table.redraw(true);
} catch(ignore) {};
let rows = this.table.getRows("active");
rows.forEach(row => {
if ("reformat" in row) { // This is a bug has been reported here: https://github.com/olifolkerd/tabulator/issues/3580
row.reformat();
}
});
if (!Utils.Obj.isEmpty(this.doc.formattedMeasures))
canFilter = true;
}
_(".filter-measures-with-errors", this.element).toggleAttr("disabled", !canFilter);
_(".filter-unformatted-measures", this.element).toggleAttr("disabled", !canFilter);
}
updateTable(redraw = true) {
if (redraw) {
if (this.table) {
this.table.destroy();
this.table = null;
}
}
this.deselectMeasures();
let data = this.formattableMeasures;
if (!this.table) {
let columns: Tabulator.ColumnDefinition[] = [];
if (this.canFormat) {
columns.push({
formatter:"rowSelection",
titleFormatter:"rowSelection",
titleFormatterParams:{
rowRange:"active"
},
hozAlign: "center",
headerHozAlign: "center",
cssClass: "column-select",
headerSort: false,
resizable: false,
width: 40,
cellClick: (e, cell) => {
cell.getRow().toggleSelect();
}
});
}
columns.push({
//field: "Icon",
title: "",
hozAlign:"center",
resizable: false,
width: 40,
cssClass: "column-icon",
formatter: (cell) => {
const measure = <TabularMeasure>cell.getData();
if (daxName(measure.tableName, measure.name) in this.previewing)
return `<div class="loader"></div>`;
const status = this.doc.analizeMeasure(measure);
if (status == MeasureStatus.NotFormatted) {
return `<div class="icon icon-unformatted" title="${i18n(strings.columnMeasureNotFormattedTooltip)}"></div>`;
} else if (status == MeasureStatus.WithErrors) {
return `<div class="icon icon-alert" title="${i18n(strings.columnMeasureWithError)}"></div>`;
} else if (status == MeasureStatus.Formatted) {
return `<div class="icon icon-completed" title="${i18n(strings.columnMeasureFormatted)}"></div>`;
} else {
if (optionsController.options.customOptions.formatting.preview) {
return `<div class="loader"></div>`;
} else {
return "";
}
}
},
sorter: (a, b, aRow, bRow, column, dir, sorterParams) => {
const measureA = <TabularMeasure>aRow.getData();
const measureAStatus = this.doc.analizeMeasure(measureA);
const measureB = <TabularMeasure>bRow.getData();
const measureBStatus = this.doc.analizeMeasure(measureB);
a = `${measureAStatus}_${measureA.name}`;
b = `${measureBStatus}_${measureB.name}`;
return String(a).toLowerCase().localeCompare(String(b).toLowerCase());
}
});
columns.push({
field: "name",
title: i18n(strings.tableColMeasure),
tooltip: true,
cssClass: "column-name",
bottomCalc: this.canFormat ? "count" : null,
bottomCalcFormatter: (cell)=> i18n(strings.tableSelectedCount, {count: this.table.getSelectedData().length}),
resizable: false
});
/*columns.push({
field: "tableName",
width: 100,
title: i18n(strings.tableColTable)
});*/
const tableConfig: Tabulator.Options = {
maxHeight: "100%",
layout: "fitColumns",
placeholder: " ", // This fixes scrollbar appearing with empty tables
initialFilter: data => this.measuresFilter(data),
initialSort:[
{column: "name", dir: "asc"},
],
rowFormatter: row => {
try { //Bypass calc rows
if ((<any>row)._row && (<any>row)._row.type == "calc") return;
const measure = <TabularMeasure>row.getData();
if (daxName(measure.tableName, measure.name) in this.previewing)
return;
let element = row.getElement();
element.classList.remove("row-error", "row-highlighted");
if (measure.isHidden)
element.classList.add("row-hidden");
const status = this.doc.analizeMeasure(measure);
if (status == MeasureStatus.WithErrors) {
element.classList.add("row-error");
} else if (status == MeasureStatus.NotFormatted) {
element.classList.add("row-highlighted");
}
}catch(ignore){}
},
columns: columns,
data: data
};
this.table = new Tabulator(`#${this.element.id} .table`, tableConfig);
this.table.on("rowSelectionChanged", (data: any[], rows: Tabulator.RowComponent[]) =>{
this.table.recalc();
this.formatButton.toggleAttr("disabled", !rows.length || !this.canFormat);
});
this.table.on("rowClick", (e, row) => {
this.activeMeasure = row.getData();
__(".row-active", this.table.element).forEach((el: HTMLElement) => {
el.classList.remove("row-active");
});
row.getElement().classList.add("row-active");
this.togglePreview(true);
});
} else {
this.table.setData(data);
//Force disabling button from parent
this.formatButton.dataset.disabledBeforeSyncing = "true";
this.formatButton.toggleAttr("disabled", true);
}
}
update() {
if (!super.update()) return false;
this.updateTable(false);
this.maybeAutoGenerateFormattedPreview();
this.updateSummary();
}
updateSummary() {
let summary = {
count: this.formattableMeasures.length,
analyzable: 0,
errors: 0,
formattable: 0
};
this.formattableMeasures.forEach(measure => {
const status = this.doc.analizeMeasure(measure);
if (status == MeasureStatus.NotAnalyzed) {
summary.analyzable += 1;
} else if (status == MeasureStatus.NotFormatted) {
summary.formattable += 1;
} else if (status == MeasureStatus.WithErrors) {
summary.errors += 1;
}
});
_(".summary p", this.element).innerHTML = i18n(summary.analyzable ? strings.daxFormatterSummary : strings.daxFormatterSummaryNoAnalysis, summary);
}
getFormatDaxRequest(measures: TabularMeasure[]): FormatDaxRequest {
// Set separators according to the region
const separators: {[key: string]: string[]} = {
[ClientOptionsFormattingRegion.US]: [',', '.'],
[ClientOptionsFormattingRegion.EU]: [';', ',']
};
let region = <string>optionsController.options.customOptions.formatting.region;
if (!(region in separators)) {
let lastC = -1;
let lastR;
for (let r in separators) {
let c = (measures[0].expression.match(new RegExp(separators[r][0], 'gmi')) || []).length;
if (c > lastC) {
lastR = r;
lastC = c;
}
}
region = lastR;
}
let formatOptions = <FormatDaxRequestOptions>Utils.Obj.clone(optionsController.options.customOptions.formatting.daxFormatter);
formatOptions.listSeparator = separators[region][0];
formatOptions.decimalSeparator = separators[region][1];
formatOptions.autoLineBreakStyle = this.doc.model.autoLineBreakStyle;
formatOptions.databaseName = this.doc.model.name;
//formatOptions.compatibilityMode = this.doc.model.compatibilityMode;
formatOptions.compatibilityLevel = this.doc.model.compatibilityLevel;
formatOptions.serverName = this.doc.model.serverName;
formatOptions.serverVersion = this.doc.model.serverVersion;
formatOptions.serverEdition = this.doc.model.serverEdition;
formatOptions.serverMode = this.doc.model.serverMode;
formatOptions.serverLocation = this.doc.model.serverLocation;
return {
options: formatOptions,
measures: measures
};
}
format() {
if (!this.canFormat) return;
let measures: TabularMeasure[] = this.table.getSelectedData();
if (!measures.length) return;
telemetry.track("Format", { "Count": measures.length });
this.formatButton.toggleAttr("disabled", true);
let formattingScene = new LoaderScene(Utils.DOM.uniqueId(), this.element.parentElement, i18n(strings.formattingMeasures), ()=>{
host.abortFormatDax(this.doc.type);
});
this.push(formattingScene);
let errorResponse = (error: AppError) => {
if (error.requestAborted) return;
let errorScene = new ErrorScene(Utils.DOM.uniqueId(), this.element.parentElement, error, () => {
this.updateMeasuresStatus();
this.updateSummary();
});
this.splice(errorScene);
};
host.formatDax(this.getFormatDaxRequest(measures))
.then(formattedMeasures => {
// Update model's formatted measures
let measuresWithErrors: string[] = [];
formattedMeasures.forEach(measure => {
const measureName = daxName(measure.tableName, measure.name);
this.doc.formattedMeasures[measureName] = measure;
if (measure.errors && measure.errors.length) {
measuresWithErrors.push(measureName);
}
});
if (measuresWithErrors.length) {
throw AppError.InitFromProblemCode(AppProblem.TOMDatabaseUpdateErrorMeasure, i18n(strings.errorTryingToUpdateMeasuresWithErrors, {measures: measuresWithErrors.join(", ")}));
}
let updateRequest;
if (this.doc.type == DocType.dataset) {
updateRequest = <UpdatePBICloudDatasetRequest>{
dataset: this.doc.sourceData,
measures: formattedMeasures
};
} else if (this.doc.type == DocType.pbix) {
updateRequest = <UpdatePBIDesktopReportRequest>{
report: this.doc.sourceData,
measures: formattedMeasures
};
} else {
throw AppError.InitFromResponseStatus(Utils.ResponseStatusCode.InternalError);
}
host.updateModel(updateRequest, this.doc.type)
.then(response => {
// Update model's measures (formula and etag)
// Strip errors from formatted measures
if (response.etag) {
// Update measures with formatted version
formattedMeasures.forEach(formattedMeasure => {
const measureName = daxName(formattedMeasure.tableName, formattedMeasure.name);
for (let i = 0; i < this.doc.measures.length; i++) {
let docMeasureName = daxName(this.doc.measures[i].tableName, this.doc.measures[i].name)
if (measureName == docMeasureName) {
this.doc.measures[i].expression = formattedMeasure.expression;
break;
}
}
});
// Update all measures etags
for (let i = 0; i < this.doc.measures.length; i++) {
this.doc.measures[i].etag = response.etag;
}
}
this.updateTable(true);
let successScene = new SuccessScene(Utils.DOM.uniqueId(), this.element.parentElement, i18n(strings.daxFormatterSuccessSceneMessage, {count: formattedMeasures.length}), ()=>{
this.pop();
this.updateSummary();
});
this.splice(successScene);
})
.catch(error => errorResponse(error));
})
.catch(error => errorResponse(error))
.finally(() => {
this.deselectMeasures();
});
}
listen() {
["keyup", "search", "paste"].forEach(listener => {
this.searchBox.addEventListener(listener, e => {
this.applyFilters();
});
});
this.searchBox.addEventListener('contextmenu', e => {
e.preventDefault();
let el = <HTMLInputElement>e.currentTarget;
if (el.hasAttribute("disabled")) return;
let selection = el.value.substring(el.selectionStart, el.selectionEnd);
ContextMenu.editorContextMenu(e, selection, el.value, el);
});
_(".filter-measures-with-errors", this.body).addEventListener("click", e => {
e.preventDefault();
let el = <HTMLElement>e.currentTarget;
if (el.hasAttribute("disabled")) return;
if (!el.classList.contains("active"))
telemetry.track("Format DAX: Filter Errors");
el.toggleClass("active");
this.showMeasuresWithErrorsOnly = el.classList.contains("active");
this.deselectMeasures();
this.applyFilters();
});
this.formatButton.addEventListener("click", e => {
e.preventDefault();
if (!this.canFormat) return;
let el = <HTMLElement>e.currentTarget;
if (el.hasAttribute("disabled")) return;
this.format();
});
this.element.addLiveEventListener("click", ".show-data-usage", (e, element) => {
e.preventDefault();
this.showDataUsageDialog();
});
this.element.addLiveEventListener("click", ".manual-analyze", (e, element) => {
e.preventDefault();
if (element.hasAttribute("disabled")) return;
let alert = new Confirm();
alert.show(i18n(strings.daxFormatterAnalyzeConfirm))
.then((response: DialogResponse) => {
if (response.action == "ok") {
element.toggleAttr("disabled", true);
element.innerHTML = Loader.html(false);
this.generateFormattedPreview(this.formattableMeasures);
telemetry.track("Format DAX: Analyze");
}
});
});
this.previewPane.on("size.change", (sizes: number[]) =>{
optionsController.update("customOptions.sizes.formatDax", sizes);
this.currentEditor.editor.refresh();
this.formattedEditor.editor.refresh();
});
this.previewPane.on("mode.change", (mode: MultiViewPaneMode) =>{
optionsController.update("customOptions.formatting.previewLayout", mode);
});
this.currentEditor.on("zoom.change", (zoom: number) => {
this.formattedEditor.updateZoom(zoom, false);
optionsController.update("customOptions.editor.zoom", zoom);
});
this.currentEditor.on("wrapping.change", (wrapping: boolean) => {
this.formattedEditor.updateWrapping(wrapping, false);
optionsController.update("customOptions.editor.wrapping", wrapping);
});
this.currentEditor.on("whitespaces.change", (whitespaces: boolean) => {
this.formattedEditor.toggleHiddenCharacters(whitespaces, false);
optionsController.update("customOptions.editor.whitespaces", whitespaces);
});
this.formattedEditor.on("zoom.change", (zoom: number) => {
this.currentEditor.updateZoom(zoom, false);
optionsController.update("customOptions.editor.zoom", zoom);
});
this.formattedEditor.on("wrapping.change", (wrapping: boolean) => {
this.currentEditor.updateWrapping(wrapping, false)
optionsController.update("customOptions.editor.wrapping", wrapping);
});
this.formattedEditor.on("whitespaces.change", (whitespaces: boolean) => {
this.currentEditor.toggleHiddenCharacters(whitespaces, false);
optionsController.update("customOptions.editor.whitespaces", whitespaces);
});
this.element.addLiveEventListener("click", ".gen-preview", (e, element) => {
e.preventDefault();
this.generateFormattedPreview([this.activeMeasure]);
telemetry.track("Format DAX: Preview");
});
this.element.addLiveEventListener("click", ".gen-preview-all", (e, element) => {
e.preventDefault();
this.generateFormattedPreview(this.formattableMeasures);
telemetry.track("Format DAX: Preview All");
});
this.element.addLiveEventListener("change", "#gen-preview-auto-option", (e, element) => {
e.preventDefault();
optionsController.update("customOptions.formatting.preview", (<HTMLInputElement>element).checked);
window.setTimeout(() => {
this.generateFormattedPreview(this.formattableMeasures);
}, 300);
});
optionsController.on("customOptions.formatting.preview.change", (changedOptions: any) => {
this.maybeAutoGenerateFormattedPreview();
});
optionsController.on("customOptions.formatting.region.change", (changedOptions: any) => {
this.maybeAutoGenerateFormattedPreview();
});
optionsController.on("customOptions.formatting.daxFormatter.spacingStyle.change", (changedOptions: any) => {
this.maybeAutoGenerateFormattedPreview();
});
optionsController.on("customOptions.formatting.daxFormatter.lineStyle.change", (changedOptions: any) => {
this.maybeAutoGenerateFormattedPreview();
});
optionsController.on("customOptions.formatting.daxFormatter.lineBreakStyle.change", (changedOptions: any) => {
this.maybeAutoGenerateFormattedPreview();
});
optionsController.on("customOptions.formatting.daxFormatter.includeTimeIntelligence.change", (changedOptions: any) => {
this.updateTable(false);
this.updateSummary();
this.maybeAutoGenerateFormattedPreview();
});
}
showDataUsageDialog() {
let dialog = new Alert("data-usage", i18n(strings.dataUsageTitle));
let html = `
<img src="images/dax-formatter${themeController.isDark ? "-dark" : ""}.svg">
${i18n(strings.dataUsageMessage)}
<p><span class="link" href="https://www.daxformatter.com">www.daxformatter.com</span></p>
`;
dialog.show(html);
telemetry.track("Data Usage Dialog");
}
applyFilters() {
if (this.table) {
this.table.clearFilter();
this.table.addFilter(data => this.measuresFilter(data));
if (this.searchBox.value)
this.table.addFilter("name", "like", sanitizeHtml(this.searchBox.value, { allowedTags: [], allowedAttributes: {}}));
}
}
measuresFilter(measure: TabularMeasure): boolean {
// Error filter
if (this.showMeasuresWithErrorsOnly) {
const status = this.doc.analizeMeasure(measure);
if (status == MeasureStatus.Formatted)
return false;
}
return true;
}
formatWithDaxFormatter() {
if (!this.activeMeasure) return;
const fx = `${this.activeMeasure.name} = ${this.activeMeasure.expression}`;
const formatRegion = optionsController.options.customOptions.formatting.region;
const formatLine = (optionsController.options.customOptions.formatting.daxFormatter.lineStyle == DaxFormatterLineStyle.LongLine ? "long" : "short");
const formatSpacing = (optionsController.options.customOptions.formatting.daxFormatter.spacingStyle == DaxFormatterSpacingStyle.SpaceAfterFunction ? "" : "true");
let queryString = `fx=${encodeURIComponent(fx)}&r=${formatRegion}&s=${formatSpacing}&l=${formatLine}${themeController.isDark ? "&dark=1" : ""}&cache=${new Date().getTime()}`;
host.navigateTo(`https://www.daxformatter.com/?${queryString}`);
telemetry.track("Format with DAX Formatter");
}
} | the_stack |
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Actions, Effect, toPayload } from '@ngrx/effects';
import { Store, Action } from '@ngrx/store';
import { AppStore } from '../../../app.store';
import { roomAction } from '../actions';
import { appAction } from '../../../actions';
import { global, StorageService, authPayload, ApiService } from '../../../services/common';
@Injectable()
export class RoomEffect {
// 获取storage里的voice状态
@Effect()
private getVoiceState$: Observable<Action> = this.actions$
.ofType(roomAction.getRoomVoiceState)
.map(toPayload)
.switchMap(async (key) => {
const voiceState = this.storageService.get(key);
if (voiceState) {
this.store$.dispatch({
type: roomAction.getRoomVoiceStateSuccess,
payload: JSON.parse(voiceState)
});
}
return { type: '[room] get room voice state useless' };
});
// 更新storage里的voice状态
@Effect()
private storageVoiceState$: Observable<Action> = this.actions$
.ofType(roomAction.storageVoiceState)
.map(toPayload)
.switchMap(async (info) => {
if (info.voiceStateKey && info.voiceState) {
this.storageService.set(info.voiceStateKey, JSON.stringify(info.voiceState));
this.store$.dispatch({
type: roomAction.getRoomVoiceStateSuccess,
payload: info.voiceState
});
}
return { type: '[room] storage room voice state useless' };
});
// 获取自己已经进入的聊天室列表,并一一退出
@Effect()
private getSelfChatrooms$: Observable<Action> = this.actions$
.ofType(roomAction.getSelfChatrooms)
.map(toPayload)
.switchMap(async (payload) => {
const data: any = await this.apiService.getSelfChatrooms();
if (data.code) {
this.errorFn(data);
} else {
let promises = [];
for (let room of data.chat_rooms) {
const roomObj = {
id: room.id
};
const pro = this.apiService.exitChatroom(roomObj);
promises.push(pro);
}
await Promise.all(promises);
this.store$.dispatch({
type: roomAction.exitAllChatroomsSuccess,
payload: null
});
}
return { type: '[room] get self chatrooms useless' };
});
// 请求聊天室列表
@Effect()
private getRoomList$: Observable<Action> = this.actions$
.ofType(roomAction.getRoomList)
.map(toPayload)
.switchMap(async (payload) => {
const roomsObj = {
start: payload.start,
appkey: payload.appkey
};
const data: any = await this.apiService.getAppkeyChatrooms(roomsObj);
if (data.code) {
this.errorFn(data);
} else {
this.store$.dispatch({
type: roomAction.getRoomListSuccess,
payload: data.result.rooms
});
}
return { type: '[room] get room list useless' };
});
// 切换active聊天室,退出聊天室,请求聊天室详情
@Effect()
private changeRoom$: Observable<Action> = this.actions$
.ofType(roomAction.changeRoom)
.map(toPayload)
.switchMap(async (payload) => {
this.store$.dispatch({
type: roomAction.changeRoomSuccess,
payload: {
active: payload,
info: {}
}
});
this.exitRoom(payload);
const roomObj = {
id: payload.id
};
const data: any = await this.apiService.getChatroomInfo(roomObj);
if (data.code) {
this.errorFn(data);
} else {
this.store$.dispatch({
type: roomAction.changeRoomSuccess,
payload: {
active: payload,
info: data.info
}
});
}
return { type: '[room] change room useless' };
});
// 进入新的聊天室
@Effect()
private enterRoom$: Observable<Action> = this.actions$
.ofType(roomAction.enterRoom)
.map(toPayload)
.switchMap(async (payload) => {
const roomObj = {
id: payload.id
};
const data: any = await this.apiService.enterChatroom(roomObj);
if (data.code) {
if (data.code === 881507) {
this.store$.dispatch({
type: roomAction.enterRoomSuccess,
payload
});
} else {
this.errorFn(data);
this.store$.dispatch({
type: roomAction.enterRoomError,
payload
});
}
} else {
this.store$.dispatch({
type: roomAction.enterRoomSuccess,
payload
});
}
return { type: '[room] enter room useless' };
});
// 退出聊天室
@Effect()
private exitRoom$: Observable<Action> = this.actions$
.ofType(roomAction.exitRoom)
.map(toPayload)
.switchMap(async (payload) => {
if (payload.id) {
this.exitRoom(payload);
}
return { type: '[room] exit room useless' };
});
// 显示聊天室资料
@Effect()
private showRoomInfomation$: Observable<Action> = this.actions$
.ofType(roomAction.showRoomInfomation)
.map(toPayload)
.switchMap(async (payload) => {
const roomObj = {
id: payload.id
};
const data: any = await this.apiService.getChatroomInfo(roomObj);
if (data.code) {
this.errorFn(data);
} else {
this.store$.dispatch({
type: roomAction.showRoomInfomationSuccess,
payload: {
show: true,
info: data.info
}
});
}
return { type: '[room] show room infomation useless' };
});
// 收到新消息
@Effect()
private receiveMessage$: Observable<Action> = this.actions$
.ofType(roomAction.receiveMessage)
.map(toPayload)
.switchMap(async (payload) => {
this.store$.dispatch({
type: roomAction.receiveMessageSuccess,
payload: payload.data
});
if (payload.data.content.msg_body.media_id) {
const urlObj = { media_id: payload.data.content.msg_body.media_id };
const data: any = await this.apiService.getResource(urlObj);
if (data.code) {
payload.data.content.msg_body.media_url = '';
} else {
payload.data.content.msg_body.media_url = data.url;
}
this.store$.dispatch({
type: roomAction.receiveMessageUrlSuccess,
payload: payload.data
});
}
// 如果接收的是名片
if (payload.data.content.msg_type === 'text' && payload.data.content.msg_body.extras &&
payload.data.content.msg_body.extras.businessCard) {
this.requestCardInfo(payload.data);
}
// 判断是否加载过这个用户的头像,加载过就直接使用本地的用户头像
const username = payload.data.content.from_id !== global.user ?
payload.data.content.from_id : payload.data.content.target_id;
let flag = false;
for (let message of payload.messageList) {
let messageUsername = message.content.from_id !== global.user ?
message.content.from_id : message.content.target_id;
if (username === messageUsername &&
(message.content.avatarUrl || message.content.avatarUrl === '')) {
payload.data.content.avatarUrl = message.content.avatarUrl;
flag = true;
break;
}
}
if (!flag) {
const userObj = {
username
};
const data: any = await this.apiService.getUserInfo(userObj);
if (!data.code && data.user_info.avatar !== '') {
const urlObj = { media_id: data.user_info.avatar };
const urlInfo: any = await this.apiService.getResource(urlObj);
if (!urlInfo.code) {
payload.data.content.avatarUrl = urlInfo.url;
}
}
}
return { type: '[room] receive message useless' };
});
// 发送文本消息
@Effect()
private sendTextMsg$: Observable<Action> = this.actions$
.ofType(roomAction.sendTextMsg)
.map(toPayload)
.switchMap(async (payload) => {
const msg: any = await this.apiService.sendChatroomMsg(payload.sendMsg);
let newPayload: any = {
localMsg: payload.localMsg,
repeatSend: payload.repeatSend
};
if (msg.code) {
payload.localMsg.success = 3;
payload.localMsg.sendMsg = payload.sendMsg;
this.errorFn(msg);
} else {
payload.localMsg.success = 2;
newPayload.msg = msg;
}
this.store$.dispatch({
type: roomAction.sendMsgComplete,
payload: newPayload
});
return { type: '[room] send text msg useless' };
});
// 发送文件消息
@Effect()
private sendFileMsg$: Observable<Action> = this.actions$
.ofType(roomAction.sendFileMsg)
.map(toPayload)
.switchMap(async (payload) => {
const msg: any = await this.apiService.sendChatroomFile(payload.sendMsg);
const newPayload: any = {
localMsg: payload.localMsg,
repeatSend: payload.repeatSend
};
if (msg.code) {
payload.localMsg.success = 3;
payload.localMsg.sendMsg = payload.sendMsg;
this.errorFn(msg);
} else {
payload.localMsg.success = 2;
newPayload.msg = msg;
}
this.store$.dispatch({
type: roomAction.sendMsgComplete,
payload: newPayload
});
return { type: '[room] send file msg useless' };
});
// 发送图片消息, 发送jpush表情
@Effect()
private sendPicMsg$: Observable<Action> = this.actions$
.ofType(roomAction.sendPicMsg, roomAction.transmitPicMsg)
.map(toPayload)
.switchMap(async (payload) => {
const msg: any = await this.apiService.sendChatroomPic(payload.sendMsg);
let newPayload: any = {
localMsg: payload.localMsg,
repeatSend: payload.repeatSend
};
if (msg.code) {
payload.localMsg.success = 3;
payload.localMsg.sendMsg = payload.sendMsg;
this.errorFn(msg);
} else {
payload.localMsg.success = 2;
newPayload.msg = msg;
}
this.store$.dispatch({
type: roomAction.sendMsgComplete,
payload: newPayload
});
return { type: '[room] send pic msg useless or transmit pic msg useless' };
});
constructor(
private actions$: Actions,
private store$: Store<AppStore>,
private storageService: StorageService,
private apiService: ApiService
) { }
private errorFn(error) {
this.store$.dispatch({
type: appAction.errorApiTip,
payload: error
});
}
// 退出聊天室
private async exitRoom(payload) {
const roomObj = {
id: payload.id
};
const data: any = await this.apiService.exitChatroom(roomObj);
if (!data.code) {
this.store$.dispatch({
type: roomAction.exitRoomSuccess,
payload: null
});
}
}
// 接收名片获取对方的信息
private async requestCardInfo(data) {
const userObj = {
username: data.content.msg_body.extras.userName,
appkey: authPayload.appkey
};
const otherInfo: any = await this.apiService.getUserInfo(userObj);
if (!otherInfo.code) {
data.content.msg_body.extras.nickName = otherInfo.user_info.nickname;
if (otherInfo.user_info.avatar !== '') {
const urlObj = { media_id: otherInfo.user_info.avatar };
const urlInfo: any = await this.apiService.getResource(urlObj);
if (!urlInfo.code) {
data.content.msg_body.extras.media_url = urlInfo.url;
}
}
}
}
}; | the_stack |
import React from 'react';
import { Table, TableBody } from '@material-ui/core';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import ExpandLessIcon from '@material-ui/icons/ExpandLess';
import CompareTableRow from './CompareTableRow';
import HeaderCell from './HeaderCell';
import * as Styles from './LocationTable.style';
import * as CompareStyles from './Compare.style';
import { SCREENSHOT_CLASS } from 'components/Screenshot';
import { EventAction } from 'components/Analytics';
import {
RankedLocationSummary,
GeoScopeFilter,
SummaryForCompare,
HomepageLocationScope,
} from 'common/utils/compare';
import { COLOR_MAP } from 'common/colors';
import { trackCompareEvent } from 'common/utils/compare';
import { Region, MetroArea } from 'common/regions';
import { ColumnDefinition } from './columns';
const LocationTableHead: React.FunctionComponent<{
setSorter: React.Dispatch<React.SetStateAction<number>>;
setSortDescending: React.Dispatch<React.SetStateAction<boolean>>;
sortDescending: boolean;
sorter: number;
arrowColorSelected: string;
arrowColorNotSelected: string;
firstColumnHeader: string;
columns: ColumnDefinition[];
isModal: boolean;
stateName?: string;
setSortByPopulation: React.Dispatch<React.SetStateAction<boolean>>;
sortByPopulation: boolean;
allCountiesView: boolean;
isHomepage?: boolean;
}> = ({
setSorter,
setSortDescending,
sortDescending,
sorter,
arrowColorSelected,
arrowColorNotSelected,
firstColumnHeader,
columns,
isModal,
stateName,
setSortByPopulation,
sortByPopulation,
allCountiesView,
isHomepage,
}) => {
const onPopulationClick = () => {
if (sortByPopulation) {
const updatedSortDescending = !sortDescending;
setSortDescending(updatedSortDescending);
trackCompareEvent(
EventAction.SELECT,
`Sort by: Population (${updatedSortDescending ? 'Desc' : 'Asc'})`,
);
} else {
setSortByPopulation(true);
setSortDescending(true);
trackCompareEvent(EventAction.SELECT, 'Sort by: Population (Desc)');
}
};
const modalLocationColumnHeader =
allCountiesView && !isHomepage ? 'USA' : stateName && `${stateName}`;
return (
<Table key="table-header">
<CompareStyles.TableHeadContainer $isModal={isModal}>
<CompareStyles.Row
$headerRowBackground={
isModal ? `${COLOR_MAP.GRAY_BODY_COPY}` : 'white'
}
>
<CompareStyles.LocationHeaderCell
$isModal={isModal}
onClick={onPopulationClick}
$sortByPopulation={sortByPopulation}
$arrowColorSelected={arrowColorSelected}
$arrowColorNotSelected={arrowColorNotSelected}
$sortDescending={sortDescending}
>
{isModal && (
<CompareStyles.StateName>
{modalLocationColumnHeader}
</CompareStyles.StateName>
)}
{firstColumnHeader}
<br />
<span>population</span>
<CompareStyles.ArrowContainer
$arrowColorNotSelected={arrowColorNotSelected}
$isModal={isModal}
>
<ExpandLessIcon onClick={() => setSortDescending(false)} />
<ExpandMoreIcon onClick={() => setSortDescending(true)} />
</CompareStyles.ArrowContainer>
</CompareStyles.LocationHeaderCell>
{columns.map((column, i) => (
<HeaderCell
key={`header-cell-${i}`}
column={column}
sorter={sorter}
sortDescending={sortDescending}
arrowColorSelected={arrowColorSelected}
arrowColorNotSelected={arrowColorNotSelected}
setSorter={setSorter}
setSortDescending={setSortDescending}
isModal={isModal}
setSortByPopulation={setSortByPopulation}
sortByPopulation={sortByPopulation}
/>
))}
</CompareStyles.Row>
</CompareStyles.TableHeadContainer>
</Table>
);
};
const LocationTableBody: React.FunctionComponent<{
sortedLocations: RankedLocationSummary[];
sorter: number;
currentLocationRank?: number;
sortByPopulation: boolean;
isHomepage?: boolean;
showStateCode: boolean;
columns: ColumnDefinition[];
}> = ({
sortedLocations,
sorter,
currentLocationRank,
sortByPopulation,
isHomepage,
showStateCode,
columns,
}) => (
<Table>
<TableBody>
{sortedLocations.map((location, i) => (
<CompareTableRow
key={`compare-table-row-${i}`}
sorter={sorter}
location={location}
isCurrentCounty={location.rank === currentLocationRank}
sortByPopulation={sortByPopulation}
isHomepage={isHomepage}
showStateCode={showStateCode}
columns={columns}
/>
))}
</TableBody>
</Table>
);
/**
* NOTE (pablo): Material UI tables have some limitations regarding some
* behaviours we need. In particular, we can't have more than one element
* pinned to the top, which is what we need to pin the current location
* in the top row.
*
* This implementation is a hack and uses 3 tables. This can create some
* accessibility issues (screen readers might have trouble reading the
* table as a single unit). We might want to explore some other solutions
* (maybe other libraries) at some point.
*/
const LocationTable: React.FunctionComponent<{
setSorter: React.Dispatch<React.SetStateAction<number>>;
setSortDescending: React.Dispatch<React.SetStateAction<boolean>>;
sortDescending: boolean;
sorter: number;
arrowColorSelected: string;
arrowColorNotSelected: string;
firstColumnHeader: string;
columns: ColumnDefinition[];
isModal: boolean;
pinnedLocation?: RankedLocationSummary;
sortedLocations: RankedLocationSummary[];
numLocations: number;
stateName?: string;
setSortByPopulation: React.Dispatch<React.SetStateAction<boolean>>;
sortByPopulation: boolean;
isHomepage?: boolean;
geoScope: GeoScopeFilter;
homepageScope: HomepageLocationScope;
region?: Region;
}> = ({
setSorter,
setSortDescending,
sortDescending,
sorter,
arrowColorSelected,
arrowColorNotSelected,
firstColumnHeader,
columns,
isModal,
pinnedLocation,
sortedLocations,
numLocations,
stateName,
setSortByPopulation,
sortByPopulation,
isHomepage,
geoScope,
homepageScope,
region,
}) => {
const Container = isModal ? Styles.ModalContainer : Styles.Container;
// Seemingly random numbers are the heights of each modal header
const homepageOffset =
homepageScope === HomepageLocationScope.COUNTY ? 198 : 115;
const locationPageOffset = geoScope === GeoScopeFilter.NEARBY ? 107 : 198;
// Changes to account for change in header height with different filters:
function getModalHeaderOffset(): number {
if (!region) {
return homepageOffset;
} else {
if (region instanceof MetroArea) {
return 60;
} else if (pinnedLocation) {
return locationPageOffset;
} else {
return 110;
}
}
}
const finalHeaderOffset = isModal ? getModalHeaderOffset() : 0;
const showBottom = pinnedLocation && pinnedLocation.rank >= numLocations;
const numLocationsMain = showBottom ? numLocations - 1 : numLocations;
const allCountiesView = geoScope === GeoScopeFilter.COUNTRY;
const currentLocationRank = pinnedLocation?.rank;
const hideInlineLocation = isModal && currentLocationRank === 1;
// In the modal, if the rank of the pinned-location-row is #1, we remove
// the location's inline row, so as to not have the location listed twice consecutively:
const isNotPinnedLocation = (location: SummaryForCompare) =>
location.region.fipsCode !== pinnedLocation?.region.fipsCode;
const modalLocations = hideInlineLocation
? sortedLocations.filter(location => isNotPinnedLocation(location))
: sortedLocations;
const getVisibleLocations = () => {
if (!isModal) {
return sortedLocations.slice(0, numLocationsMain);
} else {
if (region) {
if (geoScope === GeoScopeFilter.COUNTRY)
return modalLocations.slice(0, 100);
else return modalLocations;
} else {
if (homepageScope === HomepageLocationScope.STATE)
return sortedLocations;
else return sortedLocations.slice(0, 100);
}
}
};
const visibleLocations = getVisibleLocations();
const returnShowStateCode = (region?: Region): boolean => {
if (region) {
return region instanceof MetroArea || geoScope === GeoScopeFilter.NEARBY;
} else {
return homepageScope !== HomepageLocationScope.STATE;
}
};
const showStateCode = returnShowStateCode(region);
return (
<Styles.TableContainer $isModal={isModal} className={SCREENSHOT_CLASS}>
<Container finalHeaderOffset={finalHeaderOffset}>
<Styles.Head $isModal={isModal} $pinnedLocation={pinnedLocation}>
<LocationTableHead
setSorter={setSorter}
setSortDescending={setSortDescending}
sortDescending={sortDescending}
sorter={sorter}
arrowColorSelected={arrowColorSelected}
arrowColorNotSelected={arrowColorNotSelected}
firstColumnHeader={firstColumnHeader}
columns={columns}
isModal={isModal}
stateName={stateName}
setSortByPopulation={setSortByPopulation}
sortByPopulation={sortByPopulation}
allCountiesView={allCountiesView}
isHomepage={isHomepage}
/>
{isModal && pinnedLocation && (
<Table key="table-pinned-location">
<TableBody>
<CompareTableRow
columns={columns}
location={pinnedLocation}
sorter={sorter}
isCurrentCounty
isModal={isModal}
sortByPopulation={sortByPopulation}
showStateCode={showStateCode}
/>
</TableBody>
</Table>
)}
</Styles.Head>
<Styles.Body>
<LocationTableBody
sorter={sorter}
sortedLocations={visibleLocations}
currentLocationRank={currentLocationRank}
sortByPopulation={sortByPopulation}
isHomepage={isHomepage}
showStateCode={showStateCode}
columns={columns}
/>
</Styles.Body>
{pinnedLocation && showBottom && !isModal && (
<Styles.Body>
<LocationTableBody
columns={columns}
sorter={sorter}
sortedLocations={[pinnedLocation]}
currentLocationRank={pinnedLocation?.rank}
sortByPopulation={sortByPopulation}
showStateCode={showStateCode}
/>
</Styles.Body>
)}
</Container>
</Styles.TableContainer>
);
};
export default LocationTable; | the_stack |
import * as assert from "assert";
import { expect } from "chai";
import ElectrodeOtaDaoRdbms from "../src/ElectrodeOtaDaoRdbms";
import MyDAO from "./MyDAO";
import { clearTables } from "./ClearTables";
import {
AppDTO,
MetricInDTO,
MetricOutDTO,
MetricByStatusOutDTO,
PackageDTO,
UserDTO
} from "../src/dto";
import Encryptor from "../src/Encryptor";
import { readFileSync } from "fs";
import { version } from "punycode";
// tslint:disable:no-console
const dao = new ElectrodeOtaDaoRdbms();
const testDBConfig = {
clusterConfig: {
canRetry: true,
defaultSelector: "ORDER",
removeNodeErrorCount: 5,
restoreNodeTimeout: 0
},
poolConfigs: [
{
// debug: true,
database: "electrode_ota",
host: "localhost",
password: "ota",
port: 33060,
user: "ota"
}
],
encryptionConfig: {
keyfile: "./test/sample_encryption.key",
fields: [
"user.name",
"user.email",
"package.released_by",
"access_key.friendly_name",
"access_key.description"
]
}
};
const stageDeploymentKey = "qjPVRyntQQrKJhkkNbVJeULhAIfVtHaBDfCFggzL";
const intlStageDeploymentKey = "aoh0u3u9u0uoihaoshdfhh9842234Fdkap30";
const prodDeploymentKey = "PutMeonDyCkrSQWnbOqFnawEAwRteuxCZPeGhshl";
const metricDeploymentKey = "cJ3PGiq4Z3SQ3IEpivV4VuXF5lTDylmdMNeY1CALJrw=";
const STAGING = "Staging";
const INTLSTAGING = "IntlStaging";
const PROD = "Production";
const METRICS = "Metrics";
const packageHash =
"0848a9900dc54d5e88c90d39a7454b1b64a3557b337b9dadf6c20de5ed305182";
const ONE_MINUTE_MS = 60000;
let appId = 0;
const appName = "testApp";
let pkgId = 0;
// tslint:disable:no-unused-expression
const createMetricInDTOs = (deploymentKey:string, metrics:any) => {
let dtos = [];
for(let i=0; i<metrics.length; i++) {
const dto = new MetricInDTO();
dto.deploymentKey = deploymentKey;
dto.label = metrics[i]['label'];
dto.appVersion = metrics[i]['appVersion'];
dto.status = metrics[i]['status'];
dto.clientUniqueId = "ABCDEF12345";
dtos.push(dto);
}
return dtos;
}
process.on("unhandledRejection", (reason, p) => {
console.log("Unhandled Rejection, reason:", reason);
});
// tslint:disable-next-line:only-arrow-functions
describe("Data Access via RDBMS", function() {
this.timeout(30000);
describe("connect", () => {
it("connects to the database", () => {
return dao.connect(testDBConfig).then(() => dao.close());
});
});
describe("close", () => {
it("closes the cluster", () => {
return dao.close();
});
it("disconnect alias for close", () => {
return dao.disconnect();
})
});
describe("dao methods", () => {
const email = "test@tests.com";
before(() => {
return dao.connect(testDBConfig).then(() => {
return dao.getConnection().then(connection => clearTables(connection));
});
});
after(() => {
return dao.close();
});
describe("user-related methods", () => {
const userDTO = new UserDTO();
const createdTime = Date.now();
const expires = createdTime + 60 * 24 * 3600 * 1000;
const keyName = "02f20n02n303n";
const newKeyName = "2930jf920j02j";
userDTO.email = email;
userDTO.name = "tester";
userDTO.linkedProviders = ["ldap"];
userDTO.accessKeys = {};
userDTO.accessKeys[keyName] = {
createdBy: undefined,
createdTime,
description: "Some junk",
email: userDTO.email,
expires,
friendlyName: "Login-" + expires,
id: "some junk",
name: keyName
};
describe("createUser", () => {
it("adds a user record and access key record to the respective tables", () => {
return dao.createUser(userDTO).then(updatedUserDTO => {
expect(updatedUserDTO).not.to.be.undefined;
expect(updatedUserDTO.email).to.eq(userDTO.email);
expect(updatedUserDTO.accessKeys).not.to.be.undefined;
expect(updatedUserDTO.accessKeys[keyName]).not.to.be.undefined;
expect(updatedUserDTO.accessKeys[keyName].expires.getTime()).to.eq(
expires
);
expect(updatedUserDTO.linkedProviders).not.to.be.undefined;
expect(updatedUserDTO.linkedProviders[0]).to.eq("ldap");
});
});
it("throws an error if the email address for the user already exists", () => {
return dao.createUser(userDTO).catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("already exists");
});
});
it("can add a user without an access key or provider", () => {
const differentUser = new UserDTO();
differentUser.email = "stupid_face@smart_guy.com";
differentUser.name = "Gim Gob";
return dao.createUser(differentUser).then(created => {
expect(created).not.to.be.undefined;
expect(created.email).to.eq(differentUser.email);
expect(created.name).to.eq(differentUser.name);
expect(created.accessKeys).to.be.undefined;
expect(created.linkedProviders).to.be.undefined;
});
});
it("can handle expiration on keys as Date's instead of numbers", () => {
const anotherUser = new UserDTO();
anotherUser.email = "another@test_user.com";
anotherUser.name = "Bob Diggety";
const testKey = "2930jf02j023j02j2f";
const testExpiration = new Date();
const testLastAccess = new Date();
anotherUser.accessKeys = {};
anotherUser.accessKeys[testKey] = {
createdBy: undefined,
createdTime,
description: "Some junk",
email: userDTO.email,
expires: testExpiration,
friendlyName: "Login-" + expires,
id: "some junk",
lastAccess: testLastAccess,
name: testKey
};
return dao.createUser(anotherUser).then(created => {
expect(created).not.to.be.undefined;
expect(created.email).to.eq(anotherUser.email);
expect(created.name).to.eq(anotherUser.name);
expect(created.accessKeys).not.to.be.undefined;
expect(created.accessKeys[testKey]).not.to.be.undefined;
const createdKey = created.accessKeys[testKey];
const accessKey = anotherUser.accessKeys[testKey];
expect(createdKey.expires.getTime()).to.eq(
accessKey.expires.getTime()
);
});
});
});
describe("userByEmail", () => {
it("returns the user specified by email address", () => {
return dao.userByEmail(userDTO.email).then(found => {
userDTO.id = found.id;
expect(found).not.to.be.undefined;
expect(found.email).to.eq(userDTO.email);
expect(found.accessKeys).not.to.be.undefined;
expect(found.accessKeys[keyName]).not.to.be.undefined;
expect(found.accessKeys[keyName].expires.getTime()).to.eq(expires);
});
});
it("will throw an error if user not found", () => {
return dao.userByEmail("some-other@email.com").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("No user found");
});
});
});
describe("userByAccessKey", () => {
it("returns the user specified by access key", () => {
return dao.userByAccessKey(keyName).then(found => {
expect(found).not.to.be.undefined;
expect(found.email).to.eq(userDTO.email);
expect(found.accessKeys).not.to.be.undefined;
expect(found.accessKeys[keyName]).not.to.be.undefined;
});
});
it("will throw an error if user not found", () => {
return dao.userByAccessKey("someJunk").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("No user found");
});
});
});
describe("userById", () => {
it("returns the user specified by db id", () => {
return dao.userById(userDTO.id + "").then(found => {
expect(found).not.to.be.undefined;
expect(found.email).to.eq(userDTO.email);
expect(found.accessKeys).not.to.be.undefined;
expect(found.accessKeys[keyName]).not.to.be.undefined;
});
});
it("will throw an error if user not found", () => {
return dao.userById("123456789").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("No user found");
});
});
});
describe("updateUser", () => {
it("will add a linked provider", () => {
const updateInfo = new UserDTO();
updateInfo.email = userDTO.email;
updateInfo.accessKeys = userDTO.accessKeys;
updateInfo.linkedProviders = ([] as string[]).concat(
userDTO.linkedProviders,
["github"]
);
return dao.updateUser(userDTO.email, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.email).to.eq(userDTO.email);
expect(updated.linkedProviders).not.to.be.undefined;
expect(updated.linkedProviders.length).to.eq(2);
expect(updated.linkedProviders.indexOf("ldap")).to.be.gte(0);
expect(updated.linkedProviders.indexOf("github")).to.be.gte(0);
});
});
it("updates an access key's last access, expiration, friendly name", () => {
const updateInfo = new UserDTO();
updateInfo.email = userDTO.email;
updateInfo.accessKeys = {};
updateInfo.accessKeys[keyName] = Object.assign(
{},
userDTO.accessKeys[keyName]
);
const newExpiration = Date.now() + 60 * 24 * 3600 * 1000;
const newLastAccess = Date.now();
const newFriendlyName = "Login-junk-junk-stuff";
updateInfo.accessKeys[keyName].expires = newExpiration;
updateInfo.accessKeys[keyName].friendlyName = newFriendlyName;
updateInfo.accessKeys[keyName].lastAccess = newLastAccess;
return dao.updateUser(userDTO.email, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.email).to.eq(userDTO.email);
expect(updated.accessKeys).not.to.be.undefined;
expect(updated.accessKeys[keyName]).not.to.be.undefined;
const updatedAccessKey = updated.accessKeys[keyName];
expect(updatedAccessKey.name).to.eq(
userDTO.accessKeys[keyName].name
);
expect(updatedAccessKey.expires.getTime()).to.eq(newExpiration);
expect(updatedAccessKey.lastAccess).not.to.be.undefined;
if (updatedAccessKey.lastAccess) {
expect(updatedAccessKey.lastAccess.getTime()).to.eq(
newLastAccess
);
}
expect(updatedAccessKey.friendlyName).to.eq(newFriendlyName);
// so other tests will work right
userDTO.accessKeys[keyName].friendlyName = newFriendlyName;
userDTO.accessKeys[keyName].expires = newExpiration;
});
});
it("can update only last access and leave expiration and friendly name unchanged", () => {
const updateInfo = new UserDTO();
updateInfo.email = userDTO.email;
updateInfo.accessKeys = {};
updateInfo.accessKeys[keyName] = Object.assign(
{},
userDTO.accessKeys[keyName]
);
const newExpiration = userDTO.accessKeys[keyName].expires;
const newLastAccess = new Date();
updateInfo.accessKeys[keyName].lastAccess = newLastAccess;
delete updateInfo.accessKeys[keyName].friendlyName; // = undefined;
delete updateInfo.accessKeys[keyName].expires; // = undefined;
return dao.updateUser(userDTO.email, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.email).to.eq(userDTO.email);
expect(updated.accessKeys).not.to.be.undefined;
expect(updated.accessKeys[keyName]).not.to.be.undefined;
const updatedAccessKey = updated.accessKeys[keyName];
expect(updatedAccessKey.name).to.eq(
userDTO.accessKeys[keyName].name
);
// tslint:disable-next-line:max-line-length
expect(updatedAccessKey.expires.getTime()).to.eq(
updateInfo.accessKeys[keyName].expires.getTime()
);
expect(updatedAccessKey.lastAccess).not.to.be.undefined;
if (updatedAccessKey.lastAccess) {
expect(updatedAccessKey.lastAccess.getTime()).to.eq(
newLastAccess.getTime()
);
}
userDTO.accessKeys[keyName].lastAccess = newLastAccess.getTime();
expect(updatedAccessKey.friendlyName).to.eq(
userDTO.accessKeys[keyName].friendlyName
);
});
});
it("can update only expires", () => {
const updateInfo = new UserDTO();
updateInfo.email = userDTO.email;
updateInfo.accessKeys = {};
updateInfo.accessKeys[keyName] = Object.assign(
{},
userDTO.accessKeys[keyName]
);
const newExpiration = userDTO.accessKeys[keyName].expires;
updateInfo.accessKeys[keyName].expires = newExpiration;
delete updateInfo.accessKeys[keyName].friendlyName;
delete updateInfo.accessKeys[keyName].lastAccess;
return dao.updateUser(userDTO.email, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.email).to.eq(userDTO.email);
expect(updated.accessKeys).not.to.be.undefined;
expect(updated.accessKeys[keyName]).not.to.be.undefined;
const updatedAccessKey = updated.accessKeys[keyName];
expect(updatedAccessKey.name).to.eq(
userDTO.accessKeys[keyName].name
);
// tslint:disable-next-line:max-line-length
expect(updatedAccessKey.expires.getTime()).to.eq(
updateInfo.accessKeys[keyName].expires
);
expect(updatedAccessKey.lastAccess).not.to.be.undefined;
if (updatedAccessKey.lastAccess) {
expect(updatedAccessKey.lastAccess.getTime()).to.eq(
userDTO.accessKeys[keyName].lastAccess
);
}
expect(updatedAccessKey.friendlyName).to.eq(
userDTO.accessKeys[keyName].friendlyName
);
userDTO.accessKeys[keyName].expires = newExpiration;
});
});
it("adds a new access key", () => {
const updateInfo = new UserDTO();
updateInfo.email = userDTO.email;
updateInfo.accessKeys = {};
updateInfo.accessKeys[newKeyName] = {
createdBy: undefined,
createdTime,
description: "Some junk 2",
email: userDTO.email,
expires,
friendlyName: "Login-" + expires,
id: "some junk",
name: newKeyName
};
return dao.updateUser(userDTO.email, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.email).to.eq(userDTO.email);
expect(updated.accessKeys).not.to.be.undefined;
expect(updated.accessKeys[keyName]).not.to.be.undefined;
expect(updated.accessKeys[keyName].name).to.eq(
userDTO.accessKeys[keyName].name
);
expect(updated.accessKeys[newKeyName]).not.to.be.undefined;
expect(updated.accessKeys[newKeyName].name).to.eq(
updateInfo.accessKeys[newKeyName].name
);
});
});
it("will remove an access key", () => {
const updateInfo = new UserDTO();
updateInfo.email = userDTO.email;
updateInfo.accessKeys = Object.assign({}, userDTO.accessKeys);
delete updateInfo.accessKeys[newKeyName];
return dao.updateUser(userDTO.email, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.email).to.eq(userDTO.email);
expect(updated.accessKeys).not.to.be.undefined;
expect(updated.accessKeys[keyName]).not.to.be.undefined;
expect(updated.accessKeys[keyName].name).to.eq(
userDTO.accessKeys[keyName].name
);
expect(updated.accessKeys[newKeyName]).to.be.undefined;
});
});
it("will return existing if no changes sent", () => {
const updateInfo = new UserDTO();
updateInfo.email = userDTO.email;
updateInfo.accessKeys = Object.assign({}, userDTO.accessKeys);
return dao.updateUser(userDTO.email, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.email).to.eq(userDTO.email);
expect(updated.accessKeys).not.to.be.undefined;
expect(updated.accessKeys[keyName]).not.to.be.undefined;
expect(updated.accessKeys[keyName].name).to.eq(
userDTO.accessKeys[keyName].name
);
});
});
it("will throw an error if user not found", () => {
const updateInfo = new UserDTO();
updateInfo.accessKeys = {};
return dao.updateUser("someJunk@stuff.com", updateInfo).catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("No user found");
});
});
it("will throw an error if incoming accessKeys property is null", () => {
const updateInfo = new UserDTO();
return dao.updateUser("someJunk@stuff.com", updateInfo).catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain(
"accessKeys property must be provided"
);
});
});
});
});
describe("app-related methods", () => {
const appDTO = new AppDTO();
appDTO.name = appName;
const permission = "Owner";
appDTO.collaborators = {};
appDTO.deployments = {};
describe("createApp", () => {
it("will throw an error if creating an app with no owner", () => {
return dao.createApp(appDTO).catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("app.collaborators");
});
});
it("will throw an error if creating an app with unknown owner", () => {
const junkEmail = "some_junk@email.com";
appDTO.collaborators[junkEmail] = { permission };
return dao.createApp(appDTO).catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("not found");
delete appDTO.collaborators[junkEmail];
});
});
it("will create an app record with permissions and deployments", () => {
appDTO.collaborators[email] = { permission };
appDTO.deployments[STAGING] = {
key: stageDeploymentKey,
name: STAGING
};
appDTO.deployments[PROD] = {
key: prodDeploymentKey,
name: PROD
};
appDTO.deployments[METRICS] = {
key: metricDeploymentKey,
name: METRICS
};
return dao.createApp(appDTO).then(updated => {
appDTO.id = updated.id;
// for use in other "defines" that need an app
appId = updated.id;
expect(updated).not.to.be.undefined;
expect(updated.name).to.eq(appName);
expect(updated.collaborators).not.to.be.undefined;
expect(updated.collaborators[email]).not.to.be.undefined;
expect(updated.collaborators[email].permission).to.eq(permission);
expect(updated.deployments).not.to.be.undefined;
expect(updated.deployments).to.contain(STAGING);
expect(updated.deployments).to.contain(PROD);
});
});
it("can create an app without deployments", () => {
const differentApp = new AppDTO();
differentApp.name = "DifferentApp-Android";
differentApp.collaborators = {};
differentApp.collaborators[email] = { permission };
return dao.createApp(differentApp).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.name).to.eq(differentApp.name);
expect(updated.collaborators).not.to.be.undefined;
expect(updated.collaborators[email]).not.to.be.undefined;
expect(updated.collaborators[email].permission).to.eq(permission);
});
});
});
describe("appById", () => {
it("will return the base app info", () => {
// return dao.appById()
});
it("will throw an error if app not found", () => {
return dao.appById(-1).catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("not found");
});
});
});
describe("appsForCollaborator", () => {
it("will retrieve all the apps for a user email", () => {
return dao.appsForCollaborator(email).then(apps => {
expect(apps).not.to.be.undefined;
expect(apps.length).to.be.gt(0);
expect(apps[0].name).not.to.be.undefined;
expect(apps[0].collaborators).not.to.be.undefined;
expect(apps[0].collaborators[email]).not.to.be.undefined;
expect(apps[0].collaborators[email].permission).to.be.oneOf([
"Owner",
"Collaborator"
]);
});
});
});
describe("appForCollaborator", () => {
it("will retrieve the app for the app name and collaborator email", () => {
return dao.appForCollaborator(email, appName).then(app => {
expect(app).not.to.be.undefined;
if (app) {
expect(app.name).not.to.be.undefined;
expect(app.collaborators).not.to.be.undefined;
expect(app.collaborators[email]).not.to.be.undefined;
expect(app.collaborators[email].permission).to.be.oneOf([
"Owner",
"Collaborator"
]);
expect(app.deployments).not.to.be.undefined;
expect(app.deployments).to.contain(STAGING);
expect(app.deployments).to.contain(PROD);
}
});
});
it("will throw a Not Found error if the app is not found", () => {
return dao
.appForCollaborator(email, "someOtherStupidAppName")
.catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not Found");
});
});
});
describe("updateApp", () => {
const collabAccessKey = "23490820jf02j0cj2";
const expires = Date.now() + 24 * 60 * 60 * 1000;
const collaborator = new UserDTO();
collaborator.email = "collab@collab.net";
collaborator.linkedProviders = ["ldap"];
collaborator.accessKeys = {};
collaborator.accessKeys[collabAccessKey] = {
createdBy: undefined,
createdTime: Date.now(),
description: "Some junk 2",
email: collaborator.email,
expires,
friendlyName: "Login-" + expires,
id: "some junk",
name: collabAccessKey
};
before(() => {
// let's add another user to be a collaborator
return dao.createUser(collaborator);
});
it("can rename an app", () => {
const updateInfo = new AppDTO();
const newAppName = "newTestAppName";
updateInfo.id = appDTO.id;
updateInfo.name = newAppName;
return dao.updateApp(appDTO.id, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.name).to.eq(newAppName);
expect(updated.collaborators).not.to.be.undefined;
expect(updated.collaborators[email]).not.to.be.undefined;
appDTO.name = newAppName;
});
});
it("can add a collaborator", () => {
const updateInfo = new AppDTO();
updateInfo.name = appDTO.name;
updateInfo.collaborators = {};
updateInfo.collaborators[email] = { permission: "Owner" };
updateInfo.collaborators[collaborator.email] = {
permission: "Collaborator"
};
return dao.updateApp(appDTO.id, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.name).to.eq(appDTO.name);
expect(updated.collaborators).not.to.be.undefined;
expect(updated.collaborators[email]).not.to.be.undefined;
expect(updated.collaborators[email].permission).to.eq("Owner");
expect(updated.collaborators[collaborator.email]).not.to.be
.undefined;
expect(updated.collaborators[collaborator.email].permission).to.eq(
"Collaborator"
);
return dao.appsForCollaborator(email).then(apps => {
expect(apps).not.to.be.undefined;
expect(apps.length).to.be.gte(0);
expect(apps[0].collaborators).not.to.be.undefined;
expect(apps[0].collaborators[email]).not.to.be.undefined;
expect(apps[0].collaborators[collaborator.email]).not.to.be
.undefined;
});
});
});
it("can remove a collaborator", () => {
const updateInfo = new AppDTO();
updateInfo.name = appDTO.name;
updateInfo.collaborators = {};
updateInfo.collaborators[email] = { permission: "Owner" };
return dao.updateApp(appDTO.id, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.name).to.eq(appDTO.name);
expect(updated.collaborators).not.to.be.undefined;
expect(updated.collaborators[email]).not.to.be.undefined;
expect(updated.collaborators[email].permission).to.eq("Owner");
expect(updated.collaborators[collaborator.email]).to.be.undefined;
});
});
it("can transfer app ownership", () => {
const updateInfo = new AppDTO();
updateInfo.name = appDTO.name;
updateInfo.collaborators = {};
updateInfo.collaborators[email] = { permission: "Collaborator" };
updateInfo.collaborators[collaborator.email] = {
permission: "Owner"
};
return dao.updateApp(appDTO.id, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.name).to.eq(appDTO.name);
expect(updated.collaborators).not.to.be.undefined;
expect(updated.collaborators[email]).not.to.be.undefined;
expect(updated.collaborators[email].permission).to.eq(
"Collaborator"
);
expect(updated.collaborators[collaborator.email]).not.to.be
.undefined;
expect(updated.collaborators[collaborator.email].permission).to.eq(
"Owner"
);
updateInfo.collaborators[email] = { permission: "Owner" };
updateInfo.collaborators[collaborator.email] = {
permission: "Collaborator"
};
return dao.updateApp(appDTO.id, updateInfo).then(reverted => {
expect(reverted).not.to.be.undefined;
expect(reverted.name).to.eq(appDTO.name);
expect(reverted.collaborators).not.to.be.undefined;
expect(reverted.collaborators[email]).not.to.be.undefined;
expect(reverted.collaborators[email].permission).to.eq("Owner");
expect(reverted.collaborators[collaborator.email]).not.to.be
.undefined;
expect(
reverted.collaborators[collaborator.email].permission
).to.eq("Collaborator");
});
});
});
it("will return the existing app if no changes are provided", () => {
const updateInfo = new AppDTO();
updateInfo.name = appDTO.name;
updateInfo.collaborators = {};
updateInfo.collaborators[email] = { permission: "Owner" };
// first update will effectively delete the collaborator created in the last test
return dao.updateApp(appDTO.id, updateInfo).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.name).to.eq(appDTO.name);
expect(updated.collaborators).not.to.be.undefined;
expect(updated.collaborators[email]).not.to.be.undefined;
expect(updated.collaborators[email].permission).to.eq("Owner");
return dao.updateApp(appDTO.id, updateInfo).then(unchanged => {
expect(unchanged).not.to.be.undefined;
expect(unchanged.name).to.eq(appDTO.name);
expect(unchanged.collaborators).not.to.be.undefined;
expect(unchanged.collaborators[email]).not.to.be.undefined;
expect(unchanged.collaborators[email].permission).to.eq("Owner");
});
});
});
});
describe("appForDeploymentKey", () => {
it("throws an error if no apps are found", () => {
return dao.appForDeploymentKey("SomeRandomJunk").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("searches for and finds an app record for a given deployment key", () => {
return dao.appForDeploymentKey(stageDeploymentKey).then(app => {
expect(app).not.to.be.undefined;
expect(app.id).to.eq(appId);
expect(app.name).not.to.be.undefined;
expect(app.collaborators).not.to.be.undefined;
expect(app.collaborators[email]).not.to.be.undefined;
expect(app.collaborators[email].permission).to.be.oneOf([
"Owner",
"Collaborator"
]);
expect(app.deployments).not.to.be.undefined;
expect(app.deployments).to.contain(STAGING);
expect(app.deployments).to.contain(PROD);
});
});
});
});
describe("deployment-related methods", () => {
const myDeploymentName = "MyDeployment";
const myDeploymentKey = "19fj29j2j302f923";
const newDeplName = "MyNewDeploymentName";
describe("addDeployment", () => {
it("will fail if the deployment key already exists", () => {
return dao
.addDeployment(appId, STAGING, { key: stageDeploymentKey })
.catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("already exists");
});
});
it("adds a new deployment", () => {
return dao
.addDeployment(appId, myDeploymentName, { key: myDeploymentKey })
.then(deployment => {
expect(deployment).not.to.be.undefined;
expect(deployment.key).to.eq(myDeploymentKey);
expect(deployment.name).to.eq(myDeploymentName);
});
});
});
describe("deploymentForKey", () => {
it("will throw an error if the deployment is not found", () => {
return dao.deploymentForKey("SomeOldJunkKey").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will find and return the deployment for the given key", () => {
return dao.deploymentForKey(stageDeploymentKey).then(deployment => {
expect(deployment).not.to.be.undefined;
expect(deployment.key).to.eq(stageDeploymentKey);
expect(deployment.name).to.eq(STAGING);
});
});
});
describe("deploymentsByApp", () => {
it("will throw an error if the deployment is not found", () => {
return dao
.deploymentsByApp(appId, ["StuffKey", "ThingKey"])
.catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will find and return the deployments for given app id and key names", () => {
return dao
.deploymentsByApp(appId, [STAGING, myDeploymentName])
.then(deployments => {
expect(deployments).not.to.be.undefined;
expect(deployments[STAGING]).not.to.be.undefined;
expect(deployments[STAGING].key).to.eq(stageDeploymentKey);
expect(deployments[myDeploymentName]).not.to.be.undefined;
expect(deployments[myDeploymentName].key).to.eq(myDeploymentKey);
});
});
});
describe("deploymentByApp", () => {
it("will throw an error if the deployment is not found", () => {
return dao.deploymentByApp(appId, "SomeOldJunkKey").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will find and return the deployment for the given app id and deployment name", () => {
return dao
.deploymentByApp(appId, myDeploymentName)
.then(deployment => {
expect(deployment).not.to.be.undefined;
expect(deployment.key).to.eq(myDeploymentKey);
expect(deployment.name).to.eq(myDeploymentName);
});
});
});
describe("renameDeployment", () => {
it("will throw an error if the old deployment name is not found", () => {
return dao
.renameDeployment(appId, "somejunk", "someNewJunk")
.catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will update the deployment name", () => {
return dao
.renameDeployment(appId, myDeploymentName, newDeplName)
.then(() => {
return dao.deploymentForKey(myDeploymentKey).then(deployment => {
expect(deployment).not.to.be.undefined;
expect(deployment.name).to.eq(newDeplName);
expect(deployment.key).to.eq(myDeploymentKey);
});
});
});
});
describe("removeDeployment", () => {
it("will throw an error if the deployment name is not found", () => {
return dao.removeDeployment(appId, "some junk").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will remove the deployment", () => {
return dao.removeDeployment(appId, newDeplName).then(() => {
return dao.deploymentForKey(myDeploymentKey).catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
});
});
describe("getDeployments", () => {
it("get all deployments", () => {
return dao.getConnection().then(connection => {
return new Promise((resolve, reject) => connection.query(`SELECT * FROM deployment`, [], (err, result) => {
if (err) {
reject(err);
}
resolve(result);
}));
}).then((result:any[]) => {
return dao.getDeployments()
.then((deployments:any[]) => {
expect(deployments.length).gt(0);
expect(deployments.length).eq(result.length);
let deploymentKeys = new Set(deployments.map(x => x.key));
let queryKeys = new Set(result.map(x => x['deployment_key']));
expect(deploymentKeys).deep.eq(queryKeys);
});
});
})
});
});
describe("package-related methods", () => {
const pkg = new PackageDTO();
pkg.appVersion = "0.0.1";
pkg.blobUrl = "http://stuff.com/pkg...";
pkg.description = "my new uploaded package";
pkg.isDisabled = false;
pkg.isMandatory = false;
pkg.label = "v1";
pkg.manifestBlobUrl = "http://stuff.com/manifest...";
pkg.packageHash = packageHash;
pkg.releasedBy = "testUser";
pkg.releaseMethod = "Upload";
pkg.rollout = 100;
pkg.size = 12908201;
let newPkgId = 0;
describe("addPackage", () => {
it("will throw an error if the given deployment key is not foud", () => {
return dao.addPackage("SomeJunkKey", new PackageDTO()).catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("creates a new package for a deployment", () => {
return dao.addPackage(stageDeploymentKey, pkg).then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.appVersion).to.eq(pkg.appVersion);
expect(updated.blobUrl).to.eq(pkg.blobUrl);
expect(updated.created_).not.to.be.undefined;
expect(updated.description).to.eq(pkg.description);
expect(updated.id).not.to.be.undefined;
pkg.id = updated.id;
// for use in other tests
pkgId = pkg.id;
expect(updated.isDisabled).to.eq(pkg.isDisabled);
expect(updated.isMandatory).to.eq(pkg.isMandatory);
expect(updated.label).to.eq(pkg.label);
expect(updated.manifestBlobUrl).to.eq(pkg.manifestBlobUrl);
expect(updated.packageHash).to.eq(pkg.packageHash);
expect(updated.releasedBy).to.eq(pkg.releasedBy);
expect(updated.releaseMethod).to.eq(pkg.releaseMethod);
expect(updated.rollout).to.eq(pkg.rollout);
expect(updated.size).to.eq(pkg.size);
});
});
it("will add tags on creation", () => {
const tags = ["TAG-1", "TAG-2"];
const newPkg = new PackageDTO();
Object.assign(newPkg, pkg);
newPkg.id = 0;
newPkg.tags = tags;
return dao.addPackage(stageDeploymentKey, newPkg).then(updated => {
expect(updated).not.to.be.undefined;
newPkg.id = updated.id;
newPkgId = updated.id;
expect(updated.tags).to.deep.equal(tags);
});
});
});
describe("packageById", () => {
it("will throw an error if the given package id is not found", () => {
return dao.packageById(-100).catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("retrieves the package for the given id", () => {
return dao.packageById(pkg.id).then(found => {
expect(found).not.to.be.undefined;
expect(found.appVersion).to.eq(pkg.appVersion);
expect(found.blobUrl).to.eq(pkg.blobUrl);
expect(found.created_).not.to.be.undefined;
expect(found.description).to.eq(pkg.description);
expect(found.id).to.eq(pkg.id);
expect(found.isDisabled).to.eq(pkg.isDisabled);
expect(found.isMandatory).to.eq(pkg.isMandatory);
expect(found.label).to.eq(pkg.label);
expect(found.manifestBlobUrl).to.eq(pkg.manifestBlobUrl);
expect(found.packageHash).to.eq(pkg.packageHash);
expect(found.releasedBy).to.eq(pkg.releasedBy);
expect(found.releaseMethod).to.eq(pkg.releaseMethod);
expect(found.rollout).to.eq(pkg.rollout);
expect(found.size).to.eq(pkg.size);
});
});
it("includes tags for a package if they are available", () => {
return dao.packageById(newPkgId).then(found => {
expect(found).not.to.be.undefined;
expect(found.appVersion).to.eq(pkg.appVersion);
expect(found.blobUrl).to.eq(pkg.blobUrl);
expect(found.created_).not.to.be.undefined;
expect(found.description).to.eq(pkg.description);
expect(found.id).to.eq(newPkgId);
expect(found.isDisabled).to.eq(pkg.isDisabled);
expect(found.isMandatory).to.eq(pkg.isMandatory);
expect(found.label).to.eq(pkg.label);
expect(found.manifestBlobUrl).to.eq(pkg.manifestBlobUrl);
expect(found.packageHash).to.eq(pkg.packageHash);
expect(found.releasedBy).to.eq(pkg.releasedBy);
expect(found.releaseMethod).to.eq(pkg.releaseMethod);
expect(found.rollout).to.eq(pkg.rollout);
expect(found.size).to.eq(pkg.size);
expect(found.tags).not.to.be.undefined;
if (found.tags) {
expect(found.tags.length > 0);
expect(found.tags).to.contain("TAG-1");
expect(found.tags).to.contain("TAG-2");
}
});
});
});
describe("updatePackage", () => {
it("will throw an error if the deployment key is not found", () => {
return dao.updatePackage("SomeJunkKey", {}, "").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will throw an error if there is no deployment package history", () => {
return dao.updatePackage(prodDeploymentKey, {}, "").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will update a few key fields for a package", () => {
const updateInfo = {
appVersion: "0.0.3",
description: "NewDescriptio for this package",
isDisabled: true,
isMandatory: true,
rollout: 94
};
return dao
.updatePackage(stageDeploymentKey, updateInfo, "")
.then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.appVersion).to.eq(updateInfo.appVersion);
expect(updated.description).to.eq(updateInfo.description);
expect(updated.isDisabled).to.eq(updateInfo.isDisabled);
expect(updated.isMandatory).to.eq(updated.isMandatory);
expect(updated.rollout).to.eq(updated.rollout);
expect(updated.blobUrl).to.eq(pkg.blobUrl);
expect(updated.label).to.eq(pkg.label);
expect(updated.manifestBlobUrl).to.eq(pkg.manifestBlobUrl);
expect(updated.packageHash).to.eq(pkg.packageHash);
expect(updated.releasedBy).to.eq(pkg.releasedBy);
expect(updated.releaseMethod).to.eq(pkg.releaseMethod);
expect(updated.size).to.eq(pkg.size);
});
});
it("will update a specific package if the package id is in package info", () => {
return dao.deploymentForKey(stageDeploymentKey).then((dep) => {
// We assert that the latest package in the deployment has a version of 0.0.3
expect(dep.package).to.not.be.undefined;
expect(dep.package.appVersion).to.equal("0.0.3");
return dao.history(appId, STAGING).then((hist) => {
// We also assert that there are 2 packages in this deployment
// If we pass the id in the update info, it should update that package
// NOT the latest package in the deployment.
expect(hist.length).to.equal(2);
expect(hist[1].description).to.equal("my new uploaded package");
const updateInfo = {
appVersion: "0.0.1",
description: "One for All",
id: hist[1].id,
isDisabled: true,
isMandatory: true,
rollout: 94,
};
return dao.updatePackage(stageDeploymentKey, updateInfo, "").then((updated) => {
expect(updated).to.not.be.undefined;
return dao.history(appId, STAGING).then((updatedHist) => {
expect(updatedHist[0].appVersion).to.equal("0.0.3");
expect(updatedHist[1].appVersion).to.equal("0.0.1");
expect(updatedHist[1].description).to.equal("One for All");
});
});
});
});
});
it("will add and/or remove diffPackageMaps", () => {
// create a new package
const newPkgHash = "2390f29j2jf892hf92n289nc29";
const newPkg = new PackageDTO();
Object.assign(newPkg, pkg);
newPkg.packageHash = newPkgHash;
const diffPackageMap: any = {};
diffPackageMap[newPkgHash] = {
size: 144103903,
url: "http://stuff.com/afoi320..."
};
const updateInfo = {
diffPackageMap
};
return dao.addPackage(stageDeploymentKey, newPkg).then(result => {
// adding
return dao
.updatePackage(stageDeploymentKey, updateInfo, "")
.then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.blobUrl).to.eq(pkg.blobUrl);
expect(updated.label).to.eq(pkg.label);
expect(updated.manifestBlobUrl).to.eq(pkg.manifestBlobUrl);
expect(updated.packageHash).to.eq(newPkgHash);
expect(updated.releasedBy).to.eq(pkg.releasedBy);
expect(updated.releaseMethod).to.eq(pkg.releaseMethod);
expect(updated.size).to.eq(pkg.size);
expect(updated.diffPackageMap).not.to.be.undefined;
expect(updated.diffPackageMap[newPkgHash]).not.to.be.undefined;
expect(updated.diffPackageMap[newPkgHash].size).to.eq(
diffPackageMap[newPkgHash].size
);
expect(updated.diffPackageMap[newPkgHash].url).to.eq(
diffPackageMap[newPkgHash].url
);
// removing
delete updateInfo.diffPackageMap[newPkgHash];
return dao
.updatePackage(stageDeploymentKey, updateInfo, "")
.then(postRemoval => {
expect(postRemoval).not.to.be.undefined;
expect(postRemoval.diffPackageMap).not.to.be.undefined;
expect(postRemoval.diffPackageMap[newPkgHash]).to.be
.undefined;
});
});
});
});
it("will add and/or remove tags", () => {
const newPkg = new PackageDTO();
Object.assign(newPkg, pkg);
return dao.addPackage(stageDeploymentKey, newPkg).then(() => {
const tags = ["TAG-1", "TAG-2", "TAG-3"];
const updateInfo = {
tags
};
return dao
.updatePackage(stageDeploymentKey, updateInfo, "")
.then(updated => {
expect(updated).not.to.be.undefined;
expect(updated.tags).not.to.be.undefined;
if (updated.tags) {
tags.forEach(tag => {
expect(updated.tags).to.contain(tag);
});
}
updateInfo.tags.push("TAGS-4");
// let's add some more tags
return dao
.updatePackage(stageDeploymentKey, updateInfo, "")
.then(moreTags => {
expect(moreTags).not.to.be.undefined;
expect(moreTags.tags).not.to.be.undefined;
if (moreTags.tags) {
updateInfo.tags.forEach(tag => {
expect(moreTags.tags).to.contain(tag);
});
}
// let's remove them
const nextUpdateInfo = {
tags: []
};
return dao
.updatePackage(stageDeploymentKey, nextUpdateInfo, "")
.then(nextUpdated => {
expect(nextUpdated).not.to.be.undefined;
expect(nextUpdated.tags).to.be.undefined;
});
});
});
});
});
});
describe("addPackageDiffMap", () => {
const appId = 432;
const deployKey = "qFOiefKJFOIJNkldsjfiuhgbojFIOWFBDfCFggzL"
const pkgOne = new PackageDTO();
pkgOne.appVersion = "1.0.0";
pkgOne.blobUrl = "http://stuff.com/package2/...";
pkgOne.manifestBlobUrl = "http://stuff.com/manifest2/..";
pkgOne.packageHash = "jnowfim20m3@@#%FMM@FK@K";
pkgOne.isDisabled = false;
pkgOne.isMandatory = false;
pkgOne.label = "v1";
pkgOne.rollout = 100;
pkgOne.size = 1600;
pkgOne.releaseMethod = "Upload";
pkgOne.releasedBy = email;
const pkgTwo = new PackageDTO();
Object.assign(pkgTwo, pkgOne);
pkgTwo.appVersion = "1.0.0";
pkgTwo.packageHash = "oiwjfriefjkjbgniohwef";
pkgTwo.label = "v2";
before(() => {
return dao.addDeployment(appId, STAGING, { key: deployKey })
})
it("adds package diff", () => {
let pkgId: number = 0;
const newDiff = {
size: 1838934,
url: "http://example.com/dowldkfj.."
}
return dao.addPackage(deployKey, pkgOne)
.then(() => dao.addPackage(deployKey, pkgTwo))
.then((savedPkg) => {
pkgId = savedPkg.id;
savedPkg.diffPackageMap = {[pkgOne.packageHash]:newDiff};
return dao.addPackageDiffMap(stageDeploymentKey, savedPkg, pkgOne.packageHash)
})
.then(() => dao.packageById(pkgId))
.then((pkg) => {
expect(pkg.diffPackageMap[pkgOne.packageHash]).deep.eq(newDiff);
});
});
});
describe("getNewestApplicablePackage", () => {
const deplKey: string = "3290fnf20jf02jfjwf0ij20fj209fj20j";
let deplId: number = 0;
let pkg1DTO: PackageDTO;
let pkg2DTO: PackageDTO;
let pkg3DTO: PackageDTO;
let pkg4DTO: PackageDTO;
let pkg5DTO: PackageDTO;
before(() => {
const appDTO = new AppDTO();
const permission = "Owner";
appDTO.name = "my new test app";
appDTO.collaborators = {};
appDTO.collaborators[email] = { permission };
appDTO.deployments = {};
appDTO.deployments[STAGING] = {
key: deplKey,
name: STAGING
};
return dao.createApp(appDTO).then(app => {
return dao.deploymentForKey(deplKey).then(deployment => {
deplId = deployment.id;
});
});
});
it("will return no package if there are no matching releases", () => {
return dao
.getNewestApplicablePackage(deplKey, undefined, undefined)
.then(newest => {
expect(newest).to.be.undefined;
});
});
it("will return a release with no tags if that release is the most up-to-date release", () => {
pkg1DTO = new PackageDTO();
pkg1DTO.appVersion = "1.0.0";
pkg1DTO.blobUrl = "http://stuff.com/package1/..";
pkg1DTO.packageHash = "2930fj2j923892f9h9f831899182889hf";
pkg1DTO.isDisabled = false;
pkg1DTO.isMandatory = false;
pkg1DTO.label = "v1";
pkg1DTO.manifestBlobUrl = "http://stuff.com/manifest1/...";
pkg1DTO.rollout = 100;
pkg1DTO.size = 1500;
pkg1DTO.releaseMethod = "Upload";
pkg1DTO.releasedBy = email;
return dao.addPackage(deplKey, pkg1DTO).then(updated => {
pkg1DTO.id = updated.id;
return dao
.getNewestApplicablePackage(deplKey, undefined, undefined)
.then(newest => {
expect(newest).not.to.be.undefined;
if (newest) {
expect(newest.id).to.eq(pkg1DTO.id);
}
});
});
});
it("will return a release with no tags if none of the incoming tags match", () => {
pkg2DTO = new PackageDTO();
pkg2DTO.appVersion = "1.0.0";
pkg2DTO.blobUrl = "http://stuff.com/package2/...";
pkg2DTO.manifestBlobUrl = "http://stuff.com/manifest2/..";
pkg2DTO.packageHash = "jnowfim20m3@@#%FMM@FK@K";
pkg2DTO.isDisabled = false;
pkg2DTO.isMandatory = false;
pkg2DTO.label = "v2";
pkg2DTO.rollout = 100;
pkg2DTO.size = 1600;
pkg2DTO.tags = ["TAG-1", "TAG-2"];
pkg2DTO.releaseMethod = "Upload";
pkg2DTO.releasedBy = email;
return dao.addPackage(deplKey, pkg2DTO).then(updated => {
pkg2DTO.id = updated.id;
return dao
.getNewestApplicablePackage(deplKey, undefined, undefined)
.then(newest => {
expect(newest).not.to.be.undefined;
if (newest) {
expect(newest.id).to.eq(pkg1DTO.id);
}
})
.then(() => {
return dao
.getNewestApplicablePackage(deplKey, ["TAG-3"], undefined)
.then(newest => {
expect(newest).not.to.be.undefined;
if (newest) {
expect(newest.id).to.eq(pkg1DTO.id);
}
});
});
});
});
it("will return a release with tags if at least one incoming tag matches", () => {
return dao
.getNewestApplicablePackage(deplKey, ["TAG-1", "TAG-3"], undefined)
.then(newest => {
expect(newest).not.to.be.undefined;
if (newest) {
expect(newest.id).to.eq(pkg2DTO.id);
}
});
});
it("will return a release if there is an intermediate release that matches the incoming tags", () => {
pkg3DTO = new PackageDTO();
Object.assign(pkg3DTO, pkg1DTO);
pkg3DTO.packageHash = "fion2ff@F#@NN@!@9100j1n1";
pkg3DTO.blobUrl = "https://stuff.com/package3/...";
pkg3DTO.manifestBlobUrl = "https://stuff.com/manifest3/...";
pkg3DTO.size = 1700;
pkg3DTO.label = "v3";
pkg3DTO.tags = ["TAG-4", "TAG-5", "TAG-6"];
return dao.addPackage(deplKey, pkg3DTO).then(updated => {
pkg3DTO.id = updated.id;
/*
At this point we have, in order of newest first:
pkg3 - ["TAG-4", "TAG-5", "TAG-6"]
pkg2 - ["TAG-1", "TAG-2"]
pkg1 - no tags
*/
return dao
.getNewestApplicablePackage(deplKey, ["TAG-2"], undefined)
.then(newest => {
expect(newest).not.to.be.undefined;
if (newest) {
expect(newest.id).to.eq(pkg2DTO.id);
}
});
});
});
it("will return a release if there is an intermediate release with no tags", () => {
pkg4DTO = new PackageDTO();
Object.assign(pkg4DTO, pkg1DTO);
pkg4DTO.packageHash = "wfn2i0f02390239gnbr2";
pkg4DTO.blobUrl = "https://stuff.com/package4/...";
pkg4DTO.manifestBlobUrl = "https://stuff.com/package4/...";
pkg4DTO.size = 1800;
pkg4DTO.label = "v4";
// no tags
return dao.addPackage(deplKey, pkg4DTO).then(updated => {
pkg4DTO.id = updated.id;
pkg5DTO = new PackageDTO();
Object.assign(pkg5DTO, pkg1DTO);
pkg4DTO.packageHash = "aio059gn2nf30920910189";
pkg4DTO.blobUrl = "https://stuff.com/package5/...";
pkg4DTO.manifestBlobUrl = "https://stuff.com/package5/...";
pkg4DTO.size = 1900;
pkg5DTO.label = "v5";
pkg5DTO.tags = ["TAG-10", "TAG-11", "TAG-12", "TAG-13", "TAG-14"];
return dao.addPackage(deplKey, pkg5DTO).then(updated5 => {
pkg5DTO.id = updated5.id;
/*
Now we have
pkg5 - ["TAG-10", "TAG-11", "TAG-12", "TAG-13", "TAG-14"]
pkg4 - no tags
pkg3 - ["TAG-4", "TAG-5", "TAG-6"]
pkg2 - ["TAG-1", "TAG-2"]
pkg1 - no tags
*/
return dao
.getNewestApplicablePackage(deplKey, [], undefined)
.then(newest => {
expect(newest).not.to.be.undefined;
if (newest) {
expect(newest.id).to.eq(pkg4DTO.id);
}
});
});
});
});
it("will return release matching specified appVersion", () => {
const versionToCheck = "1.1.0";
let v1pkg = new PackageDTO();
Object.assign(v1pkg, pkg1DTO, {
appVersion: versionToCheck,
packageHash: "2930fj2j923892f9h9f831899182889hf",
label: "v1"
});
let v2pkg = new PackageDTO();
Object.assign(v2pkg, v1pkg, {
appVersion: "1.2.0",
packageHash: "ABCDEFG",
label: "v2"
});
return dao
.addPackage(deplKey, v1pkg)
.then(() => {
return dao.addPackage(deplKey, v2pkg);
})
.then(() => {
return dao
.getNewestApplicablePackage(deplKey, [], versionToCheck)
.then(release => {
expect(release).not.be.undefined;
if (release) {
expect(release.packageHash).to.eq(v1pkg.packageHash);
}
});
});
});
it("will return latest release matching specified appVersion", () => {
const versionToCheck = "1.3.0";
let v1apkg = new PackageDTO();
Object.assign(v1apkg, pkg1DTO, {
appVersion: versionToCheck,
packageHash: "ABCDEF1234",
label: "v1"
});
let v1bpkg = new PackageDTO();
Object.assign(v1bpkg, v1apkg, {
appVersion: versionToCheck,
packageHash: "ABCDEF7890",
label: "v2"
});
let v2pkg = new PackageDTO();
Object.assign(v2pkg, v1apkg, {
appVersion: "1.4.0",
packageHash: "EDCBA44321",
label: "v3"
});
return dao
.addPackage(deplKey, v1apkg)
.then(() => {
return dao.addPackage(deplKey, v1bpkg);
})
.then(() => {
return dao.addPackage(deplKey, v2pkg);
})
.then(() => {
return dao
.getNewestApplicablePackage(deplKey, [], versionToCheck)
.then(release => {
expect(release).not.be.undefined;
if (release) {
expect(release.packageHash).to.eq(v1bpkg.packageHash);
}
});
});
});
it("will return latest release for unmatched appVersion", () => {
const versionToCheck = "1.8.0";
let v1pkg = new PackageDTO();
Object.assign(v1pkg, pkg1DTO, {
appVersion: "1.7.0",
packageHash: "ACEBDF135246",
label: "v1"
});
let v2pkg = new PackageDTO();
Object.assign(v2pkg, pkg1DTO, {
appVersion: "1.9.0",
packageHash: "A1C3E5B2D4F6",
label: "v2"
});
return dao
.addPackage(deplKey, v1pkg)
.then(() => {
return dao.addPackage(deplKey, v2pkg);
})
.then(() => {
return dao
.getNewestApplicablePackage(deplKey, [], versionToCheck)
.then(release => {
expect(release).not.be.undefined;
if (release) {
expect(release.packageHash).to.eq(v2pkg.packageHash);
}
});
});
});
let matchPackage = (
packageList: any[],
searchCriteria: { tags: string[]; appVersion: string },
matchLabel: string | null
) => {
let allPkgs = packageList.map(pkg => {
let dtoPkg = new PackageDTO();
Object.assign(dtoPkg, pkg1DTO, pkg);
return dao.addPackage(deplKey, dtoPkg);
});
return Promise.all(allPkgs)
.then(() =>
dao.getNewestApplicablePackage(
deplKey,
searchCriteria.tags,
searchCriteria.appVersion
)
)
.then(release => {
if (matchLabel) {
expect(release).not.to.be.undefined;
if (release) {
expect(release.label).to.eq(matchLabel);
}
} else {
expect(release).to.be.undefined;
}
});
};
it("will return release matching appVersion and tag", () => {
const appVersion = "2.1.0";
return matchPackage(
[
{ appVersion, label: "v1", tags: ["PARROT", "EAGLE"] },
{ appVersion, label: "v2", tags: ["SNOOPY", "PITBULL"] },
{ appVersion, label: "v3", tags: ["EAGLE"] }
],
{ appVersion, tags: ["PITBULL"] },
"v2"
);
});
it("will return release for matching tag if not matching appVersion", () => {
return matchPackage(
[{ appVersion: "2.9.0", label: "v23", tags: ["MATCHME"] }],
{ appVersion: "3.1.0", tags: ["MATCHME"] },
"v23"
);
});
it("will return a untagged release if matching appVersion but not tag", () => {
const appVersion = "4.0.4";
return matchPackage(
[
{ appVersion, label: "v33", tags: ["BINGO"] },
{ appVersion, label: "v34", tags: ["GOFISH"] }
],
{ appVersion, tags: ["NOGAMES"] },
"v2"
);
});
it("will return a untagged release for matching appVersion against tagged release", () => {
const appVersion = "5.0.5";
return matchPackage(
[{ tags: ["TOYOTA"], label: "v44", appVersion }],
{ tags: [], appVersion },
"v2"
);
});
});
});
describe("history-related methods", () => {
describe("history", () => {
it("will throw an error if app not found", () => {
return dao.history(-100, "stuff").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will throw an error if deployment not found", () => {
return dao.history(appId, "strange deployment name").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will return the correct packages if deployment names are similar", () => {
return dao.addDeployment(appId, INTLSTAGING, { key : intlStageDeploymentKey }).then((dep) => {
const pkg6 = new PackageDTO();
pkg6.appVersion = "7.7.7";
pkg6.blobUrl = "http://stuff.com/pkg...";
pkg6.description = "Plus Ultra!";
pkg6.isDisabled = false;
pkg6.isMandatory = false;
pkg6.label = "v1";
pkg6.manifestBlobUrl = "http://stuff.com/manifest...";
pkg6.packageHash = packageHash;
pkg6.releasedBy = "testUser";
pkg6.releaseMethod = "Upload";
pkg6.rollout = 100;
pkg6.size = 12908201;
pkg6.tags = ["TAG-10", "TAG-11", "TAG-12", "TAG-13", "TAG-14"];
return dao.addPackage(intlStageDeploymentKey, pkg6).then(() => {
return dao.history(appId, INTLSTAGING).then((packages) => {
expect(packages).not.to.be.undefined;
expect(packages.length).to.be.eq(1);
expect(packages[0].description).to.equal("Plus Ultra!");
expect(packages[0].appVersion).to.equal("7.7.7");
});
});
});
});
it("returns a list of packages for an app and deployment", () => {
return dao.history(appId, STAGING).then(packages => {
expect(packages).not.to.be.undefined;
expect(packages.length).to.be.gte(1);
expect(packages[0].id).not.to.be.undefined;
expect(packages[0].packageHash).not.to.be.undefined;
expect(packages[0].diffPackageMap).not.to.be.undefined;
});
});
it("returns an empty list for deployment with no history", () => {
return dao.history(appId, PROD).then(packages => {
expect(packages).not.to.be.undefined;
expect(packages.length).to.eq(0);
});
});
});
describe("historyByIds", () => {
it("gets a list of packages by id", () => {
return dao.historyByIds([pkgId]).then(packages => {
expect(packages).not.to.be.undefined;
expect(packages.length).to.eq(1);
expect(packages[0].id).to.eq(pkgId);
expect(packages[0].packageHash).to.eq(packageHash);
});
});
});
describe("historyLabel", () => {
it("will throw an error if a deployment has no package history", () => {
return dao.historyLabel(appId, PROD, "").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will throw an error if there are no packages with the given label", () => {
return dao.historyLabel(appId, STAGING, "").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("gets a package for an app and deployment by label", () => {
return dao.historyLabel(appId, STAGING, "v1").then(pkg => {
expect(pkg).not.to.be.undefined;
expect(pkg.label).to.eq("v1");
});
});
});
});
describe("client ratio-related methods", () => {
const clientUniqueId = "390f9jf29j109jf90829f2983f92n";
const initRatio = 50;
const initUpdated = false;
const newRatio = 75;
const newUpdated = true;
describe("insertClientRatio", () => {
it("will throw an error if the packageHash is not found", () => {
// tslint:disable-next-line:max-line-length
return dao
.insertClientRatio(
clientUniqueId,
"SomeJunkHash",
initRatio,
initUpdated
)
.catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will add a new client ratio record", () => {
return dao
.insertClientRatio(
clientUniqueId,
packageHash,
initRatio,
initUpdated
)
.then(() => {
return dao.getConnection().then(connection => {
return new Promise((resolve, reject) => {
connection.query(
`SELECT client_unique_id, package_id, create_time,
ratio, is_updated
FROM client_ratio
WHERE client_unique_id = ?`,
[clientUniqueId],
(err, results) => {
if (err) {
reject(err);
} else {
expect(results).not.to.be.undefined;
expect(results.length).to.eq(1);
expect(results[0].client_unique_id).to.eq(
clientUniqueId
);
expect(results[0].ratio).to.eq(initRatio);
expect(results[0].is_updated === 1).to.eq(initUpdated);
resolve();
}
}
);
});
});
});
});
it("will update an existing record", () => {
return dao
.insertClientRatio(
clientUniqueId,
packageHash,
newRatio,
newUpdated
)
.then(() => {
return dao.getConnection().then(connection => {
return new Promise((resolve, reject) => {
connection.query(
`SELECT client_unique_id, package_id, create_time,
ratio, is_updated
FROM client_ratio
WHERE client_unique_id = ?`,
[clientUniqueId],
(err, results) => {
if (err) {
reject(err);
} else {
expect(results).not.to.be.undefined;
expect(results.length).to.eq(1);
expect(results[0].client_unique_id).to.eq(
clientUniqueId
);
expect(results[0].ratio).to.eq(newRatio);
expect(results[0].is_updated === 1).to.eq(newUpdated);
resolve();
}
}
);
});
});
});
});
});
describe("clientRatio", () => {
it("will return undefined if package hash is not found", () => {
return dao
.clientRatio(clientUniqueId, "SomeJunkHash")
.then(clientRatio => {
expect(clientRatio).to.be.undefined;
});
});
it("will return undefined with an unknown client id", () => {
return dao
.clientRatio("someOtherUniqueClientId", packageHash)
.then(clientRatio => {
expect(clientRatio).to.be.undefined;
});
});
it("will return client ratio records for client id and package hash", () => {
return dao
.clientRatio(clientUniqueId, packageHash)
.then(clientRatio => {
expect(clientRatio).not.to.be.undefined;
if (clientRatio) {
expect(clientRatio.clientUniqueId).to.eq(clientUniqueId);
expect(clientRatio.inserted).not.to.be.undefined;
expect(clientRatio.packageHash).to.eq(packageHash);
expect(clientRatio.updated).to.eq(newUpdated);
}
});
});
});
});
describe("metric-related methods", () => {
const appVersion = "0.0.1";
const clientUniqueId = "1290jf02f20j032j92f9n39238929212c2c2";
const label = "v1";
const status = "DeploymentSucceeded";
const metricIn = new MetricInDTO();
metricIn.deploymentKey = stageDeploymentKey;
metricIn.appVersion = appVersion;
metricIn.clientUniqueId = clientUniqueId;
metricIn.label = label;
metricIn.status = status;
describe("insertMetric", () => {
it("will throw an error if the deployment key is not found", () => {
metricIn.deploymentKey = "SomeJunkKey";
return dao.insertMetric(metricIn).catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will add a metric record to the table", () => {
metricIn.deploymentKey = stageDeploymentKey;
return dao.insertMetric(metricIn).then(() => {
return dao.getConnection().then(connection => {
return new Promise((resolve, reject) => {
connection.query(
"SELECT COUNT(*) AS count FROM metric WHERE deployment_id = " +
"(SELECT id FROM deployment WHERE deployment_key = ?)",
[stageDeploymentKey],
(err, results) => {
if (err) {
reject(err);
} else {
expect(results).not.to.be.undefined;
expect(results.length).to.eq(1);
expect(results[0].count).to.be.gte(1);
resolve();
}
}
);
});
});
});
});
});
describe("metrics", () => {
it("will throw an error if the deployment key is not found", () => {
return dao.metrics("SomeJunkKey").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("will fetch all the metrics for a deployment", () => {
return dao.metrics(stageDeploymentKey).then(metrics => {
expect(metrics).not.to.be.undefined;
if (metrics) {
expect(metrics.length).to.be.gte(1);
const found = metrics.find(result => {
return result.clientuniqueid === clientUniqueId;
});
expect(found).not.to.be.undefined;
if (found) {
expect(found.appversion).to.eq(appVersion);
expect(found.label).to.eq(label);
expect(found.status).to.eq(status);
}
}
});
});
});
describe("metrics summary", () => {
const appVersion = "0.0.1";
const clientUniqueId = "1290jf02f20j032j92f9n39238929212c2c2";
const label = "v1";
const status = "DeploymentSucceeded";
before(() => {
const metricData = [
{ label: "v1", appVersion: "1.0.0", status: "DeploymentSucceeded" },
{ label: "v1", appVersion: "1.0.0", status: "DeploymentSucceeded" },
{ label: "v1", appVersion: "1.0.0", status: "DeploymentFailed" },
{ label: "v1", appVersion: "1.1.0", status: "DeploymentFailed" },
{ label: "v2", appVersion: "1.0.0", status: "Downloaded" },
{ label: "v2", appVersion: "1.0.0", status: "Downloaded" },
{ label: "v2", appVersion: "1.2.0", status: "DeploymentSucceeded" },
{ label: "v3", appVersion: "1.2.0", status: "DeploymentFailed" },
{ label: "v3", appVersion: "1.1.0", status: "DeploymentSucceeded" },
{ label: "v2", appVersion: "1.0.0", status: "Downloaded" },
{ label: "v3", appVersion: "1.1.0", status: "DeploymentSucceeded" },
{ label: "v3", appVersion: "1.2.0", status: "DeploymentFailed" }
];
let p = [];
for (let i = 0; i < metricData.length; i++) {
const metricIn = new MetricInDTO();
metricIn.label = metricData[i].label;
metricIn.appVersion = metricData[i].appVersion;
metricIn.status = metricData[i].status;
metricIn.deploymentKey = prodDeploymentKey;
metricIn.clientUniqueId = clientUniqueId;
p.push(dao.insertMetric(metricIn));
}
return Promise.all(p);
});
it("will throw an error if the deployment key is not found", () => {
return dao.metricsByStatus("SomeJunkKey").catch(err => {
expect(err).not.to.be.undefined;
expect(err.toString()).to.contain("Not found");
});
});
it("fetch summary of metrics for a deployment", () => {
const assertCount = (
list: MetricByStatusOutDTO[],
label: string,
version: string,
status: string,
total: number
) => {
const found = list.find(item => {
return (
item.label.toString() === label &&
item.appversion.toString() === version &&
item.status.toString() === status
);
});
expect(found).not.to.be.undefined;
if (found) expect(found.total).to.eq(total);
};
return dao.metricsByStatus(prodDeploymentKey).then(metrics => {
expect(metrics).not.to.be.undefined;
expect(metrics.length).to.be.eq(7);
assertCount(metrics, "v1", "1.0.0", "DeploymentSucceeded", 2);
assertCount(metrics, "v1", "1.0.0", "DeploymentFailed", 1);
assertCount(metrics, "v1", "1.1.0", "DeploymentFailed", 1);
assertCount(metrics, "v2", "1.0.0", "Downloaded", 3);
assertCount(metrics, "v2", "1.2.0", "DeploymentSucceeded", 1);
assertCount(metrics, "v3", "1.1.0", "DeploymentSucceeded", 2);
assertCount(metrics, "v3", "1.2.0", "DeploymentFailed", 2);
});
});
it("fetch summary of metrics by status and time", () => {
const metricData = [
{ label: "v1", appVersion: "1.0.0", status:"DeploymentSucceeded"},
{ label: "v1", appVersion: "1.0.0", status:"Downloaded"},
{ label: "v2", appVersion: "1.2.0", status:"Downloaded"},
{ label: "v2", appVersion: "1.2.5", status:"DeploymentFailed"},
{ label: "v3", appVersion: "1.3.0", status:"DeploymentFailed"},
{ label: "v3", appVersion: "1.3.5", status:"Downloaded"}
]
let phase1 = createMetricInDTOs(metricDeploymentKey, metricData.slice(0,2));
let phase2 = createMetricInDTOs(metricDeploymentKey, metricData.slice(2,6));
const startTime = new Date(Date.now() - 1000);
let midTime:Date;
return Promise.all(phase1.map(d => dao.insertMetric(d)))
.then(() => {
midTime = new Date(Date.now());
return new Promise(resolve => setTimeout(resolve, 2000));
})
.then(() => {
return Promise.all(phase2.map(d => dao.insertMetric(d)));
})
.then(() => {
return dao.metricsByStatusAndTime(metricDeploymentKey, startTime, midTime)
})
.then(metrics => {
expect(metrics.length).eq(2);
const endTime = new Date(Date.now());
return dao.metricsByStatusAndTime(metricDeploymentKey, midTime, endTime);
}).then(metrics => {
expect(metrics.length).eq(4);
});
});
it("fetch summary of metrics by status, after given specific time", () => {
const metricData = [
{ label: "v1", appVersion: "1.0.0", status:"DeploymentSucceeded"},
{ label: "v1", appVersion: "1.0.0", status:"Downloaded"},
{ label: "v2", appVersion: "1.2.0", status:"Downloaded"},
{ label: "v2", appVersion: "1.2.5", status:"DeploymentFailed"},
{ label: "v3", appVersion: "1.3.0", status:"DeploymentFailed"},
{ label: "v3", appVersion: "1.3.5", status:"Downloaded"}
]
let phase1 = createMetricInDTOs(metricDeploymentKey, metricData.slice(0,2));
let phase2 = createMetricInDTOs(metricDeploymentKey, metricData.slice(2,6));
const startTime = new Date(Date.now() - 1000);
return Promise.all(phase1.map(d => dao.insertMetric(d)))
.then(() => {
return new Promise(resolve => setTimeout(resolve, 2000));
})
.then(() => {
return Promise.all(phase2.map(d => dao.insertMetric(d)));
})
.then(() => {
return dao.metricsByStatusAfterSpecificTime(metricDeploymentKey, startTime)
})
.then(metrics => {
expect(metrics.length).eq(6);
});
});
});
describe("real-time metrics", () => {
const deplKey: string = "3290fnf20jf02jfjwf0ij20fj209fj20j";
const metricDeplKey: string = "cJ3PGiq4Z3SQ3IEpivV4VuXF5lTDylmdMNeY1CALJrw=";
const email = "test@tests.com";
const newPkg = new PackageDTO();
newPkg.appVersion = "1.5.0";
newPkg.blobUrl = "http://stuff.com/package1/..";
newPkg.packageHash = "2930fj2j923892f9h9f831899182889hfa5b";
newPkg.isDisabled = false;
newPkg.isMandatory = false;
newPkg.label = "v5";
newPkg.manifestBlobUrl = "http://stuff.com/manifest1/...";
newPkg.rollout = 100;
newPkg.size = 1500;
newPkg.releaseMethod = "Promote";
newPkg.releasedBy = email;
const add6PacksOfApp1 = () => {
let v1pkg = new PackageDTO();
Object.assign(v1pkg, newPkg, {
appVersion: "1.6.0",
packageHash: "ACEBDF13524678",
label: "v6"
});
let v2pkg = new PackageDTO();
Object.assign(v2pkg, newPkg, {
appVersion: "1.7.0",
packageHash: "A1C3E5B2D4F687",
label: "v7"
});
let v3pkg = new PackageDTO();
Object.assign(v3pkg, newPkg, {
appVersion: "1.8.0",
packageHash: "ACEBDF13524786",
label: "v8"
});
let v4pkg = new PackageDTO();
Object.assign(v4pkg, newPkg, {
appVersion: "1.9.0",
packageHash: "A1C3E5B2D4F876",
label: "v9"
});
let v5pkg = new PackageDTO();
Object.assign(v5pkg, newPkg, {
appVersion: "1.10.0",
packageHash: "ACEBDF135246789",
label: "v10"
});
let v6pkg = new PackageDTO();
Object.assign(v6pkg, newPkg, {
appVersion: "1.11.0",
packageHash: "A1C3E5B2D4F6987",
label: "v11"
});
return Promise.all([v1pkg,v2pkg,v3pkg,v4pkg,v5pkg,v6pkg].map(p => dao.addPackage(deplKey, p)));
}
const add2PacksOfApp2 = () => {
let v1pkg = new PackageDTO();
Object.assign(v1pkg, newPkg, {
appVersion: "2.1.0",
packageHash: "ACEBDF1352467852",
label: "v21"
});
let v2pkg = new PackageDTO();
Object.assign(v2pkg, newPkg, {
appVersion: "2.2.0",
packageHash: "A1C3E5B2D4F68725",
label: "v22"
});
return Promise.all([v1pkg,v2pkg].map(p => dao.addPackage(metricDeplKey, p)));
}
it("should retrieve real time metrics for last promoted version", () => {
const metricData = [
{ label: "v5", appVersion: "1.5.0", status:"DeploymentSucceeded"},
{ label: "v5", appVersion: "1.5.0", status:"Downloaded"},
{ label: "v3", appVersion: "1.3.5", status:"Downloaded"}
]
let metricsData = createMetricInDTOs(deplKey, metricData);
const startTime = new Date(Date.now() - 1000);
return dao.addPackage(deplKey, newPkg)
.then(() => {
return Promise.all(metricsData.map(d => dao.insertMetric(d)));
})
.then(() => {
return dao.metricsByStatusAfterSpecificTime(deplKey, startTime)
})
.then(metrics => {
expect(metrics.length).eq(2);
});
});
it("should retrieve real time metrics for multiple recently promoted versions", () => {
const metricData1 = [
{ label: "v6", appVersion: "1.6.0", status:"DeploymentSucceeded"},
{ label: "v6", appVersion: "1.6.0", status:"Downloaded"},
{ label: "v7", appVersion: "1.7.0", status:"DeploymentSucceeded"},
{ label: "v7", appVersion: "1.7.0", status:"Downloaded"},
{ label: "v8", appVersion: "1.8.0", status:"DeploymentSucceeded"},
{ label: "v8", appVersion: "1.8.0", status:"Downloaded"},
{ label: "v9", appVersion: "1.9.0", status:"DeploymentSucceeded"},
{ label: "v9", appVersion: "1.9.0", status:"Downloaded"},
{ label: "v10", appVersion: "1.10.0", status:"DeploymentSucceeded"},
{ label: "v10", appVersion: "1.10.0", status:"Downloaded"},
{ label: "v11", appVersion: "1.11.0", status:"DeploymentSucceeded"},
{ label: "v11", appVersion: "1.11.0", status:"Downloaded"}
];
const metricData2 = [
{ label: "v21", appVersion: "2.1.0", status:"DeploymentSucceeded"},
{ label: "v21", appVersion: "2.1.0", status:"Downloaded"},
{ label: "v22", appVersion: "2.2.0", status:"DeploymentSucceeded"},
{ label: "v22", appVersion: "2.2.0", status:"Downloaded"}
];
let metricsData1 = createMetricInDTOs(deplKey, metricData1);
let metricsData2 = createMetricInDTOs(metricDeplKey, metricData2);
const startTime = new Date(Date.now() - 1000);
return add6PacksOfApp1()
.then(() => {
return add2PacksOfApp2();
})
.then(() => {
return Promise.all(metricsData1.map(d => dao.insertMetric(d)));
})
.then(() => {
return Promise.all(metricsData2.map(d => dao.insertMetric(d)));
})
.then(() => {
return dao.metricsByStatusAfterSpecificTime(deplKey, startTime)
})
.then(metrics => {
expect(metrics.length).eq(6);
})
.then(() => {
return dao.metricsByStatusAfterSpecificTime(metricDeplKey, startTime)
})
.then(metrics => {
expect(metrics.length).eq(4);
});
});
});
});
describe("upload / download methods", () => {
describe("upload", () => {
it("saves the package content", () => {
const buffer = readFileSync("./test/testContentFile.json");
return dao.upload(packageHash, buffer).then(() => {
expect(true).to.eq(true);
return new Promise((resolve, reject) => {
dao.getConnection().then(connection => {
connection.query(
`SELECT COUNT(pc.package_hash) AS count
FROM package_content pc
WHERE pc.package_hash = ?`,
[packageHash],
(e, result) => {
expect(result).not.to.be.undefined;
expect(result.length).to.be.greaterThan(0);
expect(result[0].count).to.eq(1);
resolve();
}
);
});
});
});
});
});
describe("download", () => {
it("fetches the package content", () => {
return dao.download(packageHash).then(content => {
expect(content).not.to.be.undefined;
const expected = readFileSync("./test/testContentFile.json");
expect(content.toString()).to.eq(expected.toString());
});
});
});
});
describe("destructive methods", () => {
describe("clearHistory", () => {
it("deletes all package history for the given app and deployment", () => {
return dao.clearHistory(appId, STAGING).then(() => {
return dao.history(appId, STAGING).then(packages => {
expect(packages).not.to.be.undefined;
expect(packages.length).to.eq(0);
});
});
});
});
describe("removeApp", () => {
before(() => {
const pkg = new PackageDTO();
pkg.appVersion = "0.0.1";
pkg.blobUrl = "http://stuff.com/pkg...";
pkg.description = "my new uploaded package";
pkg.isDisabled = false;
pkg.isMandatory = false;
pkg.label = "v1";
pkg.manifestBlobUrl = "http://stuff.com/manifest...";
pkg.packageHash = packageHash;
pkg.releasedBy = "testUser";
pkg.releaseMethod = "Upload";
pkg.rollout = 100;
pkg.size = 12908201;
return dao.addPackage(stageDeploymentKey, pkg);
});
it("removes an app and all its sub-tables from the db", () => {
return dao.removeApp(appId).then(() => {
return dao.getConnection().then(connection => {
return new Promise((resolve, reject) => {
// tslint:disable-next-line:max-line-length
connection.query(
"SELECT COUNT(*) AS count FROM app WHERE id = ?",
[appId],
(err, result) => {
if (err) {
reject(err);
} else {
expect(result).not.to.be.undefined;
expect(result.length).to.eq(1);
expect(result[0].count).to.eq(0);
resolve();
}
}
);
});
});
});
});
});
});
});
describe("error scenarios", () => {
const myDAO = new MyDAO();
before(() => {
return myDAO.connect(testDBConfig).catch(err => {
expect(err).not.to.be.undefined;
});
});
it("will throw an error if there's a problem getting a connection", () => {
return myDAO.getConnection().catch(err => {
expect(err).not.to.be.undefined;
});
});
it("will throw an error if there's a problem ending the pool", () => {
return myDAO.close().catch(err => {
expect(err).not.to.be.undefined;
});
});
});
describe("encrypted fields", () => {
const createdTime = Date.now();
const expires = createdTime + 60 * 24 * 3600 * 1000;
const encryptedDao = new ElectrodeOtaDaoRdbms();
const userDTO = new UserDTO();
const keyName = "2903j09fj920j10jf";
userDTO.email = "encrypt_me@walmart.com";
userDTO.name = "Encrypt Me";
userDTO.accessKeys = {};
userDTO.accessKeys[keyName] = {
createdBy: undefined,
createdTime,
description: "better encrypt me too",
email: userDTO.email,
expires,
friendlyName: "A name that should be encrypted",
id: "some junk",
name: keyName
};
before(() => {
return Encryptor.instance
.initialize(testDBConfig.encryptionConfig)
.then(() =>
encryptedDao.connect(testDBConfig).then(() => {
return encryptedDao.getConnection().then(conn => clearTables(conn));
})
);
});
after(() => {
return encryptedDao.close();
});
it("User saved with encrypted email", () => {
// Test encryption is enabled
expect(Encryptor.instance.encrypt("user.email", userDTO.email)).to.not.eq(
userDTO.email
);
expect(
Encryptor.instance.encrypt(
"access_key.friendly_name",
userDTO.accessKeys[keyName].friendlyName
)
).to.not.eq(userDTO.accessKeys[keyName].friendlyName);
expect(
Encryptor.instance.encrypt(
"access_key.description",
userDTO.accessKeys[keyName].description
)
).to.not.eq(userDTO.accessKeys[keyName].description);
// Test email and name stored encrypted
return encryptedDao
.createUser(userDTO)
.then(createdUser => {
expect(createdUser.email).to.eq(userDTO.email);
expect(createdUser.name).to.eq(userDTO.name);
expect(createdUser.accessKeys).not.to.be.undefined;
expect(createdUser.accessKeys[keyName]).not.to.be.undefined;
expect(createdUser.accessKeys[keyName].friendlyName).to.eq(
userDTO.accessKeys[keyName].friendlyName
);
expect(createdUser.accessKeys[keyName].description).to.eq(
userDTO.accessKeys[keyName].description
);
return createdUser;
})
.then(createdUser => {
return encryptedDao.getConnection().then(conn => {
return new Promise((resolve, reject) => {
conn.query(
`SELECT email, name FROM user WHERE email = ?`,
[Encryptor.instance.encrypt("user.email", createdUser.email)],
(err, results) => {
if (err) {
reject(err);
} else {
expect(results.length).to.eq(1);
expect(
Encryptor.instance.decrypt("user.email", results[0].name)
).to.eq(userDTO.name);
conn.query(
"SELECT name, friendly_name, description FROM access_key WHERE user_id = ?",
[createdUser.id],
(err, accessKeyResults) => {
if (err) {
reject(err);
} else {
expect(accessKeyResults.length).to.eq(1);
expect(accessKeyResults[0].name).to.eq(keyName);
expect(
Encryptor.instance.decrypt(
"access_key.friendly_name",
accessKeyResults[0].friendly_name
)
).to.eq(userDTO.accessKeys[keyName].friendlyName);
expect(
Encryptor.instance.decrypt(
"access_key.description",
accessKeyResults[0].description
)
).to.eq(userDTO.accessKeys[keyName].description);
resolve();
}
}
);
}
}
);
});
});
});
});
it("Save package with encrypted email", () => {
const pkg = new PackageDTO();
pkg.appVersion = "0.0.1";
pkg.blobUrl = "http://example.com/encrypt";
pkg.description = "Encrypt package description";
pkg.isDisabled = pkg.isMandatory = false;
pkg.label = "v1";
pkg.manifestBlobUrl = "http://example.com/manifest";
pkg.packageHash = "hash";
pkg.releasedBy = "secret_user@walmart.com";
pkg.releaseMethod = "download";
pkg.rollout = 100;
pkg.size = 1001;
expect(
Encryptor.instance.encrypt("package.released_by", pkg.releasedBy)
).to.not.eq(pkg.releasedBy);
return encryptedDao
.addDeployment(appId, STAGING, { key: stageDeploymentKey })
.then(() => encryptedDao.addPackage(stageDeploymentKey, pkg))
.then(updated => {
expect(updated.releasedBy).to.eql(pkg.releasedBy);
return encryptedDao.getConnection().then(conn => {
return new Promise((resolve, reject) => {
conn.query(
`SELECT released_by FROM package where id=?`,
[updated.id],
(err, results) => {
if (err) {
reject(err);
} else {
expect(results.length).to.eq(1);
expect(
Encryptor.instance.decrypt(
"package.released_by",
results[0].released_by
)
).to.eq(updated.releasedBy);
resolve();
}
}
);
});
});
});
});
describe("encryptDTO", () => {
it("can encrypt certain fields in a UserDTO", () => {
const email = "encrypt_me@walmart.com";
const name = "Encrypt Me";
const userDTO = new UserDTO();
userDTO.email = email;
userDTO.name = name;
Encryptor.instance.encryptDTO(userDTO);
expect(userDTO.email).not.to.eq(email);
expect(userDTO.name).not.to.eq(name);
});
it("can encrypt certain fields in a PackageDTO", () => {
const releasedBy = "secret_user@walmart.com";
const appVersion = "0.0.1";
const blobUrl = "http://example.com/encrypt";
const description = "Encrypt package description";
const label = "v1";
const manifestBlobUrl = "http://example.com/manifest";
const packageHash = "hash";
const releaseMethod = "upload";
const rollout = 100;
const size = 1001;
const pkg = new PackageDTO();
pkg.appVersion = appVersion;
pkg.blobUrl = blobUrl;
pkg.description = description;
pkg.isDisabled = pkg.isMandatory = false;
pkg.label = label;
pkg.manifestBlobUrl = manifestBlobUrl;
pkg.packageHash = packageHash;
pkg.releasedBy = releasedBy;
pkg.releaseMethod = releaseMethod;
pkg.rollout = rollout;
pkg.size = size;
Encryptor.instance.encryptDTO(pkg);
expect(pkg.releasedBy).not.to.eq(releasedBy);
expect(pkg.appVersion).to.eq(appVersion);
expect(pkg.blobUrl).to.eq(blobUrl);
expect(pkg.description).to.eq(description);
expect(pkg.label).to.eq(label);
expect(pkg.manifestBlobUrl).to.eq(manifestBlobUrl);
expect(pkg.releaseMethod).to.eq(releaseMethod);
expect(pkg.rollout).to.eq(rollout);
expect(pkg.size).to.eq(size);
});
it("will only encrypt certain DTOs", () => {
const appDTO = new AppDTO();
const appName = "My Cool App";
appDTO.name = appName;
Encryptor.instance.encryptDTO(appDTO);
expect(appDTO.name).to.eq(appName);
Encryptor.instance.decryptDTO(appDTO);
expect(appDTO.name).to.eq(appName);
});
});
describe("Encryptor init", () => {
it("will fail if the key file is specified but does not exist", () => {
const badConfig = {
keyfile: "./test/missing.key"
};
const local = new Encryptor();
local
.initialize(badConfig)
.then(() => {
// should not come here
expect(true).to.eq(false);
})
.catch(err => {
expect(err).not.to.be.undefined;
});
});
it("will not do anything if there is no key file", () => {
const local = new Encryptor();
const noKeyConfig = {
fields: [
"user.name",
"user.email",
"package.released_by",
"access_key.friendly_name",
"access_key.description"
]
};
local.initialize(noKeyConfig).then(() => {
const email = "encrypt_me@walmart.com";
const name = "Encrypt Me";
const userDTO = new UserDTO();
userDTO.email = email;
userDTO.name = name;
local.encryptDTO(userDTO);
expect(userDTO.email).to.eq(email);
expect(userDTO.name).to.eq(name);
});
});
});
});
}); | the_stack |
import {DragResponse, Point} from "./draggable.directive";
import {FlowchartUtils} from "./flowchart-utils";
import {MouseOverState, MouseOverType} from "./model/mouse-over-state";
import {Component, ElementRef, Input, Output, EventEmitter, OnInit, OnChanges, SimpleChanges, KeyValueChangeRecord, KeyValueDiffer, KeyValueDiffers, Renderer, DoCheck} from "@angular/core";
import {DragSelectionRect} from "./model/drag-selection-rect";
import {DragState} from "./model/drag-state";
import {FlowChart} from "./model/flow-chart.model"
import * as _ from "underscore";
@Component({
selector:'flow-chart',
styleUrls:['./flow-chart.component.scss'],
templateUrl:'./flow-chart.component.html'
})
export class FlowChartComponent implements OnInit{
// The class for connections and connectors.
connectionClass = 'flow-connection';
connectorClass = 'flow-connector';
nodeClass = 'flow-node';
/**
* The bounding box
*/
dragSelectionRect: DragSelectionRect;
@Input()
chart: FlowChart.ChartViewModel;
//Connector attrs
dragPoint1:Point;
dragPoint2:Point;
dragTangent1:Point;
dragTangent2:Point;
/**
* the size of the radius of the circle connector
* @type {number}
*/
connectorSize: number = 10;
/**
* The SVG element needed to translate coords
*/
private svgElement:Element;
public dragState:DragState = new DragState();
private mouseOverState:MouseOverState = new MouseOverState();
constructor(public element: ElementRef) {
}
/**
* Mouse down event on the entire SVG canvas
*/
onMouseDown() {
this.chart.deselectAll();
}
onMouseUp(evt:MouseEvent){
if(this.dragState.isDraggingConnection()){
this.onConnectorDragEnded();
}
else if(this.dragState.isDraggingNode()){
//no op
}
else if(this.dragState.isSelecting()) {
this.onDragRectEnd();
}
this.dragState.endDragging();
evt.preventDefault();
evt.stopPropagation();
}
onMouseMove(evt: MouseEvent) {
this.updateMouseOverState(evt);
if(this.dragState.isSelecting()){
this.onDraggingRect(evt)
}
else if(this.dragState.isDraggingConnection()){
this.onConnectorDragging(evt);
}
else if(this.dragState.isDraggingNode()){
this.onNodeDragging(evt);
}
evt.preventDefault();
evt.stopPropagation();
}
/**
* Update the mouseover state object
*/
private updateMouseOverState(evt:MouseEvent) {
// Clear out all cached mouse over elements.
this.mouseOverState.clear();
let mouseOverElement = FlowchartUtils.hitTest(evt.clientX, evt.clientY);
if (mouseOverElement == null) {
// Mouse isn't over anything, just clear all.
return;
}
let ele: JQuery;
// Figure out if the mouse is over a connection.
ele = FlowchartUtils.checkForHit(mouseOverElement, this.connectionClass);
let connection = null;
if(ele && ele.length >0){
connection = this.chart.findConnection(ele.get(0).id);
}
if(this.mouseOverState.setMouseOverConnection(connection)){
// Don't attempt to mouse over anything else.
return;
}
// Figure out if the mouse is over a connector.
ele = FlowchartUtils.checkForHit(mouseOverElement, this.connectorClass);
let connector = null;
if(ele && ele.length >0) {
connector = this.chart.findConnectorById(ele.get(0).id)
}
if(this.mouseOverState.setMouseOverConnector(connector)){
// Don't attempt to mouse over anything else.
return;
}
// Figure out if the mouse is over a node.
ele = FlowchartUtils.checkForHit(mouseOverElement, this.nodeClass);
let node = undefined;
if(ele && ele.length >0){
node = this.chart.findNode(ele.get(0).id)
}
this.mouseOverState.setMouseOverNode(node);
}
/**
* Called when we are dragging to select nodes
* @param {DragResponse} dragResponse
*/
onDragStart(response: DragResponse) {
if(!this.dragState.isDraggingNodeOrConnection() && !this.mouseOverState.isType(MouseOverType.CONNECTOR) && !this.mouseOverState.isType(MouseOverType.CONNECTION)) {
//Set the state to selecting
this.dragState.dragSelect();
//get the starting point and create the rect object with the starting
let startingPoint = this.svgCoordinatesForEvent(response.dragStartMouseEvent)
this.dragSelectionRect = new DragSelectionRect(startingPoint);
}
}
/**
* Called when the user is dragging the rectangle to select nodes
* Update the rectangle view state
* @param {MouseEvent} event
*/
onDraggingRect(event: MouseEvent) {
let currentPoint = this.svgCoordinatesForEvent(event);
this.dragSelectionRect.update(currentPoint);
}
/**
* Called when the the user completes the rectangle selectiong
*
*/
onDragRectEnd() {
//apply the selection to the chart and nodes
this.chart.applySelectionRect(this.dragSelectionRect);
//reset the rectangle to nothing
this.dragSelectionRect = undefined;
}
///NODE methods
/**
* translate the mouse event points to SVG coordinates
* @param {MouseEvent} event
* @return {any}
*/
private svgCoordinatesForEvent(event:MouseEvent){
this.ensureSvgElement();
return FlowchartUtils.translateCoordinates(this.svgElement,event.pageX, event.pageY, event);
}
/**
* Translate the mouse 'event' relative to the 'startEvent' as SVG coordinates
* @param {MouseEvent} event
* @param {MouseEvent} startEvent
* @return {any}
*/
private svgCoordinatesRelativeToStart(event:MouseEvent, startEvent:MouseEvent){
this.ensureSvgElement();
return FlowchartUtils.translateCoordinates(this.svgElement,event.pageX, event.pageY, startEvent);
}
private ensureSvgElement(){
if(this.svgElement == undefined && this.element && this.element.nativeElement && this.element.nativeElement.children){
this.svgElement = this.element.nativeElement.children[0]
}
}
ngOnInit(){
}
//identifiers
/**
* get the identifier for the node
* @param node
* @param {number} index
* @return {string}
*/
nodeIdentifier(node:FlowChart.NodeViewModel, index:number) {
return node.data.id;
}
/**
* get the identifier for the connector
* @param node
* @param {number} nodeIndex
* @param connector
* @param {number} connectorIndex
* @return {string}
*/
connectorIdentifier(node:FlowChart.NodeViewModel, nodeIndex:number, connector:FlowChart.ConnectorViewModel, connectorIndex:number) {
let id = node.data.id+'|'+connectorIndex;
return id;
}
/**
* Get the identifier for the connection
* @param connection
* @param {number} index
*/
connectionIdentifier(connection:FlowChart.ConnectionViewModel,index:number){
return connection.data.id
}
/**
* Called when the Node starts dragging
* @param {DragResponse} dragResponse
*/
onNodeDragStarted(dragResponse:DragResponse){
//allow node dragging only if we are not selecting or dragging a connection
if(!this.dragState.isDraggingConnectionOrSelecting()) {
//save the state of the starting coords
this.dragState.lastNodeMouseCoords = this.svgCoordinatesForEvent(dragResponse.dragStartMouseEvent);
this.dragState.dragStartEvent = dragResponse.dragStartMouseEvent;
let node = this.chart.findNode(dragResponse.draggableId)
this.dragState.dragNode(node);
// If nothing is selected when dragging starts,
// at least select the node we are dragging.
if (node && !node.selected()) {
this.chart.deselectAll();
node.select();
}
}
}
/**
* called when the node is dragging
* @param {MouseEvent} event
*/
onNodeDragging(event:MouseEvent) {
// Dragging selected nodes... update their x,y coordinates.
//translate off the mouse down event
let curCoords = this.svgCoordinatesRelativeToStart(event,this.dragState.dragStartEvent);
let deltaX = curCoords.x - this.dragState.lastNodeMouseCoords.x;
var deltaY = curCoords.y - this.dragState.lastNodeMouseCoords.y;
this.chart.updateSelectedNodesLocation(deltaX, deltaY);
this.dragState.lastNodeMouseCoords = curCoords;
}
onNodeClicked(dragResponse:DragResponse) {
let node = this.chart.findNode(dragResponse.draggableId)
this.chart.handleNodeClicked(node, dragResponse.event.ctrlKey);
}
// Connectors
/**
* get the node Id for a connector
* @param {string} connectorIdentifier
*/
private nodeIdentifierFromConnectorIdentifier(connectorIdentifier:string){
let nodeId = connectorIdentifier.substring(0,connectorIdentifier.indexOf('|'))
return nodeId;
}
/**
* Get the connector index from the connector id
* @param {string} connectorIdentifier
* @return {string}
*/
private connectorIndexFromConnectorIdentifier(connectorIdentifier:string){
let index = connectorIdentifier.substring(connectorIdentifier.indexOf('|')+1)
return index;
}
/**
* Called when a user is dragging out a connector
* @param {DragResponse} dragResponse
*/
onConnectorDragStarted(dragResponse:DragResponse){
let curCoords = this.svgCoordinatesForEvent(dragResponse.dragStartMouseEvent);
let connectorId = dragResponse.draggableId;
//get the node
let nodeId = this.nodeIdentifierFromConnectorIdentifier(connectorId);
let node = this.chart.findNode(nodeId);
let connectorIndex = this.connectorIndexFromConnectorIdentifier(connectorId);
let connector = this.chart.findConnector(nodeId,connectorIndex);
//update the state
this.dragState.dragConnector(node,connector);
this.updateDragPoints(curCoords, node, connector);
}
/**
* Called when the connector is dragging around the canvas.
* Update the line
* @param {MouseEvent} event
*/
onConnectorDragging(event:MouseEvent) {
let curCoords = this.svgCoordinatesForEvent(event);
let connector = this.dragState.activeConnector;
let node = this.dragState.activeNode;
this.updateDragPoints(curCoords, node, connector);
}
/**
* Called when the connection is done.
* Attempt to make the connection to a node if possible
* @param {DragResponse} dragResponse
*/
onConnectorDragEnded(){
if (this.mouseOverState.isType(MouseOverType.CONNECTOR) &&
!this.mouseOverState.isMouseOverConnector(this.dragState.activeConnector)) {
//
// Dragging has ended...
// The mouse is over a valid connector...
// Create a new connection.
//
this.chart.createNewConnection( this.dragState.activeConnector, this.mouseOverState.mouseOverConnector);
}
else if(this.mouseOverState.isType(MouseOverType.NODE) && !this.mouseOverState.isMouseOverNode(this.dragState.activeNode)) {
//find a connector and add it
let connector = this.chart.findConnector(this.mouseOverState.mouseOverNode.data.id,0);
if(connector){
this.chart.createNewConnection( this.dragState.activeConnector, connector);
}
}
this.clearDragPoints();
}
private clearDragPoints(){
this.dragPoint1 = null;
this.dragPoint2 = null;
this.dragTangent1 = null;
this.dragTangent2 = null;
}
private updateDragPoints(point:Point, node:any, connector:any){
this.dragPoint1 = FlowChart.FlowchartModelBase.computeConnectorPos(node, connector);
this.dragPoint2 = {
x: point.x,
y: point.y
};
this.dragTangent1 = FlowChart.FlowchartModelBase.computeConnectionSourceTangent(this.dragPoint1, this.dragPoint2);
this.dragTangent2 = FlowChart.FlowchartModelBase.computeConnectionDestTangent(this.dragPoint1, this.dragPoint2);
}
//Style methods
getAttrCheckboxCheckedClass(attr:any){
return attr.selected ? 'accent-color show': 'hide';
}
getAttrCheckboxUnCheckedClass(attr:any){
return attr.selected ? 'hide': ' accent-color show';
}
getAllCheckboxCheckedClass(nodeAttrs:any){
return nodeAttrs.hasAllSelected() ? 'accent-color show': 'hide';
}
getAllCheckboxUnCheckedClass(nodeAttrs:any){
return nodeAttrs.hasAllSelected() ? 'hide': 'accent-color show';
}
getNodeClass(node:any){
return this.getNodeOrConnectionClass(node,this.mouseOverState.isMouseOverNode(node),'node-rect');
}
getConnectorClass(connector:any){
return this.mouseOverState.isMouseOverConnector(connector) ? 'mouseover-connector-circle' : 'connector-circle';
}
connectionLineClass(connection:any){
return this.getNodeOrConnectionClass(connection, this.mouseOverState.isMouseOverConnection(connection),'connection-line');
}
connectionNameClass(connection:any){
return this.getNodeOrConnectionClass(connection,this.mouseOverState.isMouseOverConnection(connection),'connection-name');
}
connectionEndpointClass(connection:any){
return this.getNodeOrConnectionClass(connection,this.mouseOverState.isMouseOverConnection(connection),'connection-endpoint')
}
private getNodeOrConnectionClass(item:any,mouseOver:boolean,suffix:string){
if(item.selected()) {
return 'selected-'+suffix;
}
else if(mouseOver) {
return 'mouseover-'+suffix;
}
else {
return suffix;
}
}
// Handle mousedown on a connection.
onConnectionClicked(dragResponse:DragResponse) {
let connection = this.chart.findConnection(dragResponse.draggableId)
if(connection) {
this.chart.handleConnectionMouseDown(connection, dragResponse.event.ctrlKey);
}
// Don't let the chart handle the mouse down.
dragResponse.event.stopPropagation();
dragResponse.event.preventDefault();
}
} | the_stack |
import { KeySet } from '../ojkeyset';
import { DataProvider } from '../ojdataprovider';
import { baseComponent, baseComponentEventMap, baseComponentSettableProperties, JetElementCustomEvent, JetSetPropertyType } from '..';
export interface ojListView<K, D> extends baseComponent<ojListViewSettableProperties<K, D>> {
as: string;
currentItem: K;
data: DataProvider<K, D>;
dnd: {
drag?: {
items: {
dataTypes?: string | string[];
drag?: ((param0: Event) => void);
dragEnd?: ((param0: Event) => void);
dragStart?: ((param0: Event, param1: {
items: Element[];
}) => void);
};
};
drop?: {
items: {
dataTypes?: string | string[];
dragEnter?: ((param0: Event, param1: {
item: Element;
}) => void);
dragLeave?: ((param0: Event, param1: {
item: Element;
}) => void);
dragOver?: ((param0: Event, param1: {
item: Element;
}) => void);
drop?: ((param0: Event, param1: ojListView.ItemsDropContext) => void);
};
};
reorder: {
items: 'enabled' | 'disabled';
};
};
drillMode: 'collapsible' | 'none';
expanded: KeySet<K>;
readonly firstSelectedItem: {
key: K;
data: D;
};
groupHeaderPosition: 'static' | 'sticky';
item: {
focusable?: ((param0: ojListView.ItemContext<K, D>) => boolean) | boolean;
renderer?: ((param0: ojListView.ItemContext<K, D>) => {
insert: Element | string;
} | undefined) | null;
selectable?: ((param0: ojListView.ItemContext<K, D>) => boolean) | boolean;
};
scrollPolicy: 'auto' | 'loadMoreOnScroll';
scrollPolicyOptions: {
fetchSize?: number;
maxCount?: number;
scroller?: Element;
};
scrollPosition: {
x?: number;
y?: number;
index?: number;
parent?: K;
key?: K;
offsetX?: number;
offsetY?: number;
};
selection: K[];
selectionMode: 'none' | 'single' | 'multiple';
selectionRequired: boolean;
translations: {
accessibleNavigateSkipItems?: string;
accessibleReorderAfterItem?: string;
accessibleReorderBeforeItem?: string;
accessibleReorderInsideItem?: string;
accessibleReorderTouchInstructionText?: string;
indexerCharacters?: string;
labelCopy?: string;
labelCut?: string;
labelPaste?: string;
labelPasteAfter?: string;
labelPasteBefore?: string;
msgFetchingData?: string;
msgNoData?: string;
};
onAsChanged: ((event: JetElementCustomEvent<ojListView<K, D>["as"]>) => any) | null;
onCurrentItemChanged: ((event: JetElementCustomEvent<ojListView<K, D>["currentItem"]>) => any) | null;
onDataChanged: ((event: JetElementCustomEvent<ojListView<K, D>["data"]>) => any) | null;
onDndChanged: ((event: JetElementCustomEvent<ojListView<K, D>["dnd"]>) => any) | null;
onDrillModeChanged: ((event: JetElementCustomEvent<ojListView<K, D>["drillMode"]>) => any) | null;
onExpandedChanged: ((event: JetElementCustomEvent<ojListView<K, D>["expanded"]>) => any) | null;
onFirstSelectedItemChanged: ((event: JetElementCustomEvent<ojListView<K, D>["firstSelectedItem"]>) => any) | null;
onGroupHeaderPositionChanged: ((event: JetElementCustomEvent<ojListView<K, D>["groupHeaderPosition"]>) => any) | null;
onItemChanged: ((event: JetElementCustomEvent<ojListView<K, D>["item"]>) => any) | null;
onScrollPolicyChanged: ((event: JetElementCustomEvent<ojListView<K, D>["scrollPolicy"]>) => any) | null;
onScrollPolicyOptionsChanged: ((event: JetElementCustomEvent<ojListView<K, D>["scrollPolicyOptions"]>) => any) | null;
onScrollPositionChanged: ((event: JetElementCustomEvent<ojListView<K, D>["scrollPosition"]>) => any) | null;
onSelectionChanged: ((event: JetElementCustomEvent<ojListView<K, D>["selection"]>) => any) | null;
onSelectionModeChanged: ((event: JetElementCustomEvent<ojListView<K, D>["selectionMode"]>) => any) | null;
onSelectionRequiredChanged: ((event: JetElementCustomEvent<ojListView<K, D>["selectionRequired"]>) => any) | null;
onOjAnimateEnd: ((event: ojListView.ojAnimateEnd) => any) | null;
onOjAnimateStart: ((event: ojListView.ojAnimateStart) => any) | null;
onOjBeforeCollapse: ((event: ojListView.ojBeforeCollapse<K>) => any) | null;
onOjBeforeCurrentItem: ((event: ojListView.ojBeforeCurrentItem<K>) => any) | null;
onOjBeforeExpand: ((event: ojListView.ojBeforeExpand<K>) => any) | null;
onOjCollapse: ((event: ojListView.ojCollapse<K>) => any) | null;
onOjCopy: ((event: ojListView.ojCopy) => any) | null;
onOjCut: ((event: ojListView.ojCut) => any) | null;
onOjExpand: ((event: ojListView.ojExpand<K>) => any) | null;
onOjPaste: ((event: ojListView.ojPaste) => any) | null;
onOjReorder: ((event: ojListView.ojReorder) => any) | null;
addEventListener<T extends keyof ojListViewEventMap<K, D>>(type: T, listener: (this: HTMLElement, ev: ojListViewEventMap<K, D>[T]) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
getProperty<T extends keyof ojListViewSettableProperties<K, D>>(property: T): ojListView<K, D>[T];
getProperty(property: string): any;
setProperty<T extends keyof ojListViewSettableProperties<K, D>>(property: T, value: ojListViewSettableProperties<K, D>[T]): void;
setProperty<T extends string>(property: T, value: JetSetPropertyType<T, ojListViewSettableProperties<K, D>>): void;
setProperties(properties: ojListViewSettablePropertiesLenient<K, D>): void;
getContextByNode(node: Element): ojListView.ContextByNode<K> | null;
getDataForVisibleItem(context: {
key?: K;
index?: number;
parent?: Element;
}): D;
refresh(): void;
scrollToItem(item: {
key: K;
}): void;
}
export namespace ojListView {
interface ojAnimateEnd extends CustomEvent<{
action: string;
element: Element;
[propName: string]: any;
}> {
}
interface ojAnimateStart extends CustomEvent<{
action: string;
element: Element;
endCallback: (() => void);
[propName: string]: any;
}> {
}
interface ojBeforeCollapse<K> extends CustomEvent<{
key: K;
item: Element;
[propName: string]: any;
}> {
}
interface ojBeforeCurrentItem<K> extends CustomEvent<{
previousKey: K;
previousItem: Element;
key: K;
item: Element;
[propName: string]: any;
}> {
}
interface ojBeforeExpand<K> extends CustomEvent<{
key: K;
item: Element;
[propName: string]: any;
}> {
}
interface ojCollapse<K> extends CustomEvent<{
key: K;
item: Element;
[propName: string]: any;
}> {
}
interface ojCopy extends CustomEvent<{
items: Element[];
[propName: string]: any;
}> {
}
interface ojCut extends CustomEvent<{
items: Element[];
[propName: string]: any;
}> {
}
interface ojExpand<K> extends CustomEvent<{
key: K;
item: Element;
[propName: string]: any;
}> {
}
interface ojPaste extends CustomEvent<{
item: Element;
[propName: string]: any;
}> {
}
interface ojReorder extends CustomEvent<{
items: Element[];
position: string;
reference: Element;
[propName: string]: any;
}> {
}
// tslint:disable-next-line interface-over-type-literal
type ContextByNode<K> = {
subId: string;
key: K;
index: number;
parent?: Element;
group?: boolean;
};
// tslint:disable-next-line interface-over-type-literal
type ItemContext<K, D> = {
datasource: DataProvider<K, D>;
index: number;
key: K;
data: D;
parentElement: Element;
depth?: number;
parentKey?: K;
leaf?: boolean;
};
// tslint:disable-next-line interface-over-type-literal
type ItemsDropContext = {
item: Element;
position: 'before' | 'after' | 'inside';
reorder: boolean;
};
}
export interface ojListViewEventMap<K, D> extends baseComponentEventMap<ojListViewSettableProperties<K, D>> {
'ojAnimateEnd': ojListView.ojAnimateEnd;
'ojAnimateStart': ojListView.ojAnimateStart;
'ojBeforeCollapse': ojListView.ojBeforeCollapse<K>;
'ojBeforeCurrentItem': ojListView.ojBeforeCurrentItem<K>;
'ojBeforeExpand': ojListView.ojBeforeExpand<K>;
'ojCollapse': ojListView.ojCollapse<K>;
'ojCopy': ojListView.ojCopy;
'ojCut': ojListView.ojCut;
'ojExpand': ojListView.ojExpand<K>;
'ojPaste': ojListView.ojPaste;
'ojReorder': ojListView.ojReorder;
'asChanged': JetElementCustomEvent<ojListView<K, D>["as"]>;
'currentItemChanged': JetElementCustomEvent<ojListView<K, D>["currentItem"]>;
'dataChanged': JetElementCustomEvent<ojListView<K, D>["data"]>;
'dndChanged': JetElementCustomEvent<ojListView<K, D>["dnd"]>;
'drillModeChanged': JetElementCustomEvent<ojListView<K, D>["drillMode"]>;
'expandedChanged': JetElementCustomEvent<ojListView<K, D>["expanded"]>;
'firstSelectedItemChanged': JetElementCustomEvent<ojListView<K, D>["firstSelectedItem"]>;
'groupHeaderPositionChanged': JetElementCustomEvent<ojListView<K, D>["groupHeaderPosition"]>;
'itemChanged': JetElementCustomEvent<ojListView<K, D>["item"]>;
'scrollPolicyChanged': JetElementCustomEvent<ojListView<K, D>["scrollPolicy"]>;
'scrollPolicyOptionsChanged': JetElementCustomEvent<ojListView<K, D>["scrollPolicyOptions"]>;
'scrollPositionChanged': JetElementCustomEvent<ojListView<K, D>["scrollPosition"]>;
'selectionChanged': JetElementCustomEvent<ojListView<K, D>["selection"]>;
'selectionModeChanged': JetElementCustomEvent<ojListView<K, D>["selectionMode"]>;
'selectionRequiredChanged': JetElementCustomEvent<ojListView<K, D>["selectionRequired"]>;
}
export interface ojListViewSettableProperties<K, D> extends baseComponentSettableProperties {
as: string;
currentItem: K;
data: DataProvider<K, D>;
dnd: {
drag?: {
items: {
dataTypes?: string | string[];
drag?: ((param0: Event) => void);
dragEnd?: ((param0: Event) => void);
dragStart?: ((param0: Event, param1: {
items: Element[];
}) => void);
};
};
drop?: {
items: {
dataTypes?: string | string[];
dragEnter?: ((param0: Event, param1: {
item: Element;
}) => void);
dragLeave?: ((param0: Event, param1: {
item: Element;
}) => void);
dragOver?: ((param0: Event, param1: {
item: Element;
}) => void);
drop?: ((param0: Event, param1: ojListView.ItemsDropContext) => void);
};
};
reorder: {
items: 'enabled' | 'disabled';
};
};
drillMode: 'collapsible' | 'none';
expanded: KeySet<K>;
readonly firstSelectedItem: {
key: K;
data: D;
};
groupHeaderPosition: 'static' | 'sticky';
item: {
focusable?: ((param0: ojListView.ItemContext<K, D>) => boolean) | boolean;
renderer?: ((param0: ojListView.ItemContext<K, D>) => {
insert: Element | string;
} | undefined) | null;
selectable?: ((param0: ojListView.ItemContext<K, D>) => boolean) | boolean;
};
scrollPolicy: 'auto' | 'loadMoreOnScroll';
scrollPolicyOptions: {
fetchSize?: number;
maxCount?: number;
scroller?: Element;
};
scrollPosition: {
x?: number;
y?: number;
index?: number;
parent?: K;
key?: K;
offsetX?: number;
offsetY?: number;
};
selection: K[];
selectionMode: 'none' | 'single' | 'multiple';
selectionRequired: boolean;
translations: {
accessibleNavigateSkipItems?: string;
accessibleReorderAfterItem?: string;
accessibleReorderBeforeItem?: string;
accessibleReorderInsideItem?: string;
accessibleReorderTouchInstructionText?: string;
indexerCharacters?: string;
labelCopy?: string;
labelCut?: string;
labelPaste?: string;
labelPasteAfter?: string;
labelPasteBefore?: string;
msgFetchingData?: string;
msgNoData?: string;
};
}
export interface ojListViewSettablePropertiesLenient<K, D> extends Partial<ojListViewSettableProperties<K, D>> {
[key: string]: any;
} | the_stack |
import { AbstractLoadStrategy, ILoadConfig } from './AbstractLoadStrategy';
import { getExtension, assertNever } from '../utilities';
import { ResourceType } from '../resource_type';
// tests if CORS is supported in XHR, if not we need to use XDR
// Mainly this is for IE9 support.
const useXdr = !!((window as any).XDomainRequest && !('withCredentials' in (new XMLHttpRequest())));
const enum HttpStatus
{
None = 0,
Ok = 200,
Empty = 204,
IeEmptyBug = 1223,
}
/**
* The XHR response types.
*/
export enum XhrResponseType
{
/** string */
Default = 'text',
/** ArrayBuffer */
Buffer = 'arraybuffer',
/** Blob */
Blob = 'blob',
/** Document */
Document = 'document',
/** Object */
Json = 'json',
/** String */
Text = 'text',
};
export interface IXhrLoadConfig extends ILoadConfig
{
xhrType?: XhrResponseType;
}
/**
* Quick helper to get string xhr type.
*/
function reqType(xhr: XMLHttpRequest): string
{
return xhr.toString().replace('object ', '');
}
export class XhrLoadStrategy extends AbstractLoadStrategy<IXhrLoadConfig>
{
static readonly ResponseType = XhrResponseType;
private _boundOnLoad = this._onLoad.bind(this);
private _boundOnAbort = this._onAbort.bind(this);
private _boundOnError = this._onError.bind(this);
private _boundOnTimeout = this._onTimeout.bind(this);
private _boundOnProgress = this._onProgress.bind(this);
private _xhr = this._createRequest();
private _xhrType = XhrResponseType.Default;
load(): void
{
const config = this.config;
const ext = getExtension(config.url);
if (typeof config.xhrType !== 'string')
{
config.xhrType = this._determineXhrType(ext);
}
const xhr = this._xhr;
this._xhrType = config.xhrType || XhrResponseType.Default;
// XDomainRequest has a few quirks. Occasionally it will abort requests
// A way to avoid this is to make sure ALL callbacks are set even if not used
// More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
if (useXdr)
{
// XDR needs a timeout value or it breaks in IE9
xhr.timeout = config.timeout || 5000;
xhr.onload = this._boundOnLoad;
xhr.onerror = this._boundOnError;
xhr.ontimeout = this._boundOnTimeout;
xhr.onprogress = this._boundOnProgress;
xhr.open('GET', config.url, true);
// Note: The xdr.send() call is wrapped in a timeout to prevent an issue with
// the interface where some requests are lost if multiple XDomainRequests are
// being sent at the same time.
setTimeout(function () { xhr.send(); }, 0);
}
else
{
xhr.open('GET', config.url, true);
if (config.timeout)
xhr.timeout = config.timeout;
// load json as text and parse it ourselves. We do this because some browsers
// *cough* safari *cough* can't deal with it.
if (config.xhrType === XhrResponseType.Json || config.xhrType === XhrResponseType.Document)
xhr.responseType = XhrResponseType.Text;
else
xhr.responseType = config.xhrType;
xhr.addEventListener('load', this._boundOnLoad, false);
xhr.addEventListener('abort', this._boundOnAbort, false);
xhr.addEventListener('error', this._boundOnError, false);
xhr.addEventListener('timeout', this._boundOnTimeout, false);
xhr.addEventListener('progress', this._boundOnProgress, false);
xhr.send();
}
}
abort(): void
{
if (useXdr)
{
this._clearEvents();
this._xhr.abort();
this._onAbort();
}
else
{
// will call the abort event
this._xhr.abort();
}
}
private _createRequest(): XMLHttpRequest
{
if (useXdr)
return new (window as any).XDomainRequest();
else
return new XMLHttpRequest();
}
private _determineXhrType(ext: string): XhrResponseType
{
return XhrLoadStrategy._xhrTypeMap[ext] || XhrResponseType.Default;
}
private _clearEvents(): void
{
if (useXdr)
{
this._xhr.onload = null;
this._xhr.onerror = null;
this._xhr.ontimeout = null;
this._xhr.onprogress = null;
}
else
{
this._xhr.removeEventListener('load', this._boundOnLoad, false);
this._xhr.removeEventListener('abort', this._boundOnAbort, false);
this._xhr.removeEventListener('error', this._boundOnError, false);
this._xhr.removeEventListener('timeout', this._boundOnTimeout, false);
this._xhr.removeEventListener('progress', this._boundOnProgress, false);
}
}
private _error(errMessage: string): void
{
this._clearEvents();
this.onError.dispatch(errMessage);
}
private _complete(type: ResourceType, data: any): void
{
this._clearEvents();
this.onComplete.dispatch(type, data);
}
private _onLoad(): void
{
const xhr = this._xhr;
let text = '';
// XDR has no `.status`, assume 200.
let status = typeof xhr.status === 'undefined' ? HttpStatus.Ok : xhr.status;
// responseText is accessible only if responseType is '' or 'text' and on older browsers
if (typeof xhr.responseType === 'undefined' || xhr.responseType === '' || xhr.responseType === 'text')
{
text = xhr.responseText;
}
// status can be 0 when using the `file://` protocol so we also check if a response is set.
// If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request.
if (status === HttpStatus.None && (text.length > 0 || xhr.responseType === XhrResponseType.Buffer))
{
status = HttpStatus.Ok;
}
// handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
else if (status === HttpStatus.IeEmptyBug)
{
status = HttpStatus.Empty;
}
const flattenedStatus = Math.floor(status / 100) * 100;
if (flattenedStatus !== HttpStatus.Ok)
{
this._error(`[${xhr.status}] ${xhr.statusText}: ${xhr.responseURL}`);
return;
}
switch (this._xhrType)
{
case XhrResponseType.Buffer:
this._complete(ResourceType.Buffer, xhr.response);
break;
case XhrResponseType.Blob:
this._complete(ResourceType.Blob, xhr.response);
break;
case XhrResponseType.Document:
this._parseDocument(text);
break;
case XhrResponseType.Json:
this._parseJson(text);
break;
case XhrResponseType.Default:
case XhrResponseType.Text:
this._complete(ResourceType.Text, text);
break;
default:
assertNever(this._xhrType);
}
}
private _parseDocument(text: string): void
{
try
{
if (window.DOMParser)
{
const parser = new DOMParser();
const data = parser.parseFromString(text, 'text/xml');
this._complete(ResourceType.Xml, data);
}
else
{
const div = document.createElement('div');
div.innerHTML = text;
this._complete(ResourceType.Xml, div);
}
}
catch (e)
{
this._error(`Error trying to parse loaded xml: ${e}`);
}
}
private _parseJson(text: string): void
{
try
{
const data = JSON.parse(text);
this._complete(ResourceType.Json, data);
}
catch (e)
{
this._error(`Error trying to parse loaded json: ${e}`);
}
}
private _onAbort(): void
{
const xhr = this._xhr;
this._error(`${reqType(xhr)} Request was aborted by the user.`);
}
private _onError(): void
{
const xhr = this._xhr;
this._error(`${reqType(xhr)} Request failed. Status: ${xhr.status}, text: "${xhr.statusText}"`);
}
private _onTimeout(): void
{
const xhr = this._xhr;
this._error(`${reqType(xhr)} Request timed out.`);
}
private _onProgress(event: ProgressEvent): void
{
if (event && event.lengthComputable)
{
this.onProgress.dispatch(event.loaded / event.total);
}
}
/**
* Sets the load type to be used for a specific extension.
*
* @param extname The extension to set the type for, e.g. "png" or "fnt"
* @param xhrType The xhr type to set it to.
*/
static setExtensionXhrType(extname: string, xhrType: XhrResponseType)
{
if (extname && extname.indexOf('.') === 0)
extname = extname.substring(1);
if (!extname)
return;
XhrLoadStrategy._xhrTypeMap[extname] = xhrType;
}
private static _xhrTypeMap: Partial<Record<string, XhrResponseType>> = {
// xml
xhtml: XhrResponseType.Document,
html: XhrResponseType.Document,
htm: XhrResponseType.Document,
xml: XhrResponseType.Document,
tmx: XhrResponseType.Document,
svg: XhrResponseType.Document,
// This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component.
// Since it is way less likely for people to be loading TypeScript files instead of Tiled files,
// this should probably be fine.
tsx: XhrResponseType.Document,
// images
gif: XhrResponseType.Blob,
png: XhrResponseType.Blob,
bmp: XhrResponseType.Blob,
jpg: XhrResponseType.Blob,
jpeg: XhrResponseType.Blob,
tif: XhrResponseType.Blob,
tiff: XhrResponseType.Blob,
webp: XhrResponseType.Blob,
tga: XhrResponseType.Blob,
// json
json: XhrResponseType.Json,
// text
text: XhrResponseType.Text,
txt: XhrResponseType.Text,
// fonts
ttf: XhrResponseType.Buffer,
otf: XhrResponseType.Buffer,
};
} | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement } from "../shared";
/**
* Statement provider for service [deepcomposer](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdeepcomposer.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Deepcomposer extends PolicyStatement {
public servicePrefix = 'deepcomposer';
/**
* Statement provider for service [deepcomposer](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdeepcomposer.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Grants permission to associate a DeepComposer coupon (or DSN) with the account associated with the sender of the request
*
* Access Level: Write
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/what-it-is-keyboard.html
*/
public toAssociateCoupon() {
return this.to('AssociateCoupon');
}
/**
* Grants permission to create an audio file by converting the midi composition into a wav or mp3 file
*
* Access Level: Write
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-learn-from-pre-trained-models.html
*/
public toCreateAudio() {
return this.to('CreateAudio');
}
/**
* Grants permission to create a multi-track midi composition
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-learn-from-pre-trained-models.html
*/
public toCreateComposition() {
return this.to('CreateComposition');
}
/**
* Grants permission to start creating/training a generative-model that is able to perform inference against the user-provided piano-melody to create a multi-track midi composition
*
* Access Level: Write
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-custom-model.html
*/
public toCreateModel() {
return this.to('CreateModel');
}
/**
* Grants permission to delete the composition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-learn-from-pre-trained-models.html
*/
public toDeleteComposition() {
return this.to('DeleteComposition');
}
/**
* Grants permission to delete the model
*
* Access Level: Write
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-custom-model.html
*/
public toDeleteModel() {
return this.to('DeleteModel');
}
/**
* Grants permission to get information about the composition
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-learn-from-pre-trained-models.html
*/
public toGetComposition() {
return this.to('GetComposition');
}
/**
* Grants permission to get information about the model
*
* Access Level: Read
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-custom-model.html
*/
public toGetModel() {
return this.to('GetModel');
}
/**
* Grants permission to get information about the sample/pre-trained DeepComposer model
*
* Access Level: Read
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-learn-from-pre-trained-models.html
*/
public toGetSampleModel() {
return this.to('GetSampleModel');
}
/**
* Grants permission to list all the compositions owned by the sender of the request
*
* Access Level: List
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-learn-from-pre-trained-models.html
*/
public toListCompositions() {
return this.to('ListCompositions');
}
/**
* Grants permission to list all the models owned by the sender of the request
*
* Access Level: List
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-custom-model.html
*/
public toListModels() {
return this.to('ListModels');
}
/**
* Grants permission to list all the sample/pre-trained models provided by the DeepComposer service
*
* Access Level: List
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-learn-from-pre-trained-models.html
*/
public toListSampleModels() {
return this.to('ListSampleModels');
}
/**
* Grants permission to list tags for a resource
*
* Access Level: List
*
* Possible conditions:
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/deepcomposer-tagging.html
*/
public toListTagsForResource() {
return this.to('ListTagsForResource');
}
/**
* Grants permission to list all the training options or topic for creating/training a model
*
* Access Level: List
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-custom-model.html
*/
public toListTrainingTopics() {
return this.to('ListTrainingTopics');
}
/**
* Grants permission to tag a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/deepcomposer-tagging.html
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Grants permission to untag a resource
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifAwsTagKeys()
* - .ifAwsRequestTag()
* - .ifAwsResourceTag()
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/deepcomposer-tagging.html
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Grants permission to modify the mutable properties associated with a composition
*
* Access Level: Write
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-learn-from-pre-trained-models.html
*/
public toUpdateComposition() {
return this.to('UpdateComposition');
}
/**
* Grants permission to to modify the mutable properties associated with a model
*
* Access Level: Write
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-custom-model.html
*/
public toUpdateModel() {
return this.to('UpdateModel');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"AssociateCoupon",
"CreateAudio",
"CreateComposition",
"CreateModel",
"DeleteComposition",
"DeleteModel",
"UpdateComposition",
"UpdateModel"
],
"Read": [
"GetComposition",
"GetModel",
"GetSampleModel"
],
"List": [
"ListCompositions",
"ListModels",
"ListSampleModels",
"ListTagsForResource",
"ListTrainingTopics"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type model to the statement
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-custom-model.html
*
* @param modelId - Identifier for the modelId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onModel(modelId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:deepcomposer:${Region}:${Account}:model/${ModelId}';
arn = arn.replace('${ModelId}', modelId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type composition to the statement
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-learn-from-pre-trained-models.html
*
* @param compositionId - Identifier for the compositionId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsResourceTag()
*/
public onComposition(compositionId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:deepcomposer:${Region}:${Account}:composition/${CompositionId}';
arn = arn.replace('${CompositionId}', compositionId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Adds a resource of type audio to the statement
*
* https://docs.aws.amazon.com/deepcomposer/latest/devguide/get-started-learn-from-pre-trained-models.html
*
* @param audioId - Identifier for the audioId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*/
public onAudio(audioId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:deepcomposer:${Region}:${Account}:audio/${AudioId}';
arn = arn.replace('${AudioId}', audioId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
} | the_stack |
import { Constants } from "../Constants";
import { Test } from "../tests/Test";
import { AggregatedResult, AssertionResult, TestResult } from "@jest/test-result";
/**
* Create test suites
* @export
* @class TestSuite
*/
export class TestSuite {
/**
* Ancestor title join character
* @static
* @memberof TestSuite
*/
public static readonly JOIN_CHAR = ".";
/**
* Build table info for specific tests
* @static
* @returns {HTMLElement[]} - populated html elements
* @memberof TestSuite
*/
public static create(results: AggregatedResult): HTMLElement[] {
const elements: HTMLElement[] = [];
results.testResults.forEach((testResult) => {
// NOTE(Kelosky): jest.AggregateResult has a testResults array
// which contains a jest.TestResults array. jest.TestResults array
// is of type AssertionResults array. however, it looks like they
// somehow allow for the the field name to be assertionResults instead
// of the documented interface testResults. So, we'll cast to any, and attempt
// access assertionResults if testsResults are missing
if (testResult.testResults == null) {
// tslint:disable-next-line:no-console
console.error("Unexpected testResults field missing");
if ((testResult as any).assertionResults != null) {
// tslint:disable-next-line:no-console
console.warn("Attempting to use assertionResults: results are unpredictable");
testResult.testResults = (testResult as any).assertionResults;
}
}
let testStatusClass;
const testSectionStatus: Map<string, string> = new Map<string, string>();
for (const result of testResult.testResults) {
testStatusClass = TestSuite.asignStatus(testStatusClass, result, testSectionStatus);
}
if (testStatusClass === undefined) {
testStatusClass = Constants.PASSED_TEST;
}
// Using Bootstrap Accordion to allow for expanding and collapsing sections by testFilePath
const accordionCard = TestSuite.buildAccordionCard(testResult, testStatusClass)
// if a flat test report were to be used, simply
// testResult.testResults.forEach((test) => {
// div.appendChild(Test.create(test));
// });
const divMap: Map<string, HTMLElement> = new Map<string, HTMLElement>();
testResult.testResults.forEach((test) => {
const element = Test.create(test);
if (test.ancestorTitles.length > 0) {
test.ancestorTitles.forEach((title, index) => {
const titlesCopy = test.ancestorTitles.slice();
titlesCopy.splice(index + 1);
const key = titlesCopy.join(TestSuite.JOIN_CHAR);
if (divMap.has(key)) {
divMap.get(key).appendChild(element);
} else {
const nestDiv = document.createElement("div") as HTMLDivElement;
const statusClass = testSectionStatus.get(key) || Constants.PASSED_TEST;
nestDiv.classList.add("my-3", "p-3", "bg-white", "rounded", "box-shadow", statusClass);
const h6 = document.createElement("h6") as HTMLHeadingElement;
h6.classList.add("border-bottom", "pb-2", "mb-0", "display-6");
h6.textContent = title;
nestDiv.appendChild(h6);
nestDiv.appendChild(element);
nestDiv.id = key;
divMap.set(key, nestDiv);
if (index === 0) {
accordionCard.querySelector('.card-body').appendChild(nestDiv);
} else {
titlesCopy.pop();
const parentKey = titlesCopy.join(TestSuite.JOIN_CHAR);
divMap.get(parentKey).appendChild(nestDiv);
}
}
});
} else {
accordionCard.querySelector('.card-body').appendChild(element);
}
});
elements.push(accordionCard);
});
return elements;
}
public static asignStatus(testStatusClass: string, result: AssertionResult, testSectionStatus: Map<string, string>) {
const currentStatus = TestSuite.getStatusClassFromJestStatus(result.status);
if (!testStatusClass) {
testStatusClass = currentStatus;
} else if (testStatusClass !== currentStatus) {
testStatusClass = TestSuite.mixStatus(currentStatus, testStatusClass);
} else {
testStatusClass = currentStatus;
}
// mark all lower test sections as containing a failed test for filtering
for (let index = 0; index < result.ancestorTitles.length; index++) {
const titlesCopy = result.ancestorTitles.slice();
titlesCopy.splice(index + 1);
const key = titlesCopy.join(TestSuite.JOIN_CHAR);
if (testSectionStatus.has(key)) {
if (testStatusClass !== currentStatus) {
testSectionStatus.set(key, TestSuite.mixStatus(currentStatus, testStatusClass));
} else {
testSectionStatus.set(key, currentStatus);
}
} else {
testSectionStatus.set(key, currentStatus);
}
}
return testStatusClass;
}
private static getStatusClassFromJestStatus(jestStatus: string) {
if (jestStatus === Constants.TEST_STATUS_PEND) {
return Constants.PENDING_TEST;
} else if (jestStatus === Constants.TEST_STATUS_FAIL) {
return Constants.FAILED_TEST;
} else {
return Constants.PASSED_TEST;
}
}
private static mixStatus(currentStatus: string, oldStatus: string) {
const statusArray = oldStatus.split(TestSuite.JOIN_CHAR);
statusArray.push(currentStatus);
const sortedUniqueStatusArray = [...new Set(statusArray)].sort();
return sortedUniqueStatusArray.join(TestSuite.JOIN_CHAR);
}
private static buildAccordionCard(testResult: TestResult, testStatusClass: string) {
// Following the Bootstrap Accordion Example https://getbootstrap.com/docs/4.0/components/collapse/
// each spec/test file will have it's own card in the accordion
const accordionCard = document.createElement("div") as HTMLDivElement;
accordionCard.classList.add("my-3", "p-3", "bg-white", "rounded", "box-shadow", "card", testStatusClass);
const cardHeader = TestSuite.buildAccordionCardHeader(
testResult.testFilePath, testResult.numPassingTests, testResult.numFailingTests, testResult.numPendingTests, testResult.numTodoTests);
accordionCard.appendChild(cardHeader);
const cardBody = TestSuite.buildAccordionCardBody(testResult.testFilePath);
accordionCard.appendChild(cardBody)
return accordionCard
}
private static buildAccordionCardHeader(testFilePath: string, passCount: number, failCount: number, pendingCount: number, todoCount: number) {
const fileName = TestSuite.sanitizeFilePath(testFilePath)
const cardHeader = document.createElement("div") as HTMLDivElement;
cardHeader.classList.add("card-header");
cardHeader.id = `${fileName}_header`;
const h5 = document.createElement("h5") as HTMLHeadingElement;
h5.classList.add("border-bottom", "pb-2", "mb-0", "display-5");
const btn = document.createElement("button") as HTMLButtonElement;
btn.classList.add("btn", "btn-block");
btn.setAttribute("data-toggle", "collapse");
btn.setAttribute("data-target", `#${fileName}_detail`);
btn.textContent = testFilePath;
const resultCounts = document.createElement("div") as HTMLDivElement;
const passBadge = document.createElement("span") as HTMLSpanElement;
passBadge.classList.add("badge", "badge-success", "border");
passBadge.textContent = passCount.toString();
resultCounts.appendChild(passBadge);
const failBadge = document.createElement("span") as HTMLSpanElement;
failBadge.classList.add("badge", "badge-danger", "border");
failBadge.textContent = failCount.toString();
resultCounts.appendChild(failBadge);
const skipBadge = document.createElement("span") as HTMLSpanElement;
skipBadge.classList.add("badge", "badge-warning", "border");
skipBadge.textContent = pendingCount.toString();
resultCounts.appendChild(skipBadge);
const todoBadge = document.createElement("span") as HTMLSpanElement;
todoBadge.classList.add("badge", "badge-info", "border");
todoBadge.textContent = todoCount.toString();
resultCounts.appendChild(todoBadge);
btn.appendChild(resultCounts);
h5.appendChild(btn);
cardHeader.appendChild(h5);
return cardHeader;
}
private static buildAccordionCardBody(testFilePath: string) {
const fileName = TestSuite.sanitizeFilePath(testFilePath)
const cardContainer = document.createElement("div") as HTMLDivElement;
cardContainer.classList.add("collapse");
cardContainer.setAttribute("data-parent", "#accordion");
cardContainer.id = `${fileName}_detail`;
const cardBody = document.createElement("div") as HTMLDivElement;
cardBody.classList.add("card-body");
cardContainer.appendChild(cardBody);
return cardContainer;
}
/**
* Provides a sanitized version of the Test File Path free from characters
* that would violate contraints on element id attributes
* @param testFilePath Path for the test/spec file from the JSON Results
* @returns {String}
*/
private static sanitizeFilePath(testFilePath: string) {
return testFilePath.replace(/(\/)|\\|(:)|(\s)|\.|(@)/g, '_')
}
} | the_stack |
import 'aframe';
import 'aframe-extras';
import 'aframe-orbit-controls';
import 'aframe-event-set-component';
import '../lib/GLTFExporter';
import { Entity, Scene } from 'aframe';
import { ShortcutTools, EventTools, CameraTools, ViewportTools, HistoryTools } from './';
import systems from '../aframe/systems';
import components from '../aframe/components';
import primitives from '../aframe/primitives';
export interface ICameras {
perspective?: THREE.PerspectiveCamera;
original?: Entity;
ortho?: THREE.OrthographicCamera;
}
export interface IScene extends Omit<Scene, 'camera'> {
camera?: ICamera;
}
export interface ICamera extends THREE.Camera {
el?: Entity;
}
export interface IInsepctorOptions {
id?: string;
target?: HTMLElement;
playerCamera?: boolean;
ar?: boolean;
orbitControls?: boolean;
sceneStr?: string;
assetsStr?: string;
entitiesStr?: string;
}
const defaultInspectorOptions: IInsepctorOptions = {
playerCamera: false,
orbitControls: true,
};
systems.forEach(System => System());
components.forEach(Comp => Comp());
primitives.forEach(Prim => Prim());
class InspectorTools {
sceneEl?: IScene;
scene: THREE.Object3D;
camera?: ICamera;
container?: HTMLElement;
currentCameraEl?: Entity;
cameras?: ICameras;
sceneHelpers?: THREE.Scene;
helpers?: Record<any, any>;
cursor?: Entity;
modules?: Record<any, any>;
history?: HistoryTools;
isFirstOpen?: boolean;
opened?: boolean;
exporters?: Record<any, any>;
on?: any;
inspectorActive?: boolean;
cameraHelper?: THREE.CameraHelper;
selectedEntity?: Entity;
selected?: THREE.Object3D;
entityToCopy?: Entity;
shortcutTools?: ShortcutTools;
cameraTools?: CameraTools;
viewportTools?: ViewportTools;
selectedAsset?: Entity;
options: IInsepctorOptions;
targetEl: HTMLElement;
constructor(options: IInsepctorOptions = {}) {
this.exporters = { gltf: new AFRAME.THREE.GLTFExporter() };
this.history = new HistoryTools();
this.isFirstOpen = true;
this.modules = {};
this.on = EventTools.on;
this.opened = false;
const mergedOptions = Object.assign({}, defaultInspectorOptions, options);
this.options = mergedOptions;
const { id, target } = mergedOptions;
let sceneParentElement = document.body;
if (id) {
const targetEl = document.getElementById(id);
if (targetEl) {
sceneParentElement = targetEl;
}
}
if (target) {
sceneParentElement = target;
}
this.targetEl = sceneParentElement;
this.initScene(sceneParentElement, mergedOptions);
this.init();
}
/**
* @description Initial Inspector
* @returns
*/
init = () => {
if (!AFRAME.scenes.length) {
setTimeout(() => {
this.init();
}, 100);
return;
}
this.sceneEl = AFRAME.scenes[0];
if (!this.sceneEl.hasLoaded) {
setTimeout(() => {
this.init();
}, 100);
return;
}
if (!this.sceneEl.camera) {
this.sceneEl.addEventListener(
'camera-set-active',
() => {
this.init();
},
{ once: true },
);
return;
}
// Remove scene default inspector
this.sceneEl.removeAttribute('inspector');
this.sceneEl.removeAttribute('keyboard-shortcuts');
EventTools.emit('sceneloaded', this.sceneEl);
EventTools.emit('entityselect', this.sceneEl);
this.scene = this.sceneEl.object3D;
this.container = this.sceneEl.querySelector('.a-canvas');
this.initCamera();
this.initShortcut();
this.initViewport();
this.initEvents();
this.initARScript();
};
/**
* @description Initial Scene
* @param {HTMLElement} inspectorEl
* @param {boolean} playCamera
*/
initScene = (inspectorEl: HTMLElement, options: IInsepctorOptions) => {
const { playerCamera, orbitControls, sceneStr, assetsStr, entitiesStr } = options;
if (sceneStr) {
this.loadScene(inspectorEl, sceneStr);
inspectorEl.querySelector('a-scene');
return;
}
const scene = document.createElement('a-scene') as IScene;
const assets = document.createElement('a-assets');
assets.id = 'assets';
scene.appendChild(assets);
this.loadAssets(scene, assetsStr);
if (playerCamera) {
this.loadPlayerCamera(scene);
} else if (orbitControls) {
this.loadOrbitControls(scene);
}
scene.querySelector('a-assets').addEventListener('loaded', () => {
console.debug('a-assets loaded');
this.loadEntities(scene, entitiesStr);
});
inspectorEl.appendChild(scene);
scene.id = 'scene';
scene.title = 'Scene';
scene.style.position = 'fixed';
scene.style.top = '0';
scene.style.left = '0';
};
initCamera = () => {
this.cameraTools = new CameraTools(this);
};
initViewport = () => {
const scene = this.sceneEl.object3D;
this.helpers = {};
this.sceneHelpers = new AFRAME.THREE.Scene();
this.sceneHelpers.userData.source = 'INPSECTOR';
this.sceneHelpers.visible = true;
this.inspectorActive = false;
this.viewportTools = new ViewportTools(this);
EventTools.emit('windowresize');
scene.add(this.sceneHelpers);
scene.traverse(node => {
this.addHelper(node);
});
scene.add(this.sceneHelpers);
this.open();
};
initShortcut = () => {
this.shortcutTools = new ShortcutTools(this);
};
initEvents = () => {
window.addEventListener('keydown', evt => {
// Alt + Ctrl + i: Shorcut to toggle the inspector
const shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
if (shortcutPressed) {
this.toggle();
}
});
EventTools.on('entityselect', (entity: Entity) => {
this.selectEntity(entity, false);
});
EventTools.on('inspectortoggle', (active?: boolean) => {
this.inspectorActive = active;
this.sceneHelpers.visible = this.inspectorActive;
});
EventTools.on('entitycreate', (entity: Entity) => {
this.selectEntity(entity);
});
EventTools.on('assetcreate', (asset: Entity) => {
this.selectAsset(asset);
});
EventTools.on('assetselect', (asset: Entity) => {
this.selectAsset(asset, false);
});
document.addEventListener('child-detached', event => {
const entity = event.detail.el;
this.removeObject(entity.object3D);
});
};
initARScript = () => {
const arScript = document.head.querySelector('#ar-script');
if (arScript) {
return;
}
const script = document.createElement('script') as any;
script.src = './vendor/ar.js/aframe/build/aframe-ar.min.js';
script.async = true;
script.id = 'ar-script';
document.head.appendChild(script);
};
loadScene = (inspectorEl: HTMLElement, fragment: string) => {
return inspectorEl.appendChild(document.createRange().createContextualFragment(fragment.trim()));
};
loadEntities = (scene: IScene, fragment: string = '') => {
return scene.appendChild(document.createRange().createContextualFragment(fragment.trim()));
};
loadAssets = (scene: IScene, fragment: string = '') => {
return scene
.querySelector('a-assets')
.appendChild(document.createRange().createContextualFragment(fragment.trim()));
};
loadPlayerCamera = (scene: IScene, fragment?: string) => {
const playerCamera = document.createRange().createContextualFragment(
fragment
? fragment.trim()
: `
<!-- Camera. -->
<a-entity position="0 1.6 8" aframe-injected>
<a-entity id="camera" camera look-controls wasd-controls>
<!-- Cursor. -->
<a-entity id="cursor" position="0 0 -2"
geometry="primitive: ring; radiusOuter: 0.016; radiusInner: 0.01"
material="color: #ff9; shader: flat; transparent: true; opacity: 0.5"
scale="2 2 2" raycaster>
</a-entity>
</a-entity>
</a-entity>
`.trim(),
);
return scene.appendChild(playerCamera);
};
loadOrbitControls = (scene: IScene, fragment?: string) => {
const orbitControls = document.createRange().createContextualFragment(
fragment
? fragment.trim()
: `
<!-- Orbit Controls. -->
<a-entity
camera
look-controls="enabled: false"
orbit-controls="target: 0 0 0; minDistance: 0.5; maxDistance: 180; initialPosition: 0 5 10"
/>
`.trim(),
);
return scene.appendChild(orbitControls);
};
removeObject = (object3D: THREE.Object3D) => {
// Remove just the helper as the object will be deleted by A-Frame
this.removeHelpers(object3D);
EventTools.emit('objectremove', object3D);
};
addHelper = (object: THREE.Object3D) => {
const geometry = new AFRAME.THREE.SphereBufferGeometry(2, 4, 2);
const material = new AFRAME.THREE.MeshBasicMaterial({
color: 0xff0000,
visible: false,
});
let helper;
if (object instanceof AFRAME.THREE.Camera) {
this.cameraHelper = helper = new AFRAME.THREE.CameraHelper(object, 0.1);
} else if (object instanceof AFRAME.THREE.PointLight) {
helper = new AFRAME.THREE.PointLightHelper(object, 1);
} else if (object instanceof AFRAME.THREE.DirectionalLight) {
helper = new AFRAME.THREE.DirectionalLightHelper(object, 1);
} else if (object instanceof AFRAME.THREE.SpotLight) {
helper = new AFRAME.THREE.SpotLightHelper(object, 1);
} else if (object instanceof AFRAME.THREE.HemisphereLight) {
helper = new AFRAME.THREE.HemisphereLightHelper(object, 1);
} else if (object instanceof AFRAME.THREE.SkinnedMesh) {
helper = new AFRAME.THREE.SkeletonHelper(object);
} else {
// no helper for this object type
return;
}
helper.visible = false;
this.sceneHelpers.add(helper);
this.helpers[object.uuid] = helper;
helper.update();
};
removeHelpers = (object3D: THREE.Object3D) => {
object3D.traverse(node => {
const helper = this.helpers[node.uuid];
if (helper) {
this.sceneHelpers.remove(helper);
delete this.helpers[node.uuid];
EventTools.emit('helperremove', this.helpers[node.uuid]);
}
});
};
/**
* @description Select the entity
* @param {Entity} entity
* @param {boolean} [emit]
* @returns
*/
selectEntity = (entity: Entity, emit?: boolean) => {
this.selectedEntity = entity;
if (entity) {
this.select(entity.object3D);
} else {
this.select(null);
}
if (entity && emit === undefined) {
EventTools.emit('entityselect', entity);
}
// Update helper visibilities.
Object.keys(this.helpers).forEach(id => {
this.helpers[id].visible = false;
});
if (entity === this.sceneEl) {
return;
}
if (entity) {
entity.object3D.traverse(node => {
if (this.helpers[node.uuid]) {
this.helpers[node.uuid].visible = true;
}
});
}
};
/**
* @description Select the entity by id
* @param {number} id
* @returns
*/
selectEntityById = (id: number) => {
if (id === this.camera.id) {
this.select(this.camera);
return;
}
this.select(this.scene.getObjectById(id, true));
};
/**
* @description Select the entity by Object3D
* @param {THREE.Object3D} object3D
* @returns
*/
select = (object3D: THREE.Object3D) => {
if (this.selected === object3D) {
return;
}
this.selected = object3D;
EventTools.emit('objectselect', object3D);
};
/**
* @description Deselect entity
*/
deselect = () => {
this.select(null);
};
/**
* @description Select the asset
* @param {Entity} asset
* @param {boolean} [emit=true]
*/
selectAsset = (asset: Entity, emit: boolean = true) => {
this.selectedAsset = asset;
if (emit) {
EventTools.emit('entityselect');
EventTools.emit('assetselect', asset);
}
};
/**
* @description Open or close inspector
*/
toggle = () => {
if (this.opened) {
this.close();
} else {
this.open();
}
};
/**
* @description Open the editor UI
* @param {Entity} [focusEl]
*/
open = (focusEl?: Entity) => {
this.opened = true;
EventTools.emit('inspectortoggle', true);
if (this.sceneEl.hasAttribute('embedded')) {
// Remove embedded styles, but keep track of it.
this.sceneEl.removeAttribute('embedded');
this.sceneEl.setAttribute('aframe-inspector-removed-embedded');
}
document.body.classList.add('aframe-inspector-opened');
this.sceneEl.resize();
this.sceneEl.pause();
this.sceneEl.exitVR();
this.shortcutTools.enable();
// Trick scene to run the cursor tick.
this.sceneEl.isPlaying = true;
this.cursor.play();
if (!focusEl && this.isFirstOpen && AFRAME.utils.getUrlParameter('inspector')) {
// Focus entity with URL parameter on first open.
focusEl = document.getElementById(AFRAME.utils.getUrlParameter('inspector')) as Entity;
}
if (focusEl) {
this.selectEntity(focusEl);
EventTools.emit('objectfocus', focusEl.object3D);
}
this.isFirstOpen = false;
};
/**
* @description Closes the editor and gives the control back to the scene
*/
close = () => {
this.opened = false;
EventTools.emit('inspectortoggle', false);
// Untrick scene when we enabled this to run the cursor tick.
this.sceneEl.isPlaying = false;
this.sceneEl.play();
this.cursor.pause();
if (this.sceneEl.hasAttribute('aframe-inspector-removed-embedded')) {
this.sceneEl.setAttribute('embedded', '');
this.sceneEl.removeAttribute('aframe-inspector-removed-embedded');
}
document.body.classList.remove('aframe-inspector-opened');
this.sceneEl.resize();
this.shortcutTools.disable();
};
reload = (options: IInsepctorOptions) => {
// const arScript = document.head.querySelector('#ar-script');
// if (arScript) {
// document.head.removeChild(arScript);
// Object.keys(AFRAME.components).forEach(componentName => {
// if (componentName.includes('arjs')) {
// delete AFRAME.components[componentName];
// }
// });
// console.log(window.customElements.get('a-anchor'));
// delete AFRAME.primitives.primitives['a-anchor'];
// delete AFRAME.primitives.primitives['a-marker'];
// delete AFRAME.primitives.primitives['a-marker-camera'];
// delete AFRAME.primitives.primitives['a-camera-static'];
// delete AFRAME.systems.arjs;
// }
this.targetEl.removeChild(this.sceneEl);
const mergedOptions = Object.assign({}, this.options, options);
this.initScene(this.targetEl, mergedOptions);
this.init();
};
}
export default InspectorTools; | the_stack |
/*
* Copyright (c) 2016 - now David Sehnal, licensed under Apache 2.0, See LICENSE file for more info.
*/
namespace LiteMol.Core.Formats.Molecule.PDB {
"use strict";
export type TokenRange = { start: number; end: number };
export type HelperData = { dot: TokenRange; question: TokenRange; numberTokens: Utils.FastMap<number, TokenRange>; data: string };
export class MoleculeData {
private makeEntities() {
let data = [
`data_ent`,
`loop_`,
`_entity.id`,
`_entity.type`,
`_entity.src_method`,
`_entity.pdbx_description`,
`_entity.formula_weight`,
`_entity.pdbx_number_of_molecules`,
`_entity.details`,
`_entity.pdbx_mutation`,
`_entity.pdbx_fragment`,
`_entity.pdbx_ec`,
`1 polymer man polymer 0.0 0 ? ? ? ?`,
`2 non-polymer syn non-polymer 0.0 0 ? ? ? ?`,
`3 water nat water 0.0 0 ? ? ? ?`
].join('\n');
let file = CIF.Text.parse(data);
if (file.isError) {
throw file.toString();
}
return file.result.dataBlocks[0].getCategory('_entity') as CIF.Text.Category;
}
toCifFile(): CIF.File {
let helpers: HelperData = {
dot: Parser.getDotRange(this.data.length),
question: Parser.getQuestionmarkRange(this.data.length),
numberTokens: Parser.getNumberRanges(this.data.length),
data: this.data
};
let file = new CIF.Text.File(this.data);
let block = new CIF.Text.DataBlock(this.data, this.header.id);
file.dataBlocks.push(block);
block.addCategory(this.makeEntities());
if (this.crystInfo) {
let { cell, symm } = this.crystInfo.toCifCategory(this.header.id);
block.addCategory(cell as CIF.Text.Category);
block.addCategory(symm as CIF.Text.Category);
}
block.addCategory(this.models.toCifCategory(block, helpers));
return file;
}
constructor(
public header: Header,
public crystInfo: CrystStructureInfo | undefined,
public models: ModelsData,
public data: string
) {
}
}
export class Header {
constructor(public id: string) {
}
}
export class CrystStructureInfo {
private getValue(start: number, len: number) {
let ret = this.record.substr(6, 9).trim();
if (!ret.length) return '.';
return ret;
}
toCifCategory(id: string) {
//COLUMNS DATA TYPE CONTENTS
//--------------------------------------------------------------------------------
// 1 - 6 Record name "CRYST1"
//7 - 15 Real(9.3) a (Angstroms)
//16 - 24 Real(9.3) b (Angstroms)
//25 - 33 Real(9.3) c (Angstroms)
//34 - 40 Real(7.2) alpha (degrees)
//41 - 47 Real(7.2) beta (degrees)
//48 - 54 Real(7.2) gamma (degrees)
//56 - 66 LString Space group
//67 - 70 Integer Z value
let data = [
`_cell.entry_id '${id}'`,
`_cell.length_a ${this.getValue(6, 9)}`,
`_cell.length_b ${this.getValue(15, 9)}`,
`_cell.length_c ${this.getValue(24, 9)}`,
`_cell.angle_alpha ${this.getValue(33, 7)}`,
`_cell.angle_beta ${this.getValue(40, 7)}`,
`_cell.angle_gamma ${this.getValue(48, 7)}`,
`_cell.Z_PDB ${this.getValue(66, 4)}`,
`_cell.pdbx_unique_axis ?`,
`_symmetry.entry_id '${id}'`,
`_symmetry.space_group_name_H-M '${this.getValue(55, 11)}'`,
`_symmetry.pdbx_full_space_group_name_H-M ?`,
`_symmetry.cell_setting ?`,
`_symmetry.Int_Tables_number ?`,
`_symmetry.space_group_name_Hall ?`
].join('\n');
let cif = CIF.Text.parse(data);
if (cif.isError) {
throw new Error(cif.toString());
}
return {
cell: cif.result.dataBlocks[0].getCategory('_cell'),
symm: cif.result.dataBlocks[0].getCategory('_symmetry')
};
}
constructor(public record: string) {
}
}
export class SecondaryStructure {
toCifCategory(data: string): { helices: CIF.Category; sheets: CIF.Category } | undefined {
return void 0;
}
constructor(public helixTokens: number[], public sheetTokens: number[]) {
}
}
export class ModelData {
static COLUMNS = [
"_atom_site.group_PDB",
"_atom_site.id",
"_atom_site.type_symbol",
"_atom_site.label_atom_id",
"_atom_site.label_alt_id",
"_atom_site.label_comp_id",
"_atom_site.label_asym_id",
"_atom_site.label_entity_id",
"_atom_site.label_seq_id",
"_atom_site.pdbx_PDB_ins_code",
"_atom_site.Cartn_x",
"_atom_site.Cartn_y",
"_atom_site.Cartn_z",
"_atom_site.occupancy",
"_atom_site.B_iso_or_equiv",
"_atom_site.Cartn_x_esd",
"_atom_site.Cartn_y_esd",
"_atom_site.Cartn_z_esd",
"_atom_site.occupancy_esd",
"_atom_site.B_iso_or_equiv_esd",
"_atom_site.pdbx_formal_charge",
"_atom_site.auth_seq_id",
"_atom_site.auth_comp_id",
"_atom_site.auth_asym_id",
"_atom_site.auth_atom_id",
"_atom_site.pdbx_PDB_model_num"
];
private writeToken(index: number, cifTokens: Utils.ArrayBuilder<number>) {
Utils.ArrayBuilder.add2(cifTokens, this.atomTokens[2 * index], this.atomTokens[2 * index + 1]);
}
private writeTokenCond(index: number, cifTokens: Utils.ArrayBuilder<number>, dot: TokenRange) {
let s = this.atomTokens[2 * index];
let e = this.atomTokens[2 * index + 1];
if (s === e) Utils.ArrayBuilder.add2(cifTokens, dot.start, dot.end);
else Utils.ArrayBuilder.add2(cifTokens, s, e);
}
private writeRange(range: TokenRange, cifTokens: Utils.ArrayBuilder<number>) {
Utils.ArrayBuilder.add2(cifTokens, range.start, range.end);
}
private tokenEquals(start: number, end: number, value: string, data: string) {
let len = value.length;
if (len !== end - start) return false;
for (let i = value.length - 1; i >= 0; i--) {
if (data.charCodeAt(i + start) !== value.charCodeAt(i)) {
return false;
}
}
return true;
}
private getEntityType(row: number, data: string) {
let o = row * 14;
if (this.tokenEquals(this.atomTokens[2 * o], this.atomTokens[2 * o + 1], "HETATM", data)) {
let s = this.atomTokens[2 * (o + 4)], e = this.atomTokens[2 * (o + 4) + 1];
if (this.tokenEquals(s, e, "HOH", data) || this.tokenEquals(s, e, "WTR", data) || this.tokenEquals(s, e, "SOL", data)) {
return 3; // water
}
return 2; // non-polymer
} else {
return 1; // polymer
}
}
writeCifTokens(modelToken: TokenRange, cifTokens: Utils.ArrayBuilder<number>, helpers: HelperData) {
const columnIndices = {
//COLUMNS DATA TYPE CONTENTS
//--------------------------------------------------------------------------------
// 1 - 6 Record name "ATOM "
RECORD: 0,
// 7 - 11 Integer Atom serial number.
SERIAL: 1,
//13 - 16 Atom Atom name.
ATOM_NAME: 2,
//17 Character Alternate location indicator.
ALT_LOC: 3,
//18 - 20 Residue name Residue name.
RES_NAME: 4,
//22 Character Chain identifier.
CHAIN_ID: 5,
//23 - 26 Integer Residue sequence number.
RES_SEQN: 6,
//27 AChar Code for insertion of residues.
INS_CODE: 7,
//31 - 38 Real(8.3) Orthogonal coordinates for X in Angstroms.
X: 8,
//39 - 46 Real(8.3) Orthogonal coordinates for Y in Angstroms.
Y: 9,
//47 - 54 Real(8.3) Orthogonal coordinates for Z in Angstroms.
Z: 10,
//55 - 60 Real(6.2) Occupancy.
OCCUPANCY: 11,
//61 - 66 Real(6.2) Temperature factor (Default = 0.0).
TEMP_FACTOR: 12,
//73 - 76 LString(4) Segment identifier, left-justified.
// ignored
//77 - 78 LString(2) Element symbol, right-justified.
ELEMENT: 13
//79 - 80 LString(2) Charge on the atom.
// ignored
};
const columnCount = 14;
for (let i = 0; i < this.atomCount; i++) {
let o = i * columnCount;
//_atom_site.group_PDB
this.writeToken(o + columnIndices.RECORD, cifTokens);
//_atom_site.id
this.writeToken(o + columnIndices.SERIAL, cifTokens);
//_atom_site.type_symbol
this.writeToken(o + columnIndices.ELEMENT, cifTokens);
//_atom_site.label_atom_id
this.writeToken(o + columnIndices.ATOM_NAME, cifTokens);
//_atom_site.label_alt_id
this.writeTokenCond(o + columnIndices.ALT_LOC, cifTokens, helpers.dot);
//_atom_site.label_comp_id
this.writeToken(o + columnIndices.RES_NAME, cifTokens);
//_atom_site.label_asym_id
this.writeToken(o + columnIndices.CHAIN_ID, cifTokens);
//_atom_site.label_entity_id
this.writeRange(helpers.numberTokens.get(this.getEntityType(i, helpers.data)) !, cifTokens);
//_atom_site.label_seq_id
this.writeToken(o + columnIndices.RES_SEQN, cifTokens);
//_atom_site.pdbx_PDB_ins_code
this.writeTokenCond(o + columnIndices.INS_CODE, cifTokens, helpers.dot);
//_atom_site.Cartn_x
this.writeToken(o + columnIndices.X, cifTokens);
//_atom_site.Cartn_y
this.writeToken(o + columnIndices.Y, cifTokens);
//_atom_site.Cartn_z
this.writeToken(o + columnIndices.Z, cifTokens);
//_atom_site.occupancy
this.writeToken(o + columnIndices.OCCUPANCY, cifTokens);
//_atom_site.B_iso_or_equiv
this.writeToken(o + columnIndices.TEMP_FACTOR, cifTokens);
//_atom_site.Cartn_x_esd
this.writeRange(helpers.question, cifTokens);
//_atom_site.Cartn_y_esd
this.writeRange(helpers.question, cifTokens);
//_atom_site.Cartn_z_esd
this.writeRange(helpers.question, cifTokens);
//_atom_site.occupancy_esd
this.writeRange(helpers.question, cifTokens);
//_atom_site.B_iso_or_equiv_esd
this.writeRange(helpers.question, cifTokens);
//_atom_site.pdbx_formal_charge
this.writeRange(helpers.question, cifTokens);
//_atom_site.auth_seq_id
this.writeToken(o + columnIndices.RES_SEQN, cifTokens);
//_atom_site.auth_comp_id
this.writeToken(o + columnIndices.RES_NAME, cifTokens);
//_atom_site.auth_asym_id
this.writeToken(o + columnIndices.CHAIN_ID, cifTokens);
//_atom_site.auth_atom_id
this.writeToken(o + columnIndices.ATOM_NAME, cifTokens);
//_atom_site.pdbx_PDB_model_num
this.writeRange(modelToken, cifTokens);
}
}
constructor(public idToken: TokenRange, public atomTokens: number[], public atomCount: number) {
}
}
export class ModelsData {
toCifCategory(block: CIF.Text.DataBlock, helpers: HelperData): CIF.Text.Category {
let atomCount = 0;
for (let m of this.models) {
atomCount += m.atomCount;
}
const colCount = 26;
let tokens = Utils.ArrayBuilder.forTokenIndices(atomCount * colCount);
for (let m of this.models) {
m.writeCifTokens(m.idToken, tokens, helpers);
}
return new CIF.Text.Category(block.data, "_atom_site", 0, 0, ModelData.COLUMNS, tokens.array, atomCount * colCount);
}
constructor(public models: ModelData[]) {
}
}
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
class BulkDeleteFailureApi {
/**
* DynamicsCrm.DevKit BulkDeleteFailureApi
* @param entity The entity object
*/
constructor(entity?: any);
/**
* Get the value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedValue(alias: string, isMultiOptionSet?: boolean): any;
/**
* Get the formatted value of alias
* @param alias the alias value
* @param isMultiOptionSet true if the alias is multi OptionSet
*/
getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string;
/** The entity object */
Entity: any;
/** The entity name */
EntityName: string;
/** The entity collection name */
EntityCollectionName: string;
/** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */
"@odata.etag": string;
/** Unique identifier of the system job that created this record. */
AsyncOperationId: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the bulk deletion failure record. */
BulkDeleteFailureId: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of the bulk operation job which created this record */
BulkDeleteOperationId: DevKit.WebApi.LookupValueReadonly;
/** Description of the error. */
ErrorDescription: DevKit.WebApi.StringValueReadonly;
/** Error code for the failed bulk deletion. */
ErrorNumber: DevKit.WebApi.IntegerValueReadonly;
/** Index of the ordered query expression that retrieved this record. */
OrderedQueryIndex: DevKit.WebApi.IntegerValueReadonly;
/** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */
OwnerId_systemuser: DevKit.WebApi.LookupValueReadonly;
/** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */
OwnerId_team: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the business unit that owns the bulk deletion failure. */
OwningBusinessUnit: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of the user who owns the bulk deletion failure record.
*/
OwningUser: DevKit.WebApi.GuidValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_account: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_accountleads: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_activityfileattachment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_activitymimeattachment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_activitymonitor: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_activitypointer: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_adminsettingsentity: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_annotation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_annualfiscalcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appelement: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_applicationuser: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appmodulecomponentedge: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appmodulecomponentnode: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appnotification: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appointment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_appusersetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_attributeimageconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_attributemap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bookableresource: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bookableresourcebooking: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bookableresourcebookingexchangesyncidmapping: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bookableresourcebookingheader: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bookableresourcecategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bookableresourcecategoryassn: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bookableresourcecharacteristic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bookableresourcegroup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bookingstatus: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bot: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_botcomponent: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bulkoperation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_bulkoperationlog: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_businessunit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_businessunitnewsarticle: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_calendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_campaign: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_campaignactivity: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_campaignactivityitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_campaignitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_campaignresponse: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_canvasappextendedmetadata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_cascadegrantrevokeaccessrecordstracker: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_cascadegrantrevokeaccessversiontracker: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_catalog: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_catalogassignment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
channelaccessprofile_bulkdeletefailures: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
channelaccessprofileruleid: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_characteristic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_childincidentcount: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_commitment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_competitor: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_competitoraddress: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_competitorproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_competitorsalesliterature: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_connectionreference: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_connector: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_constraintbasedgroup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_contact: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_contactinvoices: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_contactleads: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_contactorders: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_contactquotes: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_contract: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_contractdetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_contracttemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_conversationtranscript: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customapi: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customapirequestparameter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customapiresponseproperty: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customeraddress: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customeropportunityrole: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_customerrelationship: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_datalakefolder: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_datalakefolderpermission: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_datalakeworkspace: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_datalakeworkspacepermission: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_discount: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_discounttype: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_displaystring: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_dynamicproperty: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_dynamicpropertyassociation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_dynamicpropertyinstance: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_dynamicpropertyoptionsetitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_email: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_emailserverprofile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entitlement: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entitlementchannel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entitlementcontacts: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entitlemententityallocationtypemapping: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entitlementproducts: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entitlementtemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entitlementtemplatechannel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entitlementtemplateproducts: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entityanalyticsconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entityimageconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_entitymap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_environmentvariabledefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_environmentvariablevalue: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_equipment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_exportsolutionupload: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
externalparty_bulkdeletefailures: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
externalpartyitem_bulkdeletefailures: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_fax: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_fixedmonthlyfiscalcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_flowmachine: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_flowmachinegroup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_flowsession: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_holidaywrapper: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_import: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_importdata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_importfile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_importlog: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_importmap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_incident: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_incidentknowledgebaserecord: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_incidentresolution: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_internalcatalogassignment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_invoice: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_invoicedetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_isvconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_kbarticle: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_kbarticlecomment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_kbarticletemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_keyvaultreference: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_knowledgearticle: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_knowledgearticleincident: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_knowledgebaserecord: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_lead: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_leadaddress: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_leadcompetitors: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_leadproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_leadtoopportunitysalesprocess: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_letter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_list: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_listmember: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_listoperation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_managedidentity: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_marketingformdisplayattributes: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_monthlyfiscalcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdynce_botcontent: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdynsm_marketingsitemap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdynsm_salessitemap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdynsm_servicessitemap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdynsm_settingssitemap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_3dmodel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_accountpricelist: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_actioncardregarding: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_actioncardrolesetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_actual: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_adaptivecardconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_adminappstate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agentstatushistory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreement: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreementbookingdate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreementbookingincident: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreementbookingproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreementbookingservice: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreementbookingservicetask: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreementbookingsetup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreementinvoicedate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreementinvoiceproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreementinvoicesetup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_agreementsubstatus: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibdataset: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibdatasetfile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibdatasetrecord: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibdatasetscontainer: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibfile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aibfileattacheddata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aiconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aifptrainingdocument: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aimodel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aiodimage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aiodlabel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aiodtrainingboundingbox: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aiodtrainingimage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_aitemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_analysiscomponent: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_analysisjob: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_analysisresult: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_analysisresultdetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_analytics: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_analyticsadminsettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_analyticsforcs: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_appconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_applicationextension: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_applicationtabtemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_approval: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_assetcategorytemplateassociation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_assettemplateassociation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_assignmentconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_assignmentconfigurationstep: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_authenticationsettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_autocapturerule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_autocapturesettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_batchjob: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bookableresourceassociation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bookableresourcebookingquicknote: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bookableresourcecapacityprofile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bookingalert: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bookingalertstatus: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bookingchange: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bookingjournal: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bookingrule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bookingsetupmetadata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bookingtimestamp: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bpf_2c5fe86acc8b414b8322ae571000c799: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bpf_477c16f59170487b8b4dc895c5dcd09b: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bpf_665e73aa18c247d886bfc50499c73b82: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bpf_989e9b1857e24af18787d5143b67523b: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bpf_baa0a411a239410cb8bded8b5fdd88e3: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bpf_d3d97bac8c294105840e99e37a9d1c39: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_bpf_d8f9dc7f099f44db9d641dd81fbd470d: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_businessclosure: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_callablecontext: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_cannedmessage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_capacityprofile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_caseenrichment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_casesuggestionrequestpayload: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_casetopic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_casetopicsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_casetopicsummary: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_casetopic_incident: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_cdsentityengagementctx: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_channel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_channelcapability: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_channelprovider: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_characteristicreqforteammember: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_chatansweroption: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_chatquestionnaireresponse: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_chatquestionnaireresponseitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_chatwidgetlanguage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ciprovider: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_clientextension: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_collabgraphresource: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_configuration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_consoleapplicationnotificationfield: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_consoleapplicationnotificationtemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_consoleapplicationsessiontemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_consoleapplicationtemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_consoleapplicationtemplateparameter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_consoleapplicationtype: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_consoleappparameterdefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_contactpricelist: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_contractlinedetailperformance: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_contractlineinvoiceschedule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_contractlinescheduleofvalue: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_contractperformance: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_conversationaction: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_conversationactionlocale: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_conversationdata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_conversationinsight: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_conversationsuggestionrequestpayload: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_conversationtopic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_conversationtopicsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_conversationtopicsummary: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_conversationtopic_conversation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_customengagementctx: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_customerasset: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_customerassetattachment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_customerassetcategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_dataanalyticsreport: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_dataanalyticsreport_csrmanager: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_dataanalyticsreport_ksinsights: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_dataanalyticsreport_oc: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_dataanalyticsreport_ocvoice: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_databaseversion: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_dataexport: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_dataflow: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_datainsightsandanalyticsfeature: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_decisioncontract: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_decisionruleset: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_delegation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_dimension: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_dimensionfieldname: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_entitlementapplication: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_entityconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_entityconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_entityrankingrule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_entityroutingconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_estimate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_estimateline: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_expense: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_expensecategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_expensereceipt: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_facebookengagementctx: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_fact: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_federatedarticle: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_federatedarticleincident: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_fieldcomputation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_fieldservicepricelistitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_fieldservicesetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_fieldserviceslaconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_fieldservicesystemjob: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_findworkevent: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_flowcardtype: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_forecastconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_forecastdefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_forecastinstance: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_forecastrecurrence: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_functionallocation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_gdprdata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_geofence: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_geofenceevent: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_geofencingsettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_geolocationsettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_geolocationtracking: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_helppage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_icebreakersconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_incidenttype: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_incidenttypecharacteristic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_incidenttypeproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_incidenttyperecommendationresult: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_incidenttyperecommendationrunhistory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_incidenttyperesolution: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_incidenttypeservice: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_incidenttypeservicetask: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_incidenttypessetup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_incidenttype_requirementgroup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_inspection: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_inspectionattachment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_inspectiondefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_inspectioninstance: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_inspectionresponse: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_integrationjob: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_integrationjobdetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_inventoryadjustment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_inventoryadjustmentproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_inventoryjournal: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_inventorytransfer: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_invoicefrequency: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_invoicefrequencydetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_invoicelinetransaction: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotalert: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotdevice: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotdevicecategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotdevicecommand: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotdevicecommanddefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotdevicedatahistory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotdeviceproperty: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotdeviceregistrationhistory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotdevicevisualizationconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotfieldmapping: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotpropertydefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotprovider: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotproviderinstance: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iotsettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_iottocaseprocess: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_journal: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_journalline: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_kalanguagesetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_kbenrichment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_kmfederatedsearchconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_kmpersonalizationsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgearticleimage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgearticletemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgeinteractioninsight: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgepersonalfilter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgesearchfilter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_knowledgesearchinsight: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_kpieventdata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_kpieventdefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_lineengagementctx: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_livechatconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_livechatengagementctx: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_livechatwidgetlocation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_liveconversation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_liveworkitemevent: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_liveworkstream: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_liveworkstreamcapacityprofile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_localizedsurveyquestion: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_macrosession: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_maskingrule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_masterentityroutingconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_migrationtracker: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_mlresultcache: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_msteamssetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_msteamssettingsv2: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_notesanalysisconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_notificationfield: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_notificationtemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocbotchannelregistration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_occhannelconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_occhannelstateconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_occommunicationprovidersetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_occommunicationprovidersettingentry: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_occustommessagingchannel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocfbapplication: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocfbpage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_oclanguage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_oclinechannelconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocliveworkitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocliveworkitemcapacityprofile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocliveworkitemcharacteristic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocliveworkitemcontextitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocliveworkitemparticipant: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocliveworkitemsentiment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocliveworkstreamcontextvariable: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_oclocalizationdata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocoutboundconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocoutboundmessage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocphonenumber: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocprovisioningstate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocrequest: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocruleitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsentimentdailytopic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsentimentdailytopickeyword: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsentimentdailytopictrending: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsession: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsessioncharacteristic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsessionsentiment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsimltraining: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsitdimportconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsitdskill: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsitrainingdata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocskillidentmlmodel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsmschannelsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocsystemmessage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_octag: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_octeamschannelconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_octwitterapplication: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_octwitterhandle: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocwechatchannelconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocwhatsappchannelaccount: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_ocwhatsappchannelnumber: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_oc_geolocationprovider: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_omnichannelconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_omnichannelpersonalization: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_omnichannelqueue: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_omnichannelsyncconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_operatinghour: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_opportunitylineresourcecategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_opportunitylinetransaction: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_opportunitylinetransactioncategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_opportunitylinetransactionclassificatio: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_opportunitypricelist: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_orderinvoicingdate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_orderinvoicingproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_orderinvoicingsetup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_orderinvoicingsetupdate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_orderlineresourcecategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_orderlinetransaction: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_orderlinetransactioncategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_orderlinetransactionclassification: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_orderpricelist: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_organizationalunit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_paneconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_panetabconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_panetoolconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_payment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_paymentdetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_paymentmethod: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_paymentterm: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_personalmessage: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_personalsoundsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_personasecurityrolemapping: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_playbookactivity: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_playbookactivityattribute: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_playbookcategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_playbookinstance: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_playbooktemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_pminferredtask: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_pmrecording: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_postalbum: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_postalcode: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_postconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_postruleconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_presence: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_priority: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_problematicasset: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_problematicassetfeedback: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_processnotes: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_productinventory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_productivityactioninputparameter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_productivityactionoutputparameter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_productivityagentscript: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_productivityagentscriptstep: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_productivitymacroactiontemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_productivitymacroconnector: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_productivitymacrosolutionconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_productivityparameterdefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_project: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_projectapproval: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_projectparameter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_projectparameterpricelist: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_projectpricelist: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_projecttask: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_projecttaskdependency: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_projecttaskstatususer: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_projectteam: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_projectteammembersignup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_projecttransactioncategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_property: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_propertyassetassociation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_propertylog: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_propertytemplateassociation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_provider: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_purchaseorder: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_purchaseorderbill: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_purchaseorderproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_purchaseorderreceipt: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_purchaseorderreceiptproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_purchaseordersubstatus: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_questionsequence: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotebookingincident: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotebookingproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotebookingservice: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotebookingservicetask: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotebookingsetup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quoteinvoicingproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quoteinvoicingsetup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotelineanalyticsbreakdown: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotelineinvoiceschedule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotelineresourcecategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotelinescheduleofvalue: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotelinetransaction: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotelinetransactioncategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotelinetransactionclassification: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_quotepricelist: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_relationshipinsightsunifiedconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_requirementcharacteristic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_requirementdependency: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_requirementgroup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_requirementorganizationunit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_requirementrelationship: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_requirementresourcecategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_requirementresourcepreference: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_requirementstatus: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_resolution: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_resourceassignment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_resourceassignmentdetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_resourcecategorymarkuppricelevel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_resourcecategorypricelevel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_resourcepaytype: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_resourcerequest: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_resourcerequirement: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_resourcerequirementdetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_resourceterritory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_richtextfile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_rma: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_rmaproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_rmareceipt: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_rmareceiptproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_rmasubstatus: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_rolecompetencyrequirement: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_roleutilization: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_routingconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_routingconfigurationstep: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_routingrequest: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_routingrulesetsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_rtv: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_rtvproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_rtvsubstatus: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_rulesetdependencymapping: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_salesinsightssettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_scenario: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_scheduleboardsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_schedulingfeatureflag: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_schedulingparameter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_searchconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_sentimentanalysis: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_serviceconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_servicetasktype: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_sessiondata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_sessionevent: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_sessionparticipant: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_sessionparticipantdata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_sessiontemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_shipvia: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_siconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_sikeyvalueconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_skillattachmentruleitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_skillattachmenttarget: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_slakpi: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_smartassistconfig: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_smsengagementctx: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_smsnumber: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_solutionhealthrule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_solutionhealthruleargument: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_solutionhealthruleset: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_soundfile: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_soundnotificationsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_suggestioninteraction: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_suggestionrequestpayload: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_suggestionsmodelsummary: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_suggestionssetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_surveyquestion: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_systemuserschedulersetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_taxcode: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_taxcodedetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_teamscollaboration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_teamsdialeradminsettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_teamsengagementctx: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_templateforproperties: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_templateparameter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_templatetags: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_timeentry: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_timeentrysetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_timegroup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_timegroupdetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_timeoffcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_timeoffrequest: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_tour: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_transactioncategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_transactioncategoryclassification: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_transactioncategoryhierarchyelement: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_transactioncategorypricelevel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_transactionconnection: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_transactionorigin: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_transactiontype: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_transcript: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_twitterengagementctx: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_unifiedroutingdiagnostic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_unifiedroutingrun: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_unifiedroutingsetuptracker: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_uniquenumber: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_untrackedappointment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_upgraderun: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_upgradestep: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_upgradeversion: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_urnotificationtemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_urnotificationtemplatemapping: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_usersetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_userworkhistory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_visitorjourney: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_wallsavedquery: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_wallsavedqueryusersettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_warehouse: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_wechatengagementctx: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_whatsappengagementctx: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workhourtemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workorder: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workordercharacteristic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workorderdetailsgenerationqueue: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workorderincident: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workorderproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workorderresolution: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workorderresourcerestriction: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workorderservice: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workorderservicetask: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workordersubstatus: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyn_workordertype: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_actioncallworkflow: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_agentscriptaction: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_agentscripttaskcategory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_answer: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_auditanddiagnosticssetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_configuration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_customizationfiles: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_entityassignment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_entitysearch: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_form: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_languagemodule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_scriptlet: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_scripttasktrigger: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_search: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_sessioninformation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_sessiontransfer: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_task: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_toolbarbutton: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_toolbarstrip: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_tracesourcesetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_ucisettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_uiievent: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_usersettings: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msdyusd_windowroute: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_alert: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_alertrule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_emailtemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_fileresponse: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_localizedemailtemplate: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_project: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_question: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_questionresponse: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_satisfactionmetric: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_survey: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_surveyinvite: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_surveyreminder: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_surveyresponse: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_msfp_unsubscribedrecipient: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_opportunity: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_opportunityclose: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_opportunitycompetitors: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_opportunityproduct: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_opportunitysalesprocess: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_orderclose: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_organization: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_organizationdatasyncsubscription: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_organizationdatasyncsubscriptionentity: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_organizationsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_package: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_pdfsetting: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_phonecall: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_phonetocaseprocess: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_post: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_pricelevel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_privilege: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_processstageparameter: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_product: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_productassociation: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_productpricelevel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_productsalesliterature: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_productsubstitute: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_provisionlanguageforuser: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_quarterlyfiscalcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_queue: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_queueitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_quote: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_quoteclose: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_quotedetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_ratingmodel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_ratingvalue: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_recurringappointmentmaster: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_relationshipattribute: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_relationshiprole: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_relationshiprolemap: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_resource: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_resourcegroup: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_resourcegroupexpansion: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_resourcespec: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_revokeinheritedaccessrecordstracker: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_role: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_routingrule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_routingruleitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_salesliterature: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_salesliteratureitem: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_salesorder: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_salesorderdetail: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_salesprocessinstance: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_savedquery: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_semiannualfiscalcalendar: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_service: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_serviceappointment: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_servicecontractcontacts: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_serviceplan: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_settingdefinition: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_site: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_sla: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_socialactivity: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_solutioncomponentattributeconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_solutioncomponentconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_solutioncomponentrelationshipconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_stagesolutionupload: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_subject: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_systemform: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_systemuser: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_systemuserauthorizationchangetracker: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_task: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_team: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_teammobileofflineprofilemembership: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_template: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_territory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_theme: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_topic: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_topichistory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_topicmodel: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_topicmodelconfiguration: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_topicmodelexecutionhistory: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_action: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_audit: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_context: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_hostedapplication: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_nonhostedapplication: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_option: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_savedsession: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_sessiontransfer: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_workflow: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_workflowstep: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uii_workflow_workflowstep_mapping: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uom: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_uomschedule: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_userform: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_usermapping: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_usermobileofflineprofilemembership: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_userquery: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_virtualentitymetadata: DevKit.WebApi.LookupValueReadonly;
/** Unique identifier of the record that can not be deleted. */
regardingobjectid_workflowbinary: DevKit.WebApi.LookupValueReadonly;
RegardingObjectIdYomiName: DevKit.WebApi.StringValue;
}
}
declare namespace OptionSet {
namespace BulkDeleteFailure {
enum RollupState {
/** 0 - Attribute value is yet to be calculated */
NotCalculated,
/** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */
Calculated,
/** 2 - Attribute value calculation lead to overflow error */
OverflowError,
/** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */
OtherError,
/** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */
RetryLimitExceeded,
/** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */
HierarchicalRecursionLimitReached,
/** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */
LoopDetected
}
}
}
//{'JsForm':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
"use strict";
import { SinonStub } from "sinon";
import { Context, DispatchedPayload, Dispatcher, ErrorPayload, UseCase } from "../src";
import { TYPE as CompletedPayloadType } from "../src/payload/CompletedPayload";
import { TYPE as DidExecutedPayloadType } from "../src/payload/DidExecutedPayload";
import { TYPE as WillExecutedPayloadType } from "../src/payload/WillExecutedPayload";
import { UseCaseContext } from "../src/UseCaseContext";
import { createStore } from "./helper/create-new-store";
const assert = require("assert");
const sinon = require("sinon");
describe("UseCase", function () {
describe("id", () => {
it("should have unique id in instance", () => {
class ExampleUseCase extends UseCase {
execute(..._: Array<any>): any {}
}
const aUseCase = new ExampleUseCase();
assert(typeof aUseCase.id === "string");
const bUseCase = new ExampleUseCase();
assert(typeof bUseCase.id === "string");
assert(aUseCase.id !== bUseCase.id);
});
});
describe("name", () => {
// IE9, 10 not have Function.name
xit("should have name that same with UseCase.name by default", () => {
class ExampleUseCase extends UseCase {
execute() {}
}
const useCase = new ExampleUseCase();
assert(useCase.name === "ExampleUseCase");
});
describe("when define displayName", () => {
it("#name is same with displayName", () => {
class MyUseCase extends UseCase {
execute(..._: Array<any>): any {}
}
const expectedName = "Expected UseCase";
MyUseCase.displayName = expectedName;
const store = new MyUseCase();
assert.equal(store.name, expectedName);
});
});
});
describe("#throwError", function () {
it("should dispatch thought onDispatch event", function (done) {
class TestUseCase extends UseCase {
execute() {
this.throwError(new Error("error"));
}
}
const testUseCase = new TestUseCase();
// then
testUseCase.onDispatch((payload) => {
assert.ok(payload instanceof ErrorPayload, "should be instance of ErrorPayload");
if (payload instanceof ErrorPayload) {
assert(payload.error instanceof Error);
}
done();
});
// when
testUseCase.execute();
});
});
// scenario
describe("when execute B UseCase in A UseCase", function () {
it("should execute A:will -> B:will -> B:did -> A:did", function () {
class BUseCase extends UseCase {
execute() {
return "b";
}
}
class AUseCase extends UseCase {
execute() {
const bUseCase = new BUseCase();
const useCaseContext = this.context;
useCaseContext.useCase(bUseCase).execute();
}
}
const aUseCase = new AUseCase();
// for reference fn.name
const bUseCase = new BUseCase();
const callStack: string[] = [];
const expectedCallStackOfAUseCase = [WillExecutedPayloadType, DidExecutedPayloadType, CompletedPayloadType];
const expectedCallStack = [
`${aUseCase.name}:will`,
`${bUseCase.name}:will`,
`${bUseCase.name}:did`,
`${aUseCase.name}:did`
];
const dispatcher = new Dispatcher();
const context = new Context({
dispatcher,
store: createStore({ name: "test" })
});
// then
aUseCase.onDispatch((payload) => {
const type = payload.type;
const expectedType = expectedCallStackOfAUseCase.shift();
assert.equal(type, expectedType);
});
context.events.onWillExecuteEachUseCase((_payload, meta) => {
callStack.push(`${meta.useCase && meta.useCase.name}:will`);
});
context.events.onDidExecuteEachUseCase((_payload, meta) => {
callStack.push(`${meta.useCase && meta.useCase.name}:did`);
});
// when
return context
.useCase(aUseCase)
.execute()
.then(() => {
assert.deepEqual(callStack, expectedCallStack);
});
});
it("UseCase should have `context` that is Context instance", function () {
class TestUseCase extends UseCase {
execute() {
// then
assert(this.context instanceof UseCaseContext);
assert(typeof this.dispatch === "function");
}
}
const dispatcher = new Dispatcher();
const context = new Context({
dispatcher,
store: createStore({ name: "test" })
});
const useCase = new TestUseCase();
// when
context.useCase(useCase).execute();
});
});
describe("when not implemented execute()", function () {
it("should assert error on constructor", function () {
// @ts-ignore
class WrongImplementUseCase extends UseCase {}
try {
const useCase = new WrongImplementUseCase();
useCase.execute();
throw new Error("unreachable");
} catch (error) {
assert.equal(error.name, "TypeError");
}
});
});
describe("UseCase is nesting", function () {
/*
P: Parent UseCase
C: Child UseCase
C fin. P fin.
|---------------|------------|
P | |
C----------
*/
describe("when child did completed before parent is completed", function () {
const childPayload = {
type: "ChildUseCase"
};
class ChildUseCase extends UseCase {
execute() {
this.dispatch(childPayload);
}
}
class ParentUseCase extends UseCase {
execute() {
return this.context.useCase(new ChildUseCase()).execute();
}
}
it("should delegate dispatch to parent -> dispatcher", function () {
const dispatcher = new Dispatcher();
const context = new Context({
dispatcher,
store: createStore({ name: "test" })
});
const dispatchedPayloads: DispatchedPayload[] = [];
dispatcher.onDispatch((payload) => {
dispatchedPayloads.push(payload);
});
return context
.useCase(new ParentUseCase())
.execute()
.then(() => {
// childPayload should be delegated to dispatcher(root)
assert(dispatchedPayloads.indexOf(childPayload) !== -1);
});
});
});
/*
P: Parent UseCase
C: Child UseCase
P fin. C fin.
|---------------| |
P | |
C---------------------|
|
C call dispatch()
*/
describe("when child is completed after parent did completed", function () {
let consoleErrorStub: SinonStub;
beforeEach(() => {
consoleErrorStub = sinon.stub(console, "error");
});
afterEach(() => {
consoleErrorStub.restore();
});
it("should not delegate dispatch to parent -> dispatcher and show warning", function (done) {
const childPayload = {
type: "ChildUseCase"
};
const dispatchedPayloads: DispatchedPayload[] = [];
const finishCallBack = () => {
// childPayload should not be delegated to dispatcher(root)
assert(dispatchedPayloads.indexOf(childPayload) === -1);
// insteadof of it, should be display warning messages
assert(consoleErrorStub.called);
const warningMessage = consoleErrorStub.getCalls()[0].args[0];
assert(/Warning\(UseCase\):.*?is already released/.test(warningMessage), warningMessage);
done();
};
class ChildUseCase extends UseCase {
execute() {
this.dispatch(childPayload);
finishCallBack();
}
}
class ParentUseCase extends UseCase {
execute() {
// ChildUseCase is independent from Parent
// But, ChildUseCase is executed from Parent
// This is programming error
setTimeout(() => {
this.context.useCase(new ChildUseCase()).execute();
}, 16);
return Promise.resolve();
}
}
const dispatcher = new Dispatcher();
const context = new Context({
dispatcher,
store: createStore({ name: "test" })
});
dispatcher.onDispatch((payload) => {
dispatchedPayloads.push(payload);
});
context.useCase(new ParentUseCase()).execute();
});
});
});
}); | the_stack |
import SteamID from 'steamid';
import Bot from '../../Bot';
import CommandParser from '../../CommandParser';
import { TokenType, SubTokenType } from '../../TF2GC';
import log from '../../../lib/logger';
interface CraftWeaponsBySlot {
[slot: string]: string[];
}
type SlotsForCraftableWeapons = 'primary' | 'secondary' | 'melee' | 'pda2';
const capitalize = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
export default class CraftingCommands {
private craftWeaponsBySlot: CraftWeaponsBySlot;
private isCrafting = false;
constructor(private readonly bot: Bot) {
this.bot = bot;
}
craftTokenCommand(steamID: SteamID, message: string): void {
const opt = this.bot.options.crafting;
if (opt.manual === false) {
return this.bot.sendMessage(
steamID,
'❌ Please set crafting.manual option to true in order to use this command.'
);
}
if (this.isCrafting) {
return this.bot.sendMessage(
steamID,
"❌ Crafting token still in progress. Please wait until it's completed."
);
}
message = CommandParser.removeCommand(message).trim();
const parts = message.toLowerCase().split(' ');
// !craftToken <tokenType (class/slot)> <subTokenType (scout, soldier, etc)> <amount>
if (parts.length === 1 && ['check', 'info'].includes(parts[0])) {
// !craftToken check
// !craftToken info
return this.getCraftTokenInfo(steamID);
}
if (parts.length < 3) {
return this.bot.sendMessage(
steamID,
'❌ Wrong syntax. Correct syntax: !craftToken <tokenType> <subTokenType> <amount>' +
'\n - tokenType: "class" or "slot"' +
'\n - subTokenType: one of the 9 TF2 class characters if TokenType is class, or "primary"/"secondary"/"melee"/"pda2" if TokenType is slot' +
'\n - amount: Must be an integer'
);
}
const tokenType = parts[0];
const subTokenType = parts[1];
const amount = parseInt(parts[2]);
if (isNaN(amount)) {
return this.bot.sendMessage(steamID, '❌ Amount must be type integer!');
}
if (!['class', 'slot'].includes(tokenType)) {
return this.bot.sendMessage(steamID, '❌ tokenType must only be either "class" or "slot"!');
}
const classes = ['scout', 'soldier', 'pyro', 'demoman', 'heavy', 'engineer', 'medic', 'sniper', 'spy'];
const slotType = ['primary', 'secondary', 'melee', 'pda2'];
if (tokenType === 'class' && !classes.includes(subTokenType)) {
return this.bot.sendMessage(
steamID,
'❌ subTokenType must be one of 9 TF2 class character since your tokenType is "class"!'
);
} else if (tokenType === 'slot' && !slotType.includes(subTokenType)) {
return this.bot.sendMessage(
steamID,
'❌ subTokenType must only be either "primary", "secondary", "melee", or "pda2" since your tokenType is "slot"!'
);
}
if (tokenType === 'slot') {
// only load on demand
this.defineCraftWeaponsBySlots();
}
const assetids: string[] = [];
const craftableItems = this.bot.inventoryManager.getInventory.getCurrencies(
tokenType === 'class'
? this.bot.craftWeaponsByClass[subTokenType]
: this.craftWeaponsBySlot[subTokenType as SlotsForCraftableWeapons],
false
);
for (const sku in craftableItems) {
if (!Object.prototype.hasOwnProperty.call(craftableItems, sku)) {
continue;
}
if (craftableItems[sku].length === 0) {
delete craftableItems[sku];
continue;
}
assetids.push(...craftableItems[sku]);
}
const availableAmount = assetids.length;
const amountCanCraft = Math.floor(availableAmount / 3);
const capTokenType = capitalize(tokenType);
const capSubTokenType = subTokenType === 'pda2' ? 'PDA2' : capitalize(subTokenType);
if (amount > amountCanCraft) {
return this.bot.sendMessage(
steamID,
`❌ I can only craft ${amountCanCraft} ${capTokenType} Token - ${capSubTokenType} at the moment, since I only ` +
`have ${availableAmount} of ${capSubTokenType} ${tokenType} items.`
);
}
this.bot.sendMessage(steamID, '⏳ Crafting 🔨...');
this.isCrafting = true;
let crafted = 0;
let callbackIndex = 0;
for (let i = 0; i < amount; i++) {
const assetidsToCraft = assetids.splice(0, 3);
this.bot.tf2gc.craftToken(assetidsToCraft, tokenType as TokenType, subTokenType as SubTokenType, err => {
if (err) {
log.debug(
`Error crafting ${assetidsToCraft.join(', ')} for ${capTokenType} Token - ${capSubTokenType}`
);
crafted--;
}
callbackIndex++;
crafted++;
if (amount - callbackIndex === 0) {
this.isCrafting = false;
this.bot.client.gamesPlayed([]);
this.bot.client.gamesPlayed(
this.bot.options.miscSettings.game.playOnlyTF2 ? 440 : [this.bot.handler.customGameName, 440]
);
if (crafted < amount) {
return this.bot.sendMessage(
steamID,
`✅ Successfully crafted ${crafted} ${capTokenType} Token - ${capSubTokenType} (there were some error while crafting).`
);
}
return this.bot.sendMessage(
steamID,
`✅ Successfully crafted ${crafted} ${capTokenType} Token - ${capSubTokenType}!`
);
}
});
}
}
private getCraftTokenInfo(steamID: SteamID): void {
this.defineCraftWeaponsBySlots();
const reply: string[] = [];
const craftWeaponsByClass = this.bot.craftWeaponsByClass;
const inventory = this.bot.inventoryManager.getInventory;
for (const charClass in craftWeaponsByClass) {
if (!Object.prototype.hasOwnProperty.call(craftWeaponsByClass, charClass)) {
continue;
}
const craftableItems = this.bot.inventoryManager.getInventory.getCurrencies(
craftWeaponsByClass[charClass],
false
);
const assetids: string[] = [];
for (const sku in craftableItems) {
if (!Object.prototype.hasOwnProperty.call(craftableItems, sku)) {
continue;
}
if (craftableItems[sku].length === 0) {
delete craftableItems[sku];
continue;
}
assetids.push(...craftableItems[sku]);
}
const availableAmount = assetids.length;
const amountCanCraft = Math.floor(availableAmount / 3);
const capSubTokenType = capitalize(charClass);
let sku: string;
switch (charClass) {
case 'scout':
sku = '5003;6';
break;
case 'soldier':
sku = '5005;6';
break;
case 'pyro':
sku = '5009;6';
break;
case 'demoman':
sku = '5006;6';
break;
case 'heavy':
sku = '5007;6';
break;
case 'engineer':
sku = '5011;6';
break;
case 'medic':
sku = '5008;6';
break;
case 'sniper':
sku = '5004;6';
break;
case 'spy':
sku = '5010;6';
}
const currentTokenStock = inventory.getAmount(sku, false, true);
reply.push(
`Class Token - ${capSubTokenType}: can craft ${amountCanCraft} (${availableAmount} items), token stock: ${currentTokenStock}`
);
}
const craftWeaponsBySlots = this.craftWeaponsBySlot;
for (const slot in craftWeaponsBySlots) {
if (!Object.prototype.hasOwnProperty.call(craftWeaponsBySlots, slot)) {
continue;
}
const craftableItems = this.bot.inventoryManager.getInventory.getCurrencies(
craftWeaponsBySlots[slot],
false
);
const assetids: string[] = [];
for (const sku in craftableItems) {
if (!Object.prototype.hasOwnProperty.call(craftableItems, sku)) {
continue;
}
if (craftableItems[sku].length === 0) {
delete craftableItems[sku];
continue;
}
assetids.push(...craftableItems[sku]);
}
const availableAmount = assetids.length;
const amountCanCraft = Math.floor(availableAmount / 3);
const capSubTokenType = slot === 'pda2' ? 'PDA2' : capitalize(slot);
let sku: string;
switch (slot) {
case 'primary':
sku = '5012;6';
break;
case 'secondary':
sku = '5013;6';
break;
case 'melee':
sku = '5014;6';
break;
case 'pda2':
sku = '5018;6';
break;
}
const currentTokenStock = inventory.getAmount(sku, false, true);
reply.push(
`Slot Token - ${capSubTokenType}: can craft ${amountCanCraft} (${availableAmount} items), token stock: ${currentTokenStock}`
);
}
this.bot.sendMessage(steamID, '🔨 Crafting token info:\n\n- ' + reply.join('\n- '));
}
private defineCraftWeaponsBySlots(): void {
if (this.craftWeaponsBySlot === undefined) {
// only load on demand
this.craftWeaponsBySlot = {
primary: [],
secondary: [],
melee: [],
pda2: []
};
const craftableWeapons = this.bot.schema.getCraftableWeaponsSchema();
const count = craftableWeapons.length;
for (let i = 0; i < count; i++) {
const item = craftableWeapons[i];
if (['primary', 'secondary', 'melee', 'pda2'].includes(item.item_slot)) {
this.craftWeaponsBySlot[item.item_slot as SlotsForCraftableWeapons].push(`${item.defindex};6`);
}
}
}
}
} | the_stack |
import {
stringify,
parseVersion,
isMatch,
startsWith,
endsWith,
toBoolean
} from "../src/Utils.js";
describe("Utils", () => {
describe("stringify", () => {
const user = {
id: 1,
name: "Blake",
password: "123456",
passwordResetToken: "a reset token",
myPassword: "123456",
myPasswordValue: "123456",
customValue: "Password",
value: {
Password: "123456"
}
};
test("array", () => {
const error = {
type: "error",
data: {
"@error": {
type: "Error",
message: "string error message",
stack_trace: [
{
name: "throwStringErrorImpl",
parameters: [],
file_name: "http://localhost/index.js",
line_number: 22,
column: 9
},
{
name: "throwStringError",
parameters: [],
file_name: "http://localhost/index.js",
line_number: 10,
column: 10
}, {
name: "HTMLButtonElement.onclick",
parameters: [],
file_name: "http://localhost/",
line_number: 22,
column: 10
}]
},
"@submission_method": "onerror"
},
tags: []
};
expect(stringify(error)).toBe(JSON.stringify(error));
expect(stringify([error, error])).toBe(JSON.stringify([error, error]));
});
test("circular reference", () => {
const aFoo: { a: string, b?: unknown } = { a: "foo" };
aFoo.b = aFoo;
expect(stringify(aFoo)).toBe("{\"a\":\"foo\"}");
expect(stringify([{ one: aFoo, two: aFoo }])).toBe("[{\"one\":{\"a\":\"foo\"}}]");
});
test.skip("deep circular reference", () => {
const a: { b?: unknown } = {};
const b: { c?: unknown } = {};
const c: { a?: unknown, d: string } = { d: "test" };
a.b = b;
b.c = c;
c.a = a;
const expected = "{\"b\":{\"c\":{\"d\":\"test\"}}}";
const actual = stringify(a);
expect(actual).toBe(expected);
});
describe("should behave like JSON.stringify", () => {
[new Date(), 1, true, null, undefined, () => { return undefined; }, user].forEach((value) => {
test("for " + typeof (value), () => {
expect(stringify(value)).toBe(JSON.stringify(value));
});
});
});
/*
test.skip("should respect maxDepth", () => {
const deepObject = {
a: {
b: {
c: {
d: {}
}
}
}
};
expect(deepObject).toBe("TODO");
});
*/
test("should serialize inherited properties", () => {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
// @ts-expect-error TS2683
const Foo = function () { this.a = "a"; };
// @ts-expect-error TS2683
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const Bar = function () { this.b = "b"; };
// @ts-expect-error TS7009
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
Bar.prototype = new Foo();
// @ts-expect-error TS7009
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const bar = new Bar();
const expected = {
a: "a",
b: "b"
};
const result = JSON.parse(stringify(bar)) as unknown;
expect(result).toEqual(expected);
});
describe("with exclude pattern", () => {
test("pAssword", () => {
expect(stringify(user, ["pAssword"])).toBe(
JSON.stringify({ "id": 1, "name": "Blake", "passwordResetToken": "a reset token", "myPassword": "123456", "myPasswordValue": "123456", "customValue": "Password", "value": {} })
);
});
test("*password", () => {
expect(stringify(user, ["*password"])).toBe(
JSON.stringify({ "id": 1, "name": "Blake", "passwordResetToken": "a reset token", "myPasswordValue": "123456", "customValue": "Password", "value": {} })
);
});
test("password*", () => {
expect(stringify(user, ["password*"])).toBe(
JSON.stringify({ "id": 1, "name": "Blake", "myPassword": "123456", "myPasswordValue": "123456", "customValue": "Password", "value": {} })
);
});
test("*password*", () => {
JSON.stringify(expect(stringify(user, ["*password*"])).toBe(JSON.stringify({ "id": 1, "name": "Blake", "customValue": "Password", "value": {} })));
});
test("*Address", () => {
const event = { type: "usage", source: "about" };
expect(stringify(event, ["*Address"])).toBe(JSON.stringify(event));
});
});
});
test("should parse version from url", () => {
expect(parseVersion("https://code.jquery.com/jquery-2.1.3.js")).toBe("2.1.3");
expect(parseVersion("//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css")).toBe("3.3.4");
expect(parseVersion("https://cdnjs.cloudflare.com/ajax/libs/1140/2.0/1140.css")).toBe("2.0");
expect(parseVersion("https://cdnjs.cloudflare.com/ajax/libs/Base64/0.3.0/base64.min.js")).toBe("0.3.0");
expect(parseVersion("https://cdnjs.cloudflare.com/ajax/libs/angular-google-maps/2.1.0-X.10/angular-google-maps.min.js")).toBe("2.1.0-X.10");
expect(parseVersion("https://cdnjs.cloudflare.com/ajax/libs/swagger-ui/2.1.8-M1/swagger-ui.min.js")).toBe("2.1.8-M1");
expect(parseVersion("https://cdnjs.cloudflare.com/BLAH/BLAH.min.js")).toBeNull();
});
describe("isMatch", () => {
test("input: blake patterns [\"pAssword\"]", () => {
expect(isMatch("blake", ["pAssword"])).toBe(false);
});
test("input: pAssword patterns [\"pAssword\"]", () => {
expect(isMatch("pAssword", ["pAssword"])).toBe(true);
});
test("input: passwordResetToken patterns [\"pAssword\"]", () => {
expect(isMatch("passwordResetToken", ["pAssword"])).toBe(false);
});
test("input: myPassword patterns [\"pAssword\"]", () => {
expect(isMatch("myPassword", ["pAssword"])).toBe(false);
});
test("input: blake patterns [\" * pAssword\"]", () => {
expect(isMatch("blake", ["*pAssword"])).toBe(false);
});
test("input: pAssword patterns [\" * pAssword\"]", () => {
expect(isMatch("pAssword", ["*pAssword"])).toBe(true);
});
test("input: passwordResetToken patterns [\" * pAssword\"]", () => {
expect(isMatch("passwordResetToken", ["*pAssword"])).toBe(false);
});
test("input: myPassword patterns [\" * pAssword\"]", () => {
expect(isMatch("myPassword", ["*pAssword"])).toBe(true);
});
test("input: blake patterns [\"pAssword * \"]", () => {
expect(isMatch("blake", ["pAssword*"])).toBe(false);
});
test("input: pAssword patterns [\"pAssword * \"]", () => {
expect(isMatch("pAssword", ["pAssword*"])).toBe(true);
});
test("input: passwordResetToken patterns [\"pAssword * \"]", () => {
expect(isMatch("passwordResetToken", ["pAssword*"])).toBe(true);
});
test("input: myPassword patterns [\"pAssword * \"]", () => {
expect(isMatch("myPassword", ["pAssword*"])).toBe(false);
});
test("input: blake patterns [\" * pAssword * \"]", () => {
expect(isMatch("blake", ["*pAssword*"])).toBe(false);
});
test("input: pAssword patterns [\" * pAssword * \"]", () => {
expect(isMatch("pAssword", ["*pAssword*"])).toBe(true);
});
test("input: passwordResetToken patterns [\" * pAssword * \"]", () => {
expect(isMatch("passwordResetToken", ["*pAssword*"])).toBe(true);
});
test("input: myPassword patterns [\" * pAssword * \"]", () => {
expect(isMatch("myPassword", ["*pAssword*"])).toBe(true);
});
});
describe("startsWith", () => {
test("input: blake prefix: blake", () => {
expect(startsWith("blake", "blake")).toBe(true);
});
test("input: blake prefix: bl", () => {
expect(startsWith("blake", "bl")).toBe(true);
});
test("input: blake prefix: Blake", () => {
expect(startsWith("blake", "Blake")).toBe(false);
});
test("input: @@log:* prefix: @@log:", () => {
expect(startsWith("@@log:*", "@@log:")).toBe(true);
});
test("input: test prefix: noPattern", () => {
expect(startsWith("test", "noPattern")).toBe(false);
});
});
describe("endsWith", () => {
test("input: blake suffix: blake", () => {
expect(endsWith("blake", "blake")).toBe(true);
});
test("input: blake suffix: ake", () => {
expect(endsWith("blake", "ake")).toBe(true);
});
test("input: blake suffix: Blake", () => {
expect(endsWith("blake", "Blake")).toBe(false);
});
test("input: @@log:* suffix: log:*", () => {
expect(endsWith("@@log:*", "log:*")).toBe(true);
});
test("input: test suffix: noPattern", () => {
expect(endsWith("test", "noPattern")).toBe(false);
});
});
describe("toBoolean", () => {
test("input: blake", () => {
expect(toBoolean("blake")).toBe(false);
});
test("input: 0", () => {
expect(toBoolean("0")).toBe(false);
});
test("input: no", () => {
expect(toBoolean("no")).toBe(false);
});
test("input: false", () => {
expect(toBoolean("false")).toBe(false);
});
test("input: false", () => {
expect(toBoolean(false)).toBe(false);
});
test("input: undefined", () => {
expect(toBoolean(undefined)).toBe(false);
});
test("input: null", () => {
expect(toBoolean(null)).toBe(false);
});
test("input: 1", () => {
expect(toBoolean("1")).toBe(true);
});
test("input: yes", () => {
expect(toBoolean("yes")).toBe(true);
});
test("input: true", () => {
expect(toBoolean("true")).toBe(true);
});
test("input: true", () => {
expect(toBoolean(true)).toBe(true);
});
});
}); | the_stack |
import * as React from 'react';
// Custom styles
import styles from './FileBrowser.module.scss';
// Custom properties and state
import { IFileBrowserProps, IFileBrowserState, IFile, ViewType } from './FileBrowser.types';
// PnP library for navigating through libraries
import { sp, RenderListDataParameters, RenderListDataOptions } from "@pnp/sp";
// Office Fabric
import { Spinner } from 'office-ui-fabric-react/lib/Spinner';
import {
DetailsList,
DetailsListLayoutMode,
Selection,
SelectionMode,
IColumn,
IDetailsRowProps,
DetailsRow
} from 'office-ui-fabric-react/lib/DetailsList';
import { CommandBar, ICommandBarItemProps } from 'office-ui-fabric-react/lib/CommandBar';
import { IContextualMenuItem } from 'office-ui-fabric-react/lib/ContextualMenu';
const LAYOUT_STORAGE_KEY: string = 'comparerSiteFilesLayout';
// Localized strings
import * as strings from 'PropertyPaneFilePickerStrings';
// OneDrive services
import { OneDriveServices } from '../../../../services/OneDriveServices';
import { FormatBytes, GetAbsoluteDomainUrl } from '../../../../CommonUtils';
/**
* Renders list of file in a list.
* I should have used the PnP ListView control, but I wanted specific behaviour that I didn't
* get with the PnP control.
*/
export default class FileBrowser extends React.Component<IFileBrowserProps, IFileBrowserState> {
private _selection: Selection;
constructor(props: IFileBrowserProps) {
super(props);
// If possible, load the user's favourite layout
const lastLayout: ViewType = localStorage ?
localStorage.getItem(LAYOUT_STORAGE_KEY) as ViewType
: 'list' as ViewType;
const columns: IColumn[] = [
{
key: 'column1',
name: 'Type',
ariaLabel: strings.TypeAriaLabel,
iconName: 'Page',
isIconOnly: true,
fieldName: 'docIcon',
headerClassName: styles.iconColumnHeader,
minWidth: 16,
maxWidth: 16,
onColumnClick: this._onColumnClick,
onRender: (item: IFile) => {
const folderIcon: string = strings.FolderIconUrl;
const iconUrl: string = strings.PhotoIconUrl;
const altText: string = item.isFolder ? strings.FolderAltText : strings.ImageAltText.replace('{0}', item.fileType);
return <div className={styles.fileTypeIcon}>
<img src={item.isFolder ? folderIcon : iconUrl} className={styles.fileTypeIconIcon} alt={altText} title={altText} />
</div>;
}
},
{
key: 'column2',
name: strings.NameField,
fieldName: 'fileLeafRef',
minWidth: 210,
isRowHeader: true,
isResizable: true,
isSorted: true,
isSortedDescending: false,
sortAscendingAriaLabel: strings.SortedAscending,
sortDescendingAriaLabel: strings.SortedDescending,
onColumnClick: this._onColumnClick,
data: 'string',
isPadded: true,
onRender: (item: IFile) => {
if (item.isFolder) {
return <span className={styles.folderItem} onClick={(_event) => this._handleOpenFolder(item)}>{item.fileLeafRef}</span>;
} else {
return <span className={styles.fileItem}>{item.fileLeafRef}</span>;
}
},
},
{
key: 'column3',
name: strings.ModifiedField,
fieldName: 'dateModifiedValue',
minWidth: 120,
isResizable: true,
onColumnClick: this._onColumnClick,
data: 'number',
onRender: (item: IFile) => {
//const dateModified = moment(item.modified).format(strings.DateFormat);
return <span>{item.modified}</span>;
},
isPadded: true
},
{
key: 'column4',
name: strings.ModifiedByField,
fieldName: 'modifiedBy',
minWidth: 120,
isResizable: true,
data: 'string',
onColumnClick: this._onColumnClick,
onRender: (item: IFile) => {
return <span>{item.modifiedBy}</span>;
},
isPadded: true
},
{
key: 'column5',
name: strings.FileSizeField,
fieldName: 'fileSizeRaw',
minWidth: 70,
maxWidth: 90,
isResizable: true,
data: 'number',
onColumnClick: this._onColumnClick,
onRender: (item: IFile) => {
return <span>{item.fileSize ? FormatBytes(item.fileSize, 1) : undefined}</span>;
}
}
];
this._selection = new Selection({
onSelectionChanged: () => {
}
});
this.state = {
columns: columns,
items: [],
isLoading: true,
currentPath: this.props.rootPath,
selectedView: lastLayout
};
}
/**
* Gets the list of files when settings change
* @param prevProps
* @param prevState
*/
public componentDidUpdate(prevProps: IFileBrowserProps, prevState: IFileBrowserState): void {
if (prevState.currentPath !== prevState.currentPath) {
this._getListItems();
}
}
/**
* Gets the list of files when tab first loads
*/
public componentDidMount(): void {
this._getListItems();
}
public render(): React.ReactElement<IFileBrowserProps> {
if (this.state.isLoading) {
return (<Spinner label={strings.Loading} />);
}
return (
<div>
<div className={styles.itemPickerTopBar}>
<CommandBar
items={this._getToolbarItems()}
farItems={this.getFarItems()}
/>
</div>
<DetailsList
items={this.state.items}
compact={this.state.selectedView === 'compact'}
columns={this.state.columns}
selectionMode={SelectionMode.single}
setKey="set"
layoutMode={DetailsListLayoutMode.justified}
isHeaderVisible={true}
selection={this._selection}
selectionPreservedOnEmptyClick={true}
onActiveItemChanged={(item: IFile, index: number, ev: React.FormEvent<Element>) => this._itemChangedHandler(item, index, ev)}
enterModalSelectionOnTouch={true}
onRenderRow={this._onRenderRow}
/>
{this.state.items === undefined || this.state.items.length < 1 &&
this._renderEmptyFolder()
}
</div>
);
}
/**
* Renders a placeholder to indicate that the folder is empty
*/
private _renderEmptyFolder = (): JSX.Element => {
return (<div className={styles.emptyFolder}>
<div className={styles.emptyFolderImage}>
<img
className={styles.emptyFolderImageTag}
src={strings.OneDriveEmptyFolderIconUrl}
alt={strings.OneDriveEmptyFolderAlt} />
</div>
<div role="alert">
<div className={styles.emptyFolderTitle}>
{strings.OneDriveEmptyFolderTitle}
</div>
<div className={styles.emptyFolderSubText}>
<span className={styles.emptyFolderPc}>
{strings.OneDriveEmptyFolderDescription}
</span>
{/* Removed until we add support to upload */}
{/* <span className={styles.emptyFolderMobile}>
Tap <Icon iconName="Add" className={styles.emptyFolderIcon} /> to add files here.
</span> */}
</div>
</div>
</div>);
}
private _onRenderRow = (props: IDetailsRowProps): JSX.Element => {
const fileItem: IFile = props.item;
return <DetailsRow {...props} className={fileItem.isFolder ? styles.folderRow : styles.fileRow} />;
}
/**
* Get the list of toolbar items on the left side of the toolbar.
* We leave it empty for now, but we may add the ability to upload later.
*/
private _getToolbarItems = (): ICommandBarItemProps[] => {
return [
];
}
private getFarItems = (): ICommandBarItemProps[] => {
const { selectedView } = this.state;
let viewIconName: string = undefined;
let viewName: string = undefined;
switch (this.state.selectedView) {
case 'list':
viewIconName = 'List';
viewName = strings.ListLayoutList;
break;
case 'compact':
viewIconName = 'AlignLeft';
viewName = strings.ListLayoutCompact;
break;
default:
viewIconName = 'GridViewMedium';
viewName = strings.ListLayoutTile;
}
const farItems: ICommandBarItemProps[] = [
{
key: 'listOptions',
className: styles.commandBarNoChevron,
title: strings.ListOptionsTitle,
ariaLabel: strings.ListOptionsAlt.replace('{0}', viewName),
iconProps: {
iconName: viewIconName
},
iconOnly: true,
subMenuProps: {
items: [
{
key: 'list',
name: strings.ListLayoutList,
iconProps: {
iconName: 'List'
},
canCheck: true,
checked: this.state.selectedView === 'list',
ariaLabel: strings.ListLayoutAriaLabel.replace('{0}', strings.ListLayoutList).replace('{1}', selectedView === 'list' ? strings.Selected : undefined),
title: strings.ListLayoutListDescrition,
onClick: (_ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => this._handleSwitchLayout(item)
},
{
key: 'compact',
name: strings.ListLayoutCompact,
iconProps: {
iconName: 'AlignLeft'
},
canCheck: true,
checked: this.state.selectedView === 'compact',
ariaLabel: strings.ListLayoutAriaLabel.replace('{0}', strings.ListLayoutCompact).replace('{1}', selectedView === 'compact' ? strings.Selected : undefined),
title: strings.ListLayoutCompactDescription,
onClick: (_ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => this._handleSwitchLayout(item)
},
{
key: 'tiles',
name: 'Tiles',
iconProps: {
iconName: 'GridViewMedium'
},
canCheck: true,
checked: this.state.selectedView === 'tiles',
ariaLabel: strings.ListLayoutAriaLabel.replace('{0}', strings.ListLayoutTile).replace('{1}', selectedView === 'tiles' ? strings.Selected : undefined),
title: strings.ListLayoutTileDescription,
onClick: (_ev?: React.MouseEvent<HTMLElement> | React.KeyboardEvent<HTMLElement>, item?: IContextualMenuItem) => this._handleSwitchLayout(item)
}
]
}
}
];
return farItems;
}
/**
* Called when users switch the view
*/
private _handleSwitchLayout = (item?: IContextualMenuItem) => {
if (item) {
// Store the user's favourite layout
if (localStorage) {
localStorage.setItem(LAYOUT_STORAGE_KEY, item.key);
}
this.setState({
selectedView: item.key as ViewType
});
}
}
/**
* Gratuitous sorting
*/
private _onColumnClick = (event: React.MouseEvent<HTMLElement>, column: IColumn): void => {
const { columns } = this.state;
let { items } = this.state;
let isSortedDescending = column.isSortedDescending;
// If we've sorted this column, flip it.
if (column.isSorted) {
isSortedDescending = !isSortedDescending;
}
// Sort the items.
items = items!.concat([]).sort((a, b) => {
const firstValue = a[column.fieldName || ''];
const secondValue = b[column.fieldName || ''];
if (isSortedDescending) {
return firstValue > secondValue ? -1 : 1;
} else {
return firstValue > secondValue ? 1 : -1;
}
});
// Reset the items and columns to match the state.
this.setState({
items: items,
columns: columns!.map(col => {
col.isSorted = col.key === column.key;
if (col.isSorted) {
col.isSortedDescending = isSortedDescending;
}
return col;
})
});
}
/**
* When a folder is opened, calls parent tab to navigate down
*/
private _handleOpenFolder = (item: IFile) => {
// De-select the list item that was clicked, the item in the same position
// item in the folder will appear selected
this.setState({
fileUrl: undefined,
currentPath: item.fileRef
}, () => this._getListItems());
this.props.onOpenFolder(item);
}
/**
* When user selects an item, save selection
*/
private _itemChangedHandler = (item: IFile, _index: number, _ev): void => {
if (item.isFolder) {
this.setState({
fileUrl: undefined
});
return;
}
// Notify parent tab
const absoluteFileUrl: string = item.absoluteRef;
this.props.onChange(absoluteFileUrl);
this.setState({
fileUrl: absoluteFileUrl
});
}
/**
* Gets all files in a library with a matchihg path
*/
private _getListItems() {
this.setState({
isLoading: true
});
const fileFilter: string = OneDriveServices.GetFileTypeFilter(this.props.accepts);
const parms: RenderListDataParameters = {
RenderOptions: RenderListDataOptions.ContextInfo | RenderListDataOptions.ListData | RenderListDataOptions.ListSchema | RenderListDataOptions.ViewMetadata | RenderListDataOptions.EnableMediaTAUrls | RenderListDataOptions.ParentInfo,//4231, //4103, //4231, //192, //64
AllowMultipleValueFilterForTaxonomyFields: true,
FolderServerRelativeUrl: this.state.currentPath,
ViewXml:
`<View>
<Query>
<Where>
<Or>
<And>
<Eq>
<FieldRef Name="FSObjType" />
<Value Type="Text">1</Value>
</Eq>
<Eq>
<FieldRef Name="SortBehavior" />
<Value Type="Text">1</Value>
</Eq>
</And>
<In>
<FieldRef Name="File_x0020_Type" />
${fileFilter}
</In>
</Or>
</Where>
</Query>
<ViewFields>
<FieldRef Name="DocIcon"/>
<FieldRef Name="LinkFilename"/>
<FieldRef Name="Modified"/>
<FieldRef Name="Editor"/>
<FieldRef Name="FileSizeDisplay"/>
<FieldRef Name="SharedWith"/>
<FieldRef Name="MediaServiceFastMetadata"/>
<FieldRef Name="MediaServiceOCR"/>
<FieldRef Name="_ip_UnifiedCompliancePolicyUIAction"/>
<FieldRef Name="ItemChildCount"/>
<FieldRef Name="FolderChildCount"/>
<FieldRef Name="SMTotalFileCount"/>
<FieldRef Name="SMTotalSize"/>
</ViewFields>
<RowLimit Paged="TRUE">100</RowLimit>
</View>`
};
sp.web.lists.getByTitle(this.props.libraryName).renderListDataAsStream(parms).then((value: any) => {
const fileItems: IFile[] = value.ListData.Row.map(fileItem => {
const modifiedFriendly: string = fileItem["Modified.FriendlyDisplay"];
// Get the modified date
const modifiedParts: string[] = modifiedFriendly!.split('|');
let modified: string = fileItem.Modified;
// If there is a friendly modified date, use that
if (modifiedParts.length === 2) {
modified = modifiedParts[1];
}
const file: IFile = {
fileLeafRef: fileItem.FileLeafRef,
docIcon: fileItem.DocIcon,
fileRef: fileItem.FileRef,
modified: modified,
fileSize: fileItem.File_x0020_Size,
fileType: fileItem.File_x0020_Type,
modifiedBy: fileItem.Editor![0]!.title,
isFolder: fileItem.FSObjType === "1",
absoluteRef: this._buildAbsoluteUrl(fileItem.FileRef)
};
return file;
});
// de-select anything that was previously selected
this._selection.setAllSelected(false);
this.setState({
items: fileItems,
isLoading: false
});
});
}
/**
* Creates an absolute URL
*/
private _buildAbsoluteUrl = (relativeUrl: string) => {
const siteUrl: string = GetAbsoluteDomainUrl(this.props.context.pageContext.web.absoluteUrl);
return siteUrl + relativeUrl;
}
} | the_stack |
'use strict';
import { FeatureTableUtils } from './featureMetatableUtilsNext';
import { Material, TexturedMaterial } from './Material';
import { TranslucencyType, BaseColorType } from './colorTypes';
const Cesium = require('cesium');
const util = require('./utility');
const Cartesian3 = Cesium.Cartesian3;
const CesiumMath = Cesium.Math;
const defaultValue = Cesium.defaultValue;
const Matrix4 = Cesium.Matrix4;
const Quaternion = Cesium.Quaternion;
const metersToLongitude = util.metersToLongitude;
const metersToLatitude = util.metersToLatitude;
const scratchTranslation = new Cartesian3();
const scratchRotation = new Quaternion();
const scratchScale = new Cartesian3();
const whiteOpaqueMaterial = new Material([1.0, 1.0, 1.0, 1.0]);
const whiteTranslucentMaterial = new Material([1.0, 1.0, 1.0, 0.5]);
const texturedMaterial = new TexturedMaterial('data/wood_red.jpg');
const redMaterial = new Material([1.0, 0.0, 0.0, 1.0]);
/**
* Creates a set of buildings that will be converted to a b3dm tile.
*
* @param {Object} [options] Object with the following properties:
* @param {Boolean} [options.uniform=false] Whether to create uniformly sized and spaced buildings.
* @param {Number} [options.numberOfBuildings=10] The number of buildings to create.
* @param {Number} [options.tileWidth=200.0] The width of the tile in meters. Buildings are placed randomly in this area.
* @param {Number} [options.averageWidth=4.0] Average building width in meters around which random widths and depths are generated.
* @param {Number} [options.averageHeight=5.0] Average building height in meters around which random heights are generated.
* @param {String} [options.baseColorType=BaseColorType.White] Specifies the type of diffuse color to apply to the tile.
* @param {String} [options.translucencyType=TranslucencyType.Opaque] Specifies the type of translucency to apply to the tile.
* @param {Number} [options.longitude=-1.31968] The center longitude of the tile. Used to generate metadata for the batch table.
* @param {Number} [options.latitude=0.698874] The center latitude of the tile. Used to generate metadata for the batch table.
* @param {Number} [options.seed=11] The random seed to use.
*
* @returns {Building[]} An array of buildings.
*/
export function createBuildings(options: FeatureTableUtils.BuildingGenerationOptions): Building[] {
options = defaultValue(options, {});
options.seed = defaultValue(options.seed, 11);
options.numberOfBuildings = defaultValue(options.numberOfBuildings, 10);
options.tileWidth = defaultValue(options.tileWidth, 200.0);
options.averageWidth = defaultValue(options.averageWidth, 4.0);
options.averageHeight = defaultValue(options.averageHeight, 5.0);
options.baseColorType = defaultValue(options.baseColorType, BaseColorType.White);
options.translucencyType = defaultValue(options.translucencyType, TranslucencyType.Opaque);
options.longitude = defaultValue(options.longitude, -1.31968);
options.latitude = defaultValue(options.latitude, 0.698874);
if (options.uniform) {
return createUniformBuildings(options);
}
return createRandomBuildings(options);
}
function createUniformBuildings(options): Building[] {
const numberOfBuildings = options.numberOfBuildings;
const tileWidth = options.tileWidth;
const centerLongitude = options.longitude;
const centerLatitude = options.latitude;
const buildingsPerAxis = Math.sqrt(numberOfBuildings);
const buildingWidth = tileWidth / (buildingsPerAxis * 3);
const buildings = [];
for (let i = 0; i < buildingsPerAxis; ++i) {
for (let j = 0; j < buildingsPerAxis; ++j) {
const x = buildingWidth * 1.5 + i * buildingWidth * 3.0 - tileWidth / 2.0;
const y = buildingWidth * 1.5 + j * buildingWidth * 3.0 - tileWidth / 2.0;
const z = buildingWidth / 2.0;
const rangeX = x / tileWidth - 0.5;
const rangeY = y / tileWidth - 0.5;
const translation = Cartesian3.fromElements(x, y, z, scratchTranslation);
const rotation = Quaternion.clone(Quaternion.IDENTITY, scratchRotation);
const scale = Cartesian3.fromElements(buildingWidth, buildingWidth, buildingWidth, scratchScale);
const matrix = Matrix4.fromTranslationQuaternionRotationScale(translation, rotation, scale, new Matrix4());
const longitudeExtent = metersToLongitude(tileWidth, centerLatitude);
const latitudeExtent = metersToLatitude(tileWidth, centerLongitude);
const longitude = centerLongitude + rangeX * longitudeExtent;
const latitude = centerLatitude + rangeY * latitudeExtent;
buildings.push(new Building({
matrix : matrix,
material : whiteOpaqueMaterial,
longitude : longitude,
latitude : latitude,
height : buildingWidth
}));
}
}
return buildings;
}
function createRandomBuildings(options): Building[] {
const seed = options.seed;
const numberOfBuildings = options.numberOfBuildings;
const tileWidth = options.tileWidth;
const averageWidth = options.averageWidth;
const averageHeight = options.averageHeight;
const baseColorType = options.baseColorType;
const translucencyType = options.translucencyType;
const centerLongitude = options.longitude;
const centerLatitude = options.latitude;
// Set the random number seed before creating materials
CesiumMath.setRandomNumberSeed(seed);
const materials = new Array(numberOfBuildings);
let i;
for (i = 0; i < numberOfBuildings; ++i) {
// For CesiumJS testing purposes make the first building red
const useRedMaterial = (baseColorType === BaseColorType.Color) &&
(translucencyType === TranslucencyType.Opaque) &&
i === 0;
const randomMaterial = getMaterial(baseColorType, translucencyType, i, numberOfBuildings);
materials[i] = (useRedMaterial) ? redMaterial : randomMaterial;
}
// Set the random number seed before creating buildings so that the generated buildings are the same between runs
CesiumMath.setRandomNumberSeed(seed);
const buildings = new Array(numberOfBuildings);
for (i = 0; i < numberOfBuildings; ++i) {
// Create buildings with the z-axis as up
const width = Math.max(averageWidth + (CesiumMath.nextRandomNumber() - 0.5) * 8.0, 1.0);
const depth = Math.max(width + (CesiumMath.nextRandomNumber() - 0.5) * 4.0, 1.0);
const height = Math.max(averageHeight + (CesiumMath.nextRandomNumber() - 0.5) * 8.0, 1.0);
const minX = -tileWidth / 2.0 + width / 2.0;
const maxX = tileWidth / 2.0 - width / 2.0;
const minY = -tileWidth / 2.0 + depth / 2.0;
const maxY = tileWidth / 2.0 - depth / 2.0;
let rangeX = CesiumMath.nextRandomNumber() - 0.5;
let rangeY = CesiumMath.nextRandomNumber() - 0.5;
// For CesiumJS testing purposes, always place one building in the center of the tile and make it red
if (i === 0) {
rangeX = 0.0;
rangeY = 0.0;
}
let x = rangeX * tileWidth;
let y = rangeY * tileWidth;
x = CesiumMath.clamp(x, minX, maxX);
y = CesiumMath.clamp(y, minY, maxY);
const z = height / 2.0;
const translation = Cartesian3.fromElements(x, y, z, scratchTranslation);
const rotation = Quaternion.clone(Quaternion.IDENTITY, scratchRotation);
const scale = Cartesian3.fromElements(width, depth, height, scratchScale);
const matrix = Matrix4.fromTranslationQuaternionRotationScale(translation, rotation, scale, new Matrix4());
const longitudeExtent = metersToLongitude(tileWidth, centerLatitude);
const latitudeExtent = metersToLatitude(tileWidth, centerLongitude);
const longitude = centerLongitude + rangeX * longitudeExtent;
const latitude = centerLatitude + rangeY * latitudeExtent;
buildings[i] = new Building({
matrix : matrix,
material : materials[i],
longitude : longitude,
latitude : latitude,
height : height
});
}
return buildings;
}
export interface Building {
matrix: object; // Cesium.Matrix4 TODO: proper types
material: Material;
longitude: number;
latitude: number;
height: number
}
/**
* Information that describes a building, including position, appearance, and metadata.
*
* @param {Object} options Object with the following properties:
* @param {Matrix4} options.matrix The matrix defining the position and size of the building.
* @param {Material} options.material The material of the building.
* @param {Number} options.longitude Longitude of the building - metadata for the batch table.
* @param {Number} options.latitude Latitude of the building - metadata for the batch table.
* @param {Number} options.height Height of the building - metadata for the batch table.
*
* @constructor
* @private
*/
function Building(options) {
this.matrix = options.matrix;
this.material = options.material;
this.longitude = options.longitude;
this.latitude = options.latitude;
this.height = options.height;
}
function getRandomColorMaterial(alpha) {
const red = CesiumMath.nextRandomNumber();
const green = CesiumMath.nextRandomNumber();
const blue = CesiumMath.nextRandomNumber();
return new Material([red, green, blue, alpha]);
}
function getMaterial(
baseColorType: BaseColorType,
translucencyType: TranslucencyType,
buildingIndex: number,
numberOfBuildings: number
): Material | TexturedMaterial {
const firstHalf = (buildingIndex < numberOfBuildings / 2);
if (baseColorType === BaseColorType.White) {
if (translucencyType === TranslucencyType.Opaque) {
return whiteOpaqueMaterial;
} else if (translucencyType === TranslucencyType.Translucent) {
return whiteTranslucentMaterial;
} else if (translucencyType === TranslucencyType.Mix) {
return firstHalf ? whiteOpaqueMaterial : whiteTranslucentMaterial;
}
} else if (baseColorType === BaseColorType.Color) {
if (translucencyType === TranslucencyType.Opaque) {
return getRandomColorMaterial(1.0);
} else if (translucencyType === TranslucencyType.Translucent) {
return getRandomColorMaterial(0.5);
} else if (translucencyType === TranslucencyType.Mix) {
const alpha = (firstHalf) ? 1.0 : 0.5;
return getRandomColorMaterial(alpha);
}
} else if (baseColorType === BaseColorType.Texture) {
return texturedMaterial;
}
} | the_stack |
import { Inject, Injectable, Optional } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http';
import { Response, ResponseContentType } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import * as models from '../model/models';
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration';
@Injectable()
export class DefaultApi {
protected basePath = location.protocol + '//' + location.hostname + ':' + (location.port === '4200' ? '8080' : location.port);
public defaultHeaders: Headers = new Headers();
public configuration: Configuration = new Configuration();
constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) {
if (basePath) {
this.basePath = basePath;
}
if (configuration) {
this.configuration = configuration;
}
}
/**
*
* @param bibtexkey
* @param id
*/
public deleteComment(bibtexkey: string, id: number, extraHttpRequestParams?: any): Observable<{}> {
return this.deleteCommentWithHttpInfo(bibtexkey, id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
*/
public getPdfComments(bibtexkey: string, extraHttpRequestParams?: any): Observable<Array<models.Comment>> {
return this.getPdfCommentsWithHttpInfo(bibtexkey, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
*/
public getPdfFile(bibtexkey: string, extraHttpRequestParams?: any): Observable<{}> {
return this.getPdfFileWithHttpInfo(bibtexkey, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return new Blob([response.blob()], { type: 'application/pdf' }) || {};
}
});
}
/**
*
* @param bibtexkey
*/
public getReference(bibtexkey: string, extraHttpRequestParams?: any): Observable<models.BibTeXEntry> {
return this.getReferenceWithHttpInfo(bibtexkey, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
*/
public getReferences(extraHttpRequestParams?: any): Observable<Array<models.Reference>> {
return this.getReferencesWithHttpInfo(extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
* @param id
*/
public getSuggestion(bibtexkey: string, id: number, extraHttpRequestParams?: any): Observable<models.BibTeXEntry> {
return this.getSuggestionWithHttpInfo(bibtexkey, id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
*/
public getSuggestions(bibtexkey: string, extraHttpRequestParams?: any): Observable<Array<{ [key: string]: string; }>> {
return this.getSuggestionsWithHttpInfo(bibtexkey, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
*/
public loginUser(extraHttpRequestParams?: any): Observable<string> {
return this.loginUserWithHttpInfo(extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
* @param id
* @param body
*/
public mergeSuggestion(bibtexkey: string, id: number, body: models.MergeInstruction, extraHttpRequestParams?: any): Observable<{}> {
return this.mergeSuggestionWithHttpInfo(bibtexkey, id, body, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
* @param body
*/
public rateReference(bibtexkey: string, body: models.Rating, extraHttpRequestParams?: any): Observable<models.ResponseRatingReference> {
return this.rateReferenceWithHttpInfo(bibtexkey, body, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
* @param id
* @param body
*/
public rateSuggestion(bibtexkey: string, id: number, body: models.Rating, extraHttpRequestParams?: any): Observable<models.ResponseRatingSuggestion> {
return this.rateSuggestionWithHttpInfo(bibtexkey, id, body, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param body
* @param bibtexkey
*/
public saveComment(body: models.Comment, bibtexkey: string, extraHttpRequestParams?: any): Observable<{}> {
return this.saveCommentWithHttpInfo(body, bibtexkey, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else if (response.status === 201) {
return response.url;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
* @param file
*/
public savePdfFile(bibtexkey: string, file: any, extraHttpRequestParams?: any): Observable<{}> {
return this.savePdfFileWithHttpInfo(bibtexkey, file, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
* @param body
*/
public saveReference(bibtexkey: string, body: models.BibTeXEntry, extraHttpRequestParams?: any): Observable<{}> {
return this.saveReferenceWithHttpInfo(bibtexkey, body, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} if (response.status === 201) {
return response.url;
} else {
return response.json() || {};
}
});
}
/**
*
* @param file
*/
public saveReferences(file: any, extraHttpRequestParams?: any): Observable<{}> {
return this.saveReferencesWithHttpInfo(file, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else if (response.status === 201) {
return response.url;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
* @param body
*/
public saveSuggestion(bibtexkey: string, body: models.BibTeXEntry, extraHttpRequestParams?: any): Observable<{}> {
return this.saveSuggestionWithHttpInfo(bibtexkey, body, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} if (response.status === 201) {
return response.url;
} else {
return response.json() || {};
}
});
}
/**
*
* @param username
* @param body
*/
public saveUser(username: string, body: models.User, extraHttpRequestParams?: any): Observable<{}> {
return this.saveUserWithHttpInfo(username, body, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param body
* @param bibtexkey
* @param id
*/
public updateComment(body: models.Comment, bibtexkey: string, id: number, extraHttpRequestParams?: any): Observable<{}> {
return this.updateCommentWithHttpInfo(body, bibtexkey, id, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
* @param bibtexkey
* @param id
* @param body
*/
public updateSuggestion(bibtexkey: string, id: number, body: models.BibTeXEntry, extraHttpRequestParams?: any): Observable<{}> {
return this.updateSuggestionWithHttpInfo(bibtexkey, id, body, extraHttpRequestParams)
.map((response: Response) => {
if (response.status === 204) {
return undefined;
} else {
return response.json() || {};
}
});
}
/**
*
*
* @param bibtexkey
* @param id
*/
public deleteCommentWithHttpInfo(bibtexkey: string, id: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/pdf/comments/${id}'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey))
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling deleteComment.');
}
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling deleteComment.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Delete,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
*/
public getPdfCommentsWithHttpInfo(bibtexkey: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/pdf/comments'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling getPdfComments.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
*/
public getPdfFileWithHttpInfo(bibtexkey: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/pdf'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling getPdfFile.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/octet-stream'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials: this.configuration.withCredentials,
responseType: ResponseContentType.Blob,
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
*/
public getReferenceWithHttpInfo(bibtexkey: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling getReference.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
*/
public getReferencesWithHttpInfo(extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
* @param id
*/
public getSuggestionWithHttpInfo(bibtexkey: string, id: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/suggestions/${id}'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey))
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling getSuggestion.');
}
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getSuggestion.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
*/
public getSuggestionsWithHttpInfo(bibtexkey: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/suggestions'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling getSuggestions.');
}
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
*/
public loginUserWithHttpInfo(extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/login';
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// to determine the Content-Type header
let consumes: string[] = [
];
// to determine the Accept header
let produces: string[] = [
'application/json'
];
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Get,
headers: headers,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
* @param id
* @param body
*/
public mergeSuggestionWithHttpInfo(bibtexkey: string, id: number, body: models.MergeInstruction, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/suggestions/${id}/merge'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey))
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling mergeSuggestion.');
}
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling mergeSuggestion.');
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new Error('Required parameter body was null or undefined when calling mergeSuggestion.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
* @param body
*/
public rateReferenceWithHttpInfo(bibtexkey: string, body: models.Rating, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/rating'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling rateReference.');
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new Error('Required parameter body was null or undefined when calling rateReference.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
* @param id
* @param body
*/
public rateSuggestionWithHttpInfo(bibtexkey: string, id: number, body: models.Rating, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/suggestions/${id}/rating'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey))
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling rateSuggestion.');
}
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling rateSuggestion.');
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new Error('Required parameter body was null or undefined when calling rateSuggestion.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param body
* @param bibtexkey
*/
public saveCommentWithHttpInfo(body: models.Comment, bibtexkey: string, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/pdf/comments'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new Error('Required parameter body was null or undefined when calling saveComment.');
}
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling saveComment.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
* @param file
*/
public savePdfFileWithHttpInfo(bibtexkey: string, file: any, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/pdf'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey));
let queryParameters = new URLSearchParams();
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling savePdfFile.');
}
// verify required parameter 'file' is not null or undefined
if (file === null || file === undefined) {
throw new Error('Required parameter file was null or undefined when calling savePdfFile.');
}
// to determine the Content-Type header
let consumes: string[] = [
'multipart/form-data'
];
// to determine the Accept header
let produces: string[] = [
];
//headers.set('Content-Type', 'application/x-www-form-urlencoded');
const input = new FormData();
if (file !== undefined) {
input.append('file', file);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
body: input,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
* @param body
*/
public saveReferenceWithHttpInfo(bibtexkey: string, body: models.BibTeXEntry, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling saveReference.');
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new Error('Required parameter body was null or undefined when calling saveReference.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param file
*/
public saveReferencesWithHttpInfo(file: any, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references';
let queryParameters = new URLSearchParams();
// verify required parameter 'file' is not null or undefined
if (file === null || file === undefined) {
throw new Error('Required parameter file was null or undefined when calling savePdfFile.');
}
// to determine the Content-Type header
let consumes: string[] = [
'multipart/form-data'
];
// to determine the Accept header
let produces: string[] = [
];
//headers.set('Content-Type', 'application/x-www-form-urlencoded');
const input = new FormData();
if (file !== undefined) {
input.append('file', file);
}
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
body: input,
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
* @param body
*/
public saveSuggestionWithHttpInfo(bibtexkey: string, body: models.BibTeXEntry, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/suggestions'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling saveSuggestion.');
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new Error('Required parameter body was null or undefined when calling saveSuggestion.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Post,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param username
* @param body
*/
public saveUserWithHttpInfo(username: string, body: models.User, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/users/${username}'
.replace('${' + 'username' + '}', String(username));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'username' is not null or undefined
if (username === null || username === undefined) {
throw new Error('Required parameter username was null or undefined when calling saveUser.');
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new Error('Required parameter body was null or undefined when calling saveUser.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param body
* @param bibtexkey
* @param id
*/
public updateCommentWithHttpInfo(body: models.Comment, bibtexkey: string, id: number, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/pdf/comments/${id}'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey))
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new Error('Required parameter body was null or undefined when calling updateComment.');
}
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling updateComment.');
}
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling updateComment.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
/**
*
*
* @param bibtexkey
* @param id
* @param body
*/
public updateSuggestionWithHttpInfo(bibtexkey: string, id: number, body: models.BibTeXEntry, extraHttpRequestParams?: any): Observable<Response> {
const path = this.basePath + '/references/${bibtexkey}/suggestions/${id}'
.replace('${' + 'bibtexkey' + '}', String(bibtexkey))
.replace('${' + 'id' + '}', String(id));
let queryParameters = new URLSearchParams();
let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845
// verify required parameter 'bibtexkey' is not null or undefined
if (bibtexkey === null || bibtexkey === undefined) {
throw new Error('Required parameter bibtexkey was null or undefined when calling updateSuggestion.');
}
// verify required parameter 'id' is not null or undefined
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling updateSuggestion.');
}
// verify required parameter 'body' is not null or undefined
if (body === null || body === undefined) {
throw new Error('Required parameter body was null or undefined when calling updateSuggestion.');
}
// to determine the Content-Type header
let consumes: string[] = [
'application/json'
];
// to determine the Accept header
let produces: string[] = [
];
headers.set('Content-Type', 'application/json');
let requestOptions: RequestOptionsArgs = new RequestOptions({
method: RequestMethod.Put,
headers: headers,
body: body == null ? '' : JSON.stringify(body), // https://github.com/angular/angular/issues/10612
search: queryParameters,
withCredentials:this.configuration.withCredentials
});
// https://github.com/swagger-api/swagger-codegen/issues/4037
if (extraHttpRequestParams) {
requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams);
}
return this.http.request(path, requestOptions);
}
} | the_stack |
* @fileoverview Macro and environment implementations for the mathtools package.
*
* @author v.sorge@mathjax.org (Volker Sorge)
* @author dpvc@mathjax.org (Davide P. Cervone)
*/
import {ArrayItem, EqnArrayItem} from '../base/BaseItems.js';
import {StackItem} from '../StackItem.js';
import ParseUtil from '../ParseUtil.js';
import {ParseMethod, ParseResult} from '../Types.js';
import {AmsMethods} from '../ams/AmsMethods.js';
import BaseMethods from '../base/BaseMethods.js';
import TexParser from '../TexParser.js';
import TexError from '../TexError.js';
import NodeUtil from '../NodeUtil.js';
import {TEXCLASS} from '../../../core/MmlTree/MmlNode.js';
import {length2em, em} from '../../../util/lengths.js';
import {lookup} from '../../../util/Options.js';
import NewcommandUtil from '../newcommand/NewcommandUtil.js';
import NewcommandMethods from '../newcommand/NewcommandMethods.js';
import {MathtoolsTags} from './MathtoolsTags.js';
import {MathtoolsUtil} from './MathtoolsUtil.js';
/**
* The implementations for the macros and environments for the mathtools package.
*/
export const MathtoolsMethods: Record<string, ParseMethod> = {
/**
* Handle a mathtools matrix environment, with optional alignment.
*
* @param {TexParser} parser The active tex parser.
* @param {StackItem} begin The BeginItem for the environment.
* @param {string} open The open delimiter for the matrix.
* @param {string} close The close delimiter for the matrix.
* @return {ParserResult} The ArrayItem for the matrix.
*/
MtMatrix(parser: TexParser, begin: StackItem, open: string, close: string): ParseResult {
const align = parser.GetBrackets(`\\begin{${begin.getName()}}`, 'c');
return MathtoolsMethods.Array(parser, begin, open, close, align);
},
/**
* Create a smallmatrix with given delimiters, and with optional alignment (and settable default)
*
* @param {TexParser} parser The active tex parser.
* @param {StackItem} begin The BeginItem for the environment.
* @param {string} open The open delimiter for the matrix.
* @param {string} close The close delimiter for the matrix.
* @param {string} align The (optional) alignment. If not given, use a bracket argument for it.
* @return {ParseResult} The ArrayItem for the matrix.
*/
MtSmallMatrix(parser: TexParser, begin: StackItem, open: string, close: string, align?: string): ParseResult {
if (!align) {
align = parser.GetBrackets(`\\begin{${begin.getName()}}`, parser.options.mathtools['smallmatrix-align']);
}
return MathtoolsMethods.Array(
parser, begin, open, close, align, ParseUtil.Em(1 / 3), '.2em', 'S', 1
);
},
/**
* Create the multlined StackItem.
*
* @param {TexParser} parser The active tex parser.
* @param {StackItem} begin The BeginItem for the environment.
* @return {ParseResult} The MultlinedItem.
*/
MtMultlined(parser: TexParser, begin: StackItem): ParseResult {
const name = `\\begin{${begin.getName()}}`;
let pos = parser.GetBrackets(name, parser.options.mathtools['multlined-pos'] || 'c');
let width = pos ? parser.GetBrackets(name, '') : '';
if (pos && !pos.match(/^[cbt]$/)) {
[width, pos] = [pos, width];
}
parser.Push(begin);
const item = parser.itemFactory.create('multlined', parser, begin) as ArrayItem;
item.arraydef = {
displaystyle: true,
rowspacing: '.5em',
width: width || 'auto',
columnwidth: '100%',
};
return ParseUtil.setArrayAlign(item as ArrayItem, pos || 'c');
},
/**
* Replacement for the AMS HandleShove that includes optional spacing values
*
* @param {TexParser} parser The active tex parser.
* @param {string} name The name of the calling macro.
* @param {string} shove Which way to shove the result.
*/
HandleShove(parser: TexParser, name: string, shove: string) {
let top = parser.stack.Top();
if (top.kind !== 'multline' && top.kind !== 'multlined') {
throw new TexError(
'CommandInMultlined',
'%1 can only appear within the multline or multlined environments',
name);
}
if (top.Size()) {
throw new TexError(
'CommandAtTheBeginingOfLine',
'%1 must come at the beginning of the line',
name);
}
top.setProperty('shove', shove);
let shift = parser.GetBrackets(name);
let mml = parser.ParseArg(name);
if (shift) {
let mrow = parser.create('node', 'mrow', []);
let mspace = parser.create('node', 'mspace', [], {width: shift});
if (shove === 'left') {
mrow.appendChild(mspace);
mrow.appendChild(mml);
} else {
mrow.appendChild(mml);
mrow.appendChild(mspace);
}
mml = mrow;
}
parser.Push(mml);
},
/**
* Handle the spreadlines environment.
*
* @param {TexParser} parser The active tex parser.
* @param {StackItem} begin The BeginItem for the environment.
*/
SpreadLines(parser: TexParser, begin: StackItem) {
if (parser.stack.env.closing === begin.getName()) {
//
// When the environment ends, look through the contents and
// adjust the spacing in any tables, then push the results.
//
delete parser.stack.env.closing;
const top = parser.stack.Pop();
const mml = top.toMml();
const spread = top.getProperty('spread') as string;
if (mml.isInferred) {
for (const child of NodeUtil.getChildren(mml)) {
MathtoolsUtil.spreadLines(child, spread);
}
} else {
MathtoolsUtil.spreadLines(mml, spread);
}
parser.Push(mml);
} else {
//
// Read the spread dimension and save it, then begin the environment.
//
const spread = parser.GetDimen(`\\begin{${begin.getName()}}`);
begin.setProperty('spread', spread);
parser.Push(begin);
}
},
/**
* Implements the various cases environments.
*
* @param {TexParser} parser The calling parser.
* @param {StackItem} begin The BeginItem for the environment.
* @param {string} open The open delimiter for the matrix.
* @param {string} close The close delimiter for the matrix.
* @param {string} style The style (D, T, S, SS) for the contents of the array
* @return {ArrayItem} The ArrayItem for the environment
*/
Cases(parser: TexParser, begin: StackItem, open: string, close: string, style: string): ArrayItem {
const array = parser.itemFactory.create('array').setProperty('casesEnv', begin.getName()) as ArrayItem;
array.arraydef = {
rowspacing: '.2em',
columnspacing: '1em',
columnalign: 'left'
};
if (style === 'D') {
array.arraydef.displaystyle = true;
}
array.setProperties({open, close});
parser.Push(begin);
return array;
},
/**
* Handle \mathrlap, \mathllap, \mathclap, and their cramped versions.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
* @param {string} pos The position (l, c, r) of the lapped content
* @param {boolean} cramped True if the style should be cramped
*/
MathLap(parser: TexParser, name: string, pos: string, cramped: boolean) {
const style = parser.GetBrackets(name, '').trim();
let mml = parser.create('node', 'mstyle', [
parser.create('node', 'mpadded', [parser.ParseArg(name)], {
width: 0, ...(pos === 'r' ? {} : {lspace: (pos === 'l' ? '-1width' : '-.5width')})
})
], {'data-cramped': cramped});
MathtoolsUtil.setDisplayLevel(mml, style);
parser.Push(parser.create('node', 'TeXAtom', [mml]));
},
/**
* Implements \cramped.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
Cramped(parser: TexParser, name: string) {
const style = parser.GetBrackets(name, '').trim();
const arg = parser.ParseArg(name);
const mml = parser.create('node', 'mstyle', [arg], {'data-cramped': true});
MathtoolsUtil.setDisplayLevel(mml, style);
parser.Push(mml);
},
/**
* Implements \clap (and could do \llap and \rlap, where the contents are text mode).
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
* @param {string} pos The position (l, c, r) of the lapped content
*/
MtLap(parser: TexParser, name: string, pos: string) {
const content = ParseUtil.internalMath(parser, parser.GetArgument(name), 0);
let mml = parser.create('node', 'mpadded', content, {width: 0});
if (pos !== 'r') {
NodeUtil.setAttribute(mml, 'lspace', pos === 'l' ? '-1width' : '-.5width');
}
parser.Push(mml);
},
/**
* Implements \mathmakebox.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
MathMakeBox(parser: TexParser, name: string) {
const width = parser.GetBrackets(name);
const pos = parser.GetBrackets(name, 'c');
const mml = parser.create('node', 'mpadded', [parser.ParseArg(name)]);
if (width) {
NodeUtil.setAttribute(mml, 'width', width);
}
const align = lookup(pos, {c: 'center', r: 'right'}, '');
if (align) {
NodeUtil.setAttribute(mml, 'data-align', align);
}
parser.Push(mml);
},
/**
* Implements \mathmbox.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
MathMBox(parser: TexParser, name: string) {
parser.Push(parser.create('node', 'mrow', [parser.ParseArg(name)]));
},
/**
* Implements \underbacket and \overbracket.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
UnderOverBracket(parser: TexParser, name: string) {
const thickness = length2em(parser.GetBrackets(name, '.1em'), .1);
const height = parser.GetBrackets(name, '.2em');
const arg = parser.GetArgument(name);
const [pos, accent, border] = (
name.charAt(1) === 'o' ?
['over', 'accent', 'bottom'] :
['under', 'accentunder', 'top']
);
const t = em(thickness);
const base = new TexParser(arg, parser.stack.env, parser.configuration).mml();
const copy = new TexParser(arg, parser.stack.env, parser.configuration).mml();
const script = parser.create('node', 'mpadded', [
parser.create('node', 'mphantom', [copy])
], {
style: `border: ${t} solid; border-${border}: none`,
height: height,
depth: 0
});
const node = ParseUtil.underOver(parser, base, script, pos, true);
const munderover = NodeUtil.getChildAt(NodeUtil.getChildAt(node, 0), 0); // TeXAtom.inferredMrow child 0
NodeUtil.setAttribute(munderover, accent, true);
parser.Push(node);
},
/**
* Implements \Aboxed.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
Aboxed(parser: TexParser, name: string) {
//
// Check that the top item is an alignment, and that we are on an even number of cells
// (othewise add one to make it even).
//
const top = MathtoolsUtil.checkAlignment(parser, name);
if (top.row.length % 2 === 1) {
top.row.push(parser.create('node', 'mtd', []));
}
//
// Get the argument and the rest of the TeX string.
//
const arg = parser.GetArgument(name);
const rest = parser.string.substr(parser.i);
//
// Put the argument back, followed by "&&", and a marker that we look for below.
//
parser.string = arg + '&&\\endAboxed';
parser.i = 0;
//
// Get the two parts separated by ampersands, and ignore the rest.
//
const left = parser.GetUpTo(name, '&');
const right = parser.GetUpTo(name, '&');
parser.GetUpTo(name, '\\endAboxed');
//
// Insert the TeX needed for the boxed content
//
const tex = ParseUtil.substituteArgs(
parser, [left, right], '\\rlap{\\boxed{#1{}#2}}\\kern.267em\\phantom{#1}&\\phantom{{}#2}\\kern.267em'
);
parser.string = tex + rest;
parser.i = 0;
},
/**
* Implements \ArrowBetweenLines.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
ArrowBetweenLines(parser: TexParser, name: string) {
const top = MathtoolsUtil.checkAlignment(parser, name);
if (top.Size() || top.row.length) {
throw new TexError('BetweenLines', '%1 must be on a row by itself', name);
}
const star = parser.GetStar();
const symbol = parser.GetBrackets(name, '\\Updownarrow');
if (star) {
top.EndEntry();
top.EndEntry();
}
const tex = (star ? '\\quad' + symbol : symbol + '\\quad');
const mml = new TexParser(tex, parser.stack.env, parser.configuration).mml();
parser.Push(mml);
top.EndEntry();
top.EndRow();
},
/**
* Implements \vdotswithin.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
VDotsWithin(parser: TexParser, name: string) {
const top = parser.stack.Top() as EqnArrayItem;
const isFlush = (top.getProperty('flushspaceabove') === top.table.length);
const arg = '\\mmlToken{mi}{}' + parser.GetArgument(name) + '\\mmlToken{mi}{}';
const base = new TexParser(arg, parser.stack.env, parser.configuration).mml();
let mml = parser.create('node', 'mpadded', [
parser.create('node', 'mpadded', [
parser.create('node', 'mo', [
parser.create('text', '\u22EE')
])
], {
width: 0,
lspace: '-.5width', ...(isFlush ? {height: '-.6em', voffset: '-.18em'} : {})
}),
parser.create('node', 'mphantom', [base])
], {
lspace: '.5width'
});
parser.Push(mml);
},
/**
* Implements \shortvdotswithin.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
ShortVDotsWithin(parser: TexParser, _name: string) {
const top = parser.stack.Top() as EqnArrayItem;
const star = parser.GetStar();
MathtoolsMethods.FlushSpaceAbove(parser, '\\MTFlushSpaceAbove');
!star && top.EndEntry();
MathtoolsMethods.VDotsWithin(parser, '\\vdotswithin');
star && top.EndEntry();
MathtoolsMethods.FlushSpaceBelow(parser, '\\MTFlushSpaceBelow');
},
/**
* Implements \MTFlushSpaceAbove.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
FlushSpaceAbove(parser: TexParser, name: string) {
const top = MathtoolsUtil.checkAlignment(parser, name);
top.setProperty('flushspaceabove', top.table.length); // marker so \vdotswithin can shorten its height
top.addRowSpacing('-' + parser.options.mathtools['shortvdotsadjustabove']);
},
/**
* Implements \MTFlushSpaceBelow.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
FlushSpaceBelow(parser: TexParser, name: string) {
const top = MathtoolsUtil.checkAlignment(parser, name);
top.Size() && top.EndEntry();
top.EndRow();
top.addRowSpacing('-' + parser.options.mathtools['shortvdotsadjustbelow']);
},
/**
* Implements a paired delimiter (e.g., from \DeclarePairedDelimiter).
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
* @param {string} open The open delimiter.
* @param {string} close The close delimiter.
* @param {string?} body The body betweeen the delimiters.
* @param {number?} n The number of arguments to use for the body.
* @param {string?} pre The TeX to go before the open delimiter.
* @param {string?} post The TeX to go after the close delimiter.
*/
PairedDelimiters(parser: TexParser, name: string,
open: string, close: string,
body: string = '#1', n: number = 1,
pre: string = '', post: string = '') {
const star = parser.GetStar();
const size = (star ? '' : parser.GetBrackets(name));
const [left, right] = (star ? ['\\left', '\\right'] : size ? [size + 'l' , size + 'r'] : ['', '']);
const delim = (star ? '\\middle' : size || '');
if (n) {
const args: string[] = [];
for (let i = args.length; i < n; i++) {
args.push(parser.GetArgument(name));
}
pre = ParseUtil.substituteArgs(parser, args, pre);
body = ParseUtil.substituteArgs(parser, args, body);
post = ParseUtil.substituteArgs(parser, args, post);
}
body = body.replace(/\\delimsize/g, delim);
parser.string = [pre, left, open, body, right, close, post, parser.string.substr(parser.i)]
.reduce((s, part) => ParseUtil.addArgs(parser, s, part), '');
parser.i = 0;
ParseUtil.checkMaxMacros(parser);
},
/**
* Implements \DeclarePairedDelimiter.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
DeclarePairedDelimiter(parser: TexParser, name: string) {
const cs = NewcommandUtil.GetCsNameArgument(parser, name);
const open = parser.GetArgument(name);
const close = parser.GetArgument(name);
MathtoolsUtil.addPairedDelims(parser.configuration, cs, [open, close]);
},
/**
* Implements \DeclarePairedDelimiterX.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
DeclarePairedDelimiterX(parser: TexParser, name: string) {
const cs = NewcommandUtil.GetCsNameArgument(parser, name);
const n = NewcommandUtil.GetArgCount(parser, name);
const open = parser.GetArgument(name);
const close = parser.GetArgument(name);
const body = parser.GetArgument(name);
MathtoolsUtil.addPairedDelims(parser.configuration, cs, [open, close, body, n]);
},
/**
* Implements \DeclarePairedDelimiterXPP.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
DeclarePairedDelimiterXPP(parser: TexParser, name: string) {
const cs = NewcommandUtil.GetCsNameArgument(parser, name);
const n = NewcommandUtil.GetArgCount(parser, name);
const pre = parser.GetArgument(name);
const open = parser.GetArgument(name);
const close = parser.GetArgument(name);
const post = parser.GetArgument(name);
const body = parser.GetArgument(name);
MathtoolsUtil.addPairedDelims(parser.configuration, cs, [open, close, body, n, pre, post]);
},
/**
* Implements \centeredcolon, \ordinarycolon, \MTThinColon.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
* @param {boolean} center True if colon should be centered
* @param {boolean} force True menas always center (don't use centercolon option).
* @param {boolean} thin True if this is a thin color (for \coloneqq, etc).
*/
CenterColon(parser: TexParser, _name: string, center: boolean, force: boolean = false, thin: boolean = false) {
const options = parser.options.mathtools;
let mml = parser.create('token', 'mo', {}, ':');
if (center && (options['centercolon'] || force)) {
const dy = options['centercolon-offset'];
mml = parser.create('node', 'mpadded', [mml], {
voffset: dy, height: `+${dy}`, depth: `-${dy}`,
...(thin ? {width: options['thincolon-dw'], lspace: options['thincolon-dx']} : {})
});
}
parser.Push(mml);
},
/**
* Implements \coloneqq and related macros.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
* @param {string} tex The tex string to use (if not using unicode versions or if there isn't one).
* @param {string} unicode The unicode character (if there is one).
*/
Relation(parser: TexParser, _name: string, tex: string, unicode?: string) {
const options = parser.options.mathtools;
if (options['use-unicode'] && unicode) {
parser.Push(parser.create('token', 'mo', {texClass: TEXCLASS.REL}, unicode));
} else {
tex = '\\mathrel{' + tex.replace(/:/g, '\\MTThinColon').replace(/-/g, '\\mathrel{-}') + '}';
parser.string = ParseUtil.addArgs(parser, tex, parser.string.substr(parser.i));
parser.i = 0;
}
},
/**
* Implements \ndownarrow and \nuparrow via a terrible hack (visual only, no chance of this working with SRE).
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
* @param {string} c The base arrow for the slashed version
* @param {string} dy A vertical offset for the slash
*/
NArrow(parser: TexParser, _name: string, c: string, dy: string) {
parser.Push(
parser.create('node', 'TeXAtom', [
parser.create('token', 'mtext', {}, c),
parser.create('node', 'mpadded', [
parser.create('node', 'mpadded', [
parser.create('node', 'menclose', [
parser.create('node', 'mspace', [], {height: '.2em', depth: 0, width: '.4em'})
], {notation: 'updiagonalstrike', 'data-thickness': '.05em', 'data-padding': 0})
], {width: 0, lspace: '-.5width', voffset: dy}),
parser.create('node', 'mphantom', [
parser.create('token', 'mtext', {}, c)
])
], {width: 0, lspace: '-.5width'})
], {texClass: TEXCLASS.REL})
);
},
/**
* Implements \splitfrac and \splitdfrac.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
* @param {boolean} display True if \splitdfrac.
*/
SplitFrac(parser: TexParser, name: string, display: boolean) {
const num = parser.ParseArg(name);
const den = parser.ParseArg(name);
parser.Push(
parser.create('node', 'mstyle', [
parser.create('node', 'mfrac', [
parser.create('node', 'mstyle', [
num,
parser.create('token', 'mi'),
parser.create('token', 'mspace', {width: '1em'}) // no parameter for this in mathtools. Should we add one?
], {scriptlevel: 0}),
parser.create('node', 'mstyle', [
parser.create('token', 'mspace', {width: '1em'}),
parser.create('token', 'mi'),
den
], {scriptlevel: 0})
], {linethickness: 0, numalign: 'left', denomalign: 'right'})
], {displaystyle: display, scriptlevel: 0})
);
},
/**
* Implements \xmathstrut.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
XMathStrut(parser: TexParser, name: string) {
let dd = parser.GetBrackets(name);
let dh = parser.GetArgument(name);
dh = MathtoolsUtil.plusOrMinus(name, dh);
dd = MathtoolsUtil.plusOrMinus(name, dd || dh);
parser.Push(
parser.create('node', 'TeXAtom', [
parser.create('node', 'mpadded', [
parser.create('node', 'mphantom', [
parser.create('token', 'mo', {stretchy: false}, '(')
])
], {width: 0, height: dh + 'height', depth: dd + 'depth'})
], {texClass: TEXCLASS.ORD})
);
},
/**
* Implements \prescript.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
Prescript(parser: TexParser, name: string) {
const sup = MathtoolsUtil.getScript(parser, name, 'sup');
const sub = MathtoolsUtil.getScript(parser, name, 'sub');
const base = MathtoolsUtil.getScript(parser, name, 'arg');
if (NodeUtil.isType(sup, 'none') && NodeUtil.isType(sub, 'none')) {
parser.Push(base);
return;
}
const mml = parser.create('node', 'mmultiscripts', [base]);
NodeUtil.getChildren(mml).push(null, null);
NodeUtil.appendChildren(mml, [parser.create('node', 'mprescripts'), sub, sup]);
mml.setProperty('fixPrescript', true);
parser.Push(mml);
},
/**
* Implements \newtagform and \renewtagform.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
* @param {boolean=} renew True if \renewtagform.
*/
NewTagForm(parser: TexParser, name: string, renew: boolean = false) {
const tags = parser.tags as MathtoolsTags;
if (!('mtFormats' in tags)) {
throw new TexError('TagsNotMT', '%1 can only be used with ams or mathtools tags', name);
}
const id = parser.GetArgument(name).trim();
if (!id) {
throw new TexError('InvalidTagFormID', 'Tag form name can\'t be empty');
}
const format = parser.GetBrackets(name, '');
const left = parser.GetArgument(name);
const right = parser.GetArgument(name);
if (!renew && tags.mtFormats.has(id)) {
throw new TexError('DuplicateTagForm', 'Duplicate tag form: %1', id);
}
tags.mtFormats.set(id, [left, right, format]);
},
/**
* Implements \usetagform.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
UseTagForm(parser: TexParser, name: string) {
const tags = parser.tags as MathtoolsTags;
if (!('mtFormats' in tags)) {
throw new TexError('TagsNotMT', '%1 can only be used with ams or mathtools tags', name);
}
const id = parser.GetArgument(name).trim();
if (!id) {
tags.mtCurrent = null;
return;
}
if (!tags.mtFormats.has(id)) {
throw new TexError('UndefinedTagForm', 'Undefined tag form: %1', id);
}
tags.mtCurrent = tags.mtFormats.get(id);
},
/**
* Implements \mathtoolsset.
*
* @param {TexParser} parser The calling parser.
* @param {string} name The macro name.
*/
SetOptions(parser: TexParser, name: string) {
const options = parser.options.mathtools;
if (!options['allow-mathtoolsset']) {
throw new TexError('ForbiddenMathtoolsSet', '%1 is disabled', name);
}
const allowed = {} as {[id: string]: number};
Object.keys(options).forEach(id => {
if (id !== 'pariedDelimiters' && id !== 'tagforms' && id !== 'allow-mathtoolsset') {
allowed[id] = 1;
}
});
const args = parser.GetArgument(name);
const keys = ParseUtil.keyvalOptions(args, allowed, true);
for (const id of Object.keys(keys)) {
options[id] = keys[id];
}
},
/**
* Use the Base or AMS methods for these
*/
Array: BaseMethods.Array,
Macro: BaseMethods.Macro,
xArrow: AmsMethods.xArrow,
HandleRef: AmsMethods.HandleRef,
AmsEqnArray: AmsMethods.AmsEqnArray,
MacroWithTemplate: NewcommandMethods.MacroWithTemplate,
}; | the_stack |
/// <reference path="ps.constants.d.ts" />
declare class ActionDescriptor {
/**
* The number of keys contained in the descriptor.
*/
readonly count: number
/**
* The class name of the referenced actionDescriptor object.
*/
readonly typename: string
/**
* Clears the descriptor.
*/
clear(): void
/**
* Erases a key from the descriptor.
*/
erase(key: number): void
/**
* Creates a descriptor from a stream of bytes; for reading from disk.
*/
fromStream(value: string): void
/**
* Gets the value of a key of type boolean.
*/
getBoolean(key: number): boolean
/**
* Gets the value of a key of type class.
*/
getClass(key: number): number
/**
* Gets raw byte data as a string value.
*/
getData(key: number): string
/**
* Gets the value of a key of type double.
*/
getDouble(key: number): number
/**
* Gets the enumeration type of a key.
*/
getEnumerationType(key: number): number
/**
* Gets the enumeration value of a key.
*/
getEnumerationValue(key: number): number
/**
* Gets the value of a key of type integer.
*/
getInteger(key: number): number
/**
* Gets the ID of the Nth key, provided by index.
*/
getKey(index: number): number
/**
* Gets the value of a key of type large integer.
*/
getLargeInteger(key: number): number
/**
* Gets the value of a key of type list.
*/
getList(key: number): ActionList
/**
* Gets the class ID of an object in a key of type object.
*/
getObjectType(key: number): number
/**
* Gets the value of a key of type object.
*/
getObjectValue(key: number): ActionDescriptor
/**
* Gets the value of a key of type File.
*/
getPath(key: number): File
/**
* Gets the value of a key of type ActionReference.
*/
getReference(key: number): ActionReference
/**
* Gets the value of a key of type string.
*/
getString(key: number): string
/**
* Gets the type of a key.
*/
getType(key: number): DescValueType
/**
* Gets the unit type of a key of type UnitDouble.
*/
getUnitDoubleType(key: number): number
/**
* Gets the value of a key of type UnitDouble.
*/
getUnitDoubleValue(key: number): number
/**
* Checks whether the descriptor contains the provided key.
*/
hasKey(key: number): boolean
/**
* Determines whether the descriptor is the same as another descriptor.
*/
isEqual(otherDesc: ActionDescriptor): boolean
/**
* Sets the value for a key whose type is boolean.
*/
putBoolean(key: number, value: boolean): void
/**
* Sets the value for a key whose type is class.
*/
putClass(key: number, value: number): void
/**
* Puts raw byte data as a string value.
*/
putData(key: number, value: string): void
/**
* Sets the value for a key whose type is double.
*/
putDouble(key: number, value: number): void
/**
* Sets the enumeration type and value for a key.
*/
putEnumerated(key: number, enumType: number, value: number): void
/**
* Sets the value for a key whose type is integer.
*/
putInteger(key: number, value: number): void
/**
* Sets the value for a key whose type is large integer.
*/
putLargeInteger(key: number, value: number): void
/**
* Sets the value for a key whose type is an ActionList object.
*/
putList(key: number, value: ActionList): void
/**
* Sets the value for a key whose type is an object, represented by an
* Action Descriptor.
*/
putObject(key: number, classID: number, value: ActionDescriptor): void
/**
* Sets the value for a key whose type is path.
*/
putPath(key: number, value: File): void
/**
* Sets the value for a key whose type is an object reference.
*/
putReference(key: number, value: ActionReference): void
/**
* Sets the value for a key whose type is string.
*/
putString(key: number, value: string): void
/**
* Sets the value for a key whose type is a unit value formatted as a double.
*/
putUnitDouble(key: number, unitID: number, value: number): void
/**
* Gets the entire descriptor as a stream of bytes, for writing to disk.
*/
toStream(): string
}
declare class ActionList {
/**
* The number of commands that comprise the action.
*/
readonly count: number
/**
* The class name of the referenced ActionList object.
*/
readonly typename: string
/**
* Clears the list.
*/
clear(): void
/**
* Gets the value of a list element of type boolean.
*/
getBoolean(index: number): boolean
/**
* Gets the value of a list element of type class.
*/
getClass(index: number): number
/**
* Gets raw byte data as a string value.
*/
getData(index: number): string
/**
* Gets the value of a list element of type double.
*/
getDouble(index: number): number
/**
* Gets the enumeration type of a list element.
*/
getEnumerationType(index: number): number
/**
* Gets the enumeration value of a list element.
*/
getEnumerationValue(index: number): number
/**
* Gets the value of a list element of type integer.
*/
getInteger(index: number): number
/**
* Gets the value of a list element of type large integer.
*/
getLargeInteger(index: number): number
/**
* Gets the value of a list element of type list.
*/
getList(index: number): ActionList
/**
* Gets the class ID of a list element of type object.
*/
getObjectType(index: number): number
/**
* Gets the value of a list element of type object.
*/
getObjectValue(index: number): ActionDescriptor
/**
* Gets the value of a list element of type File.
*/
getPath(index: number): File
/**
* Gets the value of a list element of type ActionReference.
*/
getReference(index: number): ActionReference
/**
* Gets the value of a list element of type string.
*/
getString(index: number): string
/**
* Gets the type of a list element.
*/
getType(index: number): DescValueType
/**
* Gets the unit value type of a list element of type Double.
*/
getUnitDoubleType(index: number): number
/**
* Gets the unit value of a list element of type double.
*/
getUnitDoubleValue(index: number): number
/**
* Appends a new value, true or false.
*/
putBoolean(value: boolean): void
/**
* Appends a new value, a class or data type.
*/
putClass(value: number): void
/**
* Appends a new value, a string containing raw byte data.
*/
putData(value: string): void
/**
* Appends a new value, a double.
*/
putDouble(value: number): void
/**
* Appends a new value, an enumerated (constant) value.
*/
putEnumerated(enumType: number, value: number): void
/**
* Appends a new value, an integer.
*/
putInteger(value: number): void
/**
* Appends a new value, a large integer.
*/
putLargeInteger(value: number): void
/**
* Appends a new value, a nested action list.
*/
putList(value: ActionList): void
/**
* Appends a new value, an object.
*/
putObject(classID: number, value: ActionDescriptor): void
/**
* Appends a new value, a path.
*/
putPath(value: File): void
/**
* Appends a new value, a reference to an object created in the script.
*/
putReference(value: ActionReference): void
/**
* Appends a new value, a string.
*/
putString(value: string): void
/**
* Appends a new value, a unit/value pair.
*/
putUnitDouble(classID: number, value: number): void
}
declare class ActionReference {
/**
* The class name of the referenced Action object.
*/
readonly typename: string
/**
* Gets a reference contained in this reference. Container references
* provide additional pieces to the reference. This looks like another
* reference, but it is actually part of the same reference.
*/
getContainer(): ActionReference
/**
* Gets a number representing the class of the object.
*/
getDesiredClass(): number
/**
* Gets the enumeration type.
*/
getEnumeratedType(): number
/**
* Gets the enumeration value.
*/
getEnumeratedValue(): number
/**
* Gets the form of this action reference.
*/
getForm(): ReferenceFormType
/**
* Gets the identifier value for a reference whose form is identifier.
*/
getIdentifier(): number
/**
* Gets the index value for a reference in a list or array.
*/
getIndex(): number
/**
* Gets the name of a reference.
*/
getName(): string
/**
* Gets the offset of the object’s index value.
*/
getOffset(): number
/**
* Gets the property ID value.
*/
getProperty(): number
/**
* Puts a new class form and class type into the reference.
*/
putClass(desiredClass: number): void
/**
* Puts an enumeration type and ID into a reference along with the desired
* class for the reference.
*/
putEnumerated(desiredClass: number, enumType: number, value: number): void
/**
* Puts a new identifier and value into the reference.
*/
putIdentifier(desiredClass: number, value: number): void
/**
* Puts a new index and value into the reference.
*/
putIndex(desiredClass: number, value: number): void
/**
* Puts a new name and value into the reference.
*/
putName(desiredClass: number, value: string): void
/**
* Puts a new offset and value into the reference.
*/
putOffset(desiredClass: number, value: number): void
/**
* Puts a new property and value into the reference.
*/
putProperty(desiredClass: number, value: number): void
}
interface Application {
/**
* The frontmost document. Setting this property is equivalent to clicking
* an open document in the Adobe Photoshop CC application to bring it to the
* front of the screen. Tip: If there is no open document, accessing this
* property throws an exception.
*/
activeDocument: Document
/**
* The default background color and color style for documents.
*/
backgroundColor: SolidColor
/**
* Information about the application.
*/
readonly build: string
/**
* The name of the current color settings, as selected with Edit > Color
* Settings.
*/
colorSettings: string
/**
* The dialog mode for the application, which controls what types of
* dialogs should be displayed when running scripts.
*/
displayDialogs: DialogModes
/**
* The collection of open documents. This is the primary point of access
* for documents that are currently open in the application. The array
* allows you to access any open document, or to iterate through all open
* documents.
*/
readonly documents: Documents
/**
* The fonts installed on this system.
*/
readonly fonts: TextFonts
/**
* The default foreground color (used to paint, fill, and stroke
* selections).
*/
foregroundColor: SolidColor
/**
* The amount of unused memory available to Adobe Photoshop CC.
*/
readonly freeMemory: number
/**
* The language location of the application. An Adobe locale code consists
* of a 2-letter ISO-639 language code and an optional 2-letter ISO 3166
* country code separated by an underscore. Case is significant. For
* example, en_US, en_UK, ja_JP, de_DE, fr_FR.
*/
readonly locale: string
/**
* A list of file image types Adobe Photoshop CC can open.
*/
readonly macintoshFileTypes: string[]
/**
* The log of measurements taken.
*/
readonly measurementLog: MeasurementLog
/**
* The application's name.
*/
readonly name: string
/**
* The collection of notifiers currently configured (in the Scripts Events
* Manager menu in the Adobe Photoshop CC application).
*/
readonly notifiers: Notifiers
/**
* True if all notifiers are enabled.
*/
notifiersEnabled: boolean
/**
* The full path to the location of the Adobe Photoshop CC application.
*/
readonly path: File
/**
* The dialog mode for playback mode, which controls what types of dialog
* to display when playing back a recorded action with the Actions palette.
*/
playbackDisplayDialogs: DialogModes
/**
* Stores and retrieves parameters used as part of a recorded action. Can
* be used, for example, to control playback speed.
*/
playbackParameters: ActionDescriptor
/**
* The application preference settings (equivalent to selecting Edit >
* Preferences in the Adobe Photoshop CC application in Windows or Photoshop
* > Preferences in Mac OS).
*/
readonly preferences: Preferences
/**
* The full path to the Preferences folder.
*/
readonly preferencesFolder: File
/**
* Files in the Recent Files list.
*/
readonly recentFiles: File[]
/**
* The build date of the Scripting interface.
*/
readonly scriptingBuildDate: string
/**
* The version of the Scripting interface.
*/
readonly scriptingVersion: string
/**
* Runtime details of the application and system.
*/
readonly systemInformation: string
/**
* The class name of the referenced app object. Methods
*/
readonly typename: string
/**
* The version of Adobe Photoshop application you are running.
*/
readonly version: string
/**
* A list of file image extensions Adobe Photoshop CC can open.
*/
readonly windowsFileTypes: string[]
/**
* Runs the batch automation routine (similar to the File > Automate > Batch
* command). The inputFiles parameter specifies the sources for the files to
* be manipulated by the batch command.
*/
batch(inputFiles: File[], action: string, from: string, options?: BatchOptions): string
/**
* Causes a "beep" sound.
*/
beep(): void
/**
* Makes Adobe Photoshop CC the active (front-most) application.
*/
bringToFront(): void
/**
* Converts from a four character code (character ID) to a runtime ID.
*/
charIDToTypeID(charID: string): number
/**
* Plays an action from the Actions palette. The action parameter is the
* name of the action, the from parameter is the name of the action set.
*/
doAction(action: string, from: string): void
/**
* Erases the user object with specified ID value from the Photoshop
* registry.
*/
eraseCustomOptions(key: string): void
/**
* Plays an Action Manager event.
*/
executeAction(eventID: number, descriptor?: ActionDescriptor, displayDialogs?: DialogModes): ActionDescriptor
/**
* Obtains information about a predefined or recorded action.
*/
executeActionGet(reference: ActionReference): ActionDescriptor
/**
* Determines whether the feature specified by name is enabled. The
* following features are supported as values for name: "photoshop/extended"
* "photoshop/standard" "photoshop/trial"
*/
featureEnabled(name: string): boolean
/**
* Retreives user objects in the Photoshop registry for the ID with value
* key.
*/
getCustomOptions(key: string): ActionDescriptor
/**
* Returns true if Quicktime is installed.
*/
isQuicktimeAvailable(): boolean
/**
* Loads a support file (as opposed to a Photoshop image document) from the
* specified location.
*/
load(document: File): void
/**
* DEPRECATED for Adobe Photoshop CS4.
*/
makeContactSheet(inputFiles: File[], options?: ContactSheetOptions): string
/**
* DEPRECATED for Adobe Photoshop CS4.
*/
makePDFPresentation(inputFiles: File[], outputFiles: File, options?: PresentationOptions): string
/**
* DEPRECATED for Adobe Photoshop CS4.
*/
makePhotoGallery(inputFolder: File, outputFolder: File, options?: GalleryOptions): string
/**
* DEPRECATED for Adobe Photoshop CC. Use provided script:
* runphotomergeFromScript = true; $.evalFile( app.path +
* "Presets/Scripts/Photomerge.jsx") photomerge.createPanorama( fileList,
* displayDialog ); Merges multiple files into one, with user interaction
* required.
*/
makePhotomerge(inputFiles: File[]): string
/**
* DEPRECATED for Adobe Photoshop CS4.
*/
makePicturePackage(inputFiles: File[], options?: PicturePackageOptions): string
/**
* Opens the specified document. Use the optional as parameter to specify
* the file format using the constants in OpenDocumentType; or, you can
* specify a file format together with its open options using these objects:
* CameraRAWOpenOptions DICOMOpenOptions EPSOpenOptions PDFOpenOptions
* PhotoCDOpenOptions RawFormatOpenOptions Use the optional parameter
* asSmartObject (default: false) to create a smart object around the opened
* document. See the Application sample scripts for an example of using the
* File object in the open method.
*/
open(document: File, as?: any, asSmartObject?: boolean): Document
open(document: File, as?: OpenDocumentType, asSmartObject?: boolean): Document
/**
* Invokes the Photoshop Open dialog box for the user to select files.
* Returns an array of File objects for the files selected in the dialog.
*/
openDialog(): File[]
/**
* Purges one or more caches.
*/
purge(target: PurgeTarget): void
/**
* Saves a customized settings object in the Photoshop registry. key is the
* unique identifier for your custom settings. customObject is the object to
* save in the registry. persistent indicates whether the object should
* persist once the script has finished.
*/
putCustomOptions(key: string, customObject: ActionDescriptor, persistent?: boolean): void
/**
* Pauses the script while the application refreshes. Use to slow down
* execution and show the results to the user as the script runs. Use
* carefully; your script runs much more slowly when using this method.
*/
refresh(): void
/**
* Force the font list to get updated.
*/
refreshFonts(): void
/**
* Run a menu item given the menu ID.
*/
runMenuItem(menuID: number): void
/**
* Returns false if dialog is cancelled, true otherwise.
*/
showColorPicker(): boolean
/**
* Converts from a string ID to a runtime ID.
*/
stringIDToTypeID(stringID: string): number
/**
* Toggle palette visibility.
*/
togglePalettes(): void
/**
* Converts from a runtime ID to a character ID.
*/
typeIDToCharID(typeID: number): string
/**
* Converts from a runtime ID to a string ID.
*/
typeIDToStringID(typeID: number): string
}
interface ArtLayer {
/**
* True to completely lock the contents and settings of this layer.
*/
allLocked: boolean
/**
* The blending mode.
*/
blendMode: BlendMode
/**
* An array of coordinates that describes the bounding rectangle of the
* layer.
*/
readonly bounds: UnitValue[]
/**
* An array of coordinates that describes the bounding rectangle of the
* layer not including effects.
*/
readonly boundsNoEffects: UnitValue[]
/**
* The interior opacity of the layer, a percentage value.
*/
fillOpacity: number
/**
* The density of the filter mask (between 0.0 and 250.0)
*/
filterMaskDensity: number
/**
* The feather of the filter mask (between 0.0 and 250.0)
*/
filterMaskFeather: number
/**
* True if this layer is grouped with the layer beneath it.
*/
grouped: boolean
/**
* True if this is the background layer of the document. A document can
* have only one background layer. If there is no background layer, setting
* this to true causes this to become the background layer.
*/
isBackgroundLayer: boolean
/**
* Sets the type (such as 'text layer') for an empty layer. Valid only when
* the layer is empty and when isBackgroundLayer is false. See
* isBackgroundLayer. You can use the kind property to make a background
* layer a normal layer; however, to make a layer a background layer, you
* must set isBackgroundLayer to true.
*/
kind: LayerKind
/**
* The density of the layer mask (between 0.0 and 100.0)
*/
layerMaskDensity: number
/**
* The feather of the layer mask (between 0.0 and 250.0)
*/
layerMaskFeather: number
/**
* The layers linked to this layer. See ArtLayer.link.
*/
readonly linkedLayers: ArtLayer[]
/**
* The name.
*/
name: string
/**
* The master opacity of the layer, a percentage value.
*/
opacity: number
/**
* The object's container.
*/
readonly parent: Document
/**
* True if the pixels in the layer’s image cannot be edited using the
* paintbrush tool.
*/
pixelsLocked: boolean
/**
* True if the pixels in the layer’s image cannot be moved within the layer.
*/
positionLocked: boolean
/**
* The text item that is associated with the layer. Valid only when kind =
* LayerKind.TEXT.
*/
readonly textItem: TextItem
/**
* True if editing is confined to the opaque portions of the layer.
*/
transparentPixelsLocked: boolean
/**
* The class name of the referenced artLayer object.
*/
readonly typename: string
/**
* The density of the vector mask (between 0.0 and 250.0)
*/
vectorMaskDensity: number
/**
* The feather of the vector mask (between 0.0 and 250.0)
*/
vectorMaskFeather: number
/**
* True if the layer is visible.
*/
visible: boolean
/**
* Metadata for the layer. Methods
*/
xmpMetadata: xmpMetadata
/**
* Adjusts the brightness in the range [-100..100] and contrast [-100..100].
*/
adjustBrightnessContrast(brightness: number, contrast: number): void
/**
* Adjusts the color balance of the layer’s component channels. For shadows,
* midtones, and highlights, the array must include three values in the
* range [-100..100], which represent cyan or red, magenta or green, and
* yellow or blue, when the document mode is CMYK or RGB. See Document.mode.
*/
adjustColorBalance(shadows?: number[], midtones?: number[], highlights?: number[], preserveLuminosity?: boolean): void
/**
* Adjusts the tonal range of the selected channel using up to fourteen
* points. Each value in the curveShape array is a point pair, an array of
* an x and y integer value.
*/
adjustCurves(curveShape: number[][]): void
/**
* Adjusts the levels of the selected channels
*/
adjustLevels(inputRangeStart: number, inputRangeEnd: number, inputRangeGamma: number, outputRangeStart: number, outputRangeEnd: number): void
/**
* Applies the Add Noise filter amount is a percentage value.
*/
applyAddNoise(amount: number, distribution: NoiseDistribution, monochromatic: boolean): void
/**
* Applies the Average filter.
*/
applyAverage(): void
/**
* Applies the Blur filter.
*/
applyBlur(): void
/**
* Applies the Blur More filter.
*/
applyBlurMore(): void
/**
* Applies the Clouds filter.
*/
applyClouds(): void
/**
* Applies a custom filter. The characteristics array has 25 members. See
* Adobe Photoshop CC Help for specific instructions.
*/
applyCustomFilter(characteristics: number[], scale: number, offset: number): void
/**
* Applies the De-Interlace filter.
*/
applyDeInterlace(eliminateFields: EliminateFields, createFields: CreateFields): void
/**
* Applies the Despeckle filter.
*/
applyDespeckle(): void
/**
* Applies the Difference Clouds filter.
*/
applyDifferenceClouds(): void
/**
* Applies the Diffuse Glow filter.
*/
applyDiffuseGlow(graininess: number, glowAmount: number, clearAmount: number): void
/**
* Applies the Displace filter using the specified horizontal and vertical
* scale, mapping type, treatment of undistorted areas, and path to the
* distortion image map.
*/
applyDisplace(horizontalScale: number, verticalScale: number, displacement: DisplacementMapType, undefinedareas: UndefinedAreas, displacementMapFiles: File): void
/**
* Applies the Dust & Scratches filter.
*/
applyDustAndScratches(radius: number, threshold: number): void
/**
* Applies the Gaussian Blur filter within the specified radius (in pixels)
*/
applyGaussianBlur(radius: number): void
/**
* Applies the Glass filter. scaling is a percentage value.
*/
applyGlassEffect(distortion: number, smoothness: number, scaling: number, invert?: boolean, texture?: TextureType, textureFile?: File): void
/**
* Applies the High Pass filter within the specified radius.
*/
applyHighPass(radius: number): void
/**
* Applies the Lens Blur filter. source: The source for the depth map
* (default: DepthMapSource.NONE) focalDistance : The blur focal distance
* for the depth map (default: 0). invertDepthMask : True if the depth map
* is inverted (default: false). shape: The shape of the iris (default:
* Geometry.HEXAGON) radius: The radius of the iris (default: 15).
* bladeCurvature: The blade curvature of the iris (default: 0). rotation:
* The rotation of the iris (default: 0) brightness: The brightness for the
* specular highlights (default: 0). threshold: The threshold for the
* specular highlights (default: 0). amount: The amount of noise (default:
* 0) distribution: The distribution value for the noise (default:
* NoiseDistribution.UNIFORM). monochromatic: True if the noise is
* monochromatic (default: false).
*/
applyLensBlur(source?: DepthMapSource, focalDistance?: number, invertDepthMap?: boolean, shape?: Geometry, radius?: number, bladeCurvature?: number, rotation?: number, brightness?: number, threshold?: number, amount?: number, distribution?: NoiseDistribution, monochromatic?: boolean): void
/**
* Applies the Lens Flare filter with the specified brightness (0 - 300, as
* a percentage), the x and y coordinates (unit value) of the flare center,
* and the lens type.
*/
applyLensFlare(brightness: number, flareCenter: UnitValue[], lensType: LensType): void
/**
* Applies the Maximum filter within the specified radius (in pixels).
*/
applyMaximum(radius: number): void
/**
* Applies the Median Noise filter within the specified radius (in pixels).
*/
applyMedianNoise(radius: number): void
/**
* Applies the Minimum filter within the specified radius (in pixels) (1 -
* 100).
*/
applyMinimum(radius: number): void
/**
* Applies the Motion Blur filter.
*/
applyMotionBlur(angle: number, radius: number): void
/**
* Applies the NTSC colors filter.
*/
applyNTSC(): void
/**
* Applies the Ocean Ripple filter.
*/
applyOceanRipple(size: number, magnitude: number): void
/**
* Moves the layer the specified amount horizontally and vertically (min/max
* amounts depend on layer size), leaving an undefined area at the layer’s
* original location.
*/
applyOffset(horizontal: UnitValue, vertical: UnitValue, undefinedAreas: OffsetUndefinedAreas): void
/**
* Applies the Pinch filter. amount is a percentage value.
*/
applyPinch(amount: number): void
/**
* Applies the Polar Coordinates filter.
*/
applyPolarCoordinates(conversion: PolarConversionType): void
/**
* Applies the Radial Blur filter in the specified amount, using either a
* spin or zoom effect and the specified quality.
*/
applyRadialBlur(amount: number, blurMethod: RadialBlurMethod, blurQuality: RadialBlurQuality): void
/**
* Applies the Ripple filter in the specified amount, throughout the image
* and in the specified size.
*/
applyRipple(amount: number, size: RippleSize): void
/**
* Applies the Sharpen filter.
*/
applySharpen(): void
/**
* Applies the Sharpen Edges filter.
*/
applySharpenEdges(): void
/**
* Applies the Sharpen More filter.
*/
applySharpenMore(): void
/**
* Applies the Shear filter. The curve defines a curve with [2..255] points.
* Each value in the curve array is a point pair, an array of an x and y
* integer value.
*/
applyShear(curve: number[][], undefinedAreas: UndefinedAreas): void
/**
* Applies the Smart Blur filter.
*/
applySmartBlur(radius: number, threshold: number, blurQuality: SmartBlurQuality, mode: SmartBlurMode): void
/**
* Applies the Spherize filter. amount is a percentage value.
*/
applySpherize(amount: number, mode: SpherizeMode): void
/**
* Applies the specified style to the layer. You must use a style from the
* Styles list in the Layer Styles Palette.
*/
applyStyle(styleName: string): void
/**
* Applies the Texture Fill filter.
*/
applyTextureFill(textureFile: File): void
/**
* Applies the Twirl filter.
*/
applyTwirl(angle: number): void
/**
* Applies the Unsharp Mask filter. (amount is a percentage value.
*/
applyUnSharpMask(amount: number, radius: number, threshold: number): void
/**
* Applies the Wave filter. Scale factors are percentage values.
*/
applyWave(generatorNumber: number, minimumWavelength: number, maximumWavelength: number, minimumAmplitude: number, maximumAmplitude: number, horizontalScale: number, verticalScale: number, waveType: WaveType, undefinedAreas: UndefinedAreas, randomSeed: number): void
/**
* Applies the Zigzag filter.
*/
applyZigZag(amount: number, ridges: number, style: ZigZagType): void
/**
* Adjusts the contrast of the selected channels automatically.
*/
autoContrast(): void
/**
* Adjusts the levels of the selected channels using the auto levels option.
*/
autoLevels(): void
/**
* Cuts the layer without moving it to the clipboard.
*/
clear(): void
/**
* Copies the layer to the clipboard. When the optional argument is set to
* true, a merged copy is performed (that is, all visible layers are copied
* to the clipboard).
*/
copy(merge?: boolean): void
/**
* Cuts the layer to the clipboard.
*/
cut(): void
/**
* Converts a color image to a grayscale image in the current color mode by
* assigning equal values of each component color to each pixel.
*/
desaturate(): void
/**
* ArtLayer or LayerSet Creates a duplicate of the object on the screen.
*/
duplicate(relativeObject?: ArtLayer, insertionLocation?: ElementPlacement): ArtLayer
duplicate(relativeObject?: LayerSet, insertionLocation?: ElementPlacement): ArtLayer
/**
* Redistributes the brightness values of pixels in an image to more evenly
* represent the entire range of brightness levels within the image.
*/
equalize(): void
/**
* Inverts the colors in the layer by converting the brightness value of
* each pixel in the channels to the inverse value on the 256-step
* color-values scale.
*/
invert(): void
/**
* Links the layer with the specified layer.
*/
link(with_: LayerSet): void
/**
* Merges the layer down, removing the layer from the document; returns a
* reference to the art layer that this layer is merged into.
*/
merge(): ArtLayer
/**
* Modifies a targeted (output) color channel using a mix of the existing
* color channels in the image. The outputChannels parameter is an array of
* channel specifications. For each component channel, specify a list of
* adjustment values in the range [-200..200] followed by a 'constant' value
* [-200..200].) When monochrome = true, the maximum number of channel value
* specifications is 1. Valid only when docRef.mode = DocumentMode.RGB or
* CMYK. RGB arrays must include four values. CMYK arrays must include five
* values.
*/
mixChannels(outputChannels: number[][], monochrome?: boolean): void
/**
* Moves the layer relative to the object specified in parameters. For art
* layers, only the constant values ElementPlacement. PLACEBEFORE and
* PLACEAFTER are valid. For layer sets, only the constant values
* ElementPlacement. PLACEBEFORE and INSIDE are valid.
*/
move(relativeObject: ArtLayer, insertionLocation: ElementPlacement): void
move(relativeObject: LayerSet, insertionLocation: ElementPlacement): void
/**
* Adjust the layer’s color balance and temperature as if a color filter had
* been applied. density is a percentage value.
*/
photoFilter(fillColor?: SolidColor, density?: number, preserveLuminosity?: boolean): void
/**
* Specifies the number of tonal levels for each channel and then maps
* pixels to the closest matching level.
*/
posterize(levels: number): void
/**
* Converts the targeted contents in the layer into a flat, raster image.
*/
rasterize(target: RasterizeType): void
/**
* Deletes the object.
*/
remove(): void
/**
* Resizes the layer to the specified dimensions (as a percentage of its
* current size) and places it in the specified position.
*/
resize(horizontal?: number, vertical?: number, anchor?: AnchorPosition): void
/**
* Rotates rotates the layer around the specified anchor point (default:
* MIDDLECENTER).
*/
rotate(angle: number, anchor?: AnchorPosition): void
/**
* Modifies the amount of a process color in a specified primary color
* without affecting the other primary colors. Each color array must have
* four values.
*/
selectiveColor(selectionMethod: AdjustmentReference, reds?: number[], yellows?: number[], greens?: number[], cyans?: number[], blues?: number[], magentas?: number[], whites?: number[], neutrals?: number[], blacks?: number[]): void
/**
* Adjusts the range of tones in the image’s shadows and highlights. Amounts
* and widths are percentage values. Radius values are in pixels.
*/
shadowHighlight(shadowAmount?: number, shadowWidth?: number, shadowRadius?: number, highlightAmount?: number, highlightWidth?: number, highlightRadius?: number, colorCorrection?: number, midtoneContrast?: number, blackClip?: number, whiteClip?: number): void
/**
* Converts grayscale or color images to high-contrast, B/W images by
* converting pixels lighter than the specified threshold to white and
* pixels darker than the threshold to black.
*/
threshold(level: number): void
/**
* Moves the layer the specified amount (in the given unit) relative to its
* current position.
*/
translate(deltaX?: UnitValue, deltaY?: UnitValue): void
/**
* Unlinks the layer.
*/
unlink(): void
}
interface ArtLayers {
/**
* The number of elements in the artLayers collection.
*/
readonly length: number
/**
* The object's container.
*/
readonly parent: Document
/**
* The class name of the referenced artLayers object.
*/
readonly typename: string
/**
* Creates a new art layer in the document and adds the new object to this
* collection.
*/
add(): ArtLayer
/**
* Get the first element in the artLayers collection with the provided name.
*/
getByName(name: string): ArtLayer
/**
* Removes all elements from the artLayers collection.
*/
removeAll(): void
}
declare class BatchOptions {
/**
* The type of destination for the processed files (default:
* BatchDestinationType.NODESTINATION).
*/
destination: BatchDestinationType
/**
* The folder location for the processed files. Valid only when destination
* = BatchDestinationType.FOLDER.
*/
destinationFolder: Folder
/**
* The file in which to log errors encountered. To display errors on the
* screen (and stop batch processing when errors occur) leave blank.
*/
errorFile: File
/**
* A list of file naming options (maximum: 6). Valid only when destination
* = BatchDestinationType.FOLDER.
*/
fileNaming: FileNamingType[]
/**
* True to make the final file names Macintosh compatible (default: true).
* Valid only when destination = BatchDestinationType.FOLDER.
*/
macintoshCompatible: boolean
/**
* True to override action open commands (default: false).
*/
overrideOpen: boolean
/**
* True to override save as action steps with the specified destination
* (default: false). Valid only when destination =
* BatchDestinationType.FOLDER or SAVEANDCLOSE.
*/
overrideSave: boolean
/**
* The starting serial number to use in naming files (default: 1). Valid
* only when destination = BatchDestinationType.FOLDER.
*/
startingSerial: number
/**
* True to suppress the file open options dialogs (default: false).
*/
suppressOpen: boolean
/**
* True to suppress the color profile warnings (default: false).
*/
suppressProfile: boolean
/**
* The class name of the referenced batchOptions object.
*/
readonly typename: string
/**
* True to make the final file name Unix compatible (default: true). Valid
* only when destination = BatchDestinationType.FOLDER.
*/
unixCompatible: boolean
/**
* True to make the final file names Windows compatible (default: true).
* Valid only when destination = BatchDestinationType.FOLDER.
*/
windowsCompatible: boolean
}
declare class BitmapConversionOptions {
/**
* The angle (in degrees) at which to orient individual dots. See shape.
* Valid only when method = BitmapConversionType.HALFTONESCREEN.
*/
angle: number
/**
* The number of printer dots (per inch) to use. Valid only when method =
* BitmapConversionType.HALFTONESCREEN.
*/
frequency: number
/**
* The conversion method to use (default:
* BitmapConversionType.DIFFUSIONDITHER).
*/
method: BitmapConversionType
/**
* The name of the pattern to use. For information about pre-installed
* valid patterns, see Adobe Photoshop CC Help on the bitmap conversion
* command, or view the options availabe in the Custom Color drop down box
* after choosing the bitmap conversion command. Valid only when method =
* BitmapConversionType.CUSTOMPATTERN.
*/
patternName: string
/**
* The output resolution in pixels per inch (default: 72.0).
*/
resolution: number
/**
* The dot shape to use. Valid only when method =
* BitmapConversionType.HALFTONESCREEN.
*/
shape: BitmapHalfToneType
/**
* The class name of the referenced bitmapConversionOptions object.
*/
readonly typename: string
}
declare class BMPSaveOptions {
/**
* True to save the alpha channels.
*/
alphaChannels: boolean
/**
* The number of bits per channel.
*/
depth: BMPDepthType
/**
* True to write the image from top to bottom (default: false). Available
* only when osType = OperatingSystem.WINDOWS.
*/
flipRowOrder: boolean
/**
* The target OS. (default: OperatingSystem.WINDOWS).
*/
osType: OperatingSystem
/**
* True to use RLE compression. Available only when osType =
* OperatingSystem.WINDOWS.
*/
rleCompression: boolean
/**
* The class name of the referenced BMPSaveOptions object.
*/
readonly typename: string
}
declare class CameraRAWOpenOptions {
/**
* The number of bits per channel.
*/
bitsPerChannel: BitsPerChannelType
/**
* The blue hue of the shot.
*/
blueHue: number
/**
* The blue saturation of the shot.
*/
blueSaturation: number
/**
* The brightness of the shot.
*/
brightness: number
/**
* The chromatic aberration B/Y of the shot.
*/
chromaticAberrationBY: number
/**
* The chromatic aberration R/C of the shot
*/
chromaticAberrationRC: number
/**
* The color noise reduction of the shot.
*/
colorNoiseReduction: number
/**
* The colorspace for the image.
*/
colorSpace: ColorSpaceType
/**
* The contrast of the shot.
*/
contrast: number
/**
* The exposure of the shot.
*/
exposure: number
/**
* The green hue of the shot.
*/
greenHue: number
/**
* The green saturation of the shot.
*/
greenSaturation: number
/**
* The luminance smoothing of the shot.
*/
luminanceSmoothing: number
/**
* The red hue of the shot.
*/
redHue: number
/**
* The red saturation of the shot.
*/
redSaturation: number
/**
* The resolution of the document in pixels per inch.
*/
resolution: number
/**
* The saturation of the shot.
*/
saturation: number
/**
* The global settings for all Camera RAW options. Default:
* CameraRAWSettingsType.CAMERA.
*/
settings: CameraRAWSettingsType
/**
* The shadows of the shot.
*/
shadows: number
/**
* The shadow tint of the shot.
*/
shadowTint: number
/**
* The sharpness of the shot.
*/
sharpness: number
/**
* The size of the new document.
*/
size: CameraRAWSize
/**
* The temperature of the shot.
*/
temperature: number
/**
* The tint of the shot.
*/
tint: number
/**
* The class name of the referenced cameraRAWOpenOptions object.
*/
readonly typename: string
/**
* The vignetting amount of the shot.
*/
vignettingAmount: number
/**
* The vignetting mid point of the shot.
*/
vignettingMidpoint: number
/**
* The white balance options for the image. These are lighting conditions
* that affect color balance.
*/
whiteBalance: WhiteBalanceType
}
interface Channel {
/**
* The color of the channel. Not valid when kind = ChannelType.COMPONENT.
*/
color: SolidColor
/**
* A histogram of the color of the channel. The array contains 256 members.
* Not valid when kind = ChannelType.COMPONENT. For component channel
* histogram values, use the histogram property of the Document object
* instead.
*/
readonly histogram: number[]
/**
* The type of the channel.
*/
kind: ChannelType
/**
* The name of the channel.
*/
name: string
/**
* The opacity to use for alpha channels or the solidity to use for spot
* channels. Valid only when kind = ChannelType.MASKEDAREA or SELECTEDAREA.
*/
opacity: number
/**
* The containing document.
*/
readonly parent: Document
/**
* The class name of the referenced channel object.
*/
readonly typename: string
/**
* True if the channel is visible.
*/
visible: boolean
/**
* Duplicates the channel.
*/
duplicate(targetDocument?: Document): Channel
/**
* Merges a spot channel into the component channels.
*/
merge(): void
/**
* Deletes the channel.
*/
remove(): void
}
declare class Channels {
/**
* Creates a new channel object and adds it to this collection.
*/
add(): Channel
/**
* Get the first element in the channels collection with the provided name.
*/
getByName(name: string): Channel
/**
* Removes all alpha channel objects from the channels collection.
*/
removeAll(): void
}
declare class CMYKColor {
/**
* The black color value (as percent).
*/
black: number
/**
* The cyan color value (as percent).
*/
cyan: number
/**
* The magenta color value (as percent).
*/
magenta: number
/**
* The class name of the referenced CMYKColor object.
*/
readonly typename: string
/**
* The yellow color value (as percent).
*/
yellow: number
}
interface ColorSampler {
/**
* The color of the color sampler.
*/
readonly color: SolidColor
/**
* The position of the color sampler in the document. The array (x,y)
* represents the horizontal and vertical location of the count item.
*/
readonly position: UnitValue[]
/**
* The containing document.
*/
readonly parent: Document
/**
* The class name of the referenced ColorSampler object.
*/
readonly typename: string
/**
* Moves the color sampler to a new location in the document. The position
* parameter (x,y) represents the new horizontal and vertical locations of
* the moved color sampler.
*/
move(position: UnitValue[]): void
/**
* Deletes the ColorSampler object.
*/
remove(): void
}
interface ColorSamplers {
/**
* The number of elements in the ColorSamplers collection.
*/
readonly length: number
/**
* The containing document.
*/
readonly parent: Document
/**
* The class name of the referenced ColorSamplers object.
*/
readonly typename: string
/**
* Creates a new color sampler object and adds it to this collection. The
* position parameter (x,y) represents the new horizontal and vertical
* locations of the moved color sampler.
*/
add(position: UnitValue[]): ColorSampler
/**
* Removes all ColorSampler objects from the ColorSamplers collection.
*/
removeAll(): void
}
declare class ContactSheetOptions {
/**
* True to place the images horizontally (left to right, then top to
* bottom) first (default: true).
*/
acrossFirst: boolean
/**
* True to rotate images for the best fit (default: false).
*/
bestFit: boolean
/**
* True to use the filename as a caption for the image (default: true).
*/
caption: boolean
/**
* The number of columns to include (default: 5).
*/
columnCount: number
/**
* True to flatten all layers in the final document (default: true).
*/
flatten: boolean
/**
* The font used for the caption (default: GalleryFontType.ARIAL).
*/
font: GalleryFontType
/**
* The font size to use for the caption (default: 12).
*/
fontSize: number
/**
* The height (in pixels) of the resulting document (default: 720).
*/
height: number
/**
* The horizontal spacing (in pixels) between images (default: 1).
*/
horizontal: number
/**
* The document color mode (default: NewDocumentMode.RGB).
*/
mode: NewDocumentMode
/**
* The resolution of the document in pixels per inch (default: 72.0).
*/
resolution: number
/**
* The number of rows to use (default: 6).
*/
rowCount: number
/**
* The class name of the referenced contactSheetOptions object.
*/
readonly typename: string
/**
* True to auto space the images (default: true).
*/
useAutoSpacing: boolean
/**
* The vertical spacing (in pixels) between images (default: 1). Valid only
* when useAutoSpacing = false.
*/
vertical: number
/**
* The width (in pixels) of the resulting document (default: 576).
*/
width: number
}
interface CountItem {
/**
* The position of the count item in the document.
*/
readonly position: UnitValue[]
/**
* The containing document.
*/
readonly parent: Document
/**
* The class name of the referenced CountItem object.
*/
readonly typename: string
/**
* Deletes the CountItem object.
*/
remove(): void
}
interface CountItems {
/**
* The number of elements in the CountItems collection.
*/
readonly length: number
/**
* The containing document.
*/
readonly parent: Document
/**
* The class name of the referenced CountItems object.
*/
readonly typename: string
/**
* Creates a new count item object and adds it to this collection. Parameter
* position (x,y) represents the horizontal and vertical positions,
* respectively, of the CountItem object.
*/
add(position: UnitValue[]): CountItem
/**
* Get the first element in the CountItems collection with the provided name.
*/
getByName(name: string): CountItem
/**
* Removes all CountItem objects from the CountItems collection.
*/
removeAll(): void
}
declare class DCS1_SaveOptions {
/**
* (default: DCSType.COLORCOMPOSITE).
*/
dCS: DCSType
/**
* True to embed the color profile in the document
*/
embedColorProfile: boolean
/**
* The type of encoding to use for document (default: SaveEncoding.BINARY).
*/
encoding: SaveEncoding
/**
* True to include halftone screen (default: false).
*/
halftoneScreen: boolean
/**
* True to use image interpolation (default: false)
*/
interpolation: boolean
/**
* The type of preview (default: Preview.MACOSEIGHTBIT).
*/
preview: Preview
/**
* True to include the Transfer functions to compensate for dot gain
* between the image and film (default: false).
*/
transferFunction: boolean
/**
* The class name of the referenced DCS1_SaveOptions object.
*/
readonly typename: string
/**
* True to include vector data. Valid only if the document includes vector
* data (unrasterized text).
*/
vectorData: boolean
}
declare class DCS2_SaveOptions {
/**
* The type of composite file to create (default: DCSType.NOCOMPOSITE).
*/
dCS: DCSType
/**
* True to embed the color profile in the document.
*/
embedColorProfile: boolean
/**
* The type of encoding to use (default: SaveEncoding.BINARY).
*/
encoding: SaveEncoding
/**
* True to include the halftone screen (default: false).
*/
halftoneScreen: boolean
/**
* True to use image interpolation (default: false).
*/
interpolation: boolean
/**
* True to save color channels as multiple files or a single file (default:
* false).
*/
multiFileDCS: boolean
/**
* The preview type (default: Preview.MACOSEIGHTBIT).
*/
preview: Preview
/**
* True to save spot colors.
*/
spotColors: boolean
/**
* True to include the Transfer functions to compensate for dot gain
* between the image and film (default: false).
*/
transferFunction: boolean
/**
* The class name of the referenced DCS2_SaveOptions object.
*/
readonly typename: string
/**
* True to include vector data. Valid only if the document includes vector
* data (unrasterized text).
*/
vectorData: boolean
}
declare class DICOMOpenOptions {
/**
* True to make the patient information anonymous.
*/
anonymize: boolean
/**
* Number of columns in n-up configuration.
*/
columns: number
/**
* True to reverse (invert) the image.
*/
reverse: boolean
/**
* The number of rows in n-up configuration.
*/
rows: number
/**
* True to show overlays.
*/
showOverlays: boolean
/**
* The class name of the referenced DICOMOpenOptions object.
*/
readonly typename: string
/**
* The contrast of the image in Houndsfield units.
*/
windowLevel: number
/**
* The brightness of the image in Houndsfield units.
*/
windowWidth: number
}
interface Document {
/**
* The selected channels.
*/
activeChannels: Channel[]
/**
* The history state to use with the history brush.
*/
activeHistoryBrushSource: Guide
/**
* The selected HistoryState object.
*/
activeHistoryState: Guide
/**
* The selected layer.
*/
activeLayer: ArtLayer | LayerSet
/**
* The art layers collection.
*/
readonly artLayers: ArtLayers
/**
* The background layer of the document.
*/
readonly backgroundLayer: ArtLayer
/**
* The number of bits per channel.
*/
bitsPerChannel: BitsPerChannelType
/**
* The channels collection.
*/
readonly channels: Channels
/**
* The name of the color profile. Valid only when colorProfileType =
* ColorProfile.CUSTOM or WORKING.
*/
colorProfileName: string
/**
* Whether the document uses the working color profile, a custom profile,
* or no profile.
*/
colorProfileType: ColorProfileType
/**
* The current color samplers associated with this document.
*/
readonly colorSamplers: ColorSamplers
/**
* The color channels that make up the document; for instance, the Red,
* Green, and Blue channels for an RGB document.
*/
readonly componentChannels: Channel[]
/**
* The current count items. Note: For additional information about count
* items, see Adobe Photoshop CC help on the Count Tool.
*/
readonly countItems: CountItems
/**
* The full path name of the document.
*/
readonly fullName: File
/**
* The guides collection.
*/
readonly guides: Guides
/**
* The height of the document (unit value).
*/
readonly height: UnitValue
/**
* A histogram showing the number of pixels at each color intensity level
* for the composite channel. The array c ontains 256 members. Valid only
* when mode = DocumentMode.RGB, CMYK; or INDEXEDCOLOR.
*/
readonly histogram: number[]
/**
* The history states collection.
*/
readonly historyStates: HistoryStates
/**
* Metadata about the document.
*/
readonly info: DocumentInfo
/**
* The layer compositions collection.
*/
readonly layerComps: LayerComps
/**
* The layers collection.
*/
readonly layers: Layers
/**
* The layer set collection.
*/
readonly layerSets: LayerSets
/**
* True if the document a is workgroup document.
*/
readonly managed: boolean
/**
* The measurement scale for the document. Note: The measurement scale
* feature is available in the Extended version only.
*/
readonly measurementScale: MeasurementScale
/**
* The color profile.
*/
readonly mode: DocumentMode
/**
* The document's name.
*/
readonly name: string
/**
* The application object that contains this document.
*/
readonly parent: Application
/**
* The path to the document.
*/
readonly path: File
/**
* The path items collection.
*/
readonly pathItems: PathItems
/**
* The (custom) pixel aspect ratio to use.
*/
pixelAspectRatio: number
/**
* The print settings for the document.
*/
readonly printSettings: DocumentPrintSettings
/**
* True if the document is in Quick Mask mode.
*/
quickMaskMode: boolean
/**
* The document’s resolution (in pixels per inch).
*/
readonly resolution: number
/**
* True if the document has been saved since the last change.
*/
readonly saved: boolean
/**
* The selected area of the document.
*/
readonly selection: Selection
/**
* The class name of the Document object.
*/
readonly typename: string
/**
* The width of the document (unit value).
*/
readonly width: UnitValue
/**
* XMP metadata for the document. Camera RAW settings for the image are
* stored here for example. Methods
*/
readonly xmpMetadata: xmpMetadata
/**
* Counts the number of objects in a document. Available in the Extended
* Version only. Creates a CountItem object for each object counted. For
* additional information about how to set up objects to count, see the
* Count Tool in the Adobe Photoshop CC Help
*/
autoCount(channel: Channel, threshold: number): void
/**
* Changes the color profile of the document.
*/
changeMode(destinationMode: ChangeMode, options?: IndexedConversionOptions): void
/**
* Closes the document. If any changes have been made, the script presents
* an alert with three options: save, do not save, prompt to save. The
* optional parameter specifies a selection in the alert box (default:
* SaveOptionsType. PROMPTTOSAVECHANGES).
*/
close(saving?: SaveOptions): void
/**
* Changes the color profile. The destinationProfile parameter must be
* either a string that names the color mode or Working RGB, Working CMYK,
* Working Gray, Lab Color (meaning one of the working color spaces or Lab
* color).
*/
convertProfile(destinationProfile: string, intent: Intent, blackPointCompensation?: boolean, dither?: boolean): void
/**
* Crops the document. The bounds parameter is an array of four coordinates
* for the region remaining after cropping, [left, top, right, bottom].
*/
crop(bounds: UnitValue[], angle?: number, width?: UnitValue, height?: UnitValue): void
/**
* Creates a duplicate of the document object. The optional parameter name
* provides the name for the duplicated document. The optional parameter
* mergeLayersOnly indicates whether to only duplicate merged layers.
*/
duplicate(name?: string, mergeLayersOnly?: boolean): Document
/**
* Exports the paths in the document to an Illustrator file, or exports the
* document to a file with Web or device viewing optimizations. This is
* equivalent to choosing File > Export > Paths To Illustrator, or File >
* Save For Web and Devices.
*/
exportDocument(exportIn: File, exportAs?: ExportType, options?: ExportOptionsIllustrator|ExportOptionsSaveForWeb): void
/**
* Flattens all layers in the document.
*/
flatten(): void
/**
* Flips the image within the canvas in the specified direction.
*/
flipCanvas(direction: Direction): void
/**
* Imports annotations into the document.
*/
importAnnotations(file: File): void
/**
* Flattens all visible layers in the document.
*/
mergeVisibleLayers(): void
/**
* Pastes the contents of the clipboard into the document. If the optional
* argument is set to true and a selection is active, the contents are
* pasted into the selection.
*/
paste(intoSelection?: boolean): ArtLayer
/**
* Prints the document. printSpace specifies the color space for the
* printer. Valid values are nothing (that is, the same as the source); or
* Working RGB, Working CMYK, Working Gray, Lab Color (meaning one of the
* working color spaces or Lab color); or a string specifying a specific
* colorspace (default is same as source).
*/
print(sourceSpace?: SourceSpaceType, printSpace?: string, intent?: Intent, blackPointCompensation?: boolean): void
/**
* Print one copy of the document.
*/
printOneCopy(): void
/**
* Rasterizes all layers.
*/
rasterizeAllLayers(): void
/**
* Record measurements of document.
*/
recordMeasurements(source?: MeasurementSource, dataPoints?: string[]): void
/**
* Changes the size of the canvas to display more or less of the image but
* does not change the image size. See resizeImage.
*/
resizeCanvas(width?: UnitValue, height?: UnitValue, anchor?: AnchorPosition): void
/**
* Changes the size of the image. The amount parameter controls the amount
* of noise value when using preserve details (Range: 0 - 100).
*/
resizeImage(width?: UnitValue, height?: UnitValue, resolution?: number, resampleMethod?: ResampleMethod, amount?: number): void
/**
* Expands the document to show clipped sections.
*/
revealAll(): void
/**
* Rotates the canvas (including the image) in clockwise direction.
*/
rotateCanvas(angle: number): void
/**
* Saves the document.
*/
save(): void
/**
* Saves the document in a specific format. Specify the save options
* appropriate to the format by passing one of these objects: BMPSaveOptions
* DCS1_SaveOptions DCS2_SaveOptions EPSSaveOptions GIFSaveOptions
* JPEGSaveOptions PDFSaveOptions PhotoshopSaveOptions PICTFileSaveOptions
* PICTResourceSaveOptions PixarSaveOptions PNGSaveOptions RawSaveOptions
* SGIRGBSaveOptions TargaSaveOptions TiffSaveOptions
*/
saveAs(saveIn: File, options?: any, asCopy?: boolean, extensionType?: Extension): void
/**
* Splits the document channels into separate images.
*/
splitChannels(): Document[]
/**
* Provides a single entry in history states for the entire script provided
* by javaScriptString. Allows a single undo for all actions taken in the
* script. The historyString parameter provides the string to use for the
* history state. The javaScriptString parameter provides a string of
* JavaScript code to excute while history is suspended.
*/
suspendHistory(historyString: string, javaScriptString: string): void
/**
* Applies trapping to a CMYK document. Valid only when docRef.mode =
* DocumentMode.CMYK.
*/
trap(width: number): void
/**
* Trims the transparent area around the image on the specified sides of the
* canvas. Default is true for all Boolean parameters.
*/
trim(type?: TrimType, top?: boolean, left?: boolean, bottom?: boolean, right?: boolean): void
}
declare class DocumentPrintSettings {
/**
* Background color of page.
*/
backgroundColor: SolidColor
/**
* Bleed width
*/
bleedWidth: UnitValue
/**
* Print the caption found in FileInfo.
*/
caption: boolean
/**
* Print center crop marks.
*/
centerCropMarks: boolean
/**
* Print color calibration bars.
*/
colorBars: boolean
/**
* Number of copies to print.
*/
copies: number
/**
* Print corner crop marks.
*/
cornerCropMarks: boolean
/**
* Color handling.
*/
readonly colorHandling: PrintColorHandling
/**
* The currently active printer.
*/
activePrinter: string
/**
* Flip the image horizontally.
*/
flip: boolean
/**
* Print a hard proof.
*/
hardProof: boolean
/**
*
*/
interpolate: boolean
/**
* Prints the document title.
*/
labels: boolean
/**
* Map blacks.
*/
mapBlack: boolean
/**
* Invert the image colors.
*/
negative: boolean
/**
* Color conversion intent when print space is different from the source
* space.
*/
renderIntent: Intent
/**
* The x position of the image on page.
*/
readonly posX: UnitValue
/**
* The y position of the image on page.
*/
readonly posY: UnitValue
/**
* The width of the print border.
*/
printBorder: UnitValue
/**
* Name of the printer.
*/
printerName: string
/**
* color space for printer. Can be nothing (meaning same as source);
* 'Working RGB', 'Working CMYK', 'Working Gray', 'Lab Color' (meaning one
* of the working spaces or Lab color); or a string specifying a specific
* colorspace (default is same as source)
*/
printSpace: string
/**
* Print registration marks.
*/
registrationMarks: boolean
/**
* Scale of image on page.
*/
readonly scale: number
/**
* Include vector data. Methods
*/
vectorData: boolean
/**
* Set the position of the image on the page.
*/
setPagePosition(docPosition: DocPositionStyle, posX: UnitValue, posY: UnitValue, scale: number): void
}
interface DocumentInfo {
/**
*
*/
author: string
/**
*
*/
authorPosition: string
/**
*
*/
caption: string
/**
*
*/
captionWriter: string
/**
*
*/
category: string
/**
*
*/
city: string
/**
* The copyrighted status.
*/
copyrighted: CopyrightedType
/**
*
*/
copyrightNotice: string
/**
*
*/
country: string
/**
*
*/
creationDate: string
/**
*
*/
credit: string
/**
* Camera data that includes camera settings used when the image was taken.
* Each array member is a tag pair, an array of [tag, tag_data]; for
* example, [ "camera" "Cannon"].
*/
readonly exif: string[][]
/**
*
*/
headline: string
/**
*
*/
instructions: string
/**
*
*/
jobName: string
/**
* A list of keywords that can identify the document or its contents.
*/
keywords: string[]
/**
*
*/
ownerUrl: string
/**
* The info object's container.
*/
readonly parent: Document
/**
*
*/
provinceState: string
/**
*
*/
source: string
/**
*
*/
supplementalCategories: string[]
/**
*
*/
title: string
/**
*
*/
transmissionReference: string
/**
* The class name of the referenced info object.
*/
readonly typename: string
/**
*
*/
urgency: Urgency
}
interface Documents {
/**
* The number of elements in the documents collection.
*/
readonly length: number
/**
* The containing application.
*/
readonly parent: Application
/**
* The class name of the referenced documents object.
*/
readonly typename: string
/**
* Creates a new document object and adds it to this collection.
* pixelAspectRatio: Default is 1.0, a square aspect ratio.
* bitsPerChannelType: Default is BitsPerChannelType.EIGHT.
*/
add(width?: UnitValue, height?: UnitValue, resolution?: number, name?: string, mode?: NewDocumentMode, initialFill?: DocumentFill, pixelAspectRatio?: number, bitsPerChannel?: BitsPerChannelType, colorProfileName?: string): Document
/**
* Gets the first element in the documents collection with the provided name
*/
getByName(name: string): Document
}
declare class EPSOpenOptions {
/**
* True to use antialias.
*/
antiAlias: boolean
/**
* True to constrain the proportions of the image.
*/
constrainProportions: boolean
/**
* The height of the image (unit value).
*/
height: UnitValue
/**
* The color profile to use as the document mode.
*/
mode: OpenDocumentMode
/**
* The resolution of the document in pixels per inch.
*/
resolution: number
/**
* The class name of the referenced EPSOpenOptions object.
*/
readonly typename: string
/**
* The width of the image (unit value).
*/
width: UnitValue
}
declare class EPSSaveOptions {
/**
* True to embed the color profile in this document.
*/
embedColorProfile: boolean
/**
* The type of encoding to use (default: SaveEncoding.BINARY).
*/
encoding: SaveEncoding
/**
* True to include the halftone screen (default: false).
*/
halftoneScreen: boolean
/**
* True to use image interpolation (default: false).
*/
interpolation: boolean
/**
* The preview type.
*/
preview: Preview
/**
* True to use Postscript color management (default: false).
*/
psColorManagement: boolean
/**
* True to include the Transfer functions to compensate for dot gain
* between the image and film (default: false).
*/
transferFunction: boolean
/**
* True to display white areas as transparent. Valid only when
* document.mode = DocumentMode.BITMAP. See also changeMode().
*/
transparentWhites: boolean
/**
* The class name of the referenced EPSSaveOptions object.
*/
readonly typename: string
/**
* True to include vector data. Valid only if the document includes vector
* data (text).
*/
vectorData: boolean
}
declare class ExportOptionsIllustrator {
/**
* The type of path to export (default: IllustratorPathType.DOCUMENTBOUNDS).
*/
path: IllustratorPathType
/**
* The name of the path to export. Valid only when path =
* IllustratorPathType.NAMEDPATH.
*/
pathName: string
/**
* The class name of the referenced exportOptionsIllustrator object.
*/
readonly typename: string
}
declare class ExportOptionsSaveForWeb {
/**
* Applies blur to the image to reduce artifacts (default: 0.0).
*/
blur: number
/**
* The color reduction algorithm (default: ColorReductionType.SELECTIVE).
*/
colorReduction: ColorReductionType
/**
* The number of colors in the palette (default: 256).
*/
colors: number
/**
* The type of dither (default: Dither.DIFFUSION).
*/
dither: Dither
/**
* The amount of dither (default: 100). Valid only when dither =
* Dither.DIFFUSION.
*/
ditherAmount: number
/**
* The file format to use (default: SaveDocumentType.COMPUSERVEGIF). Note:
* For this property, only COMPUSERVEGIF, JPEG, PNG-8, PNG-24, and BMP are
* supported.
*/
format: SaveDocumentType
/**
* True to include the document’s embedded color profile (default: false).
*/
includeProfile: boolean
/**
* True to download in multiple passes; progressive (default: false).
*/
interlaced: boolean
/**
* The amount of lossiness allowed (default: 0).
*/
lossy: number
/**
* The colors to blend transparent pixels against.
*/
matteColor: RGBColor
/**
* True to create smaller but less compatible files (default: true). Valid
* only when format = SaveDocumentType.JPEG.
*/
optimized: boolean
/**
* Indicates the number of bits; true = 8, false = 24 (default: true).
* Valid only when format = SaveDocumentType.PNG.
*/
PNG8: boolean
/**
* The quality of the produced image as a percentage; default: 60.
*/
quality: number
/**
* Indication of transparent areas of the image should be included in the
* saved image(default: true).
*/
transparency: boolean
/**
* The amont of transparency dither (default: 100). Valid only if
* transparency = true.
*/
transparencyAmount: number
/**
* The transparency dither algorithm (default: transparencyDither =
* Dither.NONE).
*/
transparencyDither: Dither
/**
* The class name of the referenced ExportOptionsSaveForWeb object.
*/
readonly typename: string
/**
* The tolerance amount within which to snap close colors to web palette
* colors (default: 0). File Folder ExtendScript defines the JavaScript
* classes File and Folder to encapsulate file-system references in a
* platform-independent manner; see ‘JavaScript support in Adobe Photoshop
* CC’ on page 32. For references details of these classes, see the
* JavaScript Tools Guide.
*/
webSnap: number
}
declare class GalleryBannerOptions {
/**
* The web photo gallery contact info.
*/
contactInfo: string
/**
* The web photo gallery date (default: current date).
*/
date: string
/**
* The font setting for the banner text (default: GalleryFontType.ARIAL).
*/
font: GalleryFontType
/**
* The font size for the banner text (default: 3).
*/
fontSize: number
/**
* The web photo gallery photographer.
*/
photographer: string
/**
* The web photo gallery site name (default: Adobe Web Photo Gallery).
*/
siteName: string
/**
* The class name of the referenced galleryBannerOptions object.
*/
readonly typename: string
}
declare class GalleryCustomColorOptions {
/**
* The color to use to indicate an active link.
*/
activeLinkColor: RGBColor
/**
* The background color.
*/
backgroundColor: RGBColor
/**
* The banner color.
*/
bannerColor: RGBColor
/**
* The color to use to indicate a link.
*/
linkColor: RGBColor
/**
* The text color.
*/
textColor: RGBColor
/**
* The class name of the referenced galleryCustomColorOptions object.
*/
readonly typename: string
/**
* The color to use to indicate a visited link.
*/
visitedLinkColor: RGBColor
}
declare class GalleryImagesOptions {
/**
* The size (in pixels) of the border that separates images (default: 0).
*/
border: number
/**
* True to generate image captions (default: false).
*/
caption: boolean
/**
* The resized image dimensions in pixels (default: 350). Valid only when
* resizeImages = true.
*/
dimension: number
/**
* The font to use for image captions (default: GalleryFontType.ARIAL).
*/
font: GalleryFontType
/**
* The font size for image captions (default: 3). Valid only when caption =
* true.
*/
fontSize: number
/**
* The quality setting for a JPEG image (default: 5).
*/
imageQuality: number
/**
* True to include copyright information in captions (default: false).
* Valid only when caption = true.
*/
includeCopyright: boolean
/**
* True to include the credits in image captions (default: false). Valid
* only when caption = true.
*/
includeCredits: boolean
/**
* True to include the file name in image captions (default: true). Valid
* only when caption = true.
*/
includeFilename: boolean
/**
* True to include the title in image captions (default: false). Valid only
* when caption = true.
*/
includeTitle: boolean
/**
* True to add numeric links (default: true).
*/
numericLinks: boolean
/**
* The image dimensions to constrain in the gallery image (default:
* GalleryConstrainType.CONSTRAINBOTH). Valid only when resizeImages = true.
*/
resizeConstraint: GalleryConstrainType
/**
* True to automatically resize images for placement on the gallery pages
* (default: true).
*/
resizeImages: boolean
/**
* The class name of the referenced galleryImagesOptions object.
*/
readonly typename: string
}
declare class GalleryOptions {
/**
* True to add width and height attributes for images (default: true).
*/
addSizeAttributes: boolean
/**
* The options related to banner settings.
*/
bannerOptions: GalleryBannerOptions
/**
* The options related to custom color settings.
*/
customColorOptions: GalleryCustomColorOptions
/**
* The email address to show on the web page.
*/
emailAddress: string
/**
* The options related to images settings.
*/
imagesOptions: GalleryImagesOptions
/**
* True to include all files found in sub folders of the input folder
* (default: true).
*/
includeSubFolders: boolean
/**
* The style to use for laying out the web page (default: Centered Frame 1
* - Basic).
*/
layoutStyle: string
/**
* True to save metadata (default: false).
*/
preserveAllMetadata: boolean
/**
* The options related to security settings.
*/
securityOptions: GallerySecurityOptions
/**
* The options related to thumbnail image settings.
*/
thumbnailOptions: GalleryThumbnailOptions
/**
* The class name of the referenced galleryOptions object.
*/
readonly typename: string
/**
* True to use the short web page extension .htm. If false, use the web
* page extension .html (default: true).
*/
useShortExtension: boolean
/**
* True to use UTF-8 encoding for the web page (default: false).
*/
useUTF8Encoding: boolean
}
declare class GallerySecurityOptions {
/**
* The web photo gallery security content (default:
* GallerySecurityType.NONE).
*/
content: GallerySecurityType
/**
* The web photo gallery security font (default: GalleryFontType.ARIAL).
*/
font: GalleryFontType
/**
* The web photo gallery security font size (default: 3).
*/
fontSize: number
/**
* The web page security opacity as a percent (default: 100).
*/
opacity: number
/**
* The web photo gallery security custom text.
*/
text: string
/**
* The web page security text color.
*/
textColor: GallerySecurityTextColorType
/**
* The web photo gallery security text position (default:
* GallerySecurityTextPositionType. CENTERED).
*/
textPosition: GallerySecurityTextPositionType
/**
* The web photo gallery security text orientation to use (default:
* GallerySecurityTextRotateType. ZERO).
*/
textRotate: GallerySecurityTextRotateType
/**
* The class name of the referenced gallerySecurityOptions object.
*/
readonly typename: string
}
declare class GalleryThumbnailOptions {
/**
* The amount of border pixels you want around your thumbnail images
* (default: 0).
*/
border: number
/**
* True if there is a caption (default: false).
*/
caption: boolean
/**
* The number of columns on the page (default: 5).
*/
columnCount: number
/**
* The web photo gallery thumbnail dimension in pixels (default: 75).
*/
dimension: number
/**
* The web photo gallery font (default: GalleryFontType.ARIAL).
*/
font: GalleryFontType
/**
* The font size for thumbnail images text (default: 3).
*/
fontSize: number
/**
* True to include copyright information for thumbnails (default: false).
*/
includeCopyright: boolean
/**
* True to include credits for thumbnails (default: false).
*/
includeCredits: boolean
/**
* True to include file names for thumbnails (default: false).
*/
includeFilename: boolean
/**
* True to include titles for thumbnails (default: false).
*/
includeTitle: boolean
/**
* The number of rows on the page (default: 3).
*/
rowCount: number
/**
* The thumbnail image size (default: GalleryThumbSizeType.MEDIUM).
*/
size: GalleryThumbSizeType
/**
* The class name of the referenced GalleryThumbnailOptions object.
*/
readonly typename: string
}
declare class GIFSaveOptions {
/**
* The number of palette colors. Valid only when palette =
* Palette.LOCALADAPTIVE, LOCALPERCEPTUAL, LOCALSELECTIVE, MACOSPALETTE,
* UNIFORM, WEBPALETTE; or WINDOWSPALETTE .
*/
colors: number
/**
* The dither type.
*/
dither: Dither
/**
* The amount of dither (default: 75). Valid only when dither =
* Dither.DIFFUSION.
*/
ditherAmount: number
/**
* The type of colors to force into the color palette.
*/
forced: ForcedColors
/**
* True if rows should be interlaced (default: false).
*/
interlaced: boolean
/**
* The color to use to fill anti-aliased edges adjacent to transparent
* areas of the image (default: MatteType.WHITE). When transparency = false,
* the matte color is applied to transparent areas.
*/
matte: MatteType
/**
* The type of palette to use (default: Palette.LOCALSELECTIVE).
*/
palette: PaletteType
/**
* True to protect colors in the image that contain entries in the color
* table from being dithered. Valid only when dither = Dither.DIFFUSION.
*/
preserveExactColors: boolean
/**
* True to preserve transparent areas of the image during conversion to GIF
* format.
*/
transparency: boolean
/**
* The class name of the referenced GIFSaveOptions object.
*/
readonly typename: string
}
declare class GrayColor {
/**
* The gray value (default: 0.0).
*/
gray: number
/**
* The class name of the referenced grayColor object.
*/
readonly typename: string
}
declare class Guide {
/**
* Indicates whether the guide is vertical or horizontal.
*/
direction: Direction
/**
* Location of the guide from origin of image.
*/
coordinate: UnitValue
}
interface Guides {
/**
* The number of elements in the guides collection.
*/
readonly length: number
/**
* The containing document.
*/
readonly parent: Document
/**
* The class name of the referenced guides object.
*/
readonly typename: string
/**
* Creates a new guide object and adds it to this collection.
*/
add(direction: Direction, coordinate: UnitValue): Guide
/**
* Gets the first element in the guides collection with the provided name
*/
getByName(name: string): Guide
}
interface HistoryState {
/**
* The HistoryState object's name.
*/
readonly name: string
/**
* The containing document.
*/
readonly parent: Document
/**
* True if the history state is a snapshot.
*/
readonly snapshot: boolean
/**
* The class name of the referenced HistoryState object.
*/
readonly typename: string
}
interface HistoryStates {
/**
* The number of elements in the HistoryStates collection.
*/
readonly length: number
/**
* The containing document.
*/
readonly parent: Document
/**
* The class name of the referenced HistoryStates object.
*/
readonly typename: string
/**
* Get the first element in the HistoryStates collection with the provided
* name.
*/
getByName(name: string): Guide
}
declare class HSBColor {
/**
* The brightness value.
*/
brightness: number
/**
* The hue value.
*/
hue: number
/**
* The saturation value.
*/
saturation: number
/**
* The class name of the referenced HSBColor object.
*/
readonly typename: string
}
declare class IndexedConversionOptions {
/**
* The number of palette colors. Valid only when palette =
* Palette.LOCALADAPTIVE, LOCALPERCEPTUAL, LOCALSELECTIVE, MACOSPALETTE,
* UNIFORM, WEBPALETTE, or WINDOWSPALETTE.
*/
colors: number
/**
* The dither type.
*/
dither: Dither
/**
* The amount of dither. Valid only when dither = Dither.diffusion.
*/
ditherAmount: number
/**
* The type of colors to force into the color palette.
*/
forced: ForcedColors
/**
* The color to use to fill anti-aliased edges adjacent to transparent
* areas of the image (default: MatteType.WHITE). When transparency = false,
* the matte color is applied to transparent areas.
*/
matte: MatteType
/**
* The palette type (default: Palette.EXACT).
*/
palette: PaletteType
/**
* True to protect colors in the image that contain entries in the color
* table from being dithered. Valid only when dither = Dither.DIFFUSION.
*/
preserveExactColors: boolean
/**
* True to preserve transparent areas of the image during conversion to GIF
* format.
*/
transparency: boolean
/**
* The class name of the referenced IndexedConversionOptions object.
*/
readonly typename: string
}
declare class JPEGSaveOptions {
/**
* True to embed the color profile in the document.
*/
embedColorProfile: boolean
/**
* The download format to use (default: FormatOptions.STANDARDBASELINE).
*/
formatOptions: FormatOptions
/**
* The color to use to fill anti-aliased edges adjacent to transparent
* areas of the image (default: MatteType.WHITE). When transparency is
* turned off for an image, the matte color is applied to transparent areas.
*/
matte: MatteType
/**
* The image quality setting to use; affects file size and compression
* (default: 3).
*/
quality: number
/**
* The number of scans to make to incrementally display the image on the
* page (default: 3). Valid only for when formatOptions =
* FormatOptions.PROGRESSIVE.
*/
scans: number
/**
* The class name of the referenced JPEGSaveOptions object.
*/
readonly typename: string
}
declare class LabColor {
/**
* The a-value.
*/
a: number
/**
* The b-value.
*/
b: number
/**
* The L-value.
*/
l: number
/**
* The class name of the referenced LabColor object.
*/
readonly typename: string
}
interface LayerComp {
/**
* True to use layer appearance (layer styles) settings.
*/
appearance: boolean
/**
* A description of the layer comp.
*/
comment: string
/**
* The name of the layer comp.
*/
name: string
/**
* The containing document.
*/
parent: Document
/**
* True to use layer position.
*/
position: boolean
/**
* True if the layer comp is currently selected.
*/
readonly selected: boolean
/**
* The class name of the referenced layerComp object.
*/
readonly typename: string
/**
* True to use layer visibility settings .
*/
visibility: boolean
/**
* Applies the layer comp to the document.
*/
apply(): void
/**
* Recaptures the current layer state(s) for this layer comp.
*/
recapture(): void
/**
* Deletes the layerComp object.
*/
remove(): void
/**
* Resets the layer comp state to the document state.
*/
resetfromComp(): void
}
interface LayerComps {
/**
* The number of elements in the layerComps collection.
*/
readonly length: number
/**
* The containing document.
*/
readonly parent: Document
/**
* The class name of the referenced layerComps object.
*/
readonly typename: string
/**
* Creates a new layer composition object and adds it to this collection.
*/
add(name: string, comment: string, appearance: boolean, position: boolean, visibility: boolean): LayerComp
/**
* Gets the first element in the collection with the provided name.
*/
getByName(name: string): LayerComp
/**
* Removes all member objects from the layerComps collection.
*/
removeAll(): void
}
interface Layers {
/**
* The number of elements in the layers collection.
*/
readonly length: number
/**
* The containing document or layer set.
*/
readonly parent: Document
/**
* The class name of the referenced layers object.
*/
readonly typename: string
/**
* Gets the first element in the layers collection with the provided name.
*/
getByName(name: string): Layer
/**
* Removes all layers from the collection.
*/
removeAll(): void
}
interface LayerSet {
/**
* True if the contents in the layers in this set are not editable.
*/
allLocked: boolean
/**
* The art layers in this layer set.
*/
readonly artLayers: ArtLayers
/**
* The blend mode to use for the layer set.
*/
blendMode: BlendMode
/**
* The bounding rectangle of the layer set.
*/
readonly bounds: UnitValue[]
/**
* The channels enabled for the layer set; must be a list of component
* channels. See Channel.kind.
*/
enabledChannels: Channel[]
/**
* The layers in this layer set.
*/
readonly layers: Layers
/**
* Nested layer sets contained within this layer set. linkedLayers array of
* ArtLayer and/
*/
readonly layerSets: LayerSets
/**
* The layers linked to this layerSet object.
*/
readonly or: LayerSet
/**
* The name of this layer set.
*/
name: string
/**
* The master opacity of the set.
*/
opacity: number
/**
* The containing document or layer set.
*/
readonly parent: Document
/**
* The class name of the referenced LayerSet object.
*/
readonly typename: string
/**
* True if the set is visible. Methods
*/
visible: boolean
/**
* Creates a duplicate of the object.
*/
duplicate(relativeObject?: ArtLayer, insertionLocation?: ElementPlacement): LayerSet
duplicate(relativeObject?: LayerSet, insertionLocation?: ElementPlacement): LayerSet
/**
* Links the layer set with another layer.
*/
link(with_: LayerSet): void
/**
* Merges the layerset; returns a reference to the art layer created by this
* method.
*/
merge(): ArtLayer
/**
* Moves the object.
*/
move(relativeObject: ArtLayer, insertionLocation: ElementPlacement): void
move(relativeObject: LayerSet, insertionLocation: ElementPlacement): void
/**
* Deletes the object.
*/
remove(): void
/**
* Resizes all layers in the layer set to to the specified dimensions (as a
* percentage of its current size) and places the layer set in the specified
* position.
*/
resize(horizontal?: number, vertical?: number, anchor?: AnchorPosition): void
/**
* Rotates all layers in the layer set around the specified anchor point
* (default: AnchorPosition.MIDDLECENTER)
*/
rotate(angle: number, anchor?: AnchorPosition): void
/**
* Moves the position relative to its current position.
*/
translate(deltaX?: UnitValue, deltaY?: UnitValue): void
/**
* Unlinks the layer set.
*/
unlink(): void
}
interface LayerSets {
/**
* The number of elements in the LayerSets collection.
*/
readonly length: number
/**
* The containing document or layer set.
*/
readonly parent: Document
/**
* The class name of the referenced layerSets object.
*/
readonly typename: string
/**
* Creates a new layer set object and adds it to the collection.
*/
add(): LayerSet
/**
* Gets the first element in the collection with the provided name.
*/
getByName(name: string): LayerSet
/**
* Removes all member layer sets, and any layers or layer sets they contain,
* from the document.
*/
removeAll(): void
}
interface MeasurementLog {
/**
* Export measurement to a file.
*/
exportMeasurements(file?: File, range?: MeasurementRange, dataPoints?: string[]): void
/**
* Delete measurements from the log.
*/
deleteMeasurements(range?: MeasurementRange): void
}
interface MeasurementScale {
/**
* The length in pixels this scale equates to.
*/
pixelLength: number
/**
* The logical length this scale equates to.
*/
logicalLength: number
/**
* The logical units for this scale.
*/
logicalUnits: string
}
declare class NoColor {
/**
* The class name of the referenced noColor object.
*/
readonly typename: string
}
interface Notifier {
/**
* The event identifier, a four-character code or a unique string. For a
* list of four-character codes, see Appendix A: Event ID Codes.
*/
readonly event: string
/**
* The class identifier, a four-character code or a unique string. When an
* event applies to multiple types of objects, use this propery to
* distinguish which object this notifier applies to. For example, the Make
* event ("Mk ") can apply to documents ("Dcmn"), channels ("Chnl") and
* other objects.
*/
readonly eventClass: string
/**
* The path to the file to execute when the event occurs and activates the
* notifier.
*/
readonly eventFile: File
/**
* The containing application.
*/
readonly parent: Application
/**
* The class name of the referenced object.
*/
readonly typename: string
/**
* Deletes this object. You can also remove a Notifier object from the
* Script Events Manager drop-down list by deleting the file named Script
* Events Manager.xml from the Photoshop preferences folder. See Adobe
* Photoshop CC help for more information.
*/
remove(): void
}
interface Notifiers {
/**
* The number of elements in the notifiers collection.
*/
readonly length: number
/**
* The notifiers object’s container
*/
readonly parent: Application
/**
* The class name of the referenced notifiers object.
*/
readonly typename: string
/**
* Creates a notifier object and adds it to this collection. event defines
* the class ID of the event: use a 4-characters code or a unique string.
* See Appendix A: Event ID Codes. eventFile defines the script file that
* executes when the event occurs. When an event applies to multiple types
* of objects, use the eventClass (a 4-character ID or unique string) to
* distinguish which object this Notifier applies to. For example, the Make
* event ("Mk ") applies to documents ("Dcmn"), channels ("Chnl") and other
* objects. Tip: When specifying an event or event calss wtih a 4-character
* ID code, omit the single quotes in your code.
*/
add(event: string, eventFile: File, eventClass?: string): Notifier
/**
* Removes all member objects from the notifiers collection. You can also
* remove a notifier object from the Script Events Manager drop-down list by
* deleting the file named Script Events Manager.xml from the Photoshop
* preferences folder. See Adobe Photoshop CC help for more information.
*/
removeAll(): void
}
interface PathItem {
/**
* The type.
*/
kind: PathKind
/**
* The name.
*/
name: string
/**
* The containing document.
*/
readonly parent: Document
/**
* The contained sub-path objects.
*/
readonly subPathItems: SubPathItems
/**
* The class name of the referenced pathItem object.
*/
readonly typename: string
/**
* Deselects this pathItem object.
*/
deselect(): void
/**
* Duplicates this pathItem object with the new name.
*/
duplicate(name: string): void
/**
* Fills the area enclosed by this path. opacity is a percentage. feather is
* in pixels. If wholePath is true, all subpaths are used when doing the
* fill (default: true).
*/
fillPath(fillColor?: SolidColor, mode?: ColorBlendMode, opacity?: number, preserveTransparency?: boolean, feather?: number, wholePath?: boolean, antiAlias?: boolean): void
/**
* Makes this the clipping path for this document. flatness tells the
* PostScript printer how to approximate curves in the path.
*/
makeClippingPath(flatness?: number): void
/**
* Makes a Selection object whose border is this path. feather is in pixels.
*/
makeSelection(feather?: number, antiAlias?: boolean, operation?: SelectionType): void
/**
* Deletes this object.
*/
remove(): void
/**
* Makes this the active or selected PathItem object.
*/
select(): void
/**
* Strokes the path with the specified tool.
*/
strokePath(tool?: ToolType, simulatePressure?: boolean): void
}
interface PathItems {
/**
* The number of pathItem objects in the pathItems collection.
*/
readonly length: number
/**
* The pathItems object's container.
*/
readonly parent: Document
/**
* The class name of the referenced pathItems object.
*/
readonly typename: string
/**
* Creates a new path item object and adds it to this collection. A new
* SubPathItem object is created for each SubPathInfo object provided in
* entirePath, and those SubPathItem objects are added to the subPathItems
* collection of the returned PathItem.
*/
add(name: string, entirePath: SubPathInfo[]): PathItem
/**
* Get the first element in the pathItems collection with the provided name.
*/
getByName(name: string): PathItem
/**
* Removes all pathItem objects from the pathItems collection.
*/
removeAll(): void
}
interface PathPoint {
/**
* The X and Y coordinates of the anchor point of the curve.
*/
readonly anchor: number[][]
/**
* The role (corner or smooth) this point plays in the containing path
* segment.
*/
readonly kind: PointKind
/**
* The location of the left-direction endpoint (’in’ position).
*/
readonly leftDirection: number[]
/**
* The containing subpath object.
*/
readonly parent: SubPathItem
/**
* The location of the right-direction endpoint (’out’ position).
*/
readonly rightDirection: number[]
/**
* The class name of the referenced PathPoint object.
*/
readonly typename: string
}
declare class PathPointInfo {
/**
* The X and Y coordinates of the anchor point of the curve.
*/
anchor: number[][]
/**
* The role (corner or smooth) this point plays in the containing path
* segment.
*/
kind: PointKind
/**
* The location of the left-direction endpoint (’in’ position).
*/
leftDirection: number[]
/**
* The location of the right-direction endpoint (’out’ position).
*/
rightDirection: number[]
/**
* The class name of the referenced PathPointInfo object. var spi = new
* SubPathInfo(); spi.closed = false; spi.operation =
* ShapeOperation.SHAPEXOR; spi.entireSubPath = [startPoint, stopPoint]; var
* line = doc.pathItems.add("Line", [spi]);
* line.strokePath(ToolType.PENCIL); line.remove(); };
* drawLine(app.activeDocument, [100,100], [200,200]);
*/
readonly typename: string
}
interface PathPoints {
/**
* The number of elements in the collection.
*/
readonly length: number
/**
* The containing subpath object.
*/
readonly parent: SubPathItem
/**
* The class name of the referenced PathPoints object.
*/
readonly typename: string
}
declare class PDFOpenOptions {
/**
* True to use antialias.
*/
antiAlias: boolean
/**
* The number of bits per channel. constrainProportions boolean DEPRECATED
* for Adobe Photoshop CC.
*/
bitsPerChannel: BitsPerChannelType
/**
* The method of cropping to use. height UnitValue DEPRECATED for Adobe
* Photoshop CC.
*/
cropPage: CropToType
/**
* The color model to use.
*/
mode: OpenDocumentMode
/**
* The name of the object.
*/
name: string
/**
* The page or image to which to open the document, depending on the value
* of usePageNumber.
*/
page: number
/**
* The resolution of the document (in pixels per inch).
*/
resolution: number
/**
* True to suppress warnings when opening the document.
*/
suppressWarnings: boolean
/**
* The class name of the referenced PDFOpenOptions object.
*/
readonly typename: string
/**
* When true, the page property refers to a page number; when false, it
* refers to an image number. width UnitValue DEPRECATED for Adobe Photoshop
* CC.
*/
usePageNumber: boolean
}
declare class PDFSaveOptions {
/**
* True to save the alpha channels with the file.
*/
alphaChannels: boolean
/**
* True to save comments with the file.
*/
annotations: boolean
/**
* True to convert the color profile to a destination profile.
*/
colorConversion: boolean
/**
* True to convert a 16-bit image to 8-bit for better compatibility with
* other applications.
*/
convertToEightBit: boolean
/**
* Description of the save options to use.
*/
description: string
/**
* Description of the final RGB or CMYK output device, such as a monitor or
* a press standard. downgradeColorProfile boolean DEPRECATED for Adobe
* Photoshop CC.
*/
destinationProfile: string
/**
* The down sample method to use.
*/
downSample: PDFResample
/**
* The size to downsample images if they exceed the limit in pixels per
* inch.
*/
downSampleSize: number
/**
* Limits downsampling or subsampling to images that exceed this value in
* pixels per inch.
*/
downSampleSizeLimit: number
/**
* True to embed the color profile in the document. embedFonts boolean
* DEPRECATED for Adobe Photoshop CC.
*/
embedColorProfile: boolean
/**
* True to include a small preview image in Adobe PDF files.
*/
embedThumbnail: boolean
/**
* The type of compression to use (default: PDFEncoding.PDFZIP).
* interpolation boolean DEPRECATED for Adobe Photoshop CC.
*/
encoding: PDFEncoding
/**
* The quality of the produced image, which is inversely proportionate to
* the compression amount. Valid only when encoding = PDFEncoding.JPEG .
*/
jpegQuality: number
/**
* True to save the document’s layers.
*/
layers: boolean
/**
* True to improve performance of PDF files on Web servers.
*/
optimizeForWeb: boolean
/**
* An optional comment field for inserting descriptions of the output
* condition. The text is stored in the PDF/X file.
*/
outputCondition: string
/**
* Indentifier for the output condition.
*/
outputConditionID: string
/**
* The PDF version to make the document compatible with.
*/
PDFCompatibility: PDFCompatibility
/**
* The PDF standard to make the document compatible with.
*/
PDFStandard: PDFStandard
/**
* True to reopen the PDF in Adobe Photoshop CC with native Photoshop data
* intact.
*/
preserveEditing: boolean
/**
* The preset file to use for settings. Note: This option overrides other
* settings.
*/
presetFile: string
/**
* True to show which profiles to include.
*/
profileInclusionPolicy: boolean
/**
* URL where the output condition is registered.
*/
registryName: string
/**
* True to save spot colors.
*/
spotColors: boolean
/**
* Compression option. Valid only when encoding = PDFEncoding.JPEG2000.
* transparency boolean DEPRECATED for Adobe Photoshop CC.
*/
tileSize: number
/**
* The class name of the referenced PDFSaveOptions object. useOutlines
* boolean DEPRECATED for Adobe Photoshop CC. vectorData boolean DEPRECATED
* for Adobe Photoshop CC.
*/
readonly typename: string
/**
* True to open the saved PDF in Adobe Acrobat.
*/
view: boolean
}
declare class PhotoCDOpenOptions {
/**
* The profile to use when reading the image.
*/
colorProfileName: string
/**
* The colorspace for the image.
*/
colorSpace: PhotoCDColorSpace
/**
* The image orientation.
*/
orientation: Orientation
/**
* The image dimensions.
*/
pixelSize: PhotoCDSize
/**
* The image resolution (in pixels per inch).
*/
resolution: number
/**
* The class name of the referenced photoCDOpenOptions object.
*/
readonly typename: string
}
declare class PhotoshopSaveOptions {
/**
* True to save the alpha channels.
*/
alphaChannels: boolean
/**
* True to save the annotations.
*/
annotations: boolean
/**
* True to embed the color profile in the document.
*/
embedColorProfile: boolean
/**
* True to preserve the layers.
*/
layers: boolean
/**
* True to save the spot colors.
*/
spotColors: boolean
/**
* The class name of the referenced photoshopSaveOptions object.
*/
readonly typename: string
}
declare class PICTFileSaveOptions {
/**
* True to save the alpha channels.
*/
alphaChannels: boolean
/**
* The type of compression to use (default: PICTCompression.NONE).
*/
compression: PICTCompression
/**
* True to embed the color profile in the document.
*/
embedColorProfile: boolean
/**
* The number of bits per pixel.
*/
resolution: PICTBitsPerPixels
/**
* The class name of the referenced PICTFileSaveOptions object.
*/
readonly typename: string
}
declare class PICTResourceSaveOptions {
/**
* True to save the alpha channels.
*/
alphaChannels: boolean
/**
* The type of compression to use (default: PICTCompression.NONE).
*/
compression: PICTCompression
/**
* True to embed the color profile in the document.
*/
embedColorProfile: boolean
/**
* The name of the PICT resource.
*/
name: string
/**
* The number of bits per pixel.
*/
resolution: PICTBitsPerPixels
/**
* The ID of the PICT resource (default: 128).
*/
resourceID: number
/**
* The class name of the referenced PICTResourceSaveOptions object.
*/
readonly typename: string
}
declare class PicturePackageOptions {
/**
* The content information (default: PicturePackageTextType.NONE).
*/
content: PicturePackageTextType
/**
* True if all layers in the final document are flattened (default: true).
*/
flatten: boolean
/**
* The font used for security text (default: GalleryFontType.ARIAL).
*/
font: GalleryFontType
/**
* The font size used for security text (default: 12).
*/
fontSize: number
/**
* The layout to use to generate the picture package (default: "(2)5x7").
*/
layout: string
/**
* Read-write. The color profile to use as the document mode (default:
* NewDocumentMode.RGB).
*/
mode: NewDocumentMode
/**
* The web page security opacity as a percent (default: 100).
*/
opacity: number
/**
* The resolution of the document in pixels per inch (default: 72.0).
*/
resolution: number
/**
* The picture package custom text. Valid only when content =
* PicturePackageType.USER.
*/
text: string
/**
* The color to use for security text.
*/
textColor: RGBColor
/**
* The security text position (default: GallerySecurityTextPositionType.
* CENTERED).
*/
textPosition: GallerySecurityTextPositionType
/**
* The orientation to use for security text (default:
* GallerySecurityTextRotateType.ZERO).
*/
textRotate: GallerySecurityTextRotateType
/**
* The class name of the referenced PicturePackageOptions object.
*/
readonly typename: string
}
declare class PixarSaveOptions {
/**
* True to save the alpha channels.
*/
alphaChannels: boolean
/**
* The class name of the referenced PixarSaveOptions object.
*/
readonly typename: string
}
declare class PNGSaveOptions {
/**
* The compression value (default: 0).
*/
compression: number
/**
* True to interlace rows (default: false).
*/
interlaced: boolean
/**
* The class name of the referenced PNGSaveOptions object.
*/
readonly typename: string
}
interface Preferences {
/**
* The path to an additional plug-in folder. Valid only when
* useAdditionalPluginFolder = true.
*/
additionalPluginFolder: File
/**
* The preferred policy for writing file extensions in Windows.
*/
appendExtension: SaveBehavior
/**
* True to ask the user to verify layer preservation options when saving a
* file in TIFF format.
*/
askBeforeSavingLayeredTIFF: boolean
/**
* True to automatically update open documents.
*/
autoUpdateOpenDocuments: boolean
/**
* True to beep when a process finishes.
*/
beepWhenDone: boolean
/**
* True to display component channels in the Channels palette in color.
*/
colorChannelsInColor: boolean
/**
* The preferred color selection tool.
*/
colorPicker: ColorPicker
/**
* The width of the column gutters (in points).
*/
columnGutter: number
/**
* Column width (in points)
*/
columnWidth: number
/**
* True to automatically make the first snapshot when a new document is
* created.
*/
createFirstSnapshot: boolean
/**
* True if dynamic color sliders appear in the Color palette.
*/
dynamicColorSliders: boolean
/**
* The preferred level of detail in the history log. Valid only when
* useHistoryLog = true.
*/
editLogItems: EditLogItemsType
/**
* True to retain Adobe Photoshop CC contents on the clipboard after you
* exit the application.
*/
exportClipboard: boolean
/**
* The preferred type size to use for font previews in the type tool font
* menus.
*/
fontPreviewSize: FontPreviewType
/**
* True to show image preview as a full size image, false to show thumbnail
* (in Mac OS only).
*/
fullSizePreview: boolean
/**
* Opacity value as a percentage.
*/
gamutWarningOpacity: number
/**
* The preferred size to use for squares in the grid.
*/
gridSize: GridSize
/**
* The preferred formatting style for non-printing grid lines.
*/
gridStyle: GridLineStyle
/**
* Number of grid subdivisions.
*/
gridSubDivisions: number
/**
* The preferred formatting style for non-printing guide lines.
*/
guideStyle: GuideLineStyle
/**
* True to use icon previews (in Mac OS only).
*/
iconPreview: boolean
/**
* The number of images to hold in the cache.
*/
imageCacheLevels: number
/**
* The preferred policy for writing image previews in Windows.
*/
imagePreviews: SaveBehavior
/**
* The method to use to assign color values to any new pixels created when
* an image is resampled or resized.
*/
interpolation: ResampleMethod
/**
* True to automatically resize the window when zooming in or out using
* keyboard shortcuts.
*/
keyboardZoomResizesWindows: boolean
/**
* True to create a thumbnail when saving the image (in Mac OS only).
*/
macOSThumbnail: boolean
/**
* The preferred policy for checking whether to maximize compatibility when
* opening PSD files.
*/
maximizeCompatibility: QueryStateType
/**
* The maximum percentage of available RAM used by Adobe Photoshop CC (5 -
* 100).
*/
maxRAMuse: number
/**
* True to allow non-linear history.
*/
nonLinearHistory: boolean
/**
* The number of history states to preserve.
*/
numberofHistoryStates: number
/**
* The preferred type of pointer to use with certain tools.
*/
otherCursors: OtherPaintingCursors
/**
* The preferred type of pointer to use with certain tools.
*/
paintingCursors: PaintingCursors
/**
* The containing application.
*/
parent: Application
/**
* True to halve the resolution (double the size of pixels) to make
* previews display more quickly.
*/
pixelDoubling: boolean
/**
* The point/pica size.
*/
pointSize: PointType
/**
* The number of items in the recent file list.
*/
recentFileListLength: number
/**
* The unit the scripting system will use when receiving and returning
* values.
*/
rulerUnits: Units
/**
* Thepreferred location of history log data when saving the history items.
*/
saveLogItems: SaveLogItemsType
/**
* The path to the history log file, when the preferred location is a file.
*/
saveLogItemsFile: File
/**
* True to make new palette locations the default location.
*/
savePaletteLocations: boolean
/**
* True to display Asian text options in the Paragraph palette.
*/
showAsianTextOptions: boolean
/**
* True to list Asian font names in English.
*/
showEnglishFontNames: boolean
/**
* True to display slice numbers in the document window when using the
* Slice tool.
*/
showSliceNumber: boolean
/**
* True to show pop up definitions on mouse over.
*/
showToolTips: boolean
/**
* True to use curly, false to use straight quote marks.
*/
smartQuotes: boolean
/**
* Size of the small font used in panels and dialogs.
*/
textFontSize: FontSize
/**
* The class name of the referenced preferences object.
*/
readonly typename: string
/**
* The preferred unit for text character measurements.
*/
typeUnits: TypeUnits
/**
* True to use an additional folder for compatible plug-ins stored with a
* different application.
*/
useAdditionalPluginFolder: boolean
/**
* True to create a log file for history states.
*/
useHistoryLog: boolean
/**
* True to use lowercase for file extensions.
*/
useLowerCaseExtension: boolean
/**
* True to enable cycling through a set of hidden tools.
*/
useShiftKeyForToolSwitch: boolean
/**
* True to enable Adobe Photoshop CC to send transparency information to
* your computer’s video board. (Requires hardware support.)
*/
useVideoAlpha: boolean
/**
* True to create a thumbnail when saving the image in Windows. (Requires
* hardware support.)
*/
windowsThumbnail: boolean
}
declare class PresentationOptions {
/**
* True to auto advance images when when viewing the presentation (default:
* true). Valid only when presentation = true.
*/
autoAdvance: boolean
/**
* True to include the file name for the image (default: false).
*/
includeFilename: boolean
/**
* The time in seconds before the view is auto advanced (default: 5). Valid
* only when autoAdvance = true.
*/
interval: number
/**
* True to begin the presentation again after the last page (default:
* false). Valid only when autoAdvance = true.
*/
loop: boolean
/**
* The magnification type to use when viewing the image.
*/
magnification: MagnificationType
/**
* Options to use when creating the PDF file.
*/
PDFFileOptions: PDFSaveOptions
/**
* True if the output will be a presentation (default: false); when false,
* the output is a Multi-Page document.
*/
presentation: boolean
/**
* The method for transition from one image to the next (default:
* TransitionType.NONE). Valid only when autoAdvance = true. .
*/
transition: TransitionType
/**
* The class name of the referenced PresentationOptions object.
*/
readonly typename: string
}
declare class RawFormatOpenOptions {
/**
* The number of bits for each channel. The only valid values are
* BitsPerChannelType.EIGHT or BitsPerChannelType.SIXTEEN.
*/
bitsPerChannel: number
/**
* The order in which multibyte values are read. Valid only when
* bitsPerChannel = BitsPerChannelType.SIXTEEN.
*/
byteOrder: ByteOrder
/**
* The number of channels in the image. The value of cannot exceed the
* number of channels in the image. When bitsPerChannel =
* BitsPerChannelType.SIXTEEN, the only valid values are 1, 3, or 4.
*/
channelNumber: number
/**
* The number of bytes of information that will appear in the file before
* actual image information begins; that is, the number of zeroes inserted
* at the beginning of the file as placeholders.
*/
headerSize: number
/**
* The height of the image (in pixels).
*/
height: number
/**
* True to store color values sequentially.
*/
interleaveChannels: boolean
/**
* True to retain the header when saving. Valid only when headerSize is 1
* or greater.
*/
retainHeader: boolean
/**
* The class name of the referenced RawFormatOpenOptions object.
*/
readonly typename: string
/**
* The image width in pixels.
*/
width: number
}
declare class RawSaveOptions {
/**
* True if alpha channels should be saved.
*/
alphaChannels: boolean
/**
* True if the spot colors should be saved.
*/
spotColors: boolean
/**
* The class name of the referenced RawSaveOptions object.
*/
readonly typename: string
}
declare class RGBColor {
/**
* The blue color value (default: 255).
*/
blue: number
/**
* The green color value (default: 255)
*/
green: number
/**
* The hexadecimal representation of the color.
*/
hexValue: string
/**
* The red color value (default: 255)
*/
red: number
/**
* The class name of the referenced RGBColor object.
*/
readonly typename: string
}
interface Selection {
/**
* The bounding rectangle of the entire selection.
*/
readonly bounds: UnitValue[]
/**
* The object's container.
*/
readonly parent: Document
/**
* True if the bounding rectangle is a solid.
*/
readonly solid: boolean
/**
* The class name of the referenced selection object.
*/
readonly typename: string
/**
* Clears the selection and does not copy it to the clipboard.
*/
clear(): void
/**
* Contracts (reduces) the selection by the specified amount.
*/
contract(by: UnitValue): void
/**
* Copies the selection to the clipboard. When the optional argument is used
* and set to true, a merged copy is performed (all visible layers in the
* selection are copied).
*/
copy(merge?: boolean): void
/**
* Clears the current selection and copies it to the clipboard.
*/
cut(): void
/**
* Deselects the current selection.
*/
deselect(): void
/**
* Expands the selection by the specified amount.
*/
expand(by: UnitValue): void
/**
* Feathers the edges of the selection by the specified amount.
*/
feather(by: UnitValue): void
/**
* Fills the selection. opacity is a percentage value.
*/
fill(filltype: SolidColor, mode?: ColorBlendMode, opacity?: number, preserveTransparency?: boolean): void
/**
* Grows the selection to include all adjacent pixels falling within the
* specified tolerance range.
*/
grow(tolerance: number, antiAlias: boolean): void
/**
* Inverts the selection (deselects the selection and selects the rest of
* the layer or document). Tip: To flip the selection shape, see rotate.
*/
invert(): void
/**
* Loads the selection from the specified channel.
*/
load(from: Channel, combination?: SelectionType, inverting?: boolean): void
/**
* Makes this selection item the work path for this document.
*/
makeWorkPath(tolerance?: number): void
/**
* Resizes the selected area to the specified dimensions and anchor position.
*/
resize(horizontal?: number, vertical?: number, anchor?: AnchorPosition): void
/**
* Changes the size of the selection to the specified dimensions around the
* specified anchor.
*/
resizeBoundary(horizontal?: number, vertical?: number, anchor?: AnchorPosition): void
/**
* Rotates the selection by the specified amount around the specified anchor
* point.
*/
rotate(angle: number, anchor?: AnchorPosition): void
/**
* Rotates the boundary of the selection around the specified anchor.
*/
rotateBoundary(angle: number, anchor?: AnchorPosition): void
/**
* Selects the specified region. The region parameter is an array of four
* coordinates, [left, top, right, bottom].
*/
select(region: number[][], type?: SelectionType, feather?: number, antiAlias?: boolean): void
/**
* Selects the entire layer.
*/
selectAll(): void
/**
* Selects the selection border only (in the specified width); subsequent
* actions do not affect the selected area within the borders.
*/
selectBorder(width: UnitValue): void
/**
* Grows the selection to include pixels throughout the image falling within
* the tolerance range.
*/
similar(tolerance: number, antiAlias: boolean): void
/**
* Cleans up stray pixels left inside or outside a color-based selection
* (within the radius specified in pixels).
*/
smooth(radius: number): void
/**
* Saves the selection as a channel.
*/
store(into: Channel, combination?: SelectionType): void
/**
* Strokes the selection border. opacity is a percentage value.
*/
stroke(strokeColor: SolidColor, width: number, location?: StrokeLocation, mode?: ColorBlendMode, opacity?: number, preserveTransparency?: boolean): void
/**
* Moves the entire selection relative to its current position.
*/
translate(deltaX?: UnitValue, deltaY?: UnitValue): void
/**
* Moves the selection relative to its current position.
*/
translateBoundary(deltaX?: UnitValue, deltaY?: UnitValue): void
}
declare class SGIRGBSaveOptions {
/**
* True to save the alpha channels.
*/
alphaChannels: boolean
/**
* True to save the spot colors.
*/
spotColors: boolean
/**
* The class name of the referenced SGIRGBSaveOptions object.
*/
readonly typename: string
}
declare class SolidColor {
/**
* The CMYK color mode.
*/
cmyk: CMYKColor
/**
* The Grayscale color mode.
*/
gray: GrayColor
/**
* The HSB color mode.
*/
hsb: HSBColor
/**
* The LAB color mode.
*/
lab: LabColor
/**
* The color model.
*/
model: ColorModel
/**
* The nearest web color to the current color.
*/
readonly nearestWebColor: RGBColor
/**
* The RGB color mode.
*/
rgb: RGBColor
/**
* The class name of the referenced SolidColor object.
*/
readonly typename: string
/**
* True if the SolidColor object is visually equal to the specified color.
*/
isEqual(color: SolidColor): boolean
}
declare class SubPathInfo {
/**
* True if the path describes an enclosed area.
*/
closed: boolean
/**
*
*/
entireSubPath: PathPoint[]
/**
* The subpath’s operation on other subpaths. Specifies how to combine the
* shapes if the destination path already has a selection.
*/
operation: ShapeOperation
/**
* The class name of the referenced SubPathInfo object.
*/
readonly typename: string
}
interface SubPathItem {
/**
* True if the path is closed.
*/
readonly closed: boolean
/**
* How this object behaves when it intersects another SubPathItem object.
* Specifies how to combine the shapes if the destination path already has a
* selection.
*/
readonly operation: ShapeOperation
/**
* The object's container.
*/
readonly parent: PathItem
/**
* The PathPoints collection.
*/
readonly pathPoints: PathPoints
/**
* The class name of the referenced SubPathItem object.
*/
readonly typename: string
}
interface SubPathItems {
/**
* The number of elements in the collection.
*/
readonly length: number
/**
* The containing path item.
*/
readonly parent: PathItem
/**
* The class name of the referenced SubPathItems object.
*/
readonly typename: string
}
declare class TargaSaveOptions {
/**
* True to save the alpha channels.
*/
alphaChannels: boolean
/**
* The number of bits per pixel (default: TargaBitsPerPixels.TWENTYFOUR).
*/
resolution: TargaBitsPerPixels
/**
* True to use RLE compression (default: true).
*/
rleCompression: boolean
/**
* The class name of the referenced TargaSaveOptions object.
*/
readonly typename: string
}
interface TextFont {
/**
* The font family.
*/
readonly family: string
/**
* The name of the font.
*/
readonly name: string
/**
* The containing application.
*/
readonly parent: Application
/**
* The PostScript name of the font.
*/
readonly postScriptName: string
/**
* The font style.
*/
readonly style: string
/**
* The class name of the referenced TextFont object.
*/
readonly typename: string
}
interface TextFonts {
/**
* The number of elements in the collection.
*/
readonly length: number
/**
* The containing application.
*/
readonly parent: Application
/**
* The class name of the referenced TextFonts object.
*/
readonly typename: string
/**
* Gets the first element in the TextFonts collection with the provided name.
*/
getByName(name: string): TextFont
}
interface TextItem {
/**
* True to use alternate ligatures. Note: Alternate ligatures are the same
* as Discretionary Ligatures. See Adobe Photoshop CC Help for more
* information.
*/
alternateLigatures: boolean
/**
* The method of anti aliasing to use.
*/
antiAliasMethod: AntiAlias
/**
* The auto kerning option to use.
*/
autoKerning: AutoKernType
/**
* The percentage to use for auto (default) leading (in points). Valid only
* when useAutoLeading = true.
*/
autoLeadingAmount: number
/**
* The unit value to use in the baseline offset of text.
*/
baselineShift: UnitValue
/**
* The text case.
*/
capitalization: TextCase
/**
* The text color.
*/
color: SolidColor
/**
* The actual text in the layer.
*/
contents: string
/**
* The desired amount by which to scale the horizontal size of the text
* letters. A percentage value; at 100, the width of characters is not
* scaled. Valid only when justification = Justification.CENTERJUSTIFIED,
* FULLYJUSTIFIED, LEFTJUSTIFIED, or Justification.RIGHTJUSTIFIED. When
* used, the minimumGlyphScaling and maximumGlyphScaling values are also
* required.
*/
desiredGlyphScaling: number
/**
* The amount of space between letters (at 0, no space is added between
* letters). Equivalent to Letter Spacing in the Justification dialog
* (Select Justification on the Paragraphs palette menu). Valid only when
* justification = Justification.CENTERJUSTIFIED, FULLYJUSTIFIED,
* LEFTJUSTIFIED, or Justification.RIGHTJUSTIFIED. When used, the
* minimumLetterScaling and maximumLetterScaling values are also required.
*/
desiredLetterScaling: number
/**
* The amount (percentage) of space between words (at 100, no additional
* space is added between words). Equivalent to Word Spacing in the
* Justification dialog (Select Justification on the Paragraphs palette
* menu). Valid only when justification = Justification.CENTERJUSTIFIED,
* FULLYJUSTIFIED, LEFTJUSTIFIED, or Justification.RIGHTJUSTIFIED. When
* used, the minimumWordScaling and maximumWordScaling values are also
* required.
*/
desiredWordScaling: number
/**
* The text orientation.
*/
direction: Direction
/**
* True to use faux bold (default: false). Setting this to true is
* equivalent to selecting text and clicking Faux Bold in the Character
* palette.
*/
fauxBold: boolean
/**
* True to use faux italic (default: false). Setting this to true is
* equivalent to selecting text and clicking Faux Italic in the Character
* palette.
*/
fauxItalic: boolean
/**
* The amount (unit value) to indent the first line of paragraphs.
*/
firstLineIndent: UnitValue
/**
* The text face of the character. Use the PostScript Name of the font. See
* TextFont and use the postScriptName property.
*/
font: string
/**
* True to use Roman hanging punctuation.
*/
hangingPunctuation: boolean
/**
* The height of the bounding box (unit value) for paragraph text. Valid
* only when kind = TextType.PARAGRAPHTEXT.
*/
height: UnitValue
/**
* Character scaling (horizontal) in proportion to verticalScale (a
* percentage value).
*/
horizontalScale: number
/**
* The number of letters after which hyphenation in word wrap is allowed.
*/
hyphenateAfterFirst: number
/**
* The number of letters before which hyphenation in word wrap is allowed.
*/
hyphenateBeforeLast: number
/**
* True to allow hyphenation in word wrap of capitalized words.
*/
hyphenateCapitalWords: boolean
/**
* The minimum number of letters a word must have in order for hyphenation
* in word wrap to be allowed.
*/
hyphenateWordsLongerThan: number
/**
* True to use hyphenation in word wrap. hyphenationZone UnitValue [0..720]
* pica Read-write. The distance at the end of a line that will cause a word
* to break in unjustified type.
*/
hyphenation: boolean
/**
* The maximum number of consecutive lines that can end with a hyphenated
* word.
*/
hyphenLimit: number
/**
* The paragraph justification.
*/
justification: Justification
/**
* The text-wrap type.
*/
kind: TextType
/**
* The language to use.
*/
language: Language
/**
* The leading amount.
*/
leading: UnitValue
/**
* The amoun of space to indent text from the left.
*/
leftIndent: UnitValue
/**
* True to use ligatures.
*/
ligatures: boolean
/**
* The maximum amount to scale the horizontal size of the text letters (a
* percentage value; at 100, the width of characters is not scaled). Valid
* only when justification = Justification.CENTERJUSTIFIED, FULLYJUSTIFIED,
* LEFTJUSTIFIED, or Justification.RIGHTJUSTIFIED. When used, the
* minimumGlyphScaling and desiredGlyphScaling values are also required.
*/
maximumGlyphScaling: number
/**
* The maximum amount of space to allow between letters (at 0, no space is
* added between letters). Equivalent to Letter Spacing in the Justification
* dialog (Select Justification on the Paragraphs palette menu). Valid only
* when justification = Justification.CENTERJUSTIFIED, FULLYJUSTIFIED,
* LEFTJUSTIFIED, or Justification.RIGHTJUSTIFIED. When used, the
* minimumLetterScaling and desiredLetterScaling values are also required.
*/
maximumLetterScaling: number
/**
* The maximum amount of space to allow between words (a percentage value;
* at 100, no additional space is added between words). Equivalent to Word
* Spacing in the Justification dialog (Select Justification on the
* Paragraphs palette menu). Valid only when justification =
* Justification.CENTERJUSTIFIED, FULLYJUSTIFIED, LEFTJUSTIFIED, or
* Justification.RIGHTJUSTIFIED. When used, the minimumWordScaling and
* desiredWordScaling values are also required.
*/
maximumWordScaling: number
/**
* The minimum amount to scale the horizontal size of the text letters (a
* percentage value; at 100, the width of characters is not scaled). Valid
* only when justification = Justification.CENTERJUSTIFIED, FULLYJUSTIFIED,
* LEFTJUSTIFIED, or Justification.RIGHTJUSTIFIED. When used, the
* maximumGlyphScaling and desiredGlyphScaling values are also required.
*/
minimumGlyphScaling: number
/**
* The minimum amount of space to allow between letters (a percentage
* value; at 0, no space is removed between letters). Equivalent to Letter
* Spacing in the Justification dialog (Select Justification on the
* Paragraphs palette menu). Valid only when justification =
* Justification.CENTERJUSTIFIED, FULLYJUSTIFIED, LEFTJUSTIFIED, or
* Justification.RIGHTJUSTIFIED. When used, the maximumLetterScaling and
* desiredLetterScaling values are also required.
*/
minimumLetterScaling: number
/**
* The minimum amount of space to allow between words (a percentage value;
* at 100, no additional space is removed between words). Equivalent to Word
* Spacing in the Justification dialog (Select Justification on the
* Paragraphs palette menu). Valid only when justification =
* Justification.CENTERJUSTIFIED, FULLYJUSTIFIED, LEFTJUSTIFIED, or
* Justification.RIGHTJUSTIFIED. When used, the maximumWordScaling and
* desiredWordScaling values are also required.
*/
minimumWordScaling: number
/**
* True to disallow line breaks in this text. Tip: When true for many
* consecutive characters, can prevent word wrap and thus may prevent some
* text from appearing on the screen.
*/
noBreak: boolean
/**
* True to use old style type.
*/
oldStyle: boolean
/**
* The containing layer.
*/
parent: ArtLayer
/**
* The position of origin for the text. The array members specify the X and
* Y coordinates. Equivalent to clicking the text tool at a point in the
* document to create the point of origin for text.
*/
position: UnitValue[]
/**
* The amount of space to indent text from the right.
*/
rightIndent: UnitValue
/**
* The font size in UnitValue . NOTE: Type was points for CS3 and older..
*/
size: UnitValue
/**
* The amount of space to use after each paragraph.
*/
spaceAfter: UnitValue
/**
* The amount of space to use before each paragraph.
*/
spaceBefore: UnitValue
/**
* The text strike-through option to use.
*/
strikeThru: StrikeThruType
/**
* The composition method to use to evaluate line breaks and optimize the
* specified hyphenation and justification options. Valid only when kind =
* TextType.PARAGRAPHTEXT.
*/
textComposer: TextComposer
/**
* The amount of uniform spacing between multiple characters. Tracking
* units are 1/1000 of an em space. The width of an em space is relative to
* the current type size. In a 1-point font, 1 em equals 1 point; in a
* 10-point font, 1 em equals 10 points. So, for example, 100 units in a
* 10-point font are equivalent to 1 point.
*/
tracking: number
/**
* The class name of the referenced textItem object.
*/
readonly typename: string
/**
* The text underlining options.
*/
underline: UnderlineType
/**
* True to use a font's built-in leading information.
*/
useAutoLeading: boolean
/**
* Vertical character scaling in proportion to horizontalScale (a
* percentage value).
*/
verticalScale: number
/**
* The warp bend percentage.
*/
warpBend: number
/**
* The warp direction.
*/
warpDirection: Direction
/**
* The horizontal distortion of the warp (a percentage value).
*/
warpHorizontalDistortion: number
/**
* The style of warp to use.
*/
warpStyle: WarpStyle
/**
* The vertical distortion of the warp (a percentage value).
*/
warpVerticalDistortion: number
/**
* The width of the bounding box for paragraph text. Valid only when kind =
* TextType.PARAGRAPHTEXT. Methods
*/
width: UnitValue
/**
* Converts the text item and its containing layer to a fill layer with the
* text changed to a clipping path.
*/
convertToShape(): void
/**
* Creates a clipping path from the outlines of the actual text items (such
* as letters or words).
*/
createPath(): void
}
declare class TiffSaveOptions {
/**
* True to save the alpha channels.
*/
alphaChannels: boolean
/**
* True to save the annotations.
*/
annotations: boolean
/**
* The order in which the document’s multibyte values are read (default:
* ByteOrder.MACOS in Mac OS, ByteOrder.IBM in Windows).
*/
byteOrder: ByteOrder
/**
* True to embed the color profile in the document.
*/
embedColorProfile: boolean
/**
* The compression type (default: TIFFEncoding.NONE).
*/
imageCompression: TIFFEncoding
/**
* True if the channels in the image will be interleaved.
*/
interleaveChannels: boolean
/**
* The quality of the produced image, which is inversely proportionate to
* the amount of JPEG compression. Valid only when imageCompression =
* TIFFEncoding.JPEG.
*/
jpegQuality: number
/**
* The method of compression to use when saving layers (as opposed to
* saving composite data). Valid only when layers = true.
*/
layerCompression: LayerCompression
/**
* True to save the layers.
*/
layers: boolean
/**
* True to preserve multi-resolution information (default: false).
*/
saveImagePyramid: boolean
/**
* True to save the spot colors.
*/
spotColors: boolean
/**
* True to save the transparency as an additional alpha channel when the
* file is opened in another application.
*/
transparency: boolean
/**
* The class name of the referenced TiffSaveOptions object.
*/
readonly typename: string
}
interface UnitValue {
}
interface xmpMetadata {
/**
* The containing document.
*/
readonly parent: Document
/**
* A string containing the XMP metadata in XML (RDF) format. See the XMP
* Specification for details of this format.
*/
rawData: string
} | the_stack |
import type { RegExpVisitor } from "regexpp/visitor"
import type { Group, Quantifier } from "regexpp/ast"
import type { Quant, RegExpContext } from "../utils"
import { quantToString, createRule, defineRegexpVisitor } from "../utils"
/**
* Returns a new quant which is the combination of both given quantifiers.
*/
function getCombinedQuant(parent: Quantifier, child: Quantifier): Quant | null {
if (parent.max === 0 || child.max === 0) {
// other rules deal with this case
return null
} else if (parent.greedy === child.greedy) {
const greedy = parent.greedy
// Explanation of the following condition:
//
// We are currently given a regular expression of the form `(R{a,b}){c,d}` with a<=b, c<=d, b>0, and d>0. The
// question is: For what numbers a,b,c,d is `(R{a,b}){c,d}` == `R{a*c,b*d}`?
//
// Let's reformulate the question in terms of integer intervals. First, some definitions:
// x∈[a,b] ⇔ a <= x <= b
// [a,b]*x = [a*x, b*x] for x != 0
// = [0, 0] for x == 0
//
// The question: For what intervals [a, b] and [c, d] is X=Y for
// X = [a*c, b*d] and
// Y = { x | x ∈ [a,b]*i where i∈[c,d] } ?
//
// The first thing to note is that X ⊇ Y, so we only have to show X\Y = ∅. We can think of the elements X\Y
// as holes in Y. Holes can only appear between intervals [a,b]*j and [a,b]*(j+1), so let's look at a hole h
// between [a,b]*c and [a,b]*(c+1):
//
// 1. We can see that [a,b]*(c+1) ⊆ Y iff c+1 <= d ⇔ c != d since we are dealing with integers only and know
// that c<=d.
// 2. h > b*c and h < a*(c+1). Let's just pick h=b*c+1, then we'll get b*c+1 < a*(c+1).
//
// The condition for _no_ hole between [a,b]*c and [a,b]*(c+1) is:
// c=d ∨ b*c+1 >= a*(c+1)
//
// However, this condition is not defined for b=∞ and c=0. Since [a,b]*x = [0, 0] for x == 0, we will just
// define 0*∞ = 0. It makes sense for our problem, so the condition for b=∞ and c=0 is:
// a <= 1
//
// Now to proof that it's sufficient to only check for a hole between the first two intervals. We want to show
// that if h=b*c+1 is not a hole then there will be no j, c<j<d such that b*j+1 is a hole. The first thing to
// not that j can only exist if c!=d, so the condition for h to not exist simplifies to b*c+1 >= a*(c+1).
//
// 1) b=∞ and c=0:
// b*c+1 >= a*(c+1) ⇔ 1 >= a ⇔ a <= 1. If a <= 1, then h does not exist but since b=∞, we know that the
// union of the next interval [a, ∞]*1 = [a, ∞] and [0, 0] = [a, ∞]*0 is [0, ∞]. [0, ∞] is the largest
// possible interval meaning that there could not possibly be any holes after it. Therefore, a j, c<j<d
// cannot exist.
// 2) b==∞ and c>0:
// b*c+1 >= a*(c+1) ⇔ ∞ >= a*(c+1) is trivially true, so the hole h between [a,b]*c and [a,b]*(c+1) cannot
// exist. There can also be no other holes because [a,b]*c = [a*c,∞] ⊇ [a,b]*i = [a*i,∞] for all i>c.
// 3) b<∞:
// b*c+1 >= a*(c+1). If c+x is also not a hole for any x >= 0, then there can be no holes.
// b*(c+x)+1 >= a*(c+x+1) ⇔ b >= a + (a-1)/(c+x). We know that this is true for x=0 and increasing x will
// only make (a-1)/(c+x) smaller, so it is always true. Therefore, there can be no j c<j<d such that b*j+1
// is a hole.
//
// We've shown that if there is no hole h between the first and second interval, then there can be no other
// holes. Therefore it is sufficient to only check for the first hole.
const a = child.min
const b = child.max
const c = parent.min
const d = parent.max
const condition =
b === Infinity && c === 0
? a <= 1
: c === d || b * c + 1 >= a * (c + 1)
if (condition) {
return {
min: a * c,
max: b * d,
greedy,
}
}
return null
}
return null
}
/**
* Given a parent quantifier and a child quantifier, this will return a
* simplified child quant.
*/
function getSimplifiedChildQuant(
parent: Quantifier,
child: Quantifier,
): Quant | null {
if (parent.max === 0 || child.max === 0) {
// this rule doesn't handle this
return null
} else if (parent.greedy !== child.greedy) {
// maybe some optimization is possible, but I'm not sure, so let's be safe
return null
}
let min = child.min
let max = child.max
if (min === 0 && parent.min === 0) {
min = 1
}
if (parent.max === Infinity && (min === 0 || min === 1) && max > 1) {
max = 1
}
return { min, max, greedy: child.greedy }
}
/**
* Returns whether the given quantifier is a trivial constant zero or constant
* one quantifier.
*/
function isTrivialQuantifier(quant: Quantifier): boolean {
return quant.min === quant.max && (quant.min === 0 || quant.min === 1)
}
/**
* Iterates over the alternatives of the given group and yields all quantifiers
* that are the only element of their respective alternative.
*/
function* iterateSingleQuantifiers(group: Group): Iterable<Quantifier> {
for (const { elements } of group.alternatives) {
if (elements.length === 1) {
const single = elements[0]
if (single.type === "Quantifier") {
yield single
}
}
}
}
export default createRule("no-trivially-nested-quantifier", {
meta: {
docs: {
description:
"disallow nested quantifiers that can be rewritten as one quantifier",
category: "Best Practices",
recommended: true,
},
fixable: "code",
schema: [],
messages: {
nested: "These two quantifiers are trivially nested and can be replaced with '{{quant}}'.",
childOne: "This nested quantifier can be removed.",
childSimpler:
"This nested quantifier can be simplified to '{{quant}}'.",
},
type: "suggestion", // "problem",
},
create(context) {
/**
* Create visitor
*/
function createVisitor({
node,
fixReplaceNode,
fixReplaceQuant,
getRegexpLocation,
}: RegExpContext): RegExpVisitor.Handlers {
return {
onQuantifierEnter(qNode) {
if (isTrivialQuantifier(qNode)) {
return
}
const element = qNode.element
if (element.type !== "Group") {
return
}
for (const child of iterateSingleQuantifiers(element)) {
if (isTrivialQuantifier(child)) {
continue
}
if (element.alternatives.length === 1) {
// only one alternative
// let's see whether we can rewrite the quantifier
const quant = getCombinedQuant(qNode, child)
if (!quant) {
continue
}
const quantStr = quantToString(quant)
const replacement = child.element.raw + quantStr
context.report({
node,
loc: getRegexpLocation(qNode),
messageId: "nested",
data: { quant: quantStr },
fix: fixReplaceNode(qNode, replacement),
})
} else {
// this isn't the only child of the parent quantifier
const quant = getSimplifiedChildQuant(qNode, child)
if (!quant) {
continue
}
if (
quant.min === child.min &&
quant.max === child.max
) {
// quantifier could not be simplified
continue
}
if (quant.min === 1 && quant.max === 1) {
context.report({
node,
loc: getRegexpLocation(child),
messageId: "childOne",
// TODO: This fix depends on `qNode`
fix: fixReplaceNode(
child,
child.element.raw,
),
})
} else {
quant.greedy = undefined
context.report({
node,
loc: getRegexpLocation(child),
messageId: "childSimpler",
data: { quant: quantToString(quant) },
// TODO: This fix depends on `qNode`
fix: fixReplaceQuant(child, quant),
})
}
}
}
},
}
}
return defineRegexpVisitor(context, {
createVisitor,
})
},
}) | the_stack |
import md from 'markdown-it';
import Token from 'markdown-it/lib/token';
import hljs from 'highlight.js';
import hljs_svelte from 'highlightjs-svelte';
import { hljsDefineVue } from './highlight_vue';
import yaml from 'yaml';
import { MDContext } from '../types';
import { paths, exists } from '../../files';
import { readFileSync } from 'fs';
import { replaceAll } from '../../str';
import { InlineCodeReplacement } from './includes';
// Import additional syntax highlight modules
hljs_svelte(hljs);
hljs.registerLanguage('vue', hljsDefineVue);
/**
* Code parameters
*/
interface CodeSampleChunk {
src: string;
title: string;
hint: string;
}
interface CodeSample {
// Main fie
src: string; // Source file
title?: string; // Tab text
hint?: string; // Hint
// Extra code
extra: CodeSampleChunk[];
// Stylesheet
css?: string; // Stylesheet file, could be without extension
cssTitle?: string; // Stylesheet tab title
cssHint?: string;
// Demo
demo?: boolean | string; // True if demo should be shown below code, optional filename for demo
demoTitle?: string; // Demo tab title
demoHint?: string;
class?: string; // Class name to wrap demo
// Replacements
replacements?: InlineCodeReplacement[];
}
const defaultCodeSampleChunk: Required<CodeSampleChunk> = {
src: '',
title: '',
hint: '',
};
const defaultCodeSample: Required<CodeSample> = {
src: '',
title: '',
hint: '',
extra: [],
css: '',
cssTitle: '',
cssHint: '',
class: '',
demo: false,
demoTitle: '',
demoHint: '',
replacements: [],
};
// Keys to check for valid filenames
const validateSources: (keyof CodeSample)[] = ['src', 'css'];
/**
* Dummy callback for replacing content
*/
function returnContent(str: string): string {
return str;
}
/**
* Code tabs
*/
type TabTypes = 'src' | 'css' | 'demo';
interface CodeTab {
type: TabTypes;
title: string;
lang: string;
raw: string;
html: string;
hint: string;
replace: typeof returnContent;
}
/**
* Validate filename
*/
function validateSource(src: string): boolean {
const parts = src.split('/');
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.slice(0, 1) === '.') {
return false;
}
}
return true;
}
/**
* Locate file
*/
function locateCode(file: string, type: TabTypes): string | null {
let filename: string;
// Check for demo: force .html extension
if (type === 'demo') {
// Remove extension
const parts = file.split('.');
const ext = parts.pop()!;
// Test .demo.html
filename =
paths.rawCode + '/' + parts.slice(0).concat(['demo', 'html']).join('.');
if (exists(filename)) {
return filename;
}
// Test .html
filename = paths.rawCode + '/' + parts.slice(0).concat(['html']).join('.');
if (exists(filename)) {
return filename;
}
return null;
}
// Check for raw code
filename = paths.rawCode + '/' + file;
if (exists(filename)) {
return filename;
}
// Check for stylesheet
if (type === 'src' || type === 'css') {
filename = paths.cssCode + '/' + file;
if (exists(filename)) {
return filename;
}
// Add '_' to filename
const parts = file.split('/');
const lastPart = parts.pop()!;
parts.push('_' + lastPart);
filename = paths.cssCode + '/' + parts.join('/');
if (exists(filename)) {
return filename;
}
}
return null;
}
/**
* Change all tokens
*/
function changeTokens(tokens: Token[]) {
tokens.forEach((token) => {
if (token.type === 'fence' && !token.children) {
token.tag = '';
token.type = 'code_block';
// Check for include
if (token.info === 'yaml') {
try {
const data = yaml.parse(token.content);
if (
typeof data === 'object' &&
data.src === void 0 &&
typeof data.include === 'string'
) {
token.type = 'include';
}
} catch (err) {
//
}
}
}
if (token.children) {
changeTokens(token.children);
}
});
}
/**
* Block code
*/
export function renderCode(context: MDContext, md: md) {
const codeHeader = '<code class="highlight hljs">';
const codeFooter = '</code>';
/**
* Get file contents
*/
function getFile(filename: string): string {
let data = readFileSync(filename, 'utf8');
return replaceAll(data, context.replacements);
}
/**
* Convert replacements to object
*/
function convertReplacements(
data: InlineCodeReplacement[]
): Record<string, string> {
const replacements: Record<string, string> = Object.create(null);
data.forEach((item) => {
const search = item.search;
const replace = item.replace;
if (
typeof search !== 'string' ||
typeof replace !== 'string' ||
!search.length
) {
throw new Error(
`Invalid value type for "replacement" in code block in ${context.filename}.`
);
}
replacements[search] = replace;
});
return replacements;
}
/**
* Clean code
*/
function cleanupCode(lang: string, str: string): string {
switch (lang) {
case 'php':
if (
str.trim().slice(0, 5) === '<?php' &&
str.trim().slice(-2) === '?>'
) {
// Remove <?php and ?>
str = str.trim();
str = str.slice(5, str.length - 2).trim();
}
break;
}
return str;
}
/**
* Highlight syntax in code
*/
function highlightCode(lang: string, str: string) {
let code: string;
if (lang === 'raw') {
// Raw code
code = str;
} else {
// Check for language
if (!hljs.getLanguage(lang)) {
throw new Error(
`Bad language for code block in ${context.filename}: ${lang}`
);
}
// Prepare code
let modified = false;
switch (lang) {
case 'jsx':
if (str.slice(0, 1) === '<' && str.trim().slice(-1) === '>') {
// Wrap tag in () to allow syntax highlight
modified = true;
str = '(' + str + ')';
}
break;
}
// Parse code
try {
code = hljs.highlight(str, {
language: lang,
}).value;
} catch (err) {
console.error(err);
throw new Error(`Error parsing code block in ${context.filename}.`);
}
// Fix errors
switch (lang) {
case 'php':
case 'js':
code = replaceAll(code, {
'<span class="hljs-doctag">@iconify</span>': '@iconify',
});
break;
case 'jsx':
if (modified) {
// Remove ()
code = code.slice(1, code.length - 2);
}
break;
}
}
// Replace tabs, spaces and new lines
code = code.replace(/\t/g, ' ');
code = code.replace(/ /g, ' ');
code = code.replace(/\n/g, '<br />\n');
return codeHeader + code + codeFooter;
}
/**
* Add code
*/
function renderTab(
tabs: CodeTab[],
type: TabTypes,
title: string,
lang: string,
code: string,
hint: string,
replace: typeof returnContent
) {
// Change content
code = cleanupCode(lang, code);
// Add tab
tabs.push({
type,
title,
lang,
raw: code,
html: highlightCode(lang, replace(code)),
hint,
replace,
});
}
/**
* Render demo
*/
function renderDemo(
tabs: CodeTab[],
css: string,
title: string,
html: string,
hint: string,
replace: typeof returnContent
) {
if (css !== '') {
// Remove extensions
const parts = css.split('.');
css = parts.shift()!;
}
tabs.push({
type: 'demo',
title,
lang: 'html',
raw: '',
html:
'<div class="code-demo' +
(css === '' ? '' : ' ' + css) +
'">' +
replace(html) +
'</div>',
hint,
replace,
});
}
/**
* Parse YAML
*/
function parseYaml(tabs: CodeTab[], code: string) {
const data = yaml.parse(code) as Required<CodeSample>;
const replacements: Record<string, string> = Object.create(null);
if (typeof data !== 'object' || typeof data.src !== 'string') {
// Do not treat it as custom code
renderTab(tabs, 'src', '', 'yaml', code, '', returnContent);
return;
}
const replaceContent = (str: string): string =>
replaceAll(str, replacements);
// Clean up data
for (const key in defaultCodeSample) {
const attr = key as keyof CodeSample;
if (attr === 'extra') {
// Handle extra array
if (data.extra === void 0) {
data.extra = [];
continue;
}
if (!(data.extra instanceof Array)) {
// Wrong type?
throw new Error(
`Invalid value type for "${attr}" in code block in ${context.filename}.`
);
}
// Validate all entries in extra sources
data.extra.forEach((item) => {
const source = item as CodeSampleChunk;
if (typeof source !== 'object' || typeof source.src !== 'string') {
throw new Error(
`Invalid value type for "${attr}" in code block in ${context.filename}.`
);
}
// Check other attributes
for (const key2 in defaultCodeSampleChunk) {
const attr2 = key2 as keyof CodeSampleChunk;
if (source[attr2] === void 0) {
source[attr2] = defaultCodeSampleChunk[attr2];
continue;
}
if (typeof source[attr2] !== typeof defaultCodeSampleChunk[attr2]) {
throw new Error(
`Invalid value for "${attr}" in code block in ${context.filename}.`
);
}
}
// Validate source
if (!validateSource(source.src)) {
throw new Error(
`Invalid value for "${attr}" in code block in ${context.filename}.`
);
}
});
continue;
}
if (data[attr] === void 0) {
// Copy default value
const defaultValue = defaultCodeSample[attr];
(data as unknown as Record<string, unknown>)[attr] =
defaultValue instanceof Array ? [] : defaultValue;
continue;
}
switch (attr) {
case 'demo':
if (
typeof data[attr] !== 'boolean' &&
typeof data[attr] !== 'string'
) {
// Wrong type?
throw new Error(
`Invalid value type for "${attr}" in code block in ${context.filename}.`
);
}
break;
case 'replacements':
// Validate replacements
if (!(data.replacements instanceof Array)) {
throw new Error(
`Invalid value type for "${attr}" in code block in ${context.filename}.`
);
}
data.replacements.forEach((item) => {
const search = item.search;
const replace = item.replace;
if (
typeof search !== 'string' ||
typeof replace !== 'string' ||
!search.length
) {
throw new Error(
`Invalid value type for "${attr}" in code block in ${context.filename}.`
);
}
replacements[search] = replace;
});
break;
default:
if (typeof data[attr] !== typeof defaultCodeSample[attr]) {
// Wrong type?
throw new Error(
`Invalid value type for "${attr}" in code block in ${context.filename}.`
);
}
}
if (
validateSources.indexOf(attr) !== -1 &&
(attr === 'src' || data[attr] !== '')
) {
// Validate source
if (!validateSource(data[attr] as string)) {
throw new Error(
`Invalid value for "${attr}" in code block in ${context.filename}.`
);
}
}
}
// Check for invalid attributes
for (const key in data) {
const attr = key as keyof CodeSample;
if (defaultCodeSample[attr] === void 0) {
throw new Error(
`Invalid attribute "${attr}" in code block in ${context.filename}.`
);
}
}
// Get code
const sources: CodeSampleChunk[] = [
{
src: data.src,
title: data.title,
hint: data.hint,
},
].concat(data.extra);
sources.forEach((source) => {
const sourceFile = locateCode(source.src, 'src');
if (sourceFile === null) {
throw new Error(
`Unable to locate file "${source.src}" in code block in ${context.filename}.`
);
}
renderTab(
tabs,
'src',
source.title,
source.src.split('.').pop()!,
getFile(sourceFile),
source.hint,
replaceContent
);
});
// Get stylesheet
if (data.css !== '') {
const stylesheetFile = locateCode(data.css, 'css');
if (stylesheetFile === null) {
throw new Error(
`Unable to locate file "${data.css}" in code block in ${context.filename}.`
);
}
renderTab(
tabs,
'css',
data.cssTitle,
'scss',
getFile(stylesheetFile),
data.cssHint,
replaceContent
);
}
// Demo
if (data.demo) {
const demoFile = locateCode(
typeof data.demo === 'string' ? data.demo : data.src,
'demo'
);
if (demoFile === null) {
throw new Error(
`Unable to locate demo file "${data.src}" in code block in ${context.filename}. Demo file must match source file, but end with ".demo.html" or ".html"`
);
}
renderDemo(
tabs,
data.class,
data.demoTitle,
getFile(demoFile),
data.demoHint,
replaceContent
);
}
}
/**
* Render tabs
*/
function renderTabs(tabs: CodeTab[]): string {
let code = '<div class="code-blocks">';
tabs.forEach((tab, index) => {
let raw = '';
if (tab.raw !== '') {
const buff = Buffer.from(tab.raw, 'utf8');
raw = tab.replace(buff.toString('base64'));
}
// Container
code +=
'<div class="code-block code-block--' +
tab.type +
(tab.title === '' ? '' : ' code-block--with-title') +
'">';
// Title
if (tab.title !== '') {
code +=
'<div class="code-block-title">' + tab.replace(tab.title) + '</div>';
}
// Content
code +=
'<div class="code-block-content code-block-content--with' +
(tab.title === '' ? 'out' : '') +
'-title code-block-content--with' +
(tab.hint === '' ? 'out' : '') +
'-hint"' +
(raw === '' ? '' : ' data-raw-code="' + raw + '"') +
'>' +
tab.html +
'</div>';
// Hint
if (tab.hint !== '') {
code +=
'<div class="code-block-hint">' + tab.replace(tab.hint) + '</div>';
}
// Close container
code += '</div>';
});
code += '</div>';
return code;
// return tabs.map((tab) => tab.html).join('');
}
// Render code_block token
md.renderer.rules['code_block'] = (tokens, idx, options, env, self) => {
const token = tokens[idx];
let lang = token.info;
let code = token.content;
const tabs: CodeTab[] = [];
if (!lang) {
throw new Error(
`Missing language for code block in ${context.filename}.`
);
}
if (lang === 'yaml') {
parseYaml(tabs, code);
} else {
renderTab(tabs, 'src', '', lang, code, '', returnContent);
}
return renderTabs(tabs);
};
// Find all fence tokens, replace them with code_block
md.core.ruler.push('code_block', (state) => {
changeTokens(state.tokens);
return true;
});
} | the_stack |
JPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009
Basic GUI blocking jpeg encoder
*/
// var btoa = btoa || function (buf) {
// return Buffer.from(buf).toString('base64');
// };
function JPEGEncoder(quality) {
var self = this;
var fround = Math.round;
var ffloor = Math.floor;
var YTable = new Array(64);
var UVTable = new Array(64);
var fdtbl_Y = new Array(64);
var fdtbl_UV = new Array(64);
var YDC_HT;
var UVDC_HT;
var YAC_HT;
var UVAC_HT;
var bitcode = new Array(65535);
var category = new Array(65535);
var outputfDCTQuant = new Array(64);
var DU = new Array(64);
var byteout = [];
var bytenew = 0;
var bytepos = 7;
var YDU = new Array(64);
var UDU = new Array(64);
var VDU = new Array(64);
var clt = new Array(256);
var RGB_YUV_TABLE = new Array(2048);
var currentQuality;
var ZigZag = [
0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63
];
var std_dc_luminance_nrcodes = [0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0];
var std_dc_luminance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var std_ac_luminance_nrcodes = [0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d];
var std_ac_luminance_values = [
0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa
];
var std_dc_chrominance_nrcodes = [0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0];
var std_dc_chrominance_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
var std_ac_chrominance_nrcodes = [0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77];
var std_ac_chrominance_values = [
0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
0xf9, 0xfa
];
function initQuantTables(sf) {
var YQT = [
16, 11, 10, 16, 24, 40, 51, 61,
12, 12, 14, 19, 26, 58, 60, 55,
14, 13, 16, 24, 40, 57, 69, 56,
14, 17, 22, 29, 51, 87, 80, 62,
18, 22, 37, 56, 68, 109, 103, 77,
24, 35, 55, 64, 81, 104, 113, 92,
49, 64, 78, 87, 103, 121, 120, 101,
72, 92, 95, 98, 112, 100, 103, 99
];
for (var i = 0; i < 64; i++) {
var t = ffloor((YQT[i] * sf + 50) / 100);
if (t < 1) {
t = 1;
} else if (t > 255) {
t = 255;
}
YTable[ZigZag[i]] = t;
}
var UVQT = [
17, 18, 24, 47, 99, 99, 99, 99,
18, 21, 26, 66, 99, 99, 99, 99,
24, 26, 56, 99, 99, 99, 99, 99,
47, 66, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99,
99, 99, 99, 99, 99, 99, 99, 99
];
for (var j = 0; j < 64; j++) {
var u = ffloor((UVQT[j] * sf + 50) / 100);
if (u < 1) {
u = 1;
} else if (u > 255) {
u = 255;
}
UVTable[ZigZag[j]] = u;
}
var aasf = [
1.0, 1.387039845, 1.306562965, 1.175875602,
1.0, 0.785694958, 0.541196100, 0.275899379
];
var k = 0;
for (var row = 0; row < 8; row++) {
for (var col = 0; col < 8; col++) {
fdtbl_Y[k] = (1.0 / (YTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
fdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));
k++;
}
}
}
function computeHuffmanTbl(nrcodes, std_table) {
var codevalue = 0;
var pos_in_table = 0;
var HT = new Array();
for (var k = 1; k <= 16; k++) {
for (var j = 1; j <= nrcodes[k]; j++) {
HT[std_table[pos_in_table]] = [];
HT[std_table[pos_in_table]][0] = codevalue;
HT[std_table[pos_in_table]][1] = k;
pos_in_table++;
codevalue++;
}
codevalue *= 2;
}
return HT;
}
function initHuffmanTbl() {
YDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes, std_dc_luminance_values);
UVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes, std_dc_chrominance_values);
YAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes, std_ac_luminance_values);
UVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes, std_ac_chrominance_values);
}
function initCategoryNumber() {
var nrlower = 1;
var nrupper = 2;
for (var cat = 1; cat <= 15; cat++) {
//Positive numbers
for (var nr = nrlower; nr < nrupper; nr++) {
category[32767 + nr] = cat;
bitcode[32767 + nr] = [];
bitcode[32767 + nr][1] = cat;
bitcode[32767 + nr][0] = nr;
}
//Negative numbers
for (var nrneg = -(nrupper - 1); nrneg <= -nrlower; nrneg++) {
category[32767 + nrneg] = cat;
bitcode[32767 + nrneg] = [];
bitcode[32767 + nrneg][1] = cat;
bitcode[32767 + nrneg][0] = nrupper - 1 + nrneg;
}
nrlower <<= 1;
nrupper <<= 1;
}
}
function initRGBYUVTable() {
for (var i = 0; i < 256; i++) {
RGB_YUV_TABLE[i] = 19595 * i;
RGB_YUV_TABLE[(i + 256) >> 0] = 38470 * i;
RGB_YUV_TABLE[(i + 512) >> 0] = 7471 * i + 0x8000;
RGB_YUV_TABLE[(i + 768) >> 0] = -11059 * i;
RGB_YUV_TABLE[(i + 1024) >> 0] = -21709 * i;
RGB_YUV_TABLE[(i + 1280) >> 0] = 32768 * i + 0x807FFF;
RGB_YUV_TABLE[(i + 1536) >> 0] = -27439 * i;
RGB_YUV_TABLE[(i + 1792) >> 0] = - 5329 * i;
}
}
// IO functions
function writeBits(bs) {
var value = bs[0];
var posval = bs[1] - 1;
while (posval >= 0) {
if (value & (1 << posval)) {
bytenew |= (1 << bytepos);
}
posval--;
bytepos--;
if (bytepos < 0) {
if (bytenew == 0xFF) {
writeByte(0xFF);
writeByte(0);
}
else {
writeByte(bytenew);
}
bytepos = 7;
bytenew = 0;
}
}
}
function writeByte(value) {
//byteout.push(clt[value]); // write char directly instead of converting later
byteout.push(value);
}
function writeWord(value) {
writeByte((value >> 8) & 0xFF);
writeByte((value) & 0xFF);
}
// DCT & quantization core
function fDCTQuant(data, fdtbl) {
var d0, d1, d2, d3, d4, d5, d6, d7;
/* Pass 1: process rows. */
var dataOff = 0;
var i;
var I8 = 8;
var I64 = 64;
for (i = 0; i < I8; ++i) {
d0 = data[dataOff];
d1 = data[dataOff + 1];
d2 = data[dataOff + 2];
d3 = data[dataOff + 3];
d4 = data[dataOff + 4];
d5 = data[dataOff + 5];
d6 = data[dataOff + 6];
d7 = data[dataOff + 7];
var tmp0 = d0 + d7;
var tmp7 = d0 - d7;
var tmp1 = d1 + d6;
var tmp6 = d1 - d6;
var tmp2 = d2 + d5;
var tmp5 = d2 - d5;
var tmp3 = d3 + d4;
var tmp4 = d3 - d4;
/* Even part */
var tmp10 = tmp0 + tmp3; /* phase 2 */
var tmp13 = tmp0 - tmp3;
var tmp11 = tmp1 + tmp2;
var tmp12 = tmp1 - tmp2;
data[dataOff] = tmp10 + tmp11; /* phase 3 */
data[dataOff + 4] = tmp10 - tmp11;
var z1 = (tmp12 + tmp13) * 0.707106781; /* c4 */
data[dataOff + 2] = tmp13 + z1; /* phase 5 */
data[dataOff + 6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
var z5 = (tmp10 - tmp12) * 0.382683433; /* c6 */
var z2 = 0.541196100 * tmp10 + z5; /* c2-c6 */
var z4 = 1.306562965 * tmp12 + z5; /* c2+c6 */
var z3 = tmp11 * 0.707106781; /* c4 */
var z11 = tmp7 + z3; /* phase 5 */
var z13 = tmp7 - z3;
data[dataOff + 5] = z13 + z2; /* phase 6 */
data[dataOff + 3] = z13 - z2;
data[dataOff + 1] = z11 + z4;
data[dataOff + 7] = z11 - z4;
dataOff += 8; /* advance pointer to next row */
}
/* Pass 2: process columns. */
dataOff = 0;
for (i = 0; i < I8; ++i) {
d0 = data[dataOff];
d1 = data[dataOff + 8];
d2 = data[dataOff + 16];
d3 = data[dataOff + 24];
d4 = data[dataOff + 32];
d5 = data[dataOff + 40];
d6 = data[dataOff + 48];
d7 = data[dataOff + 56];
var tmp0p2 = d0 + d7;
var tmp7p2 = d0 - d7;
var tmp1p2 = d1 + d6;
var tmp6p2 = d1 - d6;
var tmp2p2 = d2 + d5;
var tmp5p2 = d2 - d5;
var tmp3p2 = d3 + d4;
var tmp4p2 = d3 - d4;
/* Even part */
var tmp10p2 = tmp0p2 + tmp3p2; /* phase 2 */
var tmp13p2 = tmp0p2 - tmp3p2;
var tmp11p2 = tmp1p2 + tmp2p2;
var tmp12p2 = tmp1p2 - tmp2p2;
data[dataOff] = tmp10p2 + tmp11p2; /* phase 3 */
data[dataOff + 32] = tmp10p2 - tmp11p2;
var z1p2 = (tmp12p2 + tmp13p2) * 0.707106781; /* c4 */
data[dataOff + 16] = tmp13p2 + z1p2; /* phase 5 */
data[dataOff + 48] = tmp13p2 - z1p2;
/* Odd part */
tmp10p2 = tmp4p2 + tmp5p2; /* phase 2 */
tmp11p2 = tmp5p2 + tmp6p2;
tmp12p2 = tmp6p2 + tmp7p2;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
var z5p2 = (tmp10p2 - tmp12p2) * 0.382683433; /* c6 */
var z2p2 = 0.541196100 * tmp10p2 + z5p2; /* c2-c6 */
var z4p2 = 1.306562965 * tmp12p2 + z5p2; /* c2+c6 */
var z3p2 = tmp11p2 * 0.707106781; /* c4 */
var z11p2 = tmp7p2 + z3p2; /* phase 5 */
var z13p2 = tmp7p2 - z3p2;
data[dataOff + 40] = z13p2 + z2p2; /* phase 6 */
data[dataOff + 24] = z13p2 - z2p2;
data[dataOff + 8] = z11p2 + z4p2;
data[dataOff + 56] = z11p2 - z4p2;
dataOff++; /* advance pointer to next column */
}
// Quantize/descale the coefficients
var fDCTQuant;
for (i = 0; i < I64; ++i) {
// Apply the quantization and scaling factor & Round to nearest integer
fDCTQuant = data[i] * fdtbl[i];
outputfDCTQuant[i] = (fDCTQuant > 0.0) ? ((fDCTQuant + 0.5) | 0) : ((fDCTQuant - 0.5) | 0);
//outputfDCTQuant[i] = fround(fDCTQuant);
}
return outputfDCTQuant;
}
function writeAPP0() {
writeWord(0xFFE0); // marker
writeWord(16); // length
writeByte(0x4A); // J
writeByte(0x46); // F
writeByte(0x49); // I
writeByte(0x46); // F
writeByte(0); // = "JFIF",'\0'
writeByte(1); // versionhi
writeByte(1); // versionlo
writeByte(0); // xyunits
writeWord(1); // xdensity
writeWord(1); // ydensity
writeByte(0); // thumbnwidth
writeByte(0); // thumbnheight
}
function writeAPP1(exifBuffer) {
if (!exifBuffer) return;
writeWord(0xFFE1); // APP1 marker
if (exifBuffer[0] === 0x45 &&
exifBuffer[1] === 0x78 &&
exifBuffer[2] === 0x69 &&
exifBuffer[3] === 0x66) {
// Buffer already starts with EXIF, just use it directly
writeWord(exifBuffer.length + 2); // length is buffer + length itself!
} else {
// Buffer doesn't start with EXIF, write it for them
writeWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\0 + length itself!
writeByte(0x45); // E
writeByte(0x78); // X
writeByte(0x69); // I
writeByte(0x66); // F
writeByte(0); // = "EXIF",'\0'
}
for (var i = 0; i < exifBuffer.length; i++) {
writeByte(exifBuffer[i]);
}
}
function writeSOF0(width, height) {
writeWord(0xFFC0); // marker
writeWord(17); // length, truecolor YUV JPG
writeByte(8); // precision
writeWord(height);
writeWord(width);
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0x11); // HVY
writeByte(0); // QTY
writeByte(2); // IdU
writeByte(0x11); // HVU
writeByte(1); // QTU
writeByte(3); // IdV
writeByte(0x11); // HVV
writeByte(1); // QTV
}
function writeDQT() {
writeWord(0xFFDB); // marker
writeWord(132); // length
writeByte(0);
for (var i = 0; i < 64; i++) {
writeByte(YTable[i]);
}
writeByte(1);
for (var j = 0; j < 64; j++) {
writeByte(UVTable[j]);
}
}
function writeDHT() {
writeWord(0xFFC4); // marker
writeWord(0x01A2); // length
writeByte(0); // HTYDCinfo
for (var i = 0; i < 16; i++) {
writeByte(std_dc_luminance_nrcodes[i + 1]);
}
for (var j = 0; j <= 11; j++) {
writeByte(std_dc_luminance_values[j]);
}
writeByte(0x10); // HTYACinfo
for (var k = 0; k < 16; k++) {
writeByte(std_ac_luminance_nrcodes[k + 1]);
}
for (var l = 0; l <= 161; l++) {
writeByte(std_ac_luminance_values[l]);
}
writeByte(1); // HTUDCinfo
for (var m = 0; m < 16; m++) {
writeByte(std_dc_chrominance_nrcodes[m + 1]);
}
for (var n = 0; n <= 11; n++) {
writeByte(std_dc_chrominance_values[n]);
}
writeByte(0x11); // HTUACinfo
for (var o = 0; o < 16; o++) {
writeByte(std_ac_chrominance_nrcodes[o + 1]);
}
for (var p = 0; p <= 161; p++) {
writeByte(std_ac_chrominance_values[p]);
}
}
function writeCOM(comments) {
if (typeof comments === "undefined" || comments.constructor !== Array) return;
comments.forEach(e => {
if (typeof e !== "string") return;
writeWord(0xFFFE); // marker
var l = e.length;
writeWord(l + 2); // length itself as well
var i;
for (i = 0; i < l; i++)
writeByte(e.charCodeAt(i));
});
}
function writeSOS() {
writeWord(0xFFDA); // marker
writeWord(12); // length
writeByte(3); // nrofcomponents
writeByte(1); // IdY
writeByte(0); // HTY
writeByte(2); // IdU
writeByte(0x11); // HTU
writeByte(3); // IdV
writeByte(0x11); // HTV
writeByte(0); // Ss
writeByte(0x3f); // Se
writeByte(0); // Bf
}
function processDU(CDU, fdtbl, DC, HTDC, HTAC) {
var EOB = HTAC[0x00];
var M16zeroes = HTAC[0xF0];
var pos;
var I16 = 16;
var I63 = 63;
var I64 = 64;
var DU_DCT = fDCTQuant(CDU, fdtbl);
//ZigZag reorder
for (var j = 0; j < I64; ++j) {
DU[ZigZag[j]] = DU_DCT[j];
}
var Diff = DU[0] - DC; DC = DU[0];
//Encode DC
if (Diff == 0) {
writeBits(HTDC[0]); // Diff might be 0
} else {
pos = 32767 + Diff;
writeBits(HTDC[category[pos]]);
writeBits(bitcode[pos]);
}
//Encode ACs
var end0pos = 63; // was const... which is crazy
for (; (end0pos > 0) && (DU[end0pos] == 0); end0pos--) { };
//end0pos = first element in reverse order !=0
if (end0pos == 0) {
writeBits(EOB);
return DC;
}
var i = 1;
var lng;
while (i <= end0pos) {
var startpos = i;
for (; (DU[i] == 0) && (i <= end0pos); ++i) { }
var nrzeroes = i - startpos;
if (nrzeroes >= I16) {
lng = nrzeroes >> 4;
for (var nrmarker = 1; nrmarker <= lng; ++nrmarker)
writeBits(M16zeroes);
nrzeroes = nrzeroes & 0xF;
}
pos = 32767 + DU[i];
writeBits(HTAC[(nrzeroes << 4) + category[pos]]);
writeBits(bitcode[pos]);
i++;
}
if (end0pos != I63) {
writeBits(EOB);
}
return DC;
}
function initCharLookupTable() {
var sfcc = String.fromCharCode;
for (var i = 0; i < 256; i++) { ///// ACHTUNG // 255
clt[i] = sfcc(i);
}
}
this.encode = function (image, quality) // image data object
{
var time_start = new Date().getTime();
if (quality) setQuality(quality);
// Initialize bit writer
byteout = new Array();
bytenew = 0;
bytepos = 7;
// Add JPEG headers
writeWord(0xFFD8); // SOI
writeAPP0();
writeCOM(image.comments);
writeAPP1(image.exifBuffer);
writeDQT();
writeSOF0(image.width, image.height);
writeDHT();
writeSOS();
// Encode 8x8 macroblocks
var DCY = 0;
var DCU = 0;
var DCV = 0;
bytenew = 0;
bytepos = 7;
this.encode.displayName = "_encode_";
var imageData = image.data;
var width = image.width;
var height = image.height;
var quadWidth = width * 4;
var tripleWidth = width * 3;
var x, y = 0;
var r, g, b;
var start, p, col, row, pos;
while (y < height) {
x = 0;
while (x < quadWidth) {
start = quadWidth * y + x;
p = start;
col = -1;
row = 0;
for (pos = 0; pos < 64; pos++) {
row = pos >> 3;// /8
col = (pos & 7) * 4; // %8
p = start + (row * quadWidth) + col;
if (y + row >= height) { // padding bottom
p -= (quadWidth * (y + 1 + row - height));
}
if (x + col >= quadWidth) { // padding right
p -= ((x + col) - quadWidth + 4)
}
r = imageData[p++];
g = imageData[p++];
b = imageData[p++];
/* // calculate YUV values dynamically
YDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80
UDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));
VDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));
*/
// use lookup table (slightly faster)
YDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256) >> 0] + RGB_YUV_TABLE[(b + 512) >> 0]) >> 16) - 128;
UDU[pos] = ((RGB_YUV_TABLE[(r + 768) >> 0] + RGB_YUV_TABLE[(g + 1024) >> 0] + RGB_YUV_TABLE[(b + 1280) >> 0]) >> 16) - 128;
VDU[pos] = ((RGB_YUV_TABLE[(r + 1280) >> 0] + RGB_YUV_TABLE[(g + 1536) >> 0] + RGB_YUV_TABLE[(b + 1792) >> 0]) >> 16) - 128;
}
DCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);
DCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);
DCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);
x += 32;
}
y += 8;
}
////////////////////////////////////////////////////////////////
// Do the bit alignment of the EOI marker
if (bytepos >= 0) {
var fillbits = [];
fillbits[1] = bytepos + 1;
fillbits[0] = (1 << (bytepos + 1)) - 1;
writeBits(fillbits);
}
writeWord(0xFFD9); //EOI
return new Uint8Array(byteout);
var jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));
byteout = [];
// benchmarking
var duration = new Date().getTime() - time_start;
//console.log('Encoding time: '+ duration + 'ms');
//
return jpegDataUri
}
function setQuality(quality) {
if (quality <= 0) {
quality = 1;
}
if (quality > 100) {
quality = 100;
}
if (currentQuality == quality) return // don't recalc if unchanged
var sf = 0;
if (quality < 50) {
sf = Math.floor(5000 / quality);
} else {
sf = Math.floor(200 - quality * 2);
}
initQuantTables(sf);
currentQuality = quality;
//console.log('Quality set to: '+quality +'%');
}
function init() {
var time_start = new Date().getTime();
if (!quality) quality = 50;
// Create tables
initCharLookupTable()
initHuffmanTbl();
initCategoryNumber();
initRGBYUVTable();
setQuality(quality);
var duration = new Date().getTime() - time_start;
//console.log('Initialization '+ duration + 'ms');
}
init();
};
export function encodeJPG(imgData, qu) {
if (typeof qu === 'undefined') qu = 50;
var encoder = new JPEGEncoder(qu);
var data = encoder.encode(imgData, qu);
return {
data: data,
width: imgData.width,
height: imgData.height,
};
}
// helper function to get the imageData of an existing image on the current page.
function getImageDataFromImage(idOrElement) {
var theImg = (typeof (idOrElement) == 'string') ? document.getElementById(idOrElement) : idOrElement;
var cvs = document.createElement('canvas');
cvs.width = theImg.width;
cvs.height = theImg.height;
var ctx = cvs.getContext("2d");
ctx.drawImage(theImg, 0, 0);
return (ctx.getImageData(0, 0, cvs.width, cvs.height));
}
//https://github.com/jpeg-js/jpeg-js/blob/master/lib/encoder.js | the_stack |
export interface SourceConfig {
/**
* The name you wish to set to your remote API, this will be used for building the GraphQL context
*/
name: string;
handler: Handler;
/**
* List of transforms to apply to the current API source, before unifying it with the rest of the sources
*/
transforms?: Transform[];
[k: string]: unknown;
}
/**
* Point to the handler you wish to use, it can either be a predefined handler, or a custom
*/
export interface Handler {
fhir?: FhirHandler;
graphql?: GraphQLHandler;
grpc?: GrpcHandler;
jsonSchema?: JsonSchemaHandler;
mongoose?: MongooseHandler;
mysql?: MySQLHandler;
neo4j?: Neo4JHandler;
odata?: ODataHandler;
openapi?: OpenapiHandler;
postgraphile?: PostGraphileHandler;
soap?: SoapHandler;
thrift?: ThriftHandler;
tuql?: TuqlHandler;
ContentfulHandler?: ContentfulHandler;
SlackHandler?: SlackHandler;
StripeHandler?: StripeHandler;
WeatherbitHandler?: WeatherbitHandler;
CrunchbaseHandler?: CrunchbaseHandler;
SalesforceHandler?: SalesforceHandler;
TwitterHandler?: TwitterHandler;
IPAPIHandler?: IPAPIHandler;
FusionCreatorAccountInformationUSHandler?: FusionCreatorAccountInformationUSHandler;
FusionCreatorAccountInformationPSD2STETHandler?: FusionCreatorAccountInformationPSD2STETHandler;
[k: string]: unknown;
}
export interface FhirHandler {
/**
* Ignore self-signed certificate error
*/
rejectUnauthorized?: boolean;
endpoint?: string;
}
/**
* Handler for remote/local/third-party GraphQL schema
*/
export interface GraphQLHandler {
/**
* A url or file path to your remote GraphQL endpoint.
* If you provide a path to a code file(js or ts),
* other options will be ignored and the schema exported from the file will be used directly.
*/
endpoint: string;
/**
* Ignore self-signed certificate error
*/
rejectUnauthorized?: boolean;
/**
* JSON object representing the Headers to add to the runtime of the API calls only for schema introspection
* You can also provide `.js` or `.ts` file path that exports schemaHeaders as an object
*/
schemaHeaders?:
| {
[k: string]: unknown;
}
| string
| unknown[];
/**
* JSON object representing the Headers to add to the runtime of the API calls only for operation during runtime
*/
operationHeaders?: {
[k: string]: unknown;
};
/**
* Use HTTP GET for Query operations
*/
useGETForQueries?: boolean;
/**
* HTTP method used for GraphQL operations (Allowed values: GET, POST)
*/
method?: 'GET' | 'POST';
/**
* Use Server Sent Events instead of WebSocket for Subscriptions
*/
useSSEForSubscription?: boolean;
/**
* Path to a custom W3 Compatible Fetch Implementation
*/
customFetch?:
| {
[k: string]: unknown;
}
| string
| unknown[];
/**
* Path to a custom W3 Compatible WebSocket Implementation
*/
webSocketImpl?: string;
/**
* Use legacy web socket protocol `graphql-ws` instead of the more current standard `graphql-transport-ws`
*/
useWebSocketLegacyProtocol?: boolean;
/**
* Path to the introspection
* You can seperately give schema introspection
*/
introspection?: string;
/**
* Enable multipart/formdata in order to support file uploads
*/
multipart?: boolean;
/**
* Batch requests
*/
batch?: boolean;
}
/**
* Handler for gRPC and Protobuf schemas
*/
export interface GrpcHandler {
/**
* gRPC Endpoint
*/
endpoint: string;
/**
* gRPC Proto file that contains your protobuf schema (Any of: ProtoFilePath, String)
*/
protoFilePath?: ProtoFilePath | string;
/**
* Use a binary-encoded or JSON file descriptor set file (Any of: ProtoFilePath, String)
*/
descriptorSetFilePath?: ProtoFilePath | string;
/**
* Your base service name
* Used for naming only
*/
serviceName?: string;
/**
* Your base package name
* Used for naming only
*/
packageName?: string;
/**
* Request timeout in milliseconds
* Default: 200000
*/
requestTimeout?: number;
credentialsSsl?: GrpcCredentialsSsl;
/**
* Use https instead of http for gRPC connection
*/
useHTTPS?: boolean;
/**
* MetaData
*/
metaData?: {
[k: string]: unknown;
};
/**
* Use gRPC reflection to automatically gather the connection
*/
useReflection?: boolean;
}
export interface ProtoFilePath {
file: string;
load?: LoadOptions;
}
export interface LoadOptions {
defaults?: boolean;
includeDirs?: string[];
}
/**
* SSL Credentials
*/
export interface GrpcCredentialsSsl {
rootCA?: string;
certChain?: string;
privateKey?: string;
}
/**
* Handler for JSON Schema specification. Source could be a local json file, or a url to it.
*/
export interface JsonSchemaHandler {
baseUrl?: string;
operationHeaders?: {
[k: string]: unknown;
};
schemaHeaders?: {
[k: string]: unknown;
};
/**
* Ignore self-signed certificate error
*/
rejectUnauthorized?: boolean;
operations: JsonSchemaOperation[];
disableTimestampScalar?: boolean;
baseSchema?:
| {
[k: string]: unknown;
}
| string
| unknown[];
/**
* Field name of your custom error object (default: 'message')
*/
errorMessageField?: string;
}
export interface JsonSchemaOperation {
field: string;
path?: string;
pubsubTopic?: string;
description?: string;
/**
* Allowed values: Query, Mutation, Subscription
*/
type: 'Query' | 'Mutation' | 'Subscription';
/**
* Allowed values: GET, DELETE, POST, PUT, PATCH
*/
method?: 'GET' | 'DELETE' | 'POST' | 'PUT' | 'PATCH';
requestSchema?:
| {
[k: string]: unknown;
}
| string
| unknown[];
requestSample?:
| {
[k: string]: unknown;
}
| string
| unknown[];
requestTypeName?: string;
responseSample?:
| {
[k: string]: unknown;
}
| string
| unknown[];
responseSchema?:
| {
[k: string]: unknown;
}
| string
| unknown[];
responseTypeName?: string;
argTypeMap?: {
[k: string]: unknown;
};
headers?: {
[k: string]: unknown;
};
}
export interface MongooseHandler {
connectionString?: string;
models?: MongooseModel[];
discriminators?: MongooseModel[];
}
export interface MongooseModel {
name: string;
path: string;
options?: ComposeWithMongooseOpts;
}
export interface ComposeWithMongooseOpts {
name?: string;
description?: string;
fields?: ComposeWithMongooseFieldsOpts;
inputType?: ComposeMongooseInputType;
resolvers?: TypeConverterResolversOpts;
}
export interface ComposeWithMongooseFieldsOpts {
only?: string[];
remove?: string[];
required?: string[];
}
export interface ComposeMongooseInputType {
name?: string;
description?: string;
fields?: ComposeWithMongooseFieldsOpts;
resolvers?: TypeConverterResolversOpts;
}
export interface TypeConverterResolversOpts {
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
findById?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
findByIds?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
findOne?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
findMany?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
updateById?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
updateOne?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
updateMany?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
removeById?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
removeOne?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
removeMany?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
createOne?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
createMany?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, ComposeWithMongooseResolverOpts
*/
count?: boolean | ComposeWithMongooseResolverOpts;
/**
* Any of: Boolean, JSON
*/
connection?:
| boolean
| {
[k: string]: unknown;
};
/**
* Any of: Boolean, PaginationResolverOpts
*/
pagination?: boolean | PaginationResolverOpts;
}
export interface ComposeWithMongooseResolverOpts {
filter?: FilterHelperArgsOpts;
sort?: SortHelperArgsOpts;
limit?: LimitHelperArgsOpts;
record?: RecordHelperArgsOpts;
skip?: boolean;
}
export interface FilterHelperArgsOpts {
filterTypeName?: string;
isRequired?: boolean;
onlyIndexed?: boolean;
requiredFields?: string[];
/**
* Any of: Boolean, JSON
*/
operators?:
| boolean
| {
[k: string]: unknown;
};
removeFields?: string[];
}
export interface SortHelperArgsOpts {
sortTypeName?: string;
}
export interface LimitHelperArgsOpts {
defaultValue?: number;
}
export interface RecordHelperArgsOpts {
recordTypeName?: string;
isRequired?: boolean;
removeFields?: string[];
requiredFields?: string[];
}
export interface PaginationResolverOpts {
perPage?: number;
}
export interface MySQLHandler {
host?: string;
port?: number;
user?: string;
password?: string;
database?: string;
/**
* Use existing `Pool` instance
* Format: modulePath#exportName
*/
pool?:
| {
[k: string]: unknown;
}
| string
| unknown[];
}
/**
* Handler for Neo4j
*/
export interface Neo4JHandler {
/**
* URL for the Neo4j Instance e.g. neo4j://localhost
*/
url: string;
/**
* Username for basic authentication
*/
username: string;
/**
* Password for basic authentication
*/
password: string;
/**
* Specifies whether relationships should always be included in the type definitions as [relationship](https://grandstack.io/docs/neo4j-graphql-js.html#relationship-types) types, even if the relationships do not have properties.
*/
alwaysIncludeRelationships?: boolean;
/**
* Specifies database name
*/
database?: string;
/**
* Provide GraphQL Type Definitions instead of inferring
*/
typeDefs?: string;
}
/**
* Handler for OData
*/
export interface ODataHandler {
/**
* Base URL for OData API
*/
baseUrl: string;
/**
* Custom $metadata File or URL
*/
metadata?: string;
/**
* Ignore self-signed certificate error
*/
rejectUnauthorized?: boolean;
/**
* Headers to be used with the operation requests
*/
operationHeaders?: {
[k: string]: unknown;
};
/**
* Headers to be used with the $metadata requests
*/
schemaHeaders?: {
[k: string]: unknown;
};
/**
* Enable batching (Allowed values: multipart, json)
*/
batch?: 'multipart' | 'json';
/**
* Use $expand for navigation props instead of seperate HTTP requests (Default: false)
*/
expandNavProps?: boolean;
/**
* Custom Fetch
*/
customFetch?:
| {
[k: string]: unknown;
}
| string
| unknown[];
}
/**
* Handler for Swagger / OpenAPI 2/3 specification. Source could be a local json/swagger file, or a url to it.
*/
export interface OpenapiHandler {
/**
* Ignore self-signed certificate error
*/
rejectUnauthorized?: boolean;
/**
* A pointer to your API source - could be a local file, remote file or url endpoint
*/
source:
| {
[k: string]: unknown;
}
| string
| unknown[];
/**
* Format of the source file (Allowed values: json, yaml)
*/
sourceFormat?: 'json' | 'yaml';
/**
* JSON object representing the Headers to add to the runtime of the API calls
*/
operationHeaders?: {
[k: string]: unknown;
};
/**
* If you are using a remote URL endpoint to fetch your schema, you can set headers for the HTTP request to fetch your schema.
*/
schemaHeaders?: {
[k: string]: unknown;
};
/**
* Specifies the URL on which all paths will be based on.
* Overrides the server object in the OAS.
*/
baseUrl?: string;
/**
* JSON object representing the query search parameters to add to the API calls
*/
qs?: {
[k: string]: unknown;
};
/**
* W3 Compatible Fetch Implementation
*/
customFetch?:
| {
[k: string]: unknown;
}
| string
| unknown[];
/**
* Include HTTP Response details to the result object
*/
includeHttpDetails?: boolean;
/**
* Auto-generate a 'limit' argument for all fields that return lists of objects, including ones produced by links
*/
addLimitArgument?: boolean;
/**
* Set argument name for mutation payload to 'requestBody'. If false, name defaults to camelCased pathname
*/
genericPayloadArgName?: boolean;
/**
* Allows to explicitly override the default operation (Query or Mutation) for any OAS operation
*/
selectQueryOrMutationField?: SelectQueryOrMutationFieldConfig[];
}
export interface SelectQueryOrMutationFieldConfig {
/**
* OAS Title
*/
title?: string;
/**
* Operation Path
*/
path?: string;
/**
* Target Root Type for this operation (Allowed values: Query, Mutation)
*/
type?: 'Query' | 'Mutation';
/**
* Which method is used for this operation
*/
method?: string;
}
/**
* Handler for Postgres database, based on `postgraphile`
*/
export interface PostGraphileHandler {
/**
* A connection string to your Postgres database
*/
connectionString?: string;
/**
* An array of strings which specifies the PostgreSQL schemas that PostGraphile will use to create a GraphQL schema. The default schema is the public schema.
*/
schemaName?: string[];
/**
* Connection Pool instance or settings or you can provide the path of a code file that exports any of those
*/
pool?:
| {
[k: string]: unknown;
}
| string
| unknown[];
/**
* Extra Postgraphile Plugins to append
*/
appendPlugins?: string[];
/**
* Postgraphile Plugins to skip (e.g. "graphile-build#NodePlugin")
*/
skipPlugins?: string[];
/**
* Extra Postgraphile options that will be added to the postgraphile constructor. It can either be an object or a string pointing to the object's path (e.g. "./my-config#options"). See the [postgraphile docs](https://www.graphile.org/postgraphile/usage-library/) for more information. (Any of: JSON, String)
*/
options?:
| {
[k: string]: unknown;
}
| string;
/**
* Enable GraphQL websocket transport support for subscriptions (default: true)
*/
subscriptions?: boolean;
/**
* Enables live-query support via GraphQL subscriptions (sends updated payload any time nested collections/records change) (default: true)
*/
live?: boolean;
}
/**
* Handler for SOAP
*/
export interface SoapHandler {
/**
* A url to your WSDL
*/
wsdl: string;
basicAuth?: SoapSecurityBasicAuthConfig;
securityCert?: SoapSecurityCertificateConfig;
/**
* Ignore self-signed certificate error
*/
rejectUnauthorized?: boolean;
/**
* JSON object representing the Headers to add to the runtime of the API calls only for schema introspection
* You can also provide `.js` or `.ts` file path that exports schemaHeaders as an object
*/
schemaHeaders?:
| {
[k: string]: unknown;
}
| string
| unknown[];
/**
* JSON object representing the Headers to add to the runtime of the API calls only for operation during runtime
*/
operationHeaders?: {
[k: string]: unknown;
};
}
/**
* Basic Authentication Configuration
* Including username and password fields
*/
export interface SoapSecurityBasicAuthConfig {
/**
* Username for Basic Authentication
*/
username: string;
/**
* Password for Basic Authentication
*/
password: string;
}
/**
* SSL Certificate Based Authentication Configuration
* Including public key, private key and password fields
*/
export interface SoapSecurityCertificateConfig {
/**
* Your public key
*/
publicKey?: string;
/**
* Your private key
*/
privateKey?: string;
/**
* Password
*/
password?: string;
/**
* Path to the file or URL contains your public key
*/
publicKeyPath?: string;
/**
* Path to the file or URL contains your private key
*/
privateKeyPath?: string;
/**
* Path to the file or URL contains your password
*/
passwordPath?: string;
}
/**
* Handler for OData
*/
export interface ThriftHandler {
/**
* The name of the host to connect to.
*/
hostName: string;
/**
* The port number to attach to on the host.
*/
port: number;
/**
* The path on which the Thrift service is listening. Defaults to '/thrift'.
*/
path?: string;
/**
* Boolean value indicating whether to use https. Defaults to false.
*/
https?: boolean;
/**
* Name of the Thrift protocol type to use. Defaults to 'binary'. (Allowed values: binary, compact, json)
*/
protocol?: 'binary' | 'compact' | 'json';
/**
* The name of your service. Used for logging.
*/
serviceName: string;
/**
* JSON object representing the Headers to add to the runtime of the API calls
*/
operationHeaders?: {
[k: string]: unknown;
};
/**
* If you are using a remote URL endpoint to fetch your schema, you can set headers for the HTTP request to fetch your schema.
*/
schemaHeaders?: {
[k: string]: unknown;
};
/**
* Path to IDL file
*/
idl: string;
}
/**
* Handler for SQLite database, based on `tuql`
*/
export interface TuqlHandler {
/**
* Pointer to your SQLite database
*/
db?: string;
/**
* Path to the SQL Dump file if you want to build a in-memory database
*/
infile?: string;
}
/**
* API-first content platform to build digital experiences
*/
export interface ContentfulHandler {
/**
* Authentication token
*/
token: string;
/**
* (Deprecated) Full endpoint including space ID and environment. More info: https://www.contentful.com/developers/docs/references/graphql/#/introduction/basic-api-information
*/
endpoint?: string;
/**
* Your space ID. Wonder how to find it? Check https://www.contentful.com/help/find-space-id/
*/
space?: string;
/**
* Your environment ID. What is it? Check https://www.contentful.com/faq/environments/
*/
environment?: string;
}
/**
* A proprietary business communication platform
*/
export interface SlackHandler {
/**
* Slack API access token
*/
token: string;
}
/**
* Online payment processing for internet businesses
*/
export interface StripeHandler {
/**
* Stripe secret key
*/
token: string;
}
/**
* Weather API to instantly access real-time and historical data
*/
export interface WeatherbitHandler {
/**
* Weatherbit secret key
*/
token: string;
}
/**
* A platform for finding business information about private and public companies
*/
export interface CrunchbaseHandler {
/**
* Authentication API Key
*/
userKey: string;
}
/**
* An American cloud-based software company that provides customer relationship management service.
*/
export interface SalesforceHandler {
/**
* An endpoint of your Salesforce API
*/
baseUrl: string;
/**
* Authentication token
*/
token?: string;
}
/**
* An American microblogging and social networking service on which users post and interact with messages known as 'tweets'
*/
export interface TwitterHandler {
/**
* Your bearer token (wihout 'Bearer ' substring)
*/
token: string;
}
/**
* IP Geolocation API
*/
export interface IPAPIHandler {
/**
* A pointer to IP API source
*/
source?: string;
/**
* Specifies the URL on which all paths will be based on.
* Overrides the server object in the OAS.
*/
baseUrl?: string;
}
/**
* Provides methods for interacting with data on the core banking system and third party vendors.
*/
export interface FusionCreatorAccountInformationUSHandler {
/**
* Authorization header to forward
*/
authorizationHeader: string;
}
/**
* Retrieve set of account list, balances and account history e.g. for external aggregation purposes based on consent given by the customer. (PSD2 AISP scenario - STET standard)
*/
export interface FusionCreatorAccountInformationPSD2STETHandler {
/**
* Authorization header to forward
*/
authorizationHeader: string;
}
export interface Transform {
/**
* Transformer to apply caching for your data sources
*/
cache?: CacheTransformConfig[];
encapsulate?: EncapsulateTransformObject;
extend?: ExtendTransform;
federation?: FederationTransform;
/**
* Transformer to filter (white/black list) GraphQL types, fields and arguments (Any of: FilterSchemaTransform, Any)
*/
filterSchema?:
| FilterSchemaTransform
| (
| {
[k: string]: unknown;
}
| string
| unknown[]
);
mock?: MockingConfig;
namingConvention?: NamingConventionTransformConfig;
prefix?: PrefixTransformConfig;
/**
* Transformer to rename GraphQL types and fields (Any of: RenameTransform, Any)
*/
rename?:
| RenameTransform
| (
| {
[k: string]: unknown;
}
| string
| unknown[]
);
/**
* Transformer to apply composition to resolvers (Any of: ResolversCompositionTransform, Any)
*/
resolversComposition?:
| ResolversCompositionTransform
| (
| {
[k: string]: unknown;
}
| string
| unknown[]
);
snapshot?: SnapshotTransformConfig;
[k: string]: unknown;
}
export interface CacheTransformConfig {
/**
* The type and field to apply cache to, you can use wild cards as well, for example: `Query.*`
*/
field: string;
/**
* Cache key to use to store your resolvers responses.
* The defualt is: {typeName}-{fieldName}-{argsHash}-{fieldNamesHash}
*
* Available variables:
* - {args.argName} - use resolver argument
* - {typeName} - use name of the type
* - {fieldName} - use name of the field
* - {argsHash} - a hash based on the 'args' object
* - {fieldNamesHash} - a hash based on the field names selected by the client
* - {info} - the GraphQLResolveInfo of the resolver
*
* Available interpolations:
* - {format|date} - returns the current date with a specific format
*/
cacheKey?: string;
invalidate?: CacheInvalidateConfig;
}
/**
* Invalidation rules
*/
export interface CacheInvalidateConfig {
/**
* Invalidate the cache when a specific operation is done without an error
*/
effectingOperations?: CacheEffectingOperationConfig[];
/**
* Specified in seconds, the time-to-live (TTL) value limits the lifespan
*/
ttl?: number;
}
export interface CacheEffectingOperationConfig {
/**
* Path to the operation that could effect it. In a form: Mutation.something. Note that wildcard is not supported in this field.
*/
operation: string;
/**
* Cache key to invalidate on sucessful resolver (no error), see `cacheKey` for list of available options in this field.
*/
matchKey?: string;
}
/**
* Transformer to apply encapsulation to the API source, by creating a field for it under the root query
*/
export interface EncapsulateTransformObject {
/**
* Optional, name to use for grouping under the root types. If not specific, the API name is used.
*/
name?: string;
applyTo?: EncapsulateTransformApplyTo;
}
/**
* Allow you to choose which root operations you would like to apply. By default, it's applied to all root types.
*/
export interface EncapsulateTransformApplyTo {
query?: boolean;
mutation?: boolean;
subscription?: boolean;
}
export interface ExtendTransform {
typeDefs?:
| {
[k: string]: unknown;
}
| string
| unknown[];
resolvers?:
| {
[k: string]: unknown;
}
| string
| unknown[];
}
export interface FederationTransform {
types?: FederationTransformType[];
}
export interface FederationTransformType {
name: string;
config?: FederationObjectConfig;
}
export interface FederationObjectConfig {
keyFields?: string[];
extend?: boolean;
fields?: FederationField[];
/**
* Any of: String, ResolveReferenceObject
*/
resolveReference?: string | ResolveReferenceObject;
}
export interface FederationField {
name: string;
config: FederationFieldConfig;
}
export interface FederationFieldConfig {
external?: boolean;
provides?: string;
required?: string;
}
export interface ResolveReferenceObject {
targetSource: string;
targetMethod: string;
args: {
[k: string]: unknown;
};
returnData?: string;
resultSelectedFields?: {
[k: string]: unknown;
};
resultSelectionSet?: string;
resultDepth?: number;
}
export interface FilterSchemaTransform {
/**
* Specify to apply filter-schema transforms to bare schema or by wrapping original schema (Allowed values: bare, wrap)
*/
mode?: 'bare' | 'wrap';
/**
* Array of filter rules
*/
filters: string[];
}
/**
* Mock configuration for your source
*/
export interface MockingConfig {
/**
* If this expression is truthy, mocking would be enabled
* You can use environment variables expression, for example: `${MOCKING_ENABLED}`
*/
if?: boolean;
/**
* Do not mock any other resolvers other than defined in `mocks`.
* For example, you can enable this if you don't want to mock entire schema but partially.
*/
preserveResolvers?: boolean;
/**
* Mock configurations
*/
mocks?: MockingFieldConfig[];
/**
* The path to the code runs before the store is attached to the schema
*/
initializeStore?:
| {
[k: string]: unknown;
}
| string
| unknown[];
}
export interface MockingFieldConfig {
/**
* Resolver path
* Example: User.firstName
*/
apply: string;
/**
* If this expression is truthy, mocking would be enabled
* You can use environment variables expression, for example: `${MOCKING_ENABLED}`
*/
if?: boolean;
/**
* Faker.js expression or function
* Read more (https://github.com/marak/Faker.js/#fakerfake)
* Example;
* faker: name.firstName
* faker: "{{ name.firstName }} {{ name.lastName }}"
*/
faker?: string;
/**
* Custom mocking
* It can be a module or json file.
* Both "moduleName#exportName" or only "moduleName" would work
*/
custom?: string;
/**
* Length of the mock list
* For the list types `[ObjectType]`, how many `ObjectType` you want to return?
* default: 2
*/
length?: number;
store?: GetFromMockStoreConfig;
/**
* Update the data on the mock store
*/
updateStore?: UpdateMockStoreConfig[];
}
/**
* Get the data from the mock store
*/
export interface GetFromMockStoreConfig {
type?: string;
key?: string;
fieldName?: string;
}
export interface UpdateMockStoreConfig {
type?: string;
key?: string;
fieldName?: string;
value?: string;
}
/**
* Transformer to apply naming convention to GraphQL Types
*/
export interface NamingConventionTransformConfig {
/**
* Allowed values: camelCase, capitalCase, constantCase, dotCase, headerCase, noCase, paramCase, pascalCase, pathCase, sentenceCase, snakeCase, upperCase, lowerCase
*/
typeNames?:
| 'camelCase'
| 'capitalCase'
| 'constantCase'
| 'dotCase'
| 'headerCase'
| 'noCase'
| 'paramCase'
| 'pascalCase'
| 'pathCase'
| 'sentenceCase'
| 'snakeCase'
| 'upperCase'
| 'lowerCase';
/**
* Allowed values: camelCase, capitalCase, constantCase, dotCase, headerCase, noCase, paramCase, pascalCase, pathCase, sentenceCase, snakeCase, upperCase, lowerCase
*/
fieldNames?:
| 'camelCase'
| 'capitalCase'
| 'constantCase'
| 'dotCase'
| 'headerCase'
| 'noCase'
| 'paramCase'
| 'pascalCase'
| 'pathCase'
| 'sentenceCase'
| 'snakeCase'
| 'upperCase'
| 'lowerCase';
/**
* Allowed values: camelCase, capitalCase, constantCase, dotCase, headerCase, noCase, paramCase, pascalCase, pathCase, sentenceCase, snakeCase, upperCase, lowerCase
*/
enumValues?:
| 'camelCase'
| 'capitalCase'
| 'constantCase'
| 'dotCase'
| 'headerCase'
| 'noCase'
| 'paramCase'
| 'pascalCase'
| 'pathCase'
| 'sentenceCase'
| 'snakeCase'
| 'upperCase'
| 'lowerCase';
}
/**
* Prefix transform
*/
export interface PrefixTransformConfig {
/**
* The prefix to apply to the schema types. By default it's the API name.
*/
value?: string;
/**
* List of ignored types
*/
ignore?: string[];
/**
* Changes root types and changes the field names
*/
includeRootOperations?: boolean;
}
export interface RenameTransform {
/**
* Specify to apply rename transforms to bare schema or by wrapping original schema (Allowed values: bare, wrap)
*/
mode?: 'bare' | 'wrap';
/**
* Array of rename rules
*/
renames: RenameTransformObject[];
}
export interface RenameTransformObject {
from: RenameConfig;
to: RenameConfig;
/**
* Use Regular Expression for type names
*/
useRegExpForTypes?: boolean;
/**
* Use Regular Expression for field names
*/
useRegExpForFields?: boolean;
}
export interface RenameConfig {
type?: string;
field?: string;
}
export interface ResolversCompositionTransform {
/**
* Specify to apply resolvers-composition transforms to bare schema or by wrapping original schema (Allowed values: bare, wrap)
*/
mode?: 'bare' | 'wrap';
/**
* Array of resolver/composer to apply
*/
compositions: ResolversCompositionTransformObject[];
}
export interface ResolversCompositionTransformObject {
/**
* The GraphQL Resolver path
* Example: Query.users
*/
resolver: string;
/**
* Path to the composer function
* Example: ./src/auth.js#authComposer
*/
composer:
| {
[k: string]: unknown;
}
| string
| unknown[];
}
/**
* Configuration for Snapshot extension
*/
export interface SnapshotTransformConfig {
/**
* Expression for when to activate this extension.
* Value can be a valid JS expression string or a boolean (Any of: String, Boolean)
*/
if?: string | boolean;
/**
* Resolver to be applied
* For example;
* apply:
* - Query.* <- * will apply this extension to all fields of Query type
* - Mutation.someMutationButProbablyYouWontNeedIt
*/
apply: string[];
/**
* Path to the directory of the generated snapshot files
*/
outputDir: string;
/**
* Take snapshots by respecting the requested selection set.
* This might be needed for the handlers like Postgraphile or OData that rely on the incoming GraphQL operation.
*/
respectSelectionSet?: boolean;
} | the_stack |
import OffsetSource from "@atjson/offset-annotations";
import * as fs from "fs";
import * as path from "path";
import GDocsSource from "../src";
describe("@atjson/source-gdocs-paste", () => {
let atjson: OffsetSource;
beforeAll(() => {
// https://docs.google.com/document/d/18pp4dAGx5II596HHGOLUXXcc6VKLAVRBUMLm9Ge8eOE/edit?usp=sharing
let fixturePath = path.join(__dirname, "fixtures", "complex.json");
let rawJSON = JSON.parse(fs.readFileSync(fixturePath).toString());
let gdocs = GDocsSource.fromRaw(rawJSON);
atjson = gdocs.convertTo(OffsetSource);
});
it("correctly converts -gdocs-ts_bd to bold", () => {
let bolds = atjson.where((a) => a.type === "bold");
expect(bolds.length).toEqual(2);
});
it("correctly converts italic", () => {
let italics = atjson.where((a) => a.type === "italic");
expect(italics.length).toEqual(2);
});
it("correctly converts headings, removing Titles and Subtitles", () => {
let headings = atjson.where((a) => a.type === "heading");
expect(headings.length).toEqual(2);
expect(headings.map((h) => h.attributes.level)).toEqual([1, 2]);
});
it("correctly converts lists", () => {
let lists = atjson.where((a) => a.type === "list");
expect(lists.length).toEqual(2);
});
it("adds parse tokens around newlines separating list-items", () => {
let lists = atjson.where((a) => a.type === "list").as("list");
let allParseTokens = atjson
.where((a) => a.type === "parse-token")
.as("parseTokens");
lists
.outerJoin(allParseTokens, (l, r) => l.start <= r.start && l.end >= r.end)
.forEach(({ list, parseTokens }) => {
let newlines = atjson.match(/\n/g, list.start, list.end);
expect(newlines.map((match) => [match.start, match.end])).toEqual(
parseTokens.map((a) => [a.start, a.end])
);
});
});
it("correctly converts numbered lists", () => {
let lists = atjson.where(
(a) => a.type === "list" && a.attributes.type === "numbered"
);
expect(lists.length).toEqual(1);
});
it("correctly converts bulleted lists", () => {
let lists = atjson.where(
(a) => a.type === "list" && a.attributes.type === "bulleted"
);
expect(lists.length).toEqual(1);
});
it("correctly converts list-items", () => {
let listItems = atjson.where((a) => a.type === "list-item");
expect(listItems.length).toEqual(4);
});
it("correctly converts links", () => {
let links = atjson.where((a) => a.type === "link");
expect(links.length).toEqual(1);
expect(links.map((link) => link.attributes.url)).toEqual([
"https://www.google.com/",
]);
});
it("removes underlined text aligned exactly with links", () => {
// https://docs.google.com/document/d/18pp4dAGx5II596HHGOLUXXcc6VKLAVRBUMLm9Ge8eOE/edit?usp=sharing
let fixturePath = path.join(__dirname, "fixtures", "underline.json");
let rawJSON = JSON.parse(fs.readFileSync(fixturePath).toString());
let gdocs = GDocsSource.fromRaw(rawJSON);
let doc = gdocs.convertTo(OffsetSource);
let links = doc.where({ type: "-offset-link" }).as("links");
let underlines = doc.where({ type: "-offset-underline" }).as("underline");
expect(links.join(underlines, (a, b) => a.isAlignedWith(b)).length).toBe(0);
});
});
describe("@atjson/source-gdocs-paste paragraphs", () => {
let atjson: OffsetSource;
const LINEBREAKS = [
[21, 22],
[249, 250],
[284, 285],
[285, 286],
[370, 371],
[446, 447],
[447, 448],
].map(([start, end]) => {
return {
start,
end,
type: "-offset-line-break",
attributes: {},
id: expect.anything(),
};
});
const PARAGRAPHS = [
[0, 70],
[71, 117],
[119, 163],
[166, 213],
[487, 520],
].map(([start, end]) => {
return {
start,
end,
type: "-offset-paragraph",
attributes: {},
id: expect.anything(),
};
});
const LISTS = [
[214, 486],
[521, 538],
].map(([start, end]) => {
return {
start,
end,
type: "-offset-list",
attributes: { "-offset-type": "numbered" },
id: expect.anything(),
};
});
const LIST_ITEMS = [
[214, 324],
[325, 405],
[406, 486],
[521, 537],
].map(([start, end]) => {
return {
start,
end,
type: "-offset-list-item",
attributes: {},
id: expect.anything(),
};
});
beforeAll(() => {
// https://docs.google.com/document/d/1PzhE6OJqRIHrDZcXBjw7UsjUhH_ITPP7tgg2s9fhPf4/edit
let fixturePath = path.join(__dirname, "fixtures", "paragraphs.json");
let rawJSON = JSON.parse(fs.readFileSync(fixturePath).toString());
let gdocs = GDocsSource.fromRaw(rawJSON);
atjson = gdocs.convertTo(OffsetSource);
});
it("converts vertical tabs to line breaks", () => {
// eslint-disable-next-line no-control-regex
let verticalTabs = atjson.match(/\u000b/g);
expect(
verticalTabs.map(({ start, end }) => ({ start, end }))
).toMatchObject(LINEBREAKS.map(({ start, end }) => ({ start, end })));
expect(atjson.where({ type: "-offset-line-break" }).toJSON()).toMatchObject(
LINEBREAKS
);
});
it("created paragraphs", () => {
let paragraphs = atjson.where({ type: "-offset-paragraph" });
expect(paragraphs.toJSON()).toMatchObject(PARAGRAPHS);
});
it("created four paragraphs before the list", () => {
let listsAndParagraphs = atjson
.where({ type: "-offset-list" })
.as("list")
.join(
atjson.where({ type: "-offset-paragraph" }).as("paragraphs"),
(l, r) => r.end <= l.start
);
expect(listsAndParagraphs.toJSON()[0]).toMatchObject({
list: LISTS[0],
paragraphs: PARAGRAPHS.slice(0, 4),
});
});
it("created first paragraph with one nested linebreak", () => {
let firstParagraph = atjson
.where({ type: "-offset-paragraph" })
.as("paragraph")
.join(
atjson.where({ type: "-offset-line-break" }).as("linebreaks"),
(l, r) => r.start > l.start && r.end < l.end
)
.toJSON()[0];
expect(firstParagraph).toEqual({
paragraph: PARAGRAPHS[0],
linebreaks: LINEBREAKS.slice(0, 1),
});
});
it("created linebreaks inside list-items", () => {
let linebreaksInLists = atjson
.where({ type: "-offset-line-break" })
.as("linebreak")
.join(
atjson.where({ type: "-offset-list" }).as("lists"),
(l, r) => l.start >= r.start && l.end <= r.end
)
.outerJoin(
atjson.where({ type: "-offset-list-item" }).as("list-items"),
(l, r) => l.linebreak.start >= r.start && l.linebreak.end <= r.end
);
// No linebreaks in a list outside of a list-item
expect(
linebreaksInLists
.where(
(join) => join.lists.length > 0 && join["list-items"].length === 0
)
.toJSON()
).toHaveLength(0);
expect(linebreaksInLists.toJSON()).toMatchObject([
{
linebreak: LINEBREAKS[1],
lists: [LISTS[0]],
"list-items": [LIST_ITEMS[0]],
},
{
linebreak: LINEBREAKS[2],
lists: [LISTS[0]],
"list-items": [LIST_ITEMS[0]],
},
{
linebreak: LINEBREAKS[3],
lists: [LISTS[0]],
"list-items": [LIST_ITEMS[0]],
},
{
linebreak: LINEBREAKS[4],
lists: [LISTS[0]],
"list-items": [LIST_ITEMS[1]],
},
{
linebreak: LINEBREAKS[5],
lists: [LISTS[0]],
"list-items": [LIST_ITEMS[2]],
},
{
linebreak: LINEBREAKS[6],
lists: [LISTS[0]],
"list-items": [LIST_ITEMS[2]],
},
]);
});
it("created no paragraphs inside list-items", () => {
let paragraphs = atjson
.where({ type: "-offset-paragraph" })
.as("paragraph");
let paragraphsInLists = paragraphs.join(
atjson.where({ type: "-offset-list" }).as("lists"),
(l, r) => l.start >= r.start && l.end <= r.end
);
expect(paragraphsInLists.length).toBe(0);
});
it("inserts object replaement character for single-item lists", () => {
let ocrs = atjson.match(/\uFFFC/g, LISTS[1].start, LISTS[1].end);
expect(ocrs).toEqual([
{
start: LISTS[1].end - 1,
end: LISTS[1].end,
matches: expect.anything(),
},
]);
let lists = atjson.where({ type: "-offset-list" });
expect(lists.toJSON()).toMatchObject(LISTS);
let listItems = atjson.where({ type: "-offset-list-item" });
expect(listItems.toJSON()).toMatchObject(LIST_ITEMS);
});
});
describe("@atjson/source-gdocs-paste", () => {
let atjson: OffsetSource;
// https://docs.google.com/document/d/e/2PACX-1vSty31WXqvhSHwPxJD1QpWdeW7RbZhqJUFW8DVLbxVj9BacHVQdlKoBt0NWCAKBgqXHFgbZJdBfoyUP/pub
const fixturePath = path.join(__dirname, "fixtures", "line-breaks.json");
beforeAll(() => {
let rawJSON = JSON.parse(fs.readFileSync(fixturePath).toString());
let gdocs = GDocsSource.fromRaw(rawJSON);
atjson = gdocs.convertTo(OffsetSource);
});
it("has correct paragraphs", () => {
expect(atjson.content).toBe("Test\na\nTest\n \nTest\n");
let paragraphs = atjson.where({
type: "-offset-paragraph",
});
expect(paragraphs.toJSON()).toMatchObject(
[
[0, 4],
[5, 6],
[7, 11],
[14, 18],
].map(([start, end]) => ({
start,
end,
type: "-offset-paragraph",
}))
);
});
it("has no line breaks", () => {
let linebreaks = atjson.where({
type: "-offset-line-break",
});
expect(linebreaks.length).toBe(0);
});
it("has correct parse tokens", () => {
expect(atjson.content).toBe("Test\na\nTest\n \nTest\n");
let parseTokens = atjson.where({
type: "-atjson-parse-token",
});
expect(parseTokens.toJSON()).toMatchObject(
[
[4, 5],
[6, 7],
[11, 14],
[18, 19],
].map(([start, end]) => ({
start,
end,
type: "-atjson-parse-token",
attributes: {
"-atjson-reason": "paragraph boundary",
},
}))
);
});
});
describe("@atjson/source-gdocs-paste paragraphs in list", () => {
let doc: OffsetSource;
beforeAll(() => {
// https://docs.google.com/document/d/e/2PACX-1vRX6dmzmlW4NtjFj-KlXp3TGQTVyMBVBCVBwO4q9Bwwv8clmULhLmKjGxbz6Lf_qnLEQX9gewoAVJaz/pub
let fixturePath = path.join(
__dirname,
"fixtures",
"list-with-interrupting-paragraph.json"
);
let rawJSON = JSON.parse(fs.readFileSync(fixturePath).toString());
let gdocs = GDocsSource.fromRaw(rawJSON);
doc = gdocs.convertTo(OffsetSource);
});
it("splits lists interrupted by a paragraph not in a list item", () => {
expect(doc.content).toBe("A\nB\nC\nD\uFFFC");
expect(doc.where({ type: "-offset-paragraph" }).toJSON()).toMatchObject([
{ start: 4, end: 5 },
]);
expect(doc.where({ type: "-offset-list" }).toJSON()).toMatchObject([
{ start: 0, end: 4, attributes: { "-offset-type": "numbered" } },
{ start: 6, end: 8, attributes: { "-offset-type": "numbered" } },
]);
expect(doc.where({ type: "-offset-list-item" }).toJSON()).toMatchObject([
{ start: 0, end: 1 },
{ start: 2, end: 3 },
{ start: 6, end: 7 },
]);
expect(doc.where({ type: "-atjson-parse-token" }).toJSON()).toMatchObject([
{
start: 1,
end: 2,
attributes: { "-atjson-reason": "list item separator" },
},
{
start: 3,
end: 4,
attributes: { "-atjson-reason": "list item separator" },
},
{
start: 5,
end: 6,
attributes: { "-atjson-reason": "paragraph boundary" },
},
{
start: 7,
end: 8,
attributes: {
"-atjson-reason": "object replacement character for single-item list",
},
},
]);
});
}); | the_stack |
import {Constants} from "../scripts/constants";
import {UrlUtils} from "../scripts/urlUtils";
import {TooltipType} from "../scripts/clipperUI/tooltipType";
import {TestModule} from "./testModule";
export class UrlUtilsTests extends TestModule {
protected module() {
return "urlUtils";
}
protected tests() {
test("addUrlQueryValue should add a name/value pair to a url that contains existing (and different) name/value pairs", () => {
let originalUrl = "https://www.onenote.com/strings?ids=WebClipper.&pizza=cheesy&rice=fried";
let name = "name";
let value = "matthew";
let newUrl = UrlUtils.addUrlQueryValue(originalUrl, name, value);
strictEqual(newUrl, "https://www.onenote.com/strings?ids=WebClipper.&pizza=cheesy&rice=fried&name=matthew");
});
test("addUrlQueryValue should add a name/value pair to a url that does not already contain a name/value pair", () => {
let originalUrl = "http://www.onenote.com/strings";
let name = "ids";
let value = "Whatever";
let newUrl = UrlUtils.addUrlQueryValue(originalUrl, name, value);
strictEqual(newUrl, "http://www.onenote.com/strings?ids=Whatever");
});
test("addUrlQueryValue should add a name/value pair correctly if the url contains a fragment and a name/value pair", () => {
let originalUrl = "https://www.onenote.com/strings?ids=WebClipper.#frag";
let name = "k";
let value = "p";
let newUrl = UrlUtils.addUrlQueryValue(originalUrl, name, value);
strictEqual(newUrl, "https://www.onenote.com/strings?ids=WebClipper.&k=p#frag");
});
test("addUrlQueryValue should add a name/value pair correctly if the url contains a fragment but not a name/value pair", () => {
let originalUrl = "https://www.onenote.com/strings#frag";
let name = "k";
let value = "p";
let newUrl = UrlUtils.addUrlQueryValue(originalUrl, name, value);
strictEqual(newUrl, "https://www.onenote.com/strings?k=p#frag");
});
test("addUrlQueryValue should replace the value of an existing name in the query string", () => {
let originalUrl = "http://www.onenote.com/strings?ids=old";
let name = "ids";
let value = "new";
let newUrl = UrlUtils.addUrlQueryValue(originalUrl, name, value);
strictEqual(newUrl, "http://www.onenote.com/strings?ids=new");
});
test("addUrlQueryValue should return the originalUrl parameter when passed an empty url", () => {
let url = "";
strictEqual(UrlUtils.addUrlQueryValue(url, "name", "value"), url, "The originalUrl should be returned");
});
test("addUrlQueryValue should return the originalUrl parameter when passed a null url", () => {
/* tslint:disable:no-null-keyword */
let url = null;
strictEqual(UrlUtils.addUrlQueryValue(url, "name", "value"), url, "The originalUrl should be returned");
/* tslint:enable:no-null-keyword */
});
test("addUrlQueryValue should return the originalUrl parameter when passed an undefined url", () => {
let url = undefined;
strictEqual(UrlUtils.addUrlQueryValue(url, "name", "value"), url, "The originalUrl should be returned");
});
test("addUrlQueryValue should return the originalUrl parameter when passed an empty name", () => {
let url = "http://www.thiswebsite.rules/strings?";
strictEqual(UrlUtils.addUrlQueryValue(url, "", "value"), url, "The originalUrl should be returned");
});
test("addUrlQueryValue should return the originalUrl parameter when passed a null name", () => {
/* tslint:disable:no-null-keyword */
let url = "http://www.thiswebsite.rules/strings?";
strictEqual(UrlUtils.addUrlQueryValue(url, null, "value"), url, "The originalUrl should be returned");
/* tslint:enable:no-null-keyword */
});
test("addUrlQueryValue should return the originalUrl parameter when passed an undefined name", () => {
let url = "http://www.thiswebsite.rules/strings?";
strictEqual(UrlUtils.addUrlQueryValue(url, undefined, "value"), url, "The originalUrl should be returned");
});
test("addUrlQueryValue should return the originalUrl parameter when passed an empty value", () => {
let url = "http://www.thiswebsite.rules/strings?";
strictEqual(UrlUtils.addUrlQueryValue(url, "name", ""), url, "The originalUrl should be returned");
});
test("addUrlQueryValue should return the originalUrl parameter when passed a null value", () => {
/* tslint:disable:no-null-keyword */
let url = "http://www.thiswebsite.rules/strings?";
strictEqual(UrlUtils.addUrlQueryValue(url, "name", null), url, "The originalUrl should be returned");
/* tslint:enable:no-null-keyword */
});
test("addUrlQueryValue should return the originalUrl parameter when passed an undefined value", () => {
let url = "http://www.thiswebsite.rules/strings?";
strictEqual(UrlUtils.addUrlQueryValue(url, "name", undefined), url, "The originalUrl should be returned");
});
test("addUrlQueryValue should camel case the query param key added when told to do so", () => {
let url = "http://www.thiswebsite.rules?name1=value1";
let key = "name2";
strictEqual(UrlUtils.addUrlQueryValue(url, key, "value2", true), url + "&Name2=value2", "'" + key + "' should be camel cased in the url");
});
test("getFileNameFromUrl should return the file name when the url has a pdf file name", () => {
let fileName = UrlUtils.getFileNameFromUrl("www.website.com/my-file.pdf");
strictEqual(fileName, "my-file.pdf", "File name should be retrieved from url");
});
test("getFileNameFromUrl should return the file name when the url has a doc file name", () => {
let fileName = UrlUtils.getFileNameFromUrl("www.website.com/my-file.doc");
strictEqual(fileName, "my-file.doc", "File name should be retrieved from url");
});
test("getFileNameFromUrl should return the file name when the url has a doc file name and a number in the file name", () => {
let fileName = UrlUtils.getFileNameFromUrl("www.website.com/1my-file5.doc");
strictEqual(fileName, "1my-file5.doc", "File name should be retrieved from url");
});
test("getFileNameFromUrl should return the file name when the url has a doc file name and a number in the extension", () => {
let fileName = UrlUtils.getFileNameFromUrl("www.website.com/my-file.7zip");
strictEqual(fileName, "my-file.7zip", "File name should be retrieved from url");
});
test("getFileNameFromUrl should return the file name when the url has a doc file name while preserving casing", () => {
let fileName = UrlUtils.getFileNameFromUrl("www.website.com/FILE.json");
strictEqual(fileName, "FILE.json", "File name should be retrieved from url while preserving casing");
});
test("getFileNameFromUrl should return the file name when the url has a doc file name and the url is valid but unusual/unexpected", () => {
let fileName = UrlUtils.getFileNameFromUrl("www.website.website/file.json");
strictEqual(fileName, "file.json", "File name should be retrieved from url");
fileName = UrlUtils.getFileNameFromUrl("http://www.website.com/file.json");
strictEqual(fileName, "file.json", "File name should be retrieved from url");
fileName = UrlUtils.getFileNameFromUrl("https://www.website.com/file.json");
strictEqual(fileName, "file.json", "File name should be retrieved from url");
fileName = UrlUtils.getFileNameFromUrl("website.com/file.json");
strictEqual(fileName, "file.json", "File name should be retrieved from url");
fileName = UrlUtils.getFileNameFromUrl("www.website.com/really/long/url/5/file.json");
strictEqual(fileName, "file.json", "File name should be retrieved from url");
fileName = UrlUtils.getFileNameFromUrl("www.0800-website.reviews/file.json");
strictEqual(fileName, "file.json", "File name should be retrieved from url");
});
test("getFileNameFromUrl should return undefined when the url has no file name by default", () => {
let fileName = UrlUtils.getFileNameFromUrl("www.website.com/");
strictEqual(fileName, undefined, "File name should be retrieved from url while preserving casing");
fileName = UrlUtils.getFileNameFromUrl("www.website.com");
strictEqual(fileName, undefined, "File name should be retrieved from url while preserving casing");
fileName = UrlUtils.getFileNameFromUrl("website.com");
strictEqual(fileName, undefined, "File name should be retrieved from url while preserving casing");
fileName = UrlUtils.getFileNameFromUrl("wus.www.website.com");
strictEqual(fileName, undefined, "File name should be retrieved from url while preserving casing");
fileName = UrlUtils.getFileNameFromUrl("wus.www.website.com/pages/5");
strictEqual(fileName, undefined, "File name should be retrieved from url while preserving casing");
});
test("getFileNameFromUrl should return the fallback when the url has no file name when the fallback is specified", () => {
let fallback = "Fallback.xyz";
let fileName = UrlUtils.getFileNameFromUrl("www.website.com/", fallback);
strictEqual(fileName, fallback, "File name should be retrieved from url while preserving casing");
fileName = UrlUtils.getFileNameFromUrl("www.website.com", fallback);
strictEqual(fileName, fallback, "File name should be retrieved from url while preserving casing");
fileName = UrlUtils.getFileNameFromUrl("website.com", fallback);
strictEqual(fileName, fallback, "File name should be retrieved from url while preserving casing");
fileName = UrlUtils.getFileNameFromUrl("wus.www.website.com", fallback);
strictEqual(fileName, fallback, "File name should be retrieved from url while preserving casing");
fileName = UrlUtils.getFileNameFromUrl("wus.www.website.com/pages/5", fallback);
strictEqual(fileName, fallback, "File name should be retrieved from url while preserving casing");
});
test("getFileNameFromUrl should return the fallback when passed an empty url", () => {
let fallback = "Fallback.xyz";
strictEqual(UrlUtils.getFileNameFromUrl("", fallback), fallback,
"The fallback should be returned");
});
test("getFileNameFromUrl should return the fallback when passed a null url", () => {
/* tslint:disable:no-null-keyword */
let fallback = "Fallback.xyz";
strictEqual(UrlUtils.getFileNameFromUrl(null, fallback), fallback,
"The fallback should be returned");
/* tslint:enable:no-null-keyword */
});
test("getFileNameFromUrl should return the fallback when passed an undefined url", () => {
let fallback = "Fallback.xyz";
strictEqual(UrlUtils.getFileNameFromUrl(undefined, fallback), fallback,
"The fallback should be returned");
});
test("getQueryValue should return the query value in the general case", () => {
let url = "www.website.com/stuff?q=v";
strictEqual(UrlUtils.getQueryValue(url, "q"), "v");
});
test("getQueryValue should return the query value when there is more than one pair", () => {
let url = "www.website.com/stuff?q=v&q1=v1&q2=v2";
strictEqual(UrlUtils.getQueryValue(url, "q"), "v");
strictEqual(UrlUtils.getQueryValue(url, "q1"), "v1");
strictEqual(UrlUtils.getQueryValue(url, "q2"), "v2");
});
test("getQueryValue should return undefined if the key doesn't exist", () => {
let url = "www.website.com/stuff?q=v";
strictEqual(UrlUtils.getQueryValue(url, "notexist"), undefined);
});
test("getQueryValue should return undefined if no keys exist", () => {
let url = "www.website.com/stuff?";
strictEqual(UrlUtils.getQueryValue(url, "notexist"), undefined);
url = "www.website.com/stuff";
strictEqual(UrlUtils.getQueryValue(url, "notexist"), undefined);
});
test("getQueryValue should return empty string if the key exists but the value doesn't", () => {
let url = "www.website.com/stuff?q=";
strictEqual(UrlUtils.getQueryValue(url, "q"), "");
});
test("getQueryValue should return undefined if any of the parameters are undefined or empty string", () => {
strictEqual(UrlUtils.getQueryValue("www.website.com/stuff?q=v", undefined), undefined);
strictEqual(UrlUtils.getQueryValue(undefined, "q"), undefined);
strictEqual(UrlUtils.getQueryValue("www.website.com/stuff?q=v", ""), undefined);
strictEqual(UrlUtils.getQueryValue("", "q"), undefined);
});
test("getQueryValue should return a valid error if an error is specified.", () => {
let url = "https://www.onenote.com/webclipper/auth?error=access_denied&error_description=AADSTS50000:+There+was+an+error+issuing+a+token.&state=abcdef12-6ac8-41bd-0445-f7ef7a4182e7";
strictEqual(UrlUtils.getQueryValue(url, Constants.Urls.QueryParams.error), "access_denied");
});
test("getQueryValue should return a valid error description if an O365 error_description is specified.", () => {
let url = "https://www.onenote.com/webclipper/auth?error=access_denied&error_description=AADSTS50000:+There+was+an+error+issuing+a+token.&state=abcdef12-6ac8-41bd-0445-f7ef7a4182e7";
strictEqual(UrlUtils.getQueryValue(url, Constants.Urls.QueryParams.errorDescription), "AADSTS50000: There was an error issuing a token.");
});
test("getQueryValue should return a valid error description if an MSA errorDescription is specified.", () => {
let url = "https://www.onenote.com/webclipper/auth?error=access_denied&errorDescription=AADSTS50000:+There+was+an+error+issuing+a+token.&state=abcdef12-6ac8-41bd-0445-f7ef7a4182e7";
strictEqual(UrlUtils.getQueryValue(url, Constants.Urls.QueryParams.errorDescription), "AADSTS50000: There was an error issuing a token.");
});
test("onWhiteListedDomain should return true for urls with /yyyy/mm/dd/", () => {
ok(UrlUtils.onWhitelistedDomain("http://www.sdfdsfsdasdsa.com/2014/09/25/garden/when-blogging-becomes-a-slog.html?_r=1"));
});
test("onWhiteListedDomain should return true for urls with /yyyy/mm/", () => {
ok(UrlUtils.onWhitelistedDomain("http://www.sdfdsfsdasdsa.com/2014/09/garden/when-blogging-becomes-a-slog.html?_r=1"));
});
test("onWhiteListedDomain should return true for urls with /yy/mm/", () => {
ok(UrlUtils.onWhitelistedDomain("http://www.sdfdsfsdasdsa.com/16/09/garden/when-blogging-becomes-a-slog.html?_r=1"));
});
test("onWhiteListedDomain should return true for urls with /yyyy/m/", () => {
ok(UrlUtils.onWhitelistedDomain("http://www.sdfdsfsdasdsa.com/2014/1/garden/when-blogging-becomes-a-slog.html?_r=1"));
});
test("onWhiteListedDomain should return true for urls dash-seperated dates assuming they include the year, month, and day", () => {
ok(UrlUtils.onWhitelistedDomain("http://www.sdfdsfsdasdsa.com/2014-09-25/garden/when-blogging-becomes-a-slog.html?_r=1"));
});
test("onWhiteListedDomain should return false for urls dash-seperated dates assuming they do not include the year, month, and day", () => {
ok(!UrlUtils.onWhitelistedDomain("http://www.sdfdsfsdasdsa.com/2014-09/garden/when-blogging-becomes-a-slog.html?_r=1"));
});
test("onWhiteListedDomain should return false for urls with just years", () => {
ok(!UrlUtils.onWhitelistedDomain("http://www.sdfdsfsdasdsa.com/2014/garden/when-blogging-becomes-a-slog.html?_r=1"));
});
test("onWhiteListedDomain should return false for live sign-in URL", () => {
ok(!UrlUtils.onWhitelistedDomain("https://login.live.com/oauth20_authorize.srf?client_id=123456-789a-bcde-1234-123456789abc&scope=wl.signin%20wl.basic%20wl.emails%20wl.offline_access%20office.onenote_update&redirect_uri=https://www.onenote.com/webclipper/auth&response_type=code"));
});
test("onWhiteListedDomain should return false given undefined or empty string", () => {
ok(!UrlUtils.onWhitelistedDomain(""));
ok(!UrlUtils.onWhitelistedDomain(undefined));
});
test("getPathName should return a valid path given a valid URL", () => {
ok(UrlUtils.getPathname("https://www.foo.com/bar/blah"), "/bar/blah");
ok(UrlUtils.getPathname("https://www.youtube.com/watch?v=dQw4w9WgXcQ"), "/watch");
ok(UrlUtils.getPathname("https://www.youtube.com"), "/");
});
let tooltipsToTest = [TooltipType.Pdf, TooltipType.Product, TooltipType.Recipe];
test("checkIfUrlMatchesAContentType should return UNDEFINED for an undefined, null, or empty URL", () => {
ok(!UrlUtils.checkIfUrlMatchesAContentType(undefined, tooltipsToTest));
/* tslint:disable:no-null-keyword */
ok(!UrlUtils.checkIfUrlMatchesAContentType(null, tooltipsToTest));
/* tslint:enable:no-null-keyword */
ok(!UrlUtils.checkIfUrlMatchesAContentType("", tooltipsToTest));
});
test("checkIfUrlMatchesAContentType for PDF should return UNDEFINED for a valid URL without .pdf at the end", () => {
ok(!UrlUtils.checkIfUrlMatchesAContentType("https://www.fistbump.reviews", tooltipsToTest));
ok(!UrlUtils.checkIfUrlMatchesAContentType("https://fistbumppdfs.reviews", tooltipsToTest));
});
test("checkIfUrlMatchesAContentType for PDF should return PDF for a valid URL with .pdf at the end, case insensitive", () => {
strictEqual(UrlUtils.checkIfUrlMatchesAContentType("https://wwww.wen.jen/shipItFresh.pdf", tooltipsToTest), TooltipType.Pdf);
strictEqual(UrlUtils.checkIfUrlMatchesAContentType("http://www.orimi.com/pdf-test.PDF", tooltipsToTest), TooltipType.Pdf);
});
test("checkIfUrlMatchesAContentType for Product should return UNDEFINED for an invalid url", () => {
ok(!UrlUtils.checkIfUrlMatchesAContentType("https://www.onenote.com/clipper", tooltipsToTest));
});
test("checkIfUrlMatchesAContentType for Product should return Product for a valid Wal-mart URL", () => {
strictEqual(UrlUtils.checkIfUrlMatchesAContentType("http://www.walmart.com/ip/49424374", tooltipsToTest), TooltipType.Product);
});
test("checkIfUrlMatchesAContentType for Recipe should return UNDEFINED for a valid url that isnt in the regex match", () => {
ok(!UrlUtils.checkIfUrlMatchesAContentType("https://www.onenote.com/clipper", tooltipsToTest));
});
test("checkIfUrlMatchesAContentType for Recipe should return RECIPE for a valid URL", () => {
strictEqual(UrlUtils.checkIfUrlMatchesAContentType("http://www.chowhound.com/recipes/easy-grilled-cheese-31834", tooltipsToTest), TooltipType.Recipe);
});
}
}
(new UrlUtilsTests()).runTests(); | the_stack |
import {
cleanNode, options, virtualElements, objectForEach
} from '@tko/utils'
import {
unwrap,
observable as koObservable
} from '@tko/observable'
import {
computed
} from '@tko/computed'
import { MultiProvider } from '@tko/provider.multi'
import { VirtualProvider } from '@tko/provider.virtual'
import { DataBindProvider } from '@tko/provider.databind'
import {
applyBindings, dataFor, bindingContext, bindingEvent,
applyBindingsToDescendants, applyBindingsToNode, contextFor
} from '../dist'
import { bindings as coreBindings } from '@tko/binding.core'
import { bindings as templateBindings } from '@tko/binding.template'
import { bindings as ifBindings } from '@tko/binding.if'
import '@tko/utils/helpers/jasmine-13-helper'
describe('Binding attribute syntax', function () {
var bindingHandlers
beforeEach(jasmine.prepareTestNode)
beforeEach(function () {
// Set up the default binding handlers.
var provider = new MultiProvider({providers: [
new VirtualProvider(),
new DataBindProvider()
]})
options.bindingProviderInstance = provider
bindingHandlers = provider.bindingHandlers
bindingHandlers.set(coreBindings)
bindingHandlers.set(templateBindings)
bindingHandlers.set(ifBindings)
options.onError = function (e) { throw e }
})
it('applyBindings should accept no parameters and then act on document.body with undefined model', function () {
this.after(function () { cleanNode(document.body) }) // Just to avoid interfering with other specs
var didInit = false
bindingHandlers.test = {
init: function (element, valueAccessor, allBindings, viewModel) {
expect(element.id).toEqual('testElement')
expect(viewModel).toBeUndefined()
didInit = true
}
}
testNode.innerHTML = "<div id='testElement' data-bind='test:123'></div>"
applyBindings()
expect(didInit).toEqual(true)
})
it('applyBindings should accept one parameter and then act on document.body with parameter as model', function () {
this.after(function () { cleanNode(document.body) }) // Just to avoid interfering with other specs
var didInit = false
var suppliedViewModel = {}
bindingHandlers.test = {
init: function (element, valueAccessor, allBindings, viewModel) {
expect(element.id).toEqual('testElement')
expect(viewModel).toEqual(suppliedViewModel)
didInit = true
}
}
testNode.innerHTML = "<div id='testElement' data-bind='test'></div>"
applyBindings(suppliedViewModel)
expect(didInit).toEqual(true)
})
it('applyBindings should accept two parameters and then act on second param as DOM node with first param as model', function () {
var didInit = false
var suppliedViewModel = {}
bindingHandlers.test = {
init: function (element, valueAccessor, allBindings, viewModel) {
expect(element.id).toEqual('testElement')
expect(viewModel).toEqual(suppliedViewModel)
didInit = true
}
}
testNode.innerHTML = "<div id='testElement' data-bind='test'></div>"
var shouldNotMatchNode = document.createElement('DIV')
shouldNotMatchNode.innerHTML = "<div id='shouldNotMatchThisElement' data-bind='test'></div>"
document.body.appendChild(shouldNotMatchNode)
this.after(function () { document.body.removeChild(shouldNotMatchNode) })
applyBindings(suppliedViewModel, testNode)
expect(didInit).toEqual(true)
})
it('applyBindings should accept three parameters and use the third parameter as a callback for modifying the root context', function () {
var didInit = false
bindingHandlers.test = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
expect(bindingContext.extraValue).toEqual('extra')
didInit = true
}
}
testNode.innerHTML = "<div id='testElement' data-bind='test'></div>"
applyBindings(null, testNode, function (context) {
context.extraValue = 'extra'
})
expect(didInit).toEqual(true)
})
it('Should tolerate empty or only white-space binding strings', function () {
testNode.innerHTML = "<div data-bind=''></div><div data-bind=' '></div>"
applyBindings(null, testNode) // No exception means success
})
it('Should tolerate whitespace and nonexistent handlers', function () {
testNode.innerHTML = "<div data-bind=' nonexistentHandler : \"Hello\" '></div>"
applyBindings(null, testNode) // No exception means success
})
it('Should tolerate arbitrary literals as the values for a handler', function () {
testNode.innerHTML = "<div data-bind='stringLiteral: \"hello\", numberLiteral: 123, boolLiteralTrue: true, boolLiteralFalse: false, objectLiteral: {}, lambdaLiteral: => null, nullLiteral: null, undefinedLiteral: undefined'></div>"
applyBindings(null, testNode) // No exception means success
})
it('Should tolerate wacky IE conditional comments', function () {
// Represents issue https://github.com/SteveSanderson/knockout/issues/186. Would fail on IE9, but work on earlier IE versions.
testNode.innerHTML = '<div><!--[if IE]><!-->Hello<!--<![endif]--></div>'
applyBindings(null, testNode) // No exception means success
})
it('Should produce a meaningful error if a binding value contains invalid JavaScript', function () {
bindingHandlers.test = {
init: function (element, valueAccessor) { valueAccessor() }
}
testNode.innerHTML = "<div data-bind='test: (1;2)'></div>"
expect(function () {
applyBindings(null, testNode)
}).toThrowContaining('Bad operator:')
})
it('Should produce a meaningful error if a binding value doesn\'t exist', function () {
bindingHandlers.test = {
init: function (element, valueAccessor) { valueAccessor() }
}
testNode.innerHTML = "<div data-bind='test: nonexistentValue'></div>"
expect(function () {
applyBindings(null, testNode)
}).toThrowContaining('nonexistentValue')
})
it('Should call onBindingError with relevant details of a bindingHandler init error', function () {
var saved_obe = options.onError,
obe_calls = 0
this.after(function () {
options.onError = saved_obe
})
options.onError = function (spec) {
obe_calls++
expect(spec.during).toEqual('init')
expect(spec.errorCaptured.message).toMatch(/Message: A moth!$/)
expect(spec.bindingKey).toEqual('test')
expect(spec.valueAccessor()).toEqual(64728)
expect(spec.element).toEqual(testNode.children[0])
expect(spec.bindings.test()).toEqual(64728)
expect(spec.bindingContext.$data).toEqual('0xe')
expect(spec.allBindings().test).toEqual(64728)
}
bindingHandlers.test = {
init: function () { throw new Error('A moth!') }
}
testNode.innerHTML = "<div data-bind='test: 64728'></div>"
applyBindings('0xe', testNode)
expect(obe_calls).toEqual(1)
})
it('Should call onBindingError with relevant details of a bindingHandler update error', function () {
var saved_obe = options.onError,
obe_calls = 0
this.after(function () {
options.onError = saved_obe
})
options.onError = function (spec) {
obe_calls++
expect(spec.during).toEqual('update')
expect(spec.errorCaptured.message).toMatch(/A beetle!$/)
expect(spec.bindingKey).toEqual('test')
expect(spec.valueAccessor()).toEqual(64729)
expect(spec.element).toEqual(testNode.children[0])
expect(spec.bindings.test()).toEqual(64729)
expect(spec.bindingContext.$data).toEqual('0xf')
expect(spec.allBindings().test).toEqual(64729)
}
bindingHandlers.test = {
update: function () { throw new Error('A beetle!') }
}
testNode.innerHTML = "<div data-bind='test: 64729'></div>"
applyBindings('0xf', testNode)
expect(obe_calls).toEqual(1)
})
it('Should call onBindingError with relevant details when an update fails', function () {
var saved_obe = options.onError,
obe_calls = 0,
observable = koObservable()
this.after(function () {
options.onError = saved_obe
})
options.onError = function (spec) {
obe_calls++
expect(spec.during).toEqual('update')
expect(spec.errorCaptured.message).toMatch(/Observable: 42$/)
expect(spec.bindingKey).toEqual('test')
expect(spec.valueAccessor()).toEqual(64725)
expect(spec.element).toEqual(testNode.children[0])
expect(spec.bindings.test()).toEqual(64725)
expect(spec.bindingContext.$data).toEqual('0xef')
expect(spec.allBindings().test).toEqual(64725)
}
bindingHandlers.test = {
update: function () {
if (observable() === 42) {
throw new Error('Observable: ' + observable())
}
}
}
testNode.innerHTML = "<div data-bind='test: 64725'></div>"
applyBindings('0xef', testNode)
expect(obe_calls).toEqual(0)
try { observable(42) } catch (e) {}
expect(obe_calls).toEqual(1)
observable(24)
expect(obe_calls).toEqual(1)
try { observable(42) } catch (e) {}
expect(obe_calls).toEqual(2)
})
// * This is probably poor policy, but it only applies to legacy handlers. *
it('Calls the `update` even if `init` fails', function () {
var cc = false
this.after(function () { options.set('onError', undefined) })
options.set('onError', function () {})
bindingHandlers.test = {
init () { throw new Error('X') },
update () { cc = true }
}
testNode.innerHTML = "<div data-bind='test: 64725'></div>"
applyBindings('0xef', testNode)
expect(cc).toEqual(true)
})
it('Calls options.onError, if it is defined', function () {
var oe_calls = 0
var oxy = koObservable()
this.after(function () { options.set('onError', undefined) })
options.set('onError', function (err) {
expect(err.message.indexOf('turtle')).toNotEqual(-1)
// Check for the `spec` properties
expect(err.bindingKey).toEqual('test')
oe_calls++
})
bindingHandlers.test = {
init: function () { throw new Error('A turtle!') },
update: function (e, oxy) {
unwrap(oxy()) // Create dependency.
throw new Error('Two turtles!')
}
}
testNode.innerHTML = "<div data-bind='test: oxy'></div>"
applyBindings({oxy: oxy}, testNode)
expect(oe_calls).toEqual(2)
oxy(1234)
expect(oe_calls).toEqual(3)
})
it('Should invoke registered handlers\'s init() then update() methods passing binding data', function () {
var methodsInvoked = []
bindingHandlers.test = {
init: function (element, valueAccessor, allBindings) {
methodsInvoked.push('init')
expect(element.id).toEqual('testElement')
expect(valueAccessor()).toEqual('Hello')
expect(allBindings.get('another')).toEqual(123)
},
update: function (element, valueAccessor, allBindings) {
methodsInvoked.push('update')
expect(element.id).toEqual('testElement')
expect(valueAccessor()).toEqual('Hello')
expect(allBindings.get('another')).toEqual(123)
}
}
testNode.innerHTML = "<div id='testElement' data-bind='test:\"Hello\", another:123'></div>"
applyBindings(null, testNode)
expect(methodsInvoked.length).toEqual(2)
expect(methodsInvoked[0]).toEqual('init')
expect(methodsInvoked[1]).toEqual('update')
})
it('Should invoke each handlers\'s init() and update() before running the next one', function () {
var methodsInvoked = []
bindingHandlers.test1 = bindingHandlers.test2 = {
init: function (element, valueAccessor) {
methodsInvoked.push('init' + valueAccessor())
},
update: function (element, valueAccessor) {
methodsInvoked.push('update' + valueAccessor())
}
}
testNode.innerHTML = "<div data-bind='test1:\"1\", test2:\"2\"'></div>"
applyBindings(null, testNode)
expect(methodsInvoked).toEqual(['init1', 'update1', 'init2', 'update2'])
})
it('Should be able to use $element in binding value', function () {
testNode.innerHTML = "<div data-bind='text: $element.tagName'></div>"
applyBindings({}, testNode)
expect(testNode).toContainText('DIV')
})
it('Should be able to use $context in binding value to refer to the context object', function () {
testNode.innerHTML = "<div data-bind='text: $context.$data === $data'></div>"
applyBindings({}, testNode)
expect(testNode).toContainText('true')
})
it('Should be able to refer to the bound object itself (at the root scope, the viewmodel) via $data', function () {
testNode.innerHTML = "<div data-bind='text: $data.someProp'></div>"
applyBindings({ someProp: 'My prop value' }, testNode)
expect(testNode).toContainText('My prop value')
})
it('Bindings can signal that they control descendant bindings by returning a flag from their init function', function () {
bindingHandlers.test = {
init: function () { return { controlsDescendantBindings: true } }
}
testNode.innerHTML = "<div data-bind='test: true'>" +
"<div data-bind='text: 123'>456</div>" +
'</div>' +
"<div data-bind='text: 123'>456</div>"
applyBindings(null, testNode)
expect(testNode.childNodes[0].childNodes[0].innerHTML).toEqual('456')
expect(testNode.childNodes[1].innerHTML).toEqual('123')
})
it('Should not be allowed to have multiple bindings on the same element that claim to control descendant bindings', function () {
bindingHandlers.test1 = {
init: function () { return { controlsDescendantBindings: true } }
}
bindingHandlers.test2 = bindingHandlers.test1
testNode.innerHTML = "<div data-bind='test1: true, test2: true'></div>"
expect(function () {
applyBindings(null, testNode)
}).toThrowContaining('Multiple bindings (test1 and test2) are trying to control descendant bindings of the same element.')
})
it('Should use properties on the view model in preference to properties on the binding context', function () {
// In KO 3.5 this test relied on a bit of duck-typing (it has a $data).
testNode.innerHTML = "<div data-bind='text: $data.someProp'></div>"
var outer = new bindingContext({ someProp: 'Outer value' })
var inner = new bindingContext({ someProp: 'Inner value' }, outer)
applyBindings(inner, testNode)
expect(testNode).toContainText('Inner value')
})
it('Should be able to extend a binding context, adding new custom properties, without mutating the original binding context', function () {
bindingHandlers.addCustomProperty = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
applyBindingsToDescendants(bindingContext.extend({ '$customProp': 'my value' }), element)
return { controlsDescendantBindings: true }
}
}
testNode.innerHTML = "<div data-bind='with: sub'><div data-bind='addCustomProperty: true'><div data-bind='text: $customProp'></div></div></div>"
var vm = { sub: {} }
applyBindings(vm, testNode)
expect(testNode).toContainText('my value')
expect(contextFor(testNode.childNodes[0].childNodes[0].childNodes[0]).$customProp).toEqual('my value')
expect(contextFor(testNode.childNodes[0].childNodes[0]).$customProp).toBeUndefined() // Should not affect original binding context
// value of $data and $parent should be unchanged in extended context
expect(contextFor(testNode.childNodes[0].childNodes[0].childNodes[0]).$data).toEqual(vm.sub)
expect(contextFor(testNode.childNodes[0].childNodes[0].childNodes[0]).$parent).toEqual(vm)
})
it('Binding contexts should inherit any custom properties from ancestor binding contexts', function () {
bindingHandlers.addCustomProperty = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
applyBindingsToDescendants(bindingContext.extend({ '$customProp': 'my value' }), element)
return { controlsDescendantBindings: true }
}
}
testNode.innerHTML = "<div data-bind='addCustomProperty: true'><div data-bind='with: true'><div data-bind='text: $customProp'></div></div></div>"
applyBindings(null, testNode)
expect(testNode).toContainText('my value')
})
it('Binding context should hide or not minify extra internal properties', function () {
testNode.innerHTML = "<div data-bind='with: $data'><div></div></div>"
applyBindings({}, testNode)
var allowedProperties = ['$parents', '$root', 'ko', '$rawData', '$data', '$parentContext', '$parent']
if (typeof Symbol('') !== 'symbol') { // Test for shim
allowedProperties.push('_subscribable')
}
objectForEach(contextFor(testNode.childNodes[0].childNodes[0]),
(prop) => expect(allowedProperties).toContain(prop))
})
it('Should be able to retrieve the binding context associated with any node', function () {
testNode.innerHTML = "<div><div data-bind='text: name'></div></div>"
applyBindings({ name: 'Bert' }, testNode.childNodes[0])
expect(testNode.childNodes[0].childNodes[0]).toContainText('Bert')
// Can't get binding context for unbound nodes
expect(dataFor(testNode)).toBeUndefined()
expect(contextFor(testNode)).toBeUndefined()
// Can get binding context for directly bound nodes
expect(dataFor(testNode.childNodes[0]).name).toEqual('Bert')
expect(contextFor(testNode.childNodes[0]).$data.name).toEqual('Bert')
// Can get binding context for descendants of directly bound nodes
expect(dataFor(testNode.childNodes[0].childNodes[0]).name).toEqual('Bert')
expect(contextFor(testNode.childNodes[0].childNodes[0]).$data.name).toEqual('Bert')
// Also test that a non-node object returns nothing and doesn't crash
expect(dataFor({})).toBeUndefined()
expect(contextFor({})).toBeUndefined()
})
it('Should not return a context object for unbound elements that are descendants of bound elements', function () {
// From https://github.com/knockout/knockout/issues/2148
testNode.innerHTML = '<div data-bind="visible: isVisible"><span>Some text</span><div data-bind="allowBindings: false"><input data-bind="value: someValue"></div></div>'
bindingHandlers.allowBindings = {
init: function (elem, valueAccessor) {
// Let bindings proceed as normal *only if* my value is false
var shouldAllowBindings = unwrap(valueAccessor())
return { controlsDescendantBindings: !shouldAllowBindings }
}
}
var vm = {isVisible: true}
applyBindings(vm, testNode)
// All of the bound nodes return the viewmodel
expect(dataFor(testNode.childNodes[0])).toBe(vm)
expect(dataFor(testNode.childNodes[0].childNodes[0])).toBe(vm)
expect(dataFor(testNode.childNodes[0].childNodes[1])).toBe(vm)
expect(contextFor(testNode.childNodes[0].childNodes[1]).$data).toBe(vm)
// The unbound child node returns undefined
expect(dataFor(testNode.childNodes[0].childNodes[1].childNodes[0])).toBeUndefined()
expect(contextFor(testNode.childNodes[0].childNodes[1].childNodes[0])).toBeUndefined()
})
it('Should return the context object for nodes specifically bound, but override with general binding', function () {
// See https://github.com/knockout/knockout/issues/231#issuecomment-388210267
testNode.innerHTML = '<div data-bind="text: name"></div>'
var vm1 = { name: 'specific' }
applyBindingsToNode(testNode.childNodes[0], { text: vm1.name }, vm1)
expect(testNode).toContainText(vm1.name)
expect(dataFor(testNode.childNodes[0])).toBe(vm1)
expect(contextFor(testNode.childNodes[0]).$data).toBe(vm1)
var vm2 = { name: 'general' }
applyBindings(vm2, testNode)
expect(testNode).toContainText(vm2.name)
expect(dataFor(testNode.childNodes[0])).toBe(vm2)
expect(contextFor(testNode.childNodes[0]).$data).toBe(vm2)
})
it('Should not be allowed to use containerless binding syntax for bindings other than whitelisted ones', function () {
testNode.innerHTML = 'Hello <!-- ko visible: false -->Some text<!-- /ko --> Goodbye'
expect(function () {
applyBindings(null, testNode)
}).toThrow('The binding \'visible\' cannot be used with virtual elements')
})
it('Should be able to set a custom binding to use containerless binding', function () {
var initCalls = 0
bindingHandlers.test = { init: function () { initCalls++ } }
virtualElements.allowedBindings['test'] = true
testNode.innerHTML = 'Hello <!-- ko test: false -->Some text<!-- /ko --> Goodbye'
applyBindings(null, testNode)
expect(initCalls).toEqual(1)
expect(testNode).toContainText('Hello Some text Goodbye')
})
it('Should be allowed to express containerless bindings with arbitrary internal whitespace and newlines', function () {
testNode.innerHTML = 'Hello <!-- ko\n' +
' with\n' +
' : \n ' +
' { \n' +
" \tpersonName: 'Bert'\n" +
' }\n' +
" \t --><span data-bind='text: personName'></span><!-- \n" +
' /ko \n' +
'-->, Goodbye'
applyBindings({personName: 'Bert'}, testNode)
expect(testNode).toContainText('Hello Bert, Goodbye')
})
it('Should reject closing virtual bindings, when found as a first child', function () {
testNode.innerHTML = '<div><!-- /ko --></div>'
expect(function () {
applyBindings(null, testNode)
}).toThrow()
})
it('Should reject closing virtual bindings, when found as first child at the top level', function () {
testNode.innerHTML = '<!-- /ko -->'
testNode.innerHTML = '<!-- /ko -->'
expect(function () { applyBindings(null, testNode) }).toThrow()
})
it('Should reject closing virtual bindings without matching open, when found as a sibling', function () {
testNode.innerHTML = '<div></div><!-- /ko -->'
expect(function () { applyBindings(null, testNode) }).toThrow()
})
it('Should reject duplicated closing virtual bindings', function () {
testNode.innerHTML = '<!-- ko if: true --><div></div><!-- /ko --><!-- /ko -->'
expect(function () { applyBindings(null, testNode) }).toThrow()
})
it('Should reject opening virtual bindings that are not closed', function () {
testNode.innerHTML = '<!-- ko if: true -->'
expect(function () { applyBindings(null, testNode) }).toThrow()
})
it('Should reject virtual bindings that are nested incorrectly', function () {
testNode.innerHTML = '<!-- ko if: true --><div><!-- /ko --></div>'
expect(function () { applyBindings(null, testNode) }).toThrow()
})
it('Should be able to access virtual children in custom containerless binding', function () {
var countNodes = 0
bindingHandlers.test = {
init: function (element) {
// Counts the number of virtual children, and overwrites the text contents of any text nodes
for (var node = virtualElements.firstChild(element); node; node = virtualElements.nextSibling(node)) {
countNodes++
if (node.nodeType === 3) { node.data = 'new text' }
}
}
}
virtualElements.allowedBindings['test'] = true
testNode.innerHTML = 'Hello <!-- ko test: false -->Some text<!-- /ko --> Goodbye'
applyBindings(null, testNode)
expect(countNodes).toEqual(1)
expect(testNode).toContainText('Hello new text Goodbye')
})
it('Should only bind containerless binding once inside template', function () {
var initCalls = 0
bindingHandlers.test = { init: function () { initCalls++ } }
virtualElements.allowedBindings['test'] = true
testNode.innerHTML = 'Hello <!-- ko if: true --><!-- ko test: false -->Some text<!-- /ko --><!-- /ko --> Goodbye'
applyBindings(null, testNode)
expect(initCalls).toEqual(1)
expect(testNode).toContainText('Hello Some text Goodbye')
})
it('Bindings in containerless binding in templates should be bound only once', function () {
delete bindingHandlers.nonexistentHandler
var initCalls = 0
bindingHandlers.test = { init: function () { initCalls++ } }
testNode.innerHTML = `
<div data-bind='template: { if: true }'>
xxx
<!-- ko nonexistentHandler: true -->
<span data-bind='test: true'></span>
<!-- /ko -->
</div>`
applyBindings({}, testNode)
expect(initCalls).toEqual(1)
})
it('Should automatically bind virtual descendants of containerless markers if no binding controlsDescendantBindings', function () {
testNode.innerHTML = "Hello <!-- ko dummy: false --><span data-bind='text: \"WasBound\"'>Some text</span><!-- /ko --> Goodbye"
applyBindings(null, testNode)
expect(testNode).toContainText('Hello WasBound Goodbye')
})
it('Should be able to set and access correct context in custom containerless binding', function () {
bindingHandlers.bindChildrenWithCustomContext = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var innerContext = bindingContext.createChildContext({ myCustomData: 123 })
applyBindingsToDescendants(innerContext, element)
return { 'controlsDescendantBindings': true }
}
}
virtualElements.allowedBindings['bindChildrenWithCustomContext'] = true
testNode.innerHTML = 'Hello <!-- ko bindChildrenWithCustomContext: true --><div>Some text</div><!-- /ko --> Goodbye'
applyBindings(null, testNode)
expect(dataFor(testNode.childNodes[2]).myCustomData).toEqual(123)
})
it('Should be able to set and access correct context in nested containerless binding', function () {
delete bindingHandlers.nonexistentHandler
bindingHandlers.bindChildrenWithCustomContext = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var innerContext = bindingContext.createChildContext({ myCustomData: 123 })
applyBindingsToDescendants(innerContext, element)
return { 'controlsDescendantBindings': true }
}
}
testNode.innerHTML = "Hello <div data-bind='bindChildrenWithCustomContext: true'><!-- ko nonexistentHandler: 123 --><div>Some text</div><!-- /ko --></div> Goodbye"
applyBindings(null, testNode)
expect(dataFor(testNode.childNodes[1].childNodes[0]).myCustomData).toEqual(123)
expect(dataFor(testNode.childNodes[1].childNodes[1]).myCustomData).toEqual(123)
})
// TODO: FAIL
it('Should be able to access custom context variables in child context', function () {
bindingHandlers.bindChildrenWithCustomContext = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var innerContext = bindingContext.createChildContext({ myCustomData: 123 })
innerContext.customValue = 'xyz'
applyBindingsToDescendants(innerContext, element)
return { 'controlsDescendantBindings': true }
}
}
testNode.innerHTML = "Hello <div data-bind='bindChildrenWithCustomContext: true'><!-- ko with: myCustomData --><div>Some text</div><!-- /ko --></div> Goodbye"
applyBindings(null, testNode)
expect(contextFor(testNode.childNodes[1].childNodes[0]).customValue).toEqual('xyz')
expect(dataFor(testNode.childNodes[1].childNodes[1])).toEqual(123)
expect(contextFor(testNode.childNodes[1].childNodes[1]).$parent.myCustomData).toEqual(123)
expect(contextFor(testNode.childNodes[1].childNodes[1]).$parentContext.customValue).toEqual('xyz')
})
it('Should be able to use value-less binding in containerless binding', function () {
var initCalls = 0
bindingHandlers.test = { init: function () { initCalls++ } }
virtualElements.allowedBindings['test'] = true
testNode.innerHTML = 'Hello <!-- ko test -->Some text<!-- /ko --> Goodbye'
applyBindings(null, testNode)
expect(initCalls).toEqual(1)
expect(testNode).toContainText('Hello Some text Goodbye')
})
it('Should not allow multiple applyBindings calls for the same element', function () {
testNode.innerHTML = "<div data-bind='text: \"Some Text\"'></div>"
// First call is fine
applyBindings({}, testNode)
// Second call throws an error
expect(function () {
applyBindings({}, testNode)
}).toThrow('You cannot apply bindings multiple times to the same element.')
})
it('Should allow multiple applyBindings calls for the same element if cleanNode is used', function () {
testNode.innerHTML = "<div data-bind='text: \"Some Text\"'></div>"
// First call
applyBindings({}, testNode)
// cleanNode called before second call
cleanNode(testNode)
applyBindings({}, testNode)
// Should not throw any errors
})
it('Should allow multiple applyBindings calls for the same element if subsequent call provides a binding', function () {
testNode.innerHTML = "<div data-bind='text: \"Some Text\"'></div>"
// First call uses data-bind
applyBindings({}, testNode)
// Second call provides a binding
applyBindingsToNode(testNode, { visible: false }, {})
// Should not throw any errors
})
it('Should allow multiple applyBindings calls for the same element if initial call provides a binding', function () {
testNode.innerHTML = "<div data-bind='text: \"Some Text\"'></div>"
// First call provides a binding
applyBindingsToNode(testNode, { visible: false }, {})
// Second call uses data-bind
applyBindings({}, testNode)
// Should not throw any errors
})
it(`Should allow delegation with applyBindingsToNode`, () => {
testNode.innerHTML = `<i data-bind='myBinding: o'></i>`
let read = false
let write = false
bindingHandlers.myBinding = {
init: function(element, valueAccessor, allBindings, data, context) {
const interceptor = computed({
read: function () { read = 'r' },
write: function (v) { write = 'w' },
disposeWhenNodeIsRemoved: element
})
applyBindingsToNode(element, { value: interceptor }, context)
}
}
const element = document.createElement('div')
element.setAttribute('data-bind', 'myBinding: o')
const viewModel = { o: koObservable(123) }
applyBindings(viewModel, element)
expect(read).toEqual('r')
const event = new Event('change', { 'bubbles': true, 'cancelable': true })
element.dispatchEvent(event)
expect(write).toEqual('w')
})
describe('Should not bind against text content inside restricted elements', function () {
this.beforeEach(function () {
this.restoreAfter(options, 'bindingProviderInstance')
// Developers won't expect or want binding to mutate the contents of <script> or <textarea>
// elements. Historically this wasn't a problem because the default binding provider only
// acts on elements, but now custom providers can act on text contents of elements, it's
// important to ensure we don't break these elements by mutating their contents.
// First replace the binding provider with one that's hardcoded to replace all text
// content with a special message, via a binding handler that operates on text nodes
var originalBindingProvider = options.bindingProviderInstance
options.bindingProviderInstance = {
get FOR_NODE_TYPES () { return [3] },
nodeHasBindings: function (node) {
// IE < 9 can't bind text nodes, as expando properties are not allowed on them.
// This will still prove that the binding provider was not executed on the children of a restricted element.
if (node.nodeType === 3 && jasmine.ieVersion < 9) {
node.data = 'replaced'
return false
}
return true
},
getBindingAccessors: function (node, bindingContext) {
if (node.nodeType === 3) {
return {
replaceTextNodeContent: function () { return 'replaced' }
}
} else {
return originalBindingProvider.getBindingAccessors(node, bindingContext)
}
},
bindingHandlers: originalBindingProvider.bindingHandlers
}
bindingHandlers.replaceTextNodeContent = {
update: function (textNode, valueAccessor) { textNode.data = valueAccessor() }
}
})
it('<script>', function () {
testNode.innerHTML = '<p>Hello</p><script>alert(123);</script><p>Goodbye</p>'
applyBindings({ sometext: 'hello' }, testNode)
expect(testNode).toContainHtml('<p>replaced</p><script>alert(123);</script><p>replaced</p>')
})
it('<textarea>', function () {
testNode.innerHTML = '<p>Hello</p><textarea>test</textarea><p>Goodbye</p>'
applyBindings({ sometext: 'hello' }, testNode)
expect(testNode).toContainHtml('<p>replaced</p><textarea>test</textarea><p>replaced</p>')
})
it('<template>', function () {
document.createElement('template') // For old IE
testNode.innerHTML = '<p>Hello</p><template>test</template><p>Goodbye</p>'
applyBindings({ sometext: 'hello' }, testNode)
expect(testNode).toContainHtml('<p>replaced</p><template>test</template><p>replaced</p>')
})
})
it('Should call a childrenComplete callback function after descendent elements are bound', function () {
var callbacks = 0,
callback = function (nodes, data) {
expect(nodes.length).toEqual(1)
expect(nodes[0]).toEqual(testNode.childNodes[0].childNodes[0])
expect(data).toEqual(vm)
callbacks++
},
vm = { callback: callback }
testNode.innerHTML = "<div data-bind='childrenComplete: callback'><span data-bind='text: \"Some Text\"'></span></div>"
applyBindings(vm, testNode)
expect(callbacks).toEqual(1)
})
it('Should call a childrenComplete callback function when bound to a virtual element', function () {
var callbacks = 0,
callback = function (nodes, data) {
expect(nodes.length).toEqual(1)
expect(nodes[0]).toEqual(testNode.childNodes[1])
expect(data).toEqual(vm)
callbacks++
},
vm = { callback: callback }
testNode.innerHTML = "<!-- ko childrenComplete: callback --><span data-bind='text: \"Some Text\"'></span><!-- /ko -->"
applyBindings(vm, testNode)
expect(callbacks).toEqual(1)
})
it('Should not call a childrenComplete callback function when there are no descendant nodes', function () {
var callbacks = 0
testNode.innerHTML = "<div data-bind='childrenComplete: callback'></div>"
applyBindings({ callback: function () { callbacks++ } }, testNode)
expect(callbacks).toEqual(0)
})
it('Should ignore (and not throw an error) for a null childrenComplete callback', function () {
testNode.innerHTML = "<div data-bind='childrenComplete: null'><span data-bind='text: \"Some Text\"'></span></div>"
applyBindings({}, testNode)
})
it('Should call childrenComplete callback registered with bindingEvent.subscribe', function () {
var callbacks = 0,
vm = {}
bindingEvent.subscribe(testNode, 'childrenComplete', function (node) {
callbacks++
expect(node).toEqual(testNode)
expect(dataFor(node)).toEqual(vm)
})
testNode.innerHTML = '<div></div>'
applyBindings(vm, testNode)
expect(callbacks).toEqual(1)
})
}) | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.